diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..86b308249e318f7c5c97436daf1546e9cb362d96 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/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/lightning_indexer/README.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9424afd1b942e03ade779f5e3e722fd6036587af --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/README.md @@ -0,0 +1,272 @@ +# LightningIndexer + +## 产品支持情况 + +|产品 | 是否支持 | +|:----------------------------|:-----------:| +|Ascend 950PR/Ascend 950DT| √ | +|Atlas A3 训练系列产品/Atlas A3 推理系列产品| √ | +|Atlas A2 训练系列产品/Atlas A2 推理系列产品| √ | +|Atlas 200I/500 A2 推理产品| × | +|Atlas 推理系列产品| × | +|Atlas 训练系列产品| × | + +## 功能说明 + +- 算子功能:`lightning_indexer`基于一系列操作得到每一个token对应的Top-$k$个位置。 + +- 计算公式: + + $$ + Indices=\text{Top-}k\left\{[1]_{1\times g}@\left[(W@[1]_{1\times S_{k}})\odot\text{ReLU}\left(Q_{index}@K_{index}^T\right)\right]\right\} + $$ + + 对于某个token对应的Index Query $Q_{index}\in\R^{g\times d}$,给定上下文Index Key $K_{index}\in\R^{S_{k}\times d},W\in\R^{g\times 1}$,其中$g$为GQA对应的group size,$d$为每一个头的维度,$S_{k}$是上下文的长度。 + +## 参数说明 + +> **说明:**
+> 参数维度含义:B表示Batch Size、Q_S和K_S分别表示query和key的Sequence Length、Q_N和K_N分别表示query和key的Head Num、D表示Head Dim(Q_D和K_D取值相等为128)、Q_T和K_T分别表示query和key的Total Tokens、sparse_count表示最后选取的索引个数(topK)、block_num和block_size分别表示PageAttention场景下的block总数和每个block的token数。K_N仅支持1。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出/属性描述数据类型数据格式
query输入 +
    +
  • 公式中的输入Q。
  • +
  • 不支持空tensor和非连续。
  • +
  • layout_query为BSND时,shape为[B, Q_S, Q_N, D];layout_query为TND时,shape为[Q_T, Q_N, D]。
  • +
+
FLOAT16、BFLOAT16ND
key输入 +
    +
  • 公式中的输入K。
  • +
  • 不支持空tensor和非连续。
  • +
  • layout_key为PA_BSND时,shape为[block_num, block_size, K_N, D],其中block_num为PageAttention时block总数、block_size为一个block的token数;layout_key为BSND时,shape为[B, K_S, K_N, D];layout_key为TND时,shape为[K_T, K_N, D]。
  • +
+
FLOAT16、BFLOAT16ND
weights输入 +
    +
  • 公式中的输入W。
  • +
  • 不支持空tensor和非连续。
  • +
  • layout_query为BSND时,shape为[B, Q_S, Q_N];layout_query为TND时,shape为[Q_T, Q_N]。
  • +
+
FLOAT16、BFLOAT16、FLOATND
actual_seq_lengths_query输入 +
    +
  • 每个Batch中Query的有效token数。
  • +
  • 不支持空tensor和非连续。
  • +
  • 可传入None表示与query的Q_S长度相同。
  • +
  • 支持长度为B的一维tensor,且每个Batch的有效token数不超过query中的Q_S大小且不小于0。layout_query为TND时该入参必须传入,并以元素数量作为B值。
  • +
  • 每个元素表示当前batch与之前所有batch的token数总和,即前缀和,因此后一个元素的值必须大于等于前一个元素的值。
  • +
+
INT32ND
actual_seq_lengths_key输入 +
    +
  • 每个Batch中Key的有效token数。
  • +
  • 不支持空tensor和非连续。
  • +
  • 可传入None表示与key的K_S长度相同。
  • +
  • 支持长度为B的一维tensor,且每个Batch的有效token数不超过key中的K_S大小且不小于0。
  • +
  • layout_key为TND或PA_BSND时该入参必须传入;其中layout_key为TND时,每个元素表示当前batch与之前所有batch的token数总和,即前缀和,因此后一个元素的值必须大于等于前一个元素的值。
  • +
+
INT32ND
block_table输入 +
    +
  • 表示PageAttention中KV存储使用的block映射表。
  • +
  • 不支持空tensor和非连续。
  • +
  • PageAttention场景下,block_table必须为二维,第一维长度需要等于B,第二维长度不能小于maxBlockNumPerSeq(每个batch中最大actual_seq_lengths_key对应的block数量)。
  • +
  • shape支持[B, K_S/block_size]。
  • +
+
INT32ND
layout_query属性 +
    +
  • 用于标识输入Query的数据排布格式。
  • +
  • 默认值为"BSND",当前支持BSND、TND。
  • +
+
STRING-
layout_key属性 +
    +
  • 用于标识输入Key的数据排布格式。
  • +
  • 默认值为"BSND",当前支持PA_BSND、BSND、TND。
  • +
+
STRING-
sparse_count属性 +
    +
  • topK阶段需要保留的block数量。
  • +
  • 支持[1, 2048],以及3072、4096、5120、6144、7168、8192。
  • +
  • 默认值为2048。
  • +
+
INT32-
sparse_mode属性 +
    +
  • 表示sparse的模式。
  • +
  • sparse_mode为0时代表defaultMask模式。
  • +
  • sparse_mode为3时代表rightDownCausal模式的mask,对应以右顶点为划分的下三角场景。
  • +
  • 默认值为3。
  • +
+
INT32-
pre_tokens属性用于稀疏计算,表示attention需要和前几个Token计算关联,仅支持默认值2^63-1。INT64-
next_tokens属性用于稀疏计算,表示attention需要和后几个Token计算关联,仅支持默认值2^63-1。INT64-
return_values属性 +
    +
  • 表示是否输出sparseValuesOut。
  • +
  • True表示输出,False表示不输出,默认值为False。仅在训练且layout_key不为PA_BSND场景支持。
  • +
+
BOOL-
sparse_indices输出 +
    +
  • 公式中的Indices输出。
  • +
  • 不支持空tensor和非连续。
  • +
  • layout_query为BSND时输出shape为[B, Q_S, K_N, sparse_count];layout_query为TND时输出shape为[Q_T, K_N, sparse_count]。
  • +
+
INT32-
sparse_values输出 +
    +
  • 公式中的Indices输出对应的value值。
  • +
  • 不支持空tensor和非连续。
  • +
  • shape与sparseIndicesOut保持一致。
  • +
+
FLOAT16、BFLOAT16ND
+ +## 约束说明 + +- 该接口支持图模式。 +- 参数key中的K_N支持1。 +- headdim支持128。 +- block_size取值为16的倍数,最大支持1024。 +- 参数query、key的数据类型应保持一致。 +- 参数weights不为`float32`时,参数query、key、weights的数据类型应保持一致。 +- Ascend 950PR/Ascend 950DT: + - query Q_N仅支持8、16、24、32、64。 + - 参数weights不支持`float32`类型。 +- Atlas A3 训练系列产品/Atlas A3 推理系列产品、Atlas A2 训练系列产品/Atlas A2 推理系列产品: + - query Q_N支持小于等于64。 + +## 调用示例 + + + + + + + + + + + + + +
调用方式样例代码说明
aclnn接口 + test_aclnn_lightning_indexer + + + 通过 + aclnnLightningIndexer + + 接口方式调用算子 +
diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/docs/aclnnLightningIndexer.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/docs/aclnnLightningIndexer.md new file mode 100644 index 0000000000000000000000000000000000000000..d9d75e896fe92a1229e37d254586c1a7b2ba1203 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/docs/aclnnLightningIndexer.md @@ -0,0 +1,750 @@ +# aclnnLightningIndexer + +[📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/attention/lightning_indexer) + +## 产品支持情况 + + +- Ascend 950PR/Ascend 950DT:支持 + + +- Atlas A3 训练系列产品/Atlas A3 推理系列产品:支持 + + +- Atlas A2 训练系列产品/Atlas A2 推理系列产品:支持 + + +- Atlas 200I/500 A2 推理产品:不支持 + + +- Atlas 推理系列产品:不支持 + + +- Atlas 训练系列产品:不支持 + + +## 功能说明 + +- 接口功能:`lightning_indexer`基于一系列操作得到每一个token对应的Top-$k$个位置。 + +- 计算公式: + +$$ +Indices=\text{Top-}k\left\{[1]_{1\times g}@\left[(W@[1]_{1\times S_{k}})\odot\text{ReLU}\left(Q_{index}@K_{index}^T\right)\right]\right\} +$$ + +对于某个token对应的Index Query $Q_{index}\in\R^{g\times d}$,给定上下文Index Key $K_{index}\in\R^{S_{k}\times d},W\in\R^{g\times 1}$,其中$g$为GQA对应的group size,$d$为每一个头的维度,$S_{k}$是上下文的长度。 + +## 函数原型 + +该算子采用两段式接口,必须先调用“aclnnLightningIndexerGetWorkspaceSize”接口获取计算所需workspace大小以及包含了算子计算流程的执行器,再调用“aclnnLightningIndexer”接口执行计算。 + +```Cpp +aclnnStatus aclnnLightningIndexerGetWorkspaceSize( + const aclTensor *query, + const aclTensor *key, + const aclTensor *weights, + const aclTensor *actualSeqLengthsQueryOptional, + const aclTensor *actualSeqLengthsKeyOptional, + const aclTensor *blockTableOptional, + char *layoutQueryOptional, + char *layoutKeyOptional, + int64_t sparseCount, + int64_t sparseMode, + int64_t preTokens, + int64_t nextTokens, + bool returnValues, + const aclTensor *sparseIndicesOut, + const aclTensor *sparseValuesOut, + uint64_t *workspaceSize, + aclOpExecutor **executor) +``` + +```Cpp +aclnnStatus aclnnLightningIndexer( + void *workspace, + uint64_t workspaceSize, + aclOpExecutor *executor, + const aclrtStream stream) +``` + +## aclnnLightningIndexerGetWorkspaceSize + +- **参数说明:** + +> [!NOTE] +> +> - query、key、weights参数维度含义:B(Batch Size)表示输入样本批量大小、S(Sequence Length)表示输入样本序列长度、H(Head Size)表示hidden层的大小、N(Head Num)表示多头数、D(Head Dim)表示hidden层最小的单元尺寸,且满足D=H/N、T表示所有Batch输入样本序列长度的累加和。 +> - S1表示query shape中的S,S2表示key shape中的S,T1表示query shape中的T,T2表示key shape中的T,N1表示query shape中的N,N2表示key shape中的N。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述使用说明数据类型数据格式维度(shape)非连续Tensor
query输入公式中的输入Q。不支持空tensor。FLOAT16、BFLOAT16ND +
    +
  • layout_query为BSND时,shape为(B,S1,N1,D)。
  • +
  • layout_query为TND时,shape为(T1,N1,D)。
  • +
+
x
key输入公式中的输入K。 +
    +
  • 不支持空tensor。
  • +
  • block_num为PageAttention时block总数,block_size为一个block的token数。
  • +
+
FLOAT16、BFLOAT16ND +
    +
  • layout_key为PA_BSND时,shape为(block_num, block_size, N2, D)。
  • +
  • layout_kv为BSND时,shape为(B, S2, N2, D)。
  • +
  • layout_kv为TND时,shape为(T2, N2, D)。
  • +
+
x
weights输入公式中的输入W。不支持空tensor。FLOAT16、BFLOAT16、FLOATND +
    +
  • layout_query为BSND时,shape为(B,S1,N1)。
  • +
  • layout_query为TND时,shape为(T1,N1)。
  • +
+
x
actualSeqLengthsQueryOptional输入每个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
actualSeqLengthsKeyOptional输入每个Batch中,Key的有效token数。 +
    +
  • 不支持空tensor。
  • +
  • 如果不指定seqlen可传入None,表示和key的shape的S长度相同。
  • +
  • 该参数中每个Batch的有效token数不超过`key/value`中的维度S大小且不小于0,支持长度为B的一维tensor。
  • +
  • 当`layout_key`为TND或PA_BSND时,该入参必须传入,`layout_key`为TND,该参数中每个元素的值表示当前batch与之前所有batch的token数总和,即前缀和,因此后一个元素的值必须大于等于前一个元素的值。
  • +
+
INT32ND(B,)x
blockTableOptional输入表示PageAttention中KV存储使用的block映射表。 +
    +
  • 不支持空tensor。
  • +
  • PageAttention场景下,block\_table必须为二维,第一维长度需要等于B,第二维长度不能小于maxBlockNumPerSeq(maxBlockNumPerSeq为每个batch中最大actual\_seq\_lengths\_key对应的block数量)
  • +
+
INT32NDshape支持(B,S2/block_size)x
layoutQueryOptional输入用于标识输入Query的数据排布格式。 +
    +
  • 用户不特意指定时可传入默认值"BSND"。
  • +
  • 当前支持BSND、TND。
  • +
+
STRING---
layoutKeyOptional输入用于标识输入Key的数据排布格式。 +
    +
  • 用户不特意指定时可传入默认值"BSND"。
  • +
  • 当前支持PA_BSND、BSND、TND。
  • +
+
STRING---
sparseCount输入topK阶段需要保留的block数量。支持[1, 2048],以及3072、4096、5120、6144、7168、8192INT32---
sparseMode输入表示sparse的模式。 +
    +
  • sparse_mode为0时,代表defaultMask模式。
  • +
  • sparse_mode为3时,代表rightDownCausal模式的mask,对应以右顶点为划分的下三角场景。
  • +
+
INT32---
preTokens输入用于稀疏计算,表示attention需要和前几个Token计算关联。仅支持默认值2^63-1。INT64---
nextTokens输入用于稀疏计算,表示attention需要和后几个Token计算关联。仅支持默认值2^63-1。INT64---
returnValues输入表示是否输出sparseValuesOut。 +
    +
  • True表示输出,但图模式下不支持,False表示不输出;默认值为False
  • +
  • 仅在训练且layout_key不为PA_BSND场景支持
  • +
+
BOOL---
sparseIndicesOut输出公式中的Indices输出。不支持空tensor。INT32- +
    +
  • layout_query为"BSND"时输出shape为[B, S1, N2, sparseCount]。
  • +
  • layout_query为"TND"时输出shape为[T1, N2, sparseCount]。
  • +
+
x
sparseValuesOut输出公式中的Indices输出对应的value值。不支持空tensor。FLOAT16、BFLOAT16NDshape与sparseIndicesOut保持一致x
workspaceSize输出返回需要在Device侧申请的workspace大小。-----
executor输出返回op执行器,包含了算子计算流程。-----
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + + 第一段接口会完成入参校验,出现以下场景时报错: + + + + + + + + + + + + + + + + + + + + + + + +
返回值错误码描述
ACLNN_ERR_PARAM_NULLPTR161001如果传入参数是必选输入,输出或者必选属性,且是空指针,则返回161001。
ACLNN_ERR_PARAM_INVALID161002query、key、weights、actualSeqLengthsQueryOptional、actualSeqLengthsKeyOptional、layoutQueryOptional、layoutKeyOptional、sparseCount、sparseMode、returnValues、sparseIndicesOut、sparseValuesOut的数据类型和数据格式不在支持的范围内。
+ +## aclnnLightningIndexer + +- **参数说明:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述
workspace输入在Device侧申请的workspace内存地址。
workspaceSize输入在Device侧申请的workspace大小,由第一段接口aclnnLightningIndexerGetWorkspaceSize获取。
executor输入op执行器,包含了算子计算流程。
stream输入指定执行任务的Stream。
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + +## 约束说明 + +- 参数query中的N支持小于等于64,key的N支持1。 +- headdim支持128。 +- block_size取值为16的倍数,最大支持1024。 +- 参数query、key的数据类型应保持一致。 +- 参数weights不为`float32`时,参数query、key、weights的数据类型应保持一致。 + +## 调用示例 + +以下示例代码展示接口调用流程,可供编译和运行时参考。 + +```Cpp +/** + * 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_incre_flash_attention_v4.cpp + * \brief + */ +//testci +#include +#include +#include +#include +#include "securec.h" +#include "acl/acl.h" +#include "aclnnop/aclnn_lightning_indexer.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* weightsDeviceAddr = nullptr; + void* sparseIndicesDeviceAddr = nullptr; + void* sparseValuesDeviceAddr = nullptr; + + aclTensor* queryTensor = nullptr; + aclTensor* keyTensor = nullptr; + aclTensor* weightsTensor = nullptr; + aclTensor* sparseIndicesTensor = nullptr; + aclTensor* sparseValuesTensor = nullptr; +}; + +int InitializeTensors(TensorResources& resources) { + std::vector queryShape = {1, 2, 1, 128}; + std::vector keyShape = {1, 2, 1, 128}; + std::vector weightsShape = {1, 2, 1}; + std::vector sparseIndicesShape = {1, 2, 1, 2048}; + std::vector sparseValuesShape = {1, 2, 1, 2048}; + + int64_t queryShapeSize = GetShapeSize(queryShape); + int64_t keyShapeSize = GetShapeSize(keyShape); + int64_t weightsShapeSize = GetShapeSize(weightsShape); + int64_t sparseIndicesShapeSize = GetShapeSize(sparseIndicesShape); + int64_t sparseValuesShapeSize = GetShapeSize(sparseValuesShape); + + std::vector queryHostData(queryShapeSize, 1); + std::vector keyHostData(keyShapeSize, 1); + std::vector weightsHostData(weightsShapeSize, 1); + std::vector sparseIndicesHostData(sparseIndicesShapeSize, 1); + std::vector sparseValuesHostData(sparseValuesShapeSize, 1); + + int ret = CreateAclTensor(queryHostData, queryShape, &resources.queryDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.queryTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + ret = CreateAclTensor(keyHostData, keyShape, &resources.keyDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.keyTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + ret = CreateAclTensor(weightsHostData, weightsShape, &resources.weightsDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.weightsTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + ret = CreateAclTensor(sparseIndicesHostData, sparseIndicesShape, &resources.sparseIndicesDeviceAddr, + aclDataType::ACL_INT32, &resources.sparseIndicesTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + ret = CreateAclTensor(sparseValuesHostData, sparseValuesShape, &resources.sparseValuesDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.sparseValuesTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + return ACL_SUCCESS; +} + +int ExecuteLightningIndexer(TensorResources& resources, aclrtStream stream, + void** workspaceAddr, uint64_t* workspaceSize) { + int64_t sparseCount = 2048; + int64_t sparseMode = 3; + int64_t preTokens = 9223372036854775807; + int64_t nextTokens = 9223372036854775807; + bool returnValue = true; + constexpr const char layerOutStr[] = "BSND"; + constexpr size_t layerOutLen = sizeof(layerOutStr); + char layoutQuery[layerOutLen]; + char layoutKey[layerOutLen]; + errno_t memcpyRet = memcpy_s(layoutQuery, sizeof(layoutQuery), layerOutStr, layerOutLen); + if (!CHECK_RET(memcpyRet == 0)) { + LOG_PRINT("memcpy_s layoutQuery failed. ERROR: %d\n", memcpyRet); + return -1; + } + memcpyRet = memcpy_s(layoutKey, sizeof(layoutKey), layerOutStr, layerOutLen); + if (!CHECK_RET(memcpyRet == 0)) { + LOG_PRINT("memcpy_s layoutKey failed. ERROR: %d\n", memcpyRet); + return -1; + } + aclOpExecutor* executor; + + int ret = aclnnLightningIndexerGetWorkspaceSize(resources.queryTensor, resources.keyTensor, resources.weightsTensor, nullptr, nullptr, nullptr, + layoutQuery, layoutKey, sparseCount, sparseMode, preTokens, nextTokens,returnValue, + resources.sparseIndicesTensor, resources.sparseValuesTensor, workspaceSize, &executor); + + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclnnLightningIndexerGetWorkspaceSize 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 = aclnnLightningIndexer(*workspaceAddr, *workspaceSize, executor, stream); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclnnLightningIndexer failed. ERROR: %d\n", ret); + return ret; + } + + return ACL_SUCCESS; +} + +int PrintValueOutResult(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; +} + +int PrintIndicesOutResult(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: %d\n", i, 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.weightsTensor) { + aclDestroyTensor(resources.weightsTensor); + } + if (resources.sparseIndicesTensor) { + aclDestroyTensor(resources.sparseIndicesTensor); + } + if (resources.sparseValuesTensor) { + aclDestroyTensor(resources.sparseValuesTensor); + } + + if (resources.queryDeviceAddr) { + aclrtFree(resources.queryDeviceAddr); + } + if (resources.keyDeviceAddr) { + aclrtFree(resources.keyDeviceAddr); + } + if (resources.weightsDeviceAddr) { + aclrtFree(resources.weightsDeviceAddr); + } + if (resources.sparseIndicesDeviceAddr) { + aclrtFree(resources.sparseIndicesDeviceAddr); + } + if (resources.sparseValuesDeviceAddr) { + aclrtFree(resources.sparseValuesDeviceAddr); + } + + 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 sparseIndicesShape = {1, 2, 1, 2048}; + std::vector sparseValuesShape = {1, 2, 1, 2048}; + 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 = ExecuteLightningIndexer(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 + PrintIndicesOutResult(sparseIndicesShape, &resources.sparseIndicesDeviceAddr); + PrintValueOutResult(sparseValuesShape, &resources.sparseValuesDeviceAddr); + + // 6. Cleanup resources + CleanupResources(resources, workspaceAddr, stream, deviceId); + return 0; +} +``` diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/examples/test_aclnn_lightning_indexer.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/examples/test_aclnn_lightning_indexer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9ac7c0ff85a8ddba89dd37c380e2de9ee4174422 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/examples/test_aclnn_lightning_indexer.cpp @@ -0,0 +1,324 @@ +/** + * 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_incre_flash_attention_v4.cpp + * \brief + */ +//testci +#include +#include +#include +#include +#include "securec.h" +#include "acl/acl.h" +#include "aclnnop/aclnn_lightning_indexer.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* weightsDeviceAddr = nullptr; + void* sparseIndicesDeviceAddr = nullptr; + void* sparseValuesDeviceAddr = nullptr; + + aclTensor* queryTensor = nullptr; + aclTensor* keyTensor = nullptr; + aclTensor* weightsTensor = nullptr; + aclTensor* sparseIndicesTensor = nullptr; + aclTensor* sparseValuesTensor = nullptr; +}; + +int InitializeTensors(TensorResources& resources) { + std::vector queryShape = {1, 2, 1, 128}; + std::vector keyShape = {1, 2, 1, 128}; + std::vector weightsShape = {1, 2, 1}; + std::vector sparseIndicesShape = {1, 2, 1, 2048}; + std::vector sparseValuesShape = {1, 2, 1, 2048}; + + int64_t queryShapeSize = GetShapeSize(queryShape); + int64_t keyShapeSize = GetShapeSize(keyShape); + int64_t weightsShapeSize = GetShapeSize(weightsShape); + int64_t sparseIndicesShapeSize = GetShapeSize(sparseIndicesShape); + int64_t sparseValuesShapeSize = GetShapeSize(sparseValuesShape); + + std::vector queryHostData(queryShapeSize, 1); + std::vector keyHostData(keyShapeSize, 1); + std::vector weightsHostData(weightsShapeSize, 1); + std::vector sparseIndicesHostData(sparseIndicesShapeSize, 1); + std::vector sparseValuesHostData(sparseValuesShapeSize, 1); + + int ret = CreateAclTensor(queryHostData, queryShape, &resources.queryDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.queryTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + ret = CreateAclTensor(keyHostData, keyShape, &resources.keyDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.keyTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + ret = CreateAclTensor(weightsHostData, weightsShape, &resources.weightsDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.weightsTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + ret = CreateAclTensor(sparseIndicesHostData, sparseIndicesShape, &resources.sparseIndicesDeviceAddr, + aclDataType::ACL_INT32, &resources.sparseIndicesTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + + ret = CreateAclTensor(sparseValuesHostData, sparseValuesShape, &resources.sparseValuesDeviceAddr, + aclDataType::ACL_FLOAT16, &resources.sparseValuesTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + return ret; + } + return ACL_SUCCESS; +} + +int ExecuteLightningIndexer(TensorResources& resources, aclrtStream stream, + void** workspaceAddr, uint64_t* workspaceSize) { + int64_t sparseCount = 2048; + int64_t sparseMode = 3; + int64_t preTokens = 9223372036854775807; + int64_t nextTokens = 9223372036854775807; + bool returnValue = true; + constexpr const char layerOutStr[] = "BSND"; + constexpr size_t layerOutLen = sizeof(layerOutStr); + char layoutQuery[layerOutLen]; + char layoutKey[layerOutLen]; + errno_t memcpyRet = memcpy_s(layoutQuery, sizeof(layoutQuery), layerOutStr, layerOutLen); + if (!CHECK_RET(memcpyRet == 0)) { + LOG_PRINT("memcpy_s layoutQuery failed. ERROR: %d\n", memcpyRet); + return -1; + } + memcpyRet = memcpy_s(layoutKey, sizeof(layoutKey), layerOutStr, layerOutLen); + if (!CHECK_RET(memcpyRet == 0)) { + LOG_PRINT("memcpy_s layoutKey failed. ERROR: %d\n", memcpyRet); + return -1; + } + aclOpExecutor* executor; + + int ret = aclnnLightningIndexerGetWorkspaceSize(resources.queryTensor, resources.keyTensor, resources.weightsTensor, nullptr, nullptr, nullptr, + layoutQuery, layoutKey, sparseCount, sparseMode, preTokens, nextTokens,returnValue, + resources.sparseIndicesTensor, resources.sparseValuesTensor, workspaceSize, &executor); + + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclnnLightningIndexerGetWorkspaceSize 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 = aclnnLightningIndexer(*workspaceAddr, *workspaceSize, executor, stream); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclnnLightningIndexer failed. ERROR: %d\n", ret); + return ret; + } + + return ACL_SUCCESS; +} + +int PrintValueOutResult(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; +} + +int PrintIndicesOutResult(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: %d\n", i, 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.weightsTensor) { + aclDestroyTensor(resources.weightsTensor); + } + if (resources.sparseIndicesTensor) { + aclDestroyTensor(resources.sparseIndicesTensor); + } + if (resources.sparseValuesTensor) { + aclDestroyTensor(resources.sparseValuesTensor); + } + + if (resources.queryDeviceAddr) { + aclrtFree(resources.queryDeviceAddr); + } + if (resources.keyDeviceAddr) { + aclrtFree(resources.keyDeviceAddr); + } + if (resources.weightsDeviceAddr) { + aclrtFree(resources.weightsDeviceAddr); + } + if (resources.sparseIndicesDeviceAddr) { + aclrtFree(resources.sparseIndicesDeviceAddr); + } + if (resources.sparseValuesDeviceAddr) { + aclrtFree(resources.sparseValuesDeviceAddr); + } + + 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 sparseIndicesShape = {1, 2, 1, 2048}; + std::vector sparseValuesShape = {1, 2, 1, 2048}; + 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 = ExecuteLightningIndexer(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 + PrintIndicesOutResult(sparseIndicesShape, &resources.sparseIndicesDeviceAddr); + PrintValueOutResult(sparseValuesShape, &resources.sparseValuesDeviceAddr); + + // 6. Cleanup resources + CleanupResources(resources, workspaceAddr, stream, deviceId); + return 0; +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/lightning_indexer_collect.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/lightning_indexer_collect.py new file mode 100644 index 0000000000000000000000000000000000000000..d342721d44f6585313831ae3e6a9c6d603afd804 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/lightning_indexer_collect.py @@ -0,0 +1,314 @@ +#!/usr/bin/env python3 +"""Collect golden data for lightning_indexer 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/lightning_indexer_def.cpp, op_host/lightning_indexer_infershape.cpp, +op_host/lightning_indexer_tiling.cpp and op_host/op_api/aclnn_lightning_indexer.h. + + Indices = Top-k{ [1]@( (W @ [1]^T) * ReLU(Q @ K^T) ) }; W is the per-token (per-head) weight. + head dim D is FIXED to 128; key head num N2 is FIXED to 1; query head num N1 <= 64. + + query FP16/BF16 BSND:(B,S1,N1,128) or TND:(T,N1,128) + key FP16/BF16 BSND:(B,S2,1,128) or TND:(T2,1,128) or PA_BSND:(block_num,block_size,1,128) + weights FP16/BF16/FP32 BSND:(B,S1,N1) or TND:(T,N1) (must equal query/key dtype unless fp32) + actualSeqLengthsQuery INT32 (B,) — required for TND layout (prefix sums cumulating to T); + optional (None) for BSND layout + actualSeqLengthsKey INT32 (B,) — required for TND/PA_BSND key; optional for BSND key + blockTable INT32 (B, maxBlockNumPerSeq) — required for PA_BSND key + sparseIndicesOut INT32 BSND:(B,S1,N2,sparseCount) TND:(T,N2,sparseCount) + sparseValuesOut query-dtype — same shape as indices when return_values=True, else (0,) + +LAYOUT RULES (validated by aclnn): when layout_key is non-PA, layout_query == layout_key. +sparse_count is in [1,2048] (or the 3-8k sparsities); it must equal the indices output last dim. +sparse_mode in {0=defaultMask, 3=rightDownCausal}; pre_tokens/next_tokens keep the default 2^63-1. +return_values True only when layout_key != PA_BSND. When return_values=True and sparse_count exceeds +the usable (masked) window, the kernel fills the tail positions with a garbage/padding sentinel — +sparse_values may therefore legitimately contain NaN in padded slots (by design; the regression +comparator only checks the leading finite region robustly). Indices padding uses a finite sentinel. + +CASE MATRIX (D=128, N2=1 throughout; sm=sparse_mode; rv=return_values): + +# case_0: BSND/BSND fp16 N1=1 B1 S1=4 S2=64 sc=64 sm=0 rv=True full window, values, defaultMask +# case_1: BSND/BSND bf16 N1=8 B2 S1=16 S2=128 sc=2048 sm=3 rv=False GQA, causal, default sparseCount, indices-only +# case_2: BSND/BSND fp16 N1=32 B1 S1=8 S2=128 sc=128 sm=3 rv=False large GQA (g=32), causal, indices-only +# case_3: BSND/BSND fp16 N1=4 B2 S1=16 S2=64 sc=64 sm=0 rv=True weights fp32 (query/key fp16), full, values +# case_4: BSND/PA_BSND bf16 N1=8 B2 S1=32 key(16 blk x16) sc=128 sm=3 rv=False PageAttention, indices-only +# case_5: TND/TND fp16 N1=2 B1 T=64 sc=64 sm=0 rv=True TND single-batch full window, values +# case_6: TND/TND bf16 N1=4 B1 T=64 sc=128 sm=3 rv=False TND single-batch bf16, causal, indices-only +# case_7: TND/TND fp16 N1=8 B3 T=48 sc=16 sm=0 rv=False TND multi-batch weights fp32, indices-only +# (equal batches 16 each, sc=16 -> every window fully filled, NO padding: multi-batch TND +# pads sparse_indices with a run-to-run-nondeterministic sentinel, which a stable suite +# must not freeze; equal-batch + sc<=batch keeps it fully deterministic) +# case_8: TND/PA_BSND fp16 N1=2 B1 T=16 key(2 blk x16) sc=64 sm=3 rv=False TND+PageAttention, indices-only +# (single batch: sparse_indices padding is deterministic for B=1, unlike the multi-batch TND case_7) +# case_9: BSND/BSND fp16 N1=64 B1 S1=1 S2=16 sc=16 sm=0 rv=True max heads N1=64, single token, full, values +""" +import json +import os +import sys + +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "lightning_indexer" +OP_CAMEL = "LightningIndexer" +DEVICE = "npu:0" +SEED = 2027 + +PRE_TOKENS = 2 ** 63 - 1 # only the default is supported +NEXT_TOKENS = 2 ** 63 - 1 + +# Positional order of the generated wrapper (binding.py), excluding 'out'. +PARAM_NAMES = [ + "query", "key", "weights", + "actual_seq_lengths_query", "actual_seq_lengths_key", "block_table", + "layout_query", "layout_key", "sparse_count", "sparse_mode", + "pre_tokens", "next_tokens", "return_values", +] +OUTPUT_KEYS = ["sparse_indices", "sparse_values"] + +# Each case: id, ref-id for input generation, dtype (query/key), qlayout, klayout, +# B, S1 or T, N1, S2 (BSND key) or block-count/block-size (PA) or T2 (TND key), +# sparse_count, sparse_mode, return_values, weights_dtype (defaults to dtype). +CASES = [ + {"id": 0, "dtype": torch.float16, "q_layout": "BSND", "k_layout": "BSND", + "B": 1, "S1": 4, "N1": 1, "S2": 64, "sc": 64, "sm": 0, "rv": True}, + {"id": 1, "dtype": torch.bfloat16, "q_layout": "BSND", "k_layout": "BSND", + "B": 2, "S1": 16, "N1": 8, "S2": 128, "sc": 2048, "sm": 3, "rv": False}, + {"id": 2, "dtype": torch.float16, "q_layout": "BSND", "k_layout": "BSND", + "B": 1, "S1": 8, "N1": 32, "S2": 128, "sc": 128, "sm": 3, "rv": False}, + {"id": 3, "dtype": torch.float16, "q_layout": "BSND", "k_layout": "BSND", + "B": 2, "S1": 16, "N1": 4, "S2": 64, "sc": 64, "sm": 0, "rv": True, + "weights_dtype": torch.float32}, + {"id": 4, "dtype": torch.bfloat16, "q_layout": "BSND", "k_layout": "PA_BSND", + "B": 2, "S1": 32, "N1": 8, "blocks": 16, "blk": 16, "max_blocks": 8, + "sc": 128, "sm": 3, "rv": False}, + {"id": 5, "dtype": torch.float16, "q_layout": "TND", "k_layout": "TND", + "B": 1, "T": 64, "N1": 2, "sc": 64, "sm": 0, "rv": True}, + {"id": 6, "dtype": torch.bfloat16, "q_layout": "TND", "k_layout": "TND", + "B": 1, "T": 64, "N1": 4, "sc": 128, "sm": 3, "rv": False}, + {"id": 7, "dtype": torch.float16, "q_layout": "TND", "k_layout": "TND", + "B": 3, "T": 48, "N1": 8, "sc": 16, "sm": 0, "rv": False, + "weights_dtype": torch.float32, "seq": [16, 32, 48]}, + {"id": 8, "dtype": torch.float16, "q_layout": "TND", "k_layout": "PA_BSND", + "B": 1, "T": 16, "N1": 2, "blocks": 2, "blk": 16, "max_blocks": 2, + "seq": [16], "seq_key": [32], "block_table_override": [[0, 1]], + "sc": 64, "sm": 3, "rv": False}, + {"id": 9, "dtype": torch.float16, "q_layout": "BSND", "k_layout": "BSND", + "B": 1, "S1": 1, "N1": 64, "S2": 16, "sc": 16, "sm": 0, "rv": True}, +] + +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 _rand(shape, dtype): + if dtype in (torch.float16, torch.bfloat16): + return torch.randn(shape, dtype=torch.float32, device=DEVICE).to(dtype) + return torch.randn(shape, dtype=dtype, device=DEVICE) + + +def cumulative_lens(B, T): + """B positive ints, strictly increasing, last == T.""" + if B == 1: + return torch.tensor([T], dtype=torch.int32) + cuts = sorted(torch.randint(1, T, (B - 1,)).tolist()) + while len(set(cuts)) != B - 1: + cuts = sorted(torch.randint(1, T, (B - 1,)).tolist()) + parts = [cuts[0]] + [b - a for a, b in zip(cuts, cuts[1:])] + [T - cuts[-1]] + return torch.tensor(list(parts), dtype=torch.int32) + + +def make_inputs(case): + torch.manual_seed(SEED + case["id"]) + dtype = case["dtype"] + wdtype = case.get("weights_dtype", dtype) + ql, kl = case["q_layout"], case["k_layout"] + + inputs = {} + + if ql == "BSND": + B, S1, N1 = case["B"], case["S1"], case["N1"] + query = _rand((B, S1, N1, 128), dtype) + weights = _rand((B, S1, N1), wdtype) + inputs["actual_seq_lengths_query"] = None + else: # TND + B, T, N1 = case["B"], case["T"], case["N1"] + query = _rand((T, N1, 128), dtype) + weights = _rand((T, N1), wdtype) + inputs["actual_seq_lengths_query"] = ( + torch.tensor(case["seq"], dtype=torch.int32) if case.get("seq") + else cumulative_lens(B, T)).to(DEVICE) + + inputs["query"] = query + inputs["weights"] = weights + + if kl == "BSND": + key = _rand((case["B"], case["S2"], 1, 128), dtype) + inputs["key"] = key + inputs["actual_seq_lengths_key"] = None + inputs["block_table"] = None + elif kl == "TND": + key = _rand((case["T"], 1, 128), dtype) + inputs["key"] = key + inputs["actual_seq_lengths_key"] = ( + torch.tensor(case["seq"], dtype=torch.int32) if case.get("seq") + else cumulative_lens(case["B"], case["T"])).to(DEVICE) + inputs["block_table"] = None + else: # PA_BSND + blk = case["blk"] + key = _rand((case["blocks"], blk, 1, 128), dtype) + inputs["key"] = key + # per-batch token counts (PA is NOT cumulative). Each batch uses nblk_i full blocks, so + # count_i = nblk_i * blk <= max_blocks*blk (the block_table columns it owns). A fixed + # seq_key override forces every batch to the same full-window count (no padding). + max_blocks = case["max_blocks"] + if case.get("seq_key"): + counts = list(case["seq_key"]) + else: + nblk = torch.randint(1, max_blocks + 1, (case["B"],)).tolist() + counts = [n * blk for n in nblk] + inputs["actual_seq_lengths_key"] = torch.tensor(counts, dtype=torch.int32, device=DEVICE) + if case.get("block_table_override"): + bt = torch.tensor(case["block_table_override"], dtype=torch.int32, device=DEVICE) + else: + bt = torch.randint(0, case["blocks"], (case["B"], max_blocks), dtype=torch.int32, device=DEVICE) + inputs["block_table"] = bt + + inputs["layout_query"] = ql + inputs["layout_key"] = kl + inputs["sparse_count"] = int(case["sc"]) + inputs["sparse_mode"] = int(case["sm"]) + inputs["pre_tokens"] = PRE_TOKENS + inputs["next_tokens"] = NEXT_TOKENS + inputs["return_values"] = bool(case["rv"]) + return inputs + + +def out_shape(case, sparse_count): + ql = case["q_layout"] + if ql == "BSND": + return (case["B"], case["S1"], 1, sparse_count) + return (case["T"], 1, sparse_count) + + +def make_output_bufs(case, inputs): + oshape = out_shape(case, inputs["sparse_count"]) + return [ + torch.empty(oshape, dtype=torch.int32, device=DEVICE), + torch.empty(oshape if inputs["return_values"] else (0,), + dtype=case["dtype"], device=DEVICE), + ] + + +def build_call_args(case): + inputs = make_inputs(case) + return [inputs[p] for p in PARAM_NAMES], inputs + + +def collect_case(case): + call_args, inputs = build_call_args(case) + out_bufs = make_output_bufs(case, inputs) + out_arg = out_bufs[0] if len(out_bufs) == 1 else out_bufs + + outputs = ops.npu_lightning_indexer(*call_args, out_arg) + 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)} + # sparse_indices must always be finite. sparse_values carries padding sentinels (NaN) whenever + # sparse_count > the masked window — which happens in the causal (sm=3) cases and in ANY + # multi-batch run (each batch's masked window < sc). It is only finiteness-checked for the + # single-batch / uniform BSND full-window sm=0 cases (rv=True) where every slot is real data. + if not torch.isfinite(saved_out["sparse_indices"].float()).all(): + raise RuntimeError(f"case_{case['id']}: sparse_indices has NaN/Inf — bad golden data") + full_window = case["rv"] and ( + case["q_layout"] == "BSND" or case["B"] == 1 + ) + if full_window and case["sm"] == 0 and \ + not torch.isfinite(saved_out["sparse_values"].float()).all(): + raise RuntimeError(f"case_{case['id']}: sparse_values non-finite in a full-window case — " + f"check inputs") + + 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 = [] + 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 check_signature(): + import inspect + try: + params = list(inspect.signature(ops.npu_lightning_indexer).parameters) + except (TypeError, ValueError): + print("[WARN] cannot introspect the wrapper signature — skipping the arity check") + return + 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) + + +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_lightning_indexer.__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) + 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.", ""), + "q_layout": case["q_layout"], "k_layout": case["k_layout"], + "shape": [case["B"], case.get("S1", case.get("T")), case["N1"]], + "attrs": {k: (int(v) if isinstance(v, (int,)) and not isinstance(v, bool) else + bool(v) if isinstance(v, bool) else str(v).replace("torch.", "")) + for k, v in case.items() if k not in ("id", "dtype", "q_layout", "k_layout")}, + }) + 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/lightning_indexer/lightning_indexer_test.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/lightning_indexer_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7f0d362d6c06786be6c55d33ede3e5222969782c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/lightning_indexer_test.py @@ -0,0 +1,217 @@ +#!/usr/bin/env python3 +"""Regression test: NPU operator vs golden data collected from the same operator. + +This is the canonical test script for the sandbox workflow. 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. + +Padding note: this operator fills the tail slots of sparse_values with a padding sentinel (NaN) +whenever sparse_count exceeds the masked window — the causal (sm=3) cases and multi-batch runs +(each batch's window < sc). The comparator leaves NaN-vs-NaN padding alone (rel = NaN is never +> atol, so it counts as matching) and still fully checks the leading finite region; max_diff +uses nanmax so a NaN pad row does not poison the printed figure. All return_values=True cases in +this suite are single-batch/uniform full-window, so their values are fully finite anyway. +""" +import json +import os +import sys + +import numpy as np +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "lightning_indexer" +OP_CAMEL = "LightningIndexer" +DEVICE = "npu:0" + +# Positional order of the generated wrapper (binding.py), excluding 'out'. +PARAM_NAMES = [ + "query", "key", "weights", + "actual_seq_lengths_query", "actual_seq_lengths_key", "block_table", + "layout_query", "layout_key", "sparse_count", "sparse_mode", + "pre_tokens", "next_tokens", "return_values", +] +# Order in which the operator returns its outputs. +OUTPUT_KEYS = ["sparse_indices", "sparse_values"] + +# No float32-stored intermediate outputs here: every output is in the same dtype as its source. +INTERMEDIATE_OUTPUT_KEYS = set() + +# Default tolerance. +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. {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) + + # Padding NaN slots: rel is NaN there, and NaN > atol is False, so they count as matching. + max_diff = float(np.nanmax(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 kwargs dict — 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. + out_bufs = [] + for k in OUTPUT_KEYS: + if k in golden: + out_bufs.append(torch.empty_like(golden[k]).to(DEVICE)) + + if len(out_bufs) == 1: + out_arg = out_bufs[0] + else: + out_arg = out_bufs + positional = [call_kwargs[p] for p in PARAM_NAMES] + [out_arg] + outputs = ops.npu_lightning_indexer(*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':<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/lightning_indexer/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9d5dcb5d6f361053c98f13133cfb37d64e6f2a82 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/CMakeLists.txt @@ -0,0 +1,29 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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() + +if (BUILD_OPEN_PROJECT) + target_sources(op_host_aclnnInner PRIVATE + lightning_indexer_def.cpp + ) +endif() + +add_ops_compile_options( + OP_NAME LightningIndexer + 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 lightning_indexer ACLNNTYPE aclnn_inner) +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_def.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_def.cpp new file mode 100644 index 0000000000000000000000000000000000000000..646d9d30b695b54d14756467975dc9587a7ccc48 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_def.cpp @@ -0,0 +1,81 @@ +/** + * 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 lightning_indexer_def.cpp + * \brief + */ +#include +#include "register/op_def_registry.h" + +namespace ops { +class LightningIndexer : public OpDef { +public: + explicit LightningIndexer(const char *name) : OpDef(name) + { + this->Input("query") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("key") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("weights") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("actual_seq_lengths_query") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("actual_seq_lengths_key") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("block_table") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Output("sparse_indices") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_INT32}) + .FormatList({ge::FORMAT_ND}); + this->Output("sparse_values") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16}) + .FormatList({ge::FORMAT_ND}); + this->Attr("layout_query").AttrType(OPTIONAL).String("BSND"); + this->Attr("layout_key").AttrType(OPTIONAL).String("BSND"); + this->Attr("sparse_count").AttrType(OPTIONAL).Int(2048); // 2048:默认值,筛选前2048 + 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("return_values").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(LightningIndexer); +} // namespace ops \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19255cba4b7794b8b547b9b59f9bf52c45ee2b75 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_infershape.cpp @@ -0,0 +1,117 @@ +/** + * 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 lightning_indexer_infershape.cpp + * \brief + */ +#include +#include +#include "err/ops_err.h" + + +using namespace ge; + +namespace ops { +constexpr uint32_t QUERY_INDEX = 0; +constexpr uint32_t KEY_INDEX = 1; +constexpr uint32_t ACTUAL_SEQ_K_INDEX = 4; +constexpr uint32_t ATTR_QUERY_LAYOUT_INDEX = 0; +constexpr uint32_t ATTR_KEY_LAYOUT_INDEX = 1; +constexpr uint32_t ATTR_SPARSE_COUNT_INDEX = 2; +constexpr uint32_t ATTR_RETURN_VALUE_INDEX = 6; + +static ge::graphStatus InferShapeLightningIndexer(gert::InferShapeContext *context) +{ + OP_CHECK_IF(context == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("LightningIndexer", "InferShapeContext", + "InferShapeContext is nullptr"), + return ge::GRAPH_FAILED); + const gert::Shape *queryShape = context->GetInputShape(QUERY_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, queryShape); + const gert::Shape *keyShape = context->GetInputShape(KEY_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, keyShape); + + gert::Shape *sparseIndicesShape = context->GetOutputShape(0); + OP_CHECK_NULL_WITH_CONTEXT(context, sparseIndicesShape); + gert::Shape *sparseValuesShape = context->GetOutputShape(1); + OP_CHECK_NULL_WITH_CONTEXT(context, sparseValuesShape); + + auto attrs = context->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context, attrs); + const char *inputLayoutQueryPtr = attrs->GetAttrPointer(ATTR_QUERY_LAYOUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, inputLayoutQueryPtr); + const char *inputLayoutKeyPtr = attrs->GetAttrPointer(ATTR_KEY_LAYOUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, inputLayoutKeyPtr); + const int64_t *seleced_count = attrs->GetInt(ATTR_SPARSE_COUNT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, seleced_count); + std::string inputLayoutQueryPtrStr = std::string(inputLayoutQueryPtr); + std::string inputLayoutKeyPtrStr = std::string(inputLayoutKeyPtr); + OP_CHECK_IF( + inputLayoutQueryPtrStr != "TND" && inputLayoutQueryPtrStr != "BSND", + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON("LightningIndexer", "layout_query", + inputLayoutQueryPtrStr.c_str(), "The attr layout_query should be TND or BSND"), + return ge::GRAPH_FAILED); + + sparseIndicesShape->SetDimNum(queryShape->GetDimNum()); + if (inputLayoutQueryPtrStr == "BSND") { + OP_CHECK_IF( + queryShape->GetDimNum() != 4, + OP_LOGE(context, "Layout BSND, queryDims (%zu) must be 4!", queryShape->GetDimNum()), + return ge::GRAPH_FAILED); + sparseIndicesShape->SetDim(0, queryShape->GetDim(0)); // 0:Dim B + sparseIndicesShape->SetDim(1, queryShape->GetDim(1)); // 1:Dim S + sparseIndicesShape->SetDim(2, keyShape->GetDim(2)); // 2:Dim N + sparseIndicesShape->SetDim(3, *seleced_count); // 3:Dim K + } else { + OP_CHECK_IF( + queryShape->GetDimNum() != 3, + OP_LOGE(context, "Layout TND, queryDims (%zu) must be 3!", queryShape->GetDimNum()), + return ge::GRAPH_FAILED); + sparseIndicesShape->SetDim(0, queryShape->GetDim(0)); // 0:Dim T + int32_t nDimIndex = (inputLayoutKeyPtrStr == "PA_BSND") ? 2 : 1; // 2:Key Dim N + sparseIndicesShape->SetDim(1, keyShape->GetDim(nDimIndex)); // 1:Dim N + sparseIndicesShape->SetDim(2, *seleced_count); // 2:Dim K + } + + const bool *return_value = attrs->GetAttrPointer(ATTR_RETURN_VALUE_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, return_value); + bool returnValueFlag = (return_value != nullptr) ? *return_value : false; + if (returnValueFlag) { + *sparseValuesShape = *sparseIndicesShape; + } else { + sparseValuesShape->SetDimNum(1); + sparseValuesShape->SetDim(0, 0); + } + OP_LOGI(context->GetNodeName(), "LightningIndexer InferShape end."); + + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus InferDataTypeLightningIndexer(gert::InferDataTypeContext *context) +{ + OP_CHECK_IF(context == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("LightningIndexer", "InferDataTypeContext", + "InferDataTypeContext is nullptr"), + return ge::GRAPH_FAILED); + OP_LOGI(context->GetNodeName(), "Enter LightningIndexer InferDataType impl."); + // default set q's dtype as fia's output type + ge::DataType outputType = ge::DT_INT32; + // attention_out, outidx:0 + context->SetOutputDataType(0, outputType); + context->SetOutputDataType(1, context->GetInputDataType(QUERY_INDEX)); + OP_LOGI(context->GetNodeName(), "LightningIndexer InferDataType end."); + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(LightningIndexer) + .InferShape(InferShapeLightningIndexer) + .InferDataType(InferDataTypeLightningIndexer); +} // namespace ops diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7dbd3f6e141a202c604c4f3a479bb2a1048a736c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_tiling.cpp @@ -0,0 +1,1153 @@ +/** + * 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 lightning_indexer_tiling.cpp + * \brief + */ + +#include "lightning_indexer_tiling.h" +#include "../op_kernel/lightning_indexer_template_tiling_key.h" + +using namespace ge; +using namespace AscendC; +using std::map; +using std::string; +namespace optiling { + +const std::map DATATYPE_TO_STRING_MAP = { + {ge::DT_UNDEFINED, "DT_UNDEFINED"}, // Used to indicate a DataType field has not been set. + {ge::DT_FLOAT, "DT_FLOAT"}, // float type + {ge::DT_FLOAT16, "DT_FLOAT16"}, // fp16 type + {ge::DT_FLOAT8_E4M3FN, "DT_FLOAT8_E4M3FN"}, // fp8_e4m3 type + {ge::DT_HIFLOAT8, "DT_HIFLOAT8"}, // hifloat8 type + {ge::DT_INT8, "DT_INT8"}, // int8 type + {ge::DT_INT16, "DT_INT16"}, // int16 type + {ge::DT_UINT16, "DT_UINT16"}, // uint16 type + {ge::DT_UINT8, "DT_UINT8"}, // uint8 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_BOOL, "DT_BOOL"}, // bool type + {ge::DT_DOUBLE, "DT_DOUBLE"}, // double 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_QINT8, "DT_QINT8"}, // qint8 type + {ge::DT_QINT16, "DT_QINT16"}, // qint16 type + {ge::DT_QINT32, "DT_QINT32"}, // qint32 type + {ge::DT_QUINT8, "DT_QUINT8"}, // quint8 type + {ge::DT_QUINT16, "DT_QUINT16"}, // quint16 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_INT4, "DT_INT4"}, // dt_variant 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 +}; + +static std::string LIDataTypeToSerialString(ge::DataType type) +{ + const auto liIt = DATATYPE_TO_STRING_MAP.find(type); + if (liIt != DATATYPE_TO_STRING_MAP.end()) { + return liIt->second; + } else { + OP_LOGE("LightningIndexer", "datatype %d not support", type); + return "UNDEFINED"; + } +} + +ge::graphStatus LIInfoParser::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_, "key", + "Shape of tensor key is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.weights.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "weights", + "Shape of tensor weights 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 attenOut is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.valuesOut.shape == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "valuesOut", + "Shape of tensor valuesOut is nullptr"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::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_.weights.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "weights", + "Desc of tensor weights 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 attenOut is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.valuesOut.desc == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "valuesOut", + "Desc of tensor valuesOut is nullptr"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +// --------------------------LIInfoParser类成员函数定义------------------------------------- +ge::graphStatus LIInfoParser::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 LIInfoParser::CheckRequiredAttrExistence() const +{ + OP_CHECK_IF(opParamInfo_.layOut == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "layout_query", + "attr layout_query is nullptr"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(opParamInfo_.layOutKey == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "layout_key", + "attr layout_key is nullptr"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(opParamInfo_.sparseCount == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "sparse_count", + "attr sparse_count is nullptr"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(opParamInfo_.sparseMode == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "sparse_mode", + "attr sparse_mode is nullptr"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::CheckRequiredParaExistence() const +{ + if (CheckRequiredInOutExistence() != ge::GRAPH_SUCCESS || CheckRequiredAttrExistence() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetOpName() +{ + if (context_->GetNodeName() == nullptr) { + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON("LightningIndexer", "opName", + "opName got from TilingContext is nullptr"); + return ge::GRAPH_FAILED; + } + opName_ = context_->GetNodeName(); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetNpuInfo() +{ + platformInfo_ = context_->GetPlatformInfo(); + OP_CHECK_IF(platformInfo_ == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "GetPlatformInfo", + "GetPlatformInfo is nullptr"), + return ge::GRAPH_FAILED); + + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo_); + uint32_t aivNum = ascendcPlatform.GetCoreNumAiv(); + uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); + OP_CHECK_IF(aicNum == 0 || aivNum == 0, OP_LOGE(opName_, "num of core obtained is 0."), return GRAPH_FAILED); + + socVersion_ = ascendcPlatform.GetSocVersion(); + npuArch_ = ascendcPlatform.GetCurNpuArch(); + if ((npuArch_ != NpuArch::DAV_2201) && + (npuArch_ != NpuArch::DAV_3510)) { + OP_LOGE(opName_, "NpuArch[%d] is not support.", static_cast(npuArch_)); + return GRAPH_FAILED; + } + OP_CHECK_IF(context_->GetWorkspaceSizes(1) == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "workSpaceSize", + "workSpaceSize got from ge is nullptr"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(context_->GetRawTilingData() == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "RawTilingData", + "RawTilingData got from GE context is nullptr"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +void LIInfoParser::GetOptionalInputParaInfo() +{ + opParamInfo_.actualSeqLengthsQ.tensor = context_->GetOptionalInputTensor(ACTUAL_SEQ_Q_INDEX); + opParamInfo_.actualSeqLengthsQ.desc = context_->GetOptionalInputDesc(ACTUAL_SEQ_Q_INDEX); + opParamInfo_.actualSeqLengths.tensor = context_->GetOptionalInputTensor(ACTUAL_SEQ_K_INDEX); + opParamInfo_.actualSeqLengths.desc = context_->GetOptionalInputDesc(ACTUAL_SEQ_K_INDEX); + opParamInfo_.blockTable.tensor = context_->GetOptionalInputTensor(BLOCK_TABLE_INDEX); + opParamInfo_.blockTable.desc = context_->GetOptionalInputDesc(BLOCK_TABLE_INDEX); +} + +void LIInfoParser::GetInputParaInfo() +{ + opParamInfo_.query.desc = context_->GetInputDesc(QUERY_INDEX); + opParamInfo_.query.shape = context_->GetInputShape(QUERY_INDEX); + opParamInfo_.key.desc = context_->GetInputDesc(KEY_INDEX); + opParamInfo_.key.shape = context_->GetInputShape(KEY_INDEX); + opParamInfo_.weights.desc = context_->GetInputDesc(WEIGTHS_INDEX); + opParamInfo_.weights.shape = context_->GetInputShape(WEIGTHS_INDEX); + GetOptionalInputParaInfo(); +} + +void LIInfoParser::GetOutputParaInfo() +{ + opParamInfo_.attenOut.desc = context_->GetOutputDesc(LIGHTNING_INDEXER); + opParamInfo_.attenOut.shape = context_->GetOutputShape(LIGHTNING_INDEXER); + opParamInfo_.valuesOut.desc = context_->GetOutputDesc(LIGHTNING_VALUES); + opParamInfo_.valuesOut.shape = context_->GetOutputShape(LIGHTNING_VALUES); +} + +ge::graphStatus LIInfoParser::GetAndCheckAttrParaInfo() +{ + 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); + OP_LOGI(context_->GetNodeName(), "GetAndCheckAttrParaInfo start"); + opParamInfo_.layOut = attrs->GetStr(ATTR_QUERY_LAYOUT_INDEX); + opParamInfo_.layOutKey = attrs->GetStr(ATTR_KEY_LAYOUT_INDEX); + opParamInfo_.sparseCount = attrs->GetAttrPointer(ATTR_SPARSE_COUNT_INDEX); + opParamInfo_.sparseMode = attrs->GetAttrPointer(ATTR_SPARSE_MODE_INDEX); + opParamInfo_.preTokens = attrs->GetAttrPointer(ATTR_PRE_TOKENS_INDEX); + opParamInfo_.nextTokens = attrs->GetAttrPointer(ATTR_NEXT_TOKENS_INDEX); + opParamInfo_.returnValue = attrs->GetAttrPointer(ATTR_RETURN_VALUE_INDEX); + if (opParamInfo_.layOut != nullptr) { + OP_LOGI(context_->GetNodeName(), "layout_query is:%s", opParamInfo_.layOut); + } + if (opParamInfo_.layOutKey != nullptr) { + OP_LOGI(context_->GetNodeName(), "layout_key is:%s", opParamInfo_.layOutKey); + } + if (opParamInfo_.sparseCount != nullptr) { + OP_LOGI(context_->GetNodeName(), "selscted count is:%d", *opParamInfo_.sparseCount); + } + if (opParamInfo_.sparseMode != nullptr) { + OP_LOGI(context_->GetNodeName(), "sparse mode is:%d", *opParamInfo_.sparseMode); + } + if (opParamInfo_.preTokens != nullptr) { + OP_LOGI(context_->GetNodeName(), "pre tokens is:%d", *opParamInfo_.preTokens); + } + if (opParamInfo_.nextTokens != nullptr) { + OP_LOGI(context_->GetNodeName(), "next tokens is:%d", *opParamInfo_.nextTokens); + } + if (opParamInfo_.returnValue != nullptr) { + OP_LOGI(context_->GetNodeName(), "return value is:%d", *opParamInfo_.returnValue); + } + OP_LOGI(context_->GetNodeName(), "GetAndCheckAttrParaInfo end"); + OP_CHECK_IF( + ((std::string(opParamInfo_.layOutKey) != "PA_BSND") + && (std::string(opParamInfo_.layOut) != std::string(opParamInfo_.layOutKey))), + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON(opName_, "layout_query and layout_key", + std::string(opParamInfo_.layOut) + " and " + std::string(opParamInfo_.layOutKey), + "When layOutKey is non-PA, layout_query and layout_key must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + ((std::string(opParamInfo_.layOutKey) != "PA_BSND") && (std::string(opParamInfo_.layOutKey) != "BSND") + && (std::string(opParamInfo_.layOutKey) != "TND")), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "layout_key", std::string(opParamInfo_.layOutKey).c_str(), + "input attr layout_key only supported PA_BSND, BSND or TND"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(((std::string(opParamInfo_.layOut) != "BSND") && (std::string(opParamInfo_.layOut) != "TND")), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "layout_query", std::string(opParamInfo_.layOut).c_str(), + "input attr layout_query only supported BSND or TND"), + return ge::GRAPH_FAILED); + OP_CHECK_IF((!((*opParamInfo_.sparseCount > 0) && (*opParamInfo_.sparseCount <= SPARSE_LIMIT)) && + *opParamInfo_.sparseCount % 1024 != 0), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "sparse_count", + std::to_string(*opParamInfo_.sparseCount).c_str(), + "input attr sparse_count must > 0 and <= 8192." + " And when sparse_count > 2048, sparse_count must be an interger multiple of 1024"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(!((*opParamInfo_.sparseMode == 0) || (*opParamInfo_.sparseMode == SPARSE_MODE_LOWER)), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "sparse_mode", + std::to_string(*opParamInfo_.sparseMode), "sparse_count must be 0 or 3"), return ge::GRAPH_FAILED); + OP_CHECK_IF(*opParamInfo_.preTokens != INT64_MAX, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "pre_tokens", + std::to_string(*opParamInfo_.preTokens), "preTokens must be INT64_MAX"), return ge::GRAPH_FAILED); + OP_CHECK_IF(*opParamInfo_.nextTokens != INT64_MAX, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "next_tokens", + std::to_string(*opParamInfo_.nextTokens), "nextTokens must be INT64_MAX"), return ge::GRAPH_FAILED); + OP_CHECK_IF(*opParamInfo_.returnValue && std::string(opParamInfo_.layOutKey) == "PA_BSND", + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(opName_, "layout_key", std::string(opParamInfo_.layOutKey), + "when return_value is true, key layout do not support PA_BSND"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetOpParaInfo() +{ + GetInputParaInfo(); + GetOutputParaInfo(); + if (ge::GRAPH_SUCCESS != GetAndCheckAttrParaInfo()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetAndCheckInOutDataType() +{ + inputQType_ = opParamInfo_.query.desc->GetDataType(); + inputKType_ = opParamInfo_.key.desc->GetDataType(); + weightsType_ = opParamInfo_.weights.desc->GetDataType(); + outputType_ = opParamInfo_.attenOut.desc->GetDataType(); + valuesOutType_ = opParamInfo_.valuesOut.desc->GetDataType(); + + bool inDTypeAllEqual = (inputQType_ == inputKType_); + OP_CHECK_IF(!inDTypeAllEqual, + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(opName_, "query and key", + LIDataTypeToSerialString(inputQType_) + " and " + LIDataTypeToSerialString(inputKType_), + "The dtype of query and key must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(((inputQType_ != ge::DT_FLOAT16) && (inputQType_ != ge::DT_BF16)), + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(opName_, "query and key", + LIDataTypeToSerialString(inputQType_) + " and " + LIDataTypeToSerialString(inputKType_), + "The dtype of query and key must be float16 or bfloat16"), + return ge::GRAPH_FAILED); + if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF((inputQType_ != weightsType_), + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(opName_, "query, key, and weights", + LIDataTypeToSerialString(inputQType_) + ", " + LIDataTypeToSerialString(inputKType_) + + "and " + LIDataTypeToSerialString(inputKType_), + "The dtype of query, key, and weights must be same"), + return ge::GRAPH_FAILED); + } else { + if (weightsType_ != ge::DT_FLOAT) { + OP_CHECK_IF((inputQType_ != weightsType_), + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(opName_, "query, key, and weights", + LIDataTypeToSerialString(inputQType_) + ", " + LIDataTypeToSerialString(inputKType_) + + "and " + LIDataTypeToSerialString(inputKType_), + "The dtype of query, key, and weights must be same"), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF((weightsType_ != ge::DT_FLOAT), + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opName_, "weights", + LIDataTypeToSerialString(weightsType_).c_str(), + "The dtype of weights must be float32"), + return ge::GRAPH_FAILED); + } + } + OP_CHECK_IF(outputType_ != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opName_, "sparse_indices", + LIDataTypeToSerialString(outputType_).c_str(), + "The dtype of sparse_indices must be int32"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(valuesOutType_ != inputQType_, + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON(opName_, "query and sparse_values", + LIDataTypeToSerialString(inputQType_) + " and " + LIDataTypeToSerialString(valuesOutType_), + "The dtype of query and sparse_values must be same"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetQueryKeyAndOutLayout() +{ + // 获取query,key的Layout基准值 + const map layoutMap = { + {"BSND", DataLayout::BSND}, + {"TND", DataLayout::TND}, + {"PA_BSND", DataLayout::BnBsND} + }; + + std::string layout(opParamInfo_.layOut); + auto it = layoutMap.find(layout); + if (it != layoutMap.end()) { + qLayout_ = it->second; + } + + std::string layoutKey(opParamInfo_.layOutKey); + auto itKey = layoutMap.find(layoutKey); + if (itKey != layoutMap.end()) { + kLayout_ = itKey->second; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetAndCheckOptionalInput() +{ + if (kLayout_ == DataLayout::BnBsND) { + OP_CHECK_IF(opParamInfo_.blockTable.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "block_table", + "when layout_key is PA_BSND, input block_table must not be null"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + opParamInfo_.actualSeqLengths.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "actual_seq_lengths_key", + "when layout_key is PA_BSND, input actual_seq_lengths_key must not be null"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(opParamInfo_.blockTable.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opName_, "block_table", + LIDataTypeToSerialString(opParamInfo_.blockTable.desc->GetDataType()).c_str(), + "The dtype of block_table must be int32"), return ge::GRAPH_FAILED); + } else if (kLayout_ == DataLayout::TND) { + OP_CHECK_IF(opParamInfo_.actualSeqLengths.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "actual_seq_lengths_key", + "when layout_key is TND, input actual_seq_lengths_key must not be null"), + return ge::GRAPH_FAILED); + } + OP_CHECK_IF(opParamInfo_.actualSeqLengths.tensor != nullptr && + opParamInfo_.actualSeqLengths.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opName_, "actual_seq_lengths_key", + LIDataTypeToSerialString(opParamInfo_.actualSeqLengths.desc->GetDataType()).c_str(), + "The dtype of actual_seq_lengths_key must be int32"), + return ge::GRAPH_FAILED); + if (qLayout_ == DataLayout::TND) { + OP_CHECK_IF(opParamInfo_.actualSeqLengthsQ.tensor == nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "actual_seq_lengths_query", + "when layout_query is TND, input actual_seq_lengths_query must not be null"), + return ge::GRAPH_FAILED); + } + OP_CHECK_IF(opParamInfo_.actualSeqLengthsQ.tensor != nullptr && + opParamInfo_.actualSeqLengthsQ.desc->GetDataType() != ge::DT_INT32, + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON(opName_, "actual_seq_lengths_query", + LIDataTypeToSerialString(opParamInfo_.actualSeqLengthsQ.desc->GetDataType()).c_str(), + "The dtype of actual_seq_lengths_query must be int32"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(kLayout_ != DataLayout::BnBsND && opParamInfo_.blockTable.tensor != nullptr, + OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(opName_, "block_table", + "when key layout is not PA_BSND, input block_table must be null"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::CheckShapeDim() +{ + OP_CHECK_IF((opParamInfo_.blockTable.tensor != nullptr) && + (opParamInfo_.blockTable.tensor->GetStorageShape().GetDimNum() != DIM_NUM_TWO), + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "block_table", + std::to_string(opParamInfo_.blockTable.tensor->GetStorageShape().GetDimNum()).c_str(), + "The shape dim of block_table must be 2"), + return ge::GRAPH_FAILED); + + uint32_t kShapeDim = opParamInfo_.key.shape->GetStorageShape().GetDimNum(); + uint32_t qShapeDim = opParamInfo_.query.shape->GetStorageShape().GetDimNum(); + uint32_t weightsShapeDim = opParamInfo_.weights.shape->GetStorageShape().GetDimNum(); + uint32_t outShapeDim = opParamInfo_.attenOut.shape->GetStorageShape().GetDimNum(); + uint32_t valuesOutShapeDim = opParamInfo_.valuesOut.shape->GetStorageShape().GetDimNum(); + uint32_t qExpectShapeDim = DIM_NUM_FOUR; + uint32_t kExpectShapeDim = DIM_NUM_FOUR; + if (qLayout_ == DataLayout::TND) { + qExpectShapeDim = DIM_NUM_THREE; + } + if (kLayout_ == DataLayout::TND) { + kExpectShapeDim = DIM_NUM_THREE; + } + OP_CHECK_IF(kShapeDim != kExpectShapeDim, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "key", + std::to_string(kShapeDim).c_str(), + "The shape dim of key must be " + std::to_string(kExpectShapeDim)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(qShapeDim != qExpectShapeDim, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "query", + std::to_string(qShapeDim).c_str(), + "The shape dim of query must be " + std::to_string(qExpectShapeDim)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(outShapeDim != qExpectShapeDim, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "sparse_indices", + std::to_string(outShapeDim).c_str(), + "The shape dim of sparse_indices must be " + std::to_string(qExpectShapeDim)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(valuesOutShapeDim != qExpectShapeDim && (*opParamInfo_.returnValue), + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "sparse_values", + std::to_string(valuesOutShapeDim).c_str(), + "The shape dim of sparse_values must be " + std::to_string(qExpectShapeDim)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(!(weightsShapeDim == qExpectShapeDim - 1), + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON(opName_, "weights", + std::to_string(weightsShapeDim).c_str(), + "The shape dim of weights must be " + std::to_string(qExpectShapeDim - 1)), + return ge::GRAPH_FAILED); + if (opParamInfo_.valuesOut.shape->GetStorageShape().GetShapeSize() != 0 && !(*opParamInfo_.returnValue)) { + OP_LOGW(opName_, "when returnValue is false, valuesOut must be null."); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetN1Size() +{ + if (qLayout_ == DataLayout::BSND) { + n1Size_ = static_cast(opParamInfo_.query.shape->GetStorageShape().GetDim(DIM_IDX_TWO)); + } else { + // TND + n1Size_ = static_cast(opParamInfo_.query.shape->GetStorageShape().GetDim(1)); + } + OP_LOGI(context_->GetNodeName(), "n1Size is %d", n1Size_); + if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF(n1Size_ != QUERY_HEAD_NUM_LIMIT_950_64 && n1Size_ != QUERY_HEAD_NUM_LIMIT_950_32 && + n1Size_ != QUERY_HEAD_NUM_LIMIT_950_24 && n1Size_ != QUERY_HEAD_NUM_LIMIT_950_16 && + n1Size_ != QUERY_HEAD_NUM_LIMIT_950_8, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "query", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()).c_str(), + "N1 must equal 64 or 32 or 24 or 16 or 8"), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(n1Size_ > QUERY_HEAD_NUM_LIMIT, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "query", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()).c_str(), + "query's N1 must be no greater than " + std::to_string(QUERY_HEAD_NUM_LIMIT)), + return ge::GRAPH_FAILED); + } + + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus LiGetActualSeqLenSize(uint32_t &liSize, const gert::Tensor *liTensor, + const std::string &liActualSeqLenName, const char *liOpName) +{ + liSize = static_cast(liTensor->GetShapeSize()); + if (liSize == 0) { + OP_LOGE_FOR_INVALID_SHAPESIZE_WITH_REASON(liOpName, liActualSeqLenName.c_str(), + std::to_string(liSize).c_str(), + "The shape size of " + liActualSeqLenName + "should be greater than 0"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetActualSeqLenSize(uint32_t &liSize, const gert::Tensor *liTensor, + const std::string &liSeqLenName) const +{ + return LiGetActualSeqLenSize(liSize, liTensor, liSeqLenName, opName_); +} + +ge::graphStatus LIInfoParser::GetAndCheckN2Size() +{ + uint32_t n2Index = (kLayout_ == DataLayout::TND) ? DIM_IDX_ONE : DIM_IDX_TWO; + n2Size_ = static_cast(opParamInfo_.key.shape->GetStorageShape().GetDim(n2Index)); + OP_LOGI(context_->GetNodeName(), "n2Size_ is %d", n2Size_); + OP_CHECK_IF(n2Size_ != 1, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "key", + Ops::Base::ToString(opParamInfo_.key.shape->GetStorageShape()).c_str(), + "key's head num must be 1"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetGSize() +{ + if (n1Size_ % n2Size_ != 0) { + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "query", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()).c_str(), + "input query's head_num can not be a multiple of key's head_num"); + return ge::GRAPH_FAILED; + } + gSize_ = n1Size_ / n2Size_; + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetBatchSize() +{ + // 获取B基准值 + // 1、非TND/NTD时, 以query的batch_size维度为基准; + // 2、TND/NTD时, actual_seq_lens_q必须传入, 以actual_seq_lens_q数组的长度为B轴大小 + if ((qLayout_ == DataLayout::TND)) { + return GetActualSeqLenSize(bSize_, opParamInfo_.actualSeqLengthsQ.tensor, "input actual_seq_lengths_query"); + } else { // BSND + bSize_ = opParamInfo_.query.shape->GetStorageShape().GetDim(0); + return ge::GRAPH_SUCCESS; + } +} + +static ge::graphStatus LiGetHeadDim(const TilingRequiredParaInfo &liQuery, DataLayout liQLayout, + const char *liOpName, uint32_t &liHeadDim) +{ + uint32_t liDIndex = DIM_IDX_TWO; + switch (liQLayout) { + case DataLayout::TND: + liDIndex = DIM_IDX_TWO; + break; + case DataLayout::BSND: + liDIndex = DIM_IDX_THREE; + break; + default: + OP_LOGE(liOpName, "unsupported layout for getting head dim."); + return ge::GRAPH_FAILED; + } + liHeadDim = liQuery.shape->GetStorageShape().GetDim(liDIndex); + OP_CHECK_IF(liHeadDim != HEAD_DIM_LIMIT, + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(liOpName, "query", + Ops::Base::ToString(liQuery.shape->GetStorageShape()).c_str(), + "input query's last dim head_dim only support 128"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetHeadDim() +{ + return LiGetHeadDim(opParamInfo_.query, qLayout_, opName_, headDim_); +} + +ge::graphStatus LIInfoParser::GetS1Size() +{ + if (qLayout_ == DataLayout::BSND) { + s1Size_ = opParamInfo_.query.shape->GetStorageShape().GetDim(1); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetAndCheckBlockSize() +{ + blockSize_ = static_cast(opParamInfo_.key.shape->GetStorageShape().GetDim(1)); + OP_LOGI(context_->GetNodeName(), "blockSize_ is %d", blockSize_); + + OP_CHECK_IF(((blockSize_ % 16 != 0) || (blockSize_ == 0) || (blockSize_ > 1024)), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "key", + Ops::Base::ToString(opParamInfo_.key.shape->GetShape()).c_str(), + "input key's block_size must be a multiple of 16 and be within the range (0, 1024]"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::CheckBlockCount() +{ + int32_t blockCount_ = static_cast(opParamInfo_.key.shape->GetStorageShape().GetDim(0)); + OP_CHECK_IF((blockCount_ == 0), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "key", + Ops::Base::ToString(opParamInfo_.key.shape->GetShape()).c_str(), + "input key's block_count cannot be 0"), return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetS2SizeForPageAttention() +{ + if (GetAndCheckBlockSize() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + if (CheckBlockCount() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + maxBlockNumPerBatch_ = opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(1); + s2Size_ = maxBlockNumPerBatch_ * blockSize_; + OP_LOGI(context_->GetNodeName(), "maxBlockNumPerBatch_ is %d, blockSize_ is %d, s2Size_ is %d", + maxBlockNumPerBatch_, blockSize_, s2Size_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::GetS2Size() +{ + // 获取S2基准值 + // 1、BATCH_CONTINUOUS时, 从key的S轴获取 + // 3、PAGE_ATTENTION时, S2 = block_table.dim1 * block_size + if (kLayout_ == DataLayout::BnBsND) { + return GetS2SizeForPageAttention(); + } else if (kLayout_ == DataLayout::TND) { + s2Size_ = opParamInfo_.key.shape->GetStorageShape().GetDim(0); + } else if (kLayout_ == DataLayout::BSND) { + s2Size_ = opParamInfo_.key.shape->GetStorageShape().GetDim(1); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::ValidateInputShapesMatchQtnd() +{ + // -----------------------check BatchSize------------------- + // bSize_ 来源于act_seq_q + if (kLayout_ == DataLayout::TND) { + OP_CHECK_IF( + (opParamInfo_.actualSeqLengths.tensor->GetShapeSize() != bSize_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and actual_seq_lengths_key", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.actualSeqLengths.tensor->GetStorageShape()), + "TND case input actual_seq_lengths_query, actual_seq_lengths_key are " + + std::to_string(bSize_) + ", " + + std::to_string(opParamInfo_.actualSeqLengths.tensor->GetShapeSize()) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + } else { // kLayout_ PA_BSND + OP_CHECK_IF( + (opParamInfo_.actualSeqLengths.tensor->GetShapeSize() != bSize_) || + (opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(0) != bSize_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query, actual_seq_lengths_key and block_table", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + ", " + + Ops::Base::ToString(opParamInfo_.actualSeqLengths.tensor->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.blockTable.tensor->GetStorageShape()), + "TND case input actual_seq_lengths_query, actual_seq_lengths_key, block_table dim 0 are " + + std::to_string(bSize_) + ", " + + std::to_string(opParamInfo_.actualSeqLengths.tensor->GetShapeSize()) + ", " + + std::to_string(opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + } + // -----------------------check T------------------- + uint32_t qTsize = opParamInfo_.query.shape->GetStorageShape().GetDim(0); + OP_CHECK_IF((opParamInfo_.weights.shape->GetStorageShape().GetDim(0) != qTsize) || + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0) != qTsize), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query, weights and sparse_indices", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + ", " + + Ops::Base::ToString(opParamInfo_.weights.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()), + "TND case input query, weights and sparse_indices dim 0 are " + + std::to_string(qTsize) + ", " + + std::to_string(opParamInfo_.weights.shape->GetStorageShape().GetDim(0)) + ", " + + std::to_string(opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF((opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(0) != qTsize && + (*opParamInfo_.returnValue)), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and sparse_values", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()), + "TND case input query and sparse_values dim 0 are " + + std::to_string(qTsize) + ", " + + std::to_string(opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::ValidateInputShapesMatchQbsnd() +{ + // -----------------------check BatchSize------------------- + // bSize_ 来源于query + if (kLayout_ == DataLayout::BnBsND) { + OP_CHECK_IF((opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(0) != bSize_) || + (opParamInfo_.actualSeqLengths.tensor->GetShapeSize() != bSize_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query, actual_seq_lengths_key and block_table", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + ", " + + Ops::Base::ToString(opParamInfo_.actualSeqLengths.tensor->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.blockTable.tensor->GetStorageShape()), + "BSND case input query, actual_seq_lengths_key, block_table dim 0 are " + + std::to_string(bSize_) + ", " + + std::to_string(opParamInfo_.actualSeqLengths.tensor->GetShapeSize()) + ", " + + std::to_string(opParamInfo_.blockTable.tensor->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + } else if (kLayout_ == DataLayout::BSND) { + OP_CHECK_IF(opParamInfo_.key.shape->GetStorageShape().GetDim(0) != bSize_, + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and key", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()), + "BSND case input query, key dim 0 are " + + std::to_string(bSize_) + ", " + + std::to_string(opParamInfo_.key.shape->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF((opParamInfo_.actualSeqLengths.tensor != nullptr) && + (opParamInfo_.actualSeqLengths.tensor->GetShapeSize() != bSize_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and actual_seq_lengths_key", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.actualSeqLengths.tensor->GetStorageShape()), + "BSND case input query, actual_seq_lengths_key dim 0 are " + + std::to_string(bSize_) + ", " + + std::to_string(opParamInfo_.actualSeqLengths.tensor->GetShapeSize()) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + } + OP_CHECK_IF((opParamInfo_.weights.shape->GetStorageShape().GetDim(0) != bSize_) || + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0) != bSize_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query, weights and sparse_indices", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + ", " + + Ops::Base::ToString(opParamInfo_.weights.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()), + "BSND case input query, weights and sparse_indices dim 0 are " + + std::to_string(bSize_) + ", " + + std::to_string(opParamInfo_.weights.shape->GetStorageShape().GetDim(0)) + ", " + + std::to_string(opParamInfo_.attenOut.shape->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF((opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(0) != bSize_ && + (*opParamInfo_.returnValue)), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and sparse_values", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.valuesOut.shape->GetStorageShape()), + "BSND case input query, sparse_values dim 0 are " + + std::to_string(bSize_) + ", " + + std::to_string(opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(0)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF((opParamInfo_.actualSeqLengthsQ.tensor != nullptr) && + (opParamInfo_.actualSeqLengthsQ.tensor->GetShapeSize() != bSize_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and actual_seq_lengths_query", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.actualSeqLengthsQ.tensor->GetStorageShape()), + "BSND case input query, actual_seq_lengths_query dim 0 are " + + std::to_string(bSize_) + ", " + + std::to_string(opParamInfo_.actualSeqLengthsQ.tensor->GetShapeSize()) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + // -----------------------check S1------------------- + OP_CHECK_IF((opParamInfo_.weights.shape->GetStorageShape().GetDim(1) != s1Size_) || + (opParamInfo_.attenOut.shape->GetStorageShape().GetDim(1) != s1Size_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query, weights and sparse_indices", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + ", " + + Ops::Base::ToString(opParamInfo_.weights.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()), + "BSND case input query, weights and sparse_indices dim 1 are " + + std::to_string(s1Size_) + ", " + + std::to_string(opParamInfo_.weights.shape->GetStorageShape().GetDim(1)) + ", " + + std::to_string(opParamInfo_.attenOut.shape->GetStorageShape().GetDim(1)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF((opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(1) != s1Size_ && + (*opParamInfo_.returnValue)), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and sparse_values", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.valuesOut.shape->GetStorageShape()), + "BSND case input query and sparse_values dim 1 are " + + std::to_string(s1Size_) + ", " + + std::to_string(opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(1)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::ValidateInputShapesMatch() +{ + /* + TND: + query [T,N1,D], + key [BlockNum,BlockSize,N2,D], + weight [T,N1], + block_table [BatchSize, BatchMaxBlockNum], + act_seq_k [BatchSize] + act_seq_q [BatchSize], + out [T,N2,topk] + ---------------------- + BSND: + query [BatchSize,S1,N1,D], + key [BlockNum,BlockSize,N2,D], + weight [BatchSize,S1,N1], + block_table [BatchSize, BatchMaxBlockNum], + act_seq_k [BatchSize] + act_seq_q [BatchSize] 可选 + out [BatchSize,S1,N2,topk] + */ + uint32_t queryWeightsN1Dim = 1; + uint32_t outN2Dim = 1; + if (qLayout_ == DataLayout::TND) { + if (ValidateInputShapesMatchQtnd() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } else { // qLayout_ BSND + if (ValidateInputShapesMatchQbsnd() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + queryWeightsN1Dim = DIM_IDX_TWO; + outN2Dim = DIM_IDX_TWO; + } + // -----------------------check N1------------------- + OP_CHECK_IF((opParamInfo_.weights.shape->GetStorageShape().GetDim(queryWeightsN1Dim) != n1Size_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and weights", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.weights.shape->GetStorageShape()), + "input query, weights shape dim N1 must be same"), + return ge::GRAPH_FAILED); + // -----------------------check D------------------- + uint32_t keyDDim = kLayout_ == DataLayout::TND ? DIM_IDX_TWO : DIM_IDX_THREE; + OP_CHECK_IF((opParamInfo_.key.shape->GetStorageShape().GetDim(keyDDim) != headDim_), + 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()), + "input query, key shape last dim must be same"), + return ge::GRAPH_FAILED); + // -----------------------check N2------------------- + OP_CHECK_IF((opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim) != n2Size_), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and sparse_indices", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()), + "input query and output sparse_indices shape n2 dim are " + + std::to_string(n2Size_) + ", " + + std::to_string(opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF((opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(outN2Dim) != n2Size_ && + (*opParamInfo_.returnValue)), + OP_LOGE_FOR_INVALID_SHAPES_WITH_REASON(opName_, "query and sparse_indices", + Ops::Base::ToString(opParamInfo_.query.shape->GetStorageShape()) + " and " + + Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()), + "input query and sparse_values shape n2 dim are " + + std::to_string(n2Size_) + ", " + + std::to_string(opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim)) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + // -----------------------check sparse_count------------------- + OP_CHECK_IF((opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim + 1) != *opParamInfo_.sparseCount), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "sparse_indices", + Ops::Base::ToString(opParamInfo_.attenOut.shape->GetStorageShape()), + "output sparse_indices shape last dim and attr sparse_count are " + + std::to_string(opParamInfo_.attenOut.shape->GetStorageShape().GetDim(outN2Dim + 1)) + ", " + + std::to_string(*opParamInfo_.sparseCount) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + OP_CHECK_IF((opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(outN2Dim + 1) != *opParamInfo_.sparseCount && + (*opParamInfo_.returnValue)), + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(opName_, "sparse_values", + Ops::Base::ToString(opParamInfo_.valuesOut.shape->GetStorageShape()), + "output sparse_values shape last dim and attr sparse_count are " + + std::to_string(opParamInfo_.valuesOut.shape->GetStorageShape().GetDim(outN2Dim + 1)) + ", " + + std::to_string(*opParamInfo_.sparseCount) + + " respectively, they must be same"), + return ge::GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +void LIInfoParser::GenerateInfo(LITilingInfo &liInfo) +{ + liInfo.opName = opName_; + liInfo.platformInfo = platformInfo_; + liInfo.opParamInfo = opParamInfo_; + liInfo.socVersion = socVersion_; + liInfo.npuArch = npuArch_; + + liInfo.bSize = bSize_; + liInfo.n1Size = n1Size_; + liInfo.n2Size = n2Size_; + liInfo.s1Size = s1Size_; + liInfo.s2Size = s2Size_; + liInfo.gSize = gSize_; + + liInfo.inputQType = inputQType_; + liInfo.inputKType = inputKType_; + liInfo.weightsType = weightsType_; + liInfo.outputType = outputType_; + + liInfo.blockSize = blockSize_; + liInfo.maxBlockNumPerBatch = maxBlockNumPerBatch_; + + std::string layOutKeyStr(opParamInfo_.layOutKey); + liInfo.pageAttentionFlag = layOutKeyStr == "PA_BSND" ? true : false; + liInfo.sparseMode = *opParamInfo_.sparseMode; + liInfo.sparseCount = *opParamInfo_.sparseCount; + liInfo.preTokens = *opParamInfo_.preTokens; + liInfo.nextTokens = *opParamInfo_.nextTokens; + liInfo.returnValue = *opParamInfo_.returnValue; + + liInfo.inputQLayout = qLayout_; + liInfo.inputKLayout = kLayout_; +} +ge::graphStatus LIInfoParser::CheckFeatureMlaNoQuantShape() const +{ + if (npuArch_ == NpuArch::DAV_3510) { + OP_CHECK_IF(bSize_ <= 0, + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON(opName_, "batch_size", + std::to_string(bSize_).c_str(), + "batch_size should be greater than 0"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(s1Size_ <= 0 && (qLayout_ == DataLayout::BSND), + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON(opName_, "query", + std::to_string(s1Size_).c_str(), + "BSND case input query dim 1 should be greater than 0"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(s2Size_ <= 0 && (kLayout_ == DataLayout::BSND), + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON(opName_, "key", + std::to_string(s2Size_).c_str(), + "BSND case input key dim 1 should be greater than 0"), + return ge::GRAPH_FAILED); + + uint32_t qTsize = opParamInfo_.query.shape->GetStorageShape().GetDim(0); + OP_CHECK_IF(qTsize <= 0 && (qLayout_ == DataLayout::TND), + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON(opName_, "query", + std::to_string(qTsize).c_str(), + "TND case input query dim 0 should be greater than 0"), + return ge::GRAPH_FAILED); + + uint32_t kTsize = opParamInfo_.key.shape->GetStorageShape().GetDim(0); + OP_CHECK_IF(kTsize <= 0 && (kLayout_ == DataLayout::TND), + OP_LOGE_FOR_INVALID_SHAPESIZES_WITH_REASON(opName_, "key", + std::to_string(kTsize).c_str(), + "TND case input key dim 0 should be greater than 0"), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus LIInfoParser::ParseAndCheck(LITilingInfo &liInfo) +{ + 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 != GetAndCheckInOutDataType() || + ge::GRAPH_SUCCESS != GetQueryKeyAndOutLayout() || + ge::GRAPH_SUCCESS != GetAndCheckOptionalInput()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != CheckShapeDim() || ge::GRAPH_SUCCESS != GetN1Size() || + ge::GRAPH_SUCCESS != GetAndCheckN2Size() || ge::GRAPH_SUCCESS != GetGSize()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != GetBatchSize() || ge::GRAPH_SUCCESS != GetS1Size() || + ge::GRAPH_SUCCESS != GetHeadDim() || ge::GRAPH_SUCCESS != GetS2Size()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != CheckFeatureMlaNoQuantShape()) { + return ge::GRAPH_FAILED; + } + + if (ge::GRAPH_SUCCESS != ValidateInputShapesMatch()) { + return ge::GRAPH_FAILED; + } + + GenerateInfo(liInfo); + + return ge::GRAPH_SUCCESS; +} + +// --------------------------TilingPrepare函数定义------------------------------------- +static ge::graphStatus TilingPrepareForLightningIndexer(gert::TilingParseContext * /* context */) +{ + return ge::GRAPH_SUCCESS; +} + +// --------------------------LightningIndexerTiling类成员函数定义----------------------- +static uint64_t LiCalcWorkspaceSize(const platform_ascendc::PlatformAscendC &liPlatform, + int64_t liS2Size, uint32_t liAicNum) +{ + constexpr uint32_t liMm1ResElemSize = 4; + constexpr uint32_t liDoubleBuffer = 2; + constexpr uint32_t liMBaseSize = 512; + constexpr uint32_t liS2BaseSize = 512; + constexpr uint32_t liV1ResElemSize = 4; + constexpr uint32_t liV1ResElemType = 2; + constexpr uint32_t liV1DecodeParamElemSize = 8; + constexpr uint32_t liV1DecodeParamNum = 16; + constexpr uint32_t liV1DecodeDataNum = 2; + constexpr uint32_t liS1BaseSize = 8; + constexpr uint32_t liTopkMaxSize = 2048; + + uint64_t liWorkspaceSize = liPlatform.GetLibApiWorkSpaceSize(); + if (liPlatform.GetCurNpuArch() == NpuArch::DAV_3510) { + constexpr uint32_t li3510S1Base = 4; + constexpr uint32_t li3510S2Base = 128; + liWorkspaceSize += + li3510S1Base * ((liS2Size + li3510S2Base - 1) / li3510S2Base) * li3510S2Base * + sizeof(uint32_t) * liAicNum; + } else { + constexpr uint32_t liMm1ResSize = liMBaseSize * liS2BaseSize; + liWorkspaceSize += liMm1ResSize * liMm1ResElemSize * liDoubleBuffer * liAicNum; + liWorkspaceSize += + liV1DecodeDataNum * liS1BaseSize * liV1ResElemType * liTopkMaxSize * liV1ResElemSize * liAicNum; + liWorkspaceSize += + liV1DecodeDataNum * liS1BaseSize * liV1DecodeParamNum * liV1DecodeParamElemSize * liAicNum; + } + return liWorkspaceSize; +} + +ge::graphStatus LightningIndexerTiling::DoTiling(LITilingInfo *tilingInfo) +{ + // -------------set blockdim----------------- + auto ascendcPlatform = platform_ascendc::PlatformAscendC(tilingInfo->platformInfo); + uint32_t aivNum = ascendcPlatform.GetCoreNumAiv(); + uint32_t aicNum = ascendcPlatform.GetCoreNumAic(); + uint32_t blockDim = ascendcPlatform.CalcTschBlockDim(aivNum, aicNum, aivNum); + context_->SetBlockDim(blockDim); + + // -------------set workspacesize----------------- + uint64_t workspaceSize = LiCalcWorkspaceSize(ascendcPlatform, tilingInfo->s2Size, aicNum); + size_t *workSpaces = context_->GetWorkspaceSizes(1); + workSpaces[0] = workspaceSize; + + // -------------set tilingdata----------------- + tilingData_.set_bSize(tilingInfo->bSize); + tilingData_.set_s2Size(tilingInfo->s2Size); + tilingData_.set_s1Size(tilingInfo->s1Size); + tilingData_.set_sparseCount(tilingInfo->sparseCount); + tilingData_.set_gSize(tilingInfo->gSize); + tilingData_.set_blockSize(tilingInfo->blockSize); + tilingData_.set_maxBlockNumPerBatch(tilingInfo->maxBlockNumPerBatch); + tilingData_.set_sparseMode(tilingInfo->sparseMode); + tilingData_.set_preTokens(tilingInfo->preTokens); + tilingData_.set_nextTokens(tilingInfo->nextTokens); + tilingData_.set_returnValue(tilingInfo->returnValue); + tilingData_.set_usedCoreNum(blockDim); + tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity()); + context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); + + // -------------set tilingkey----------------- + // int DT_W_FLAG, DT_Q, DT_KV, DT_OUT, PAGE_ATTENTION, FLASH_DECODE, LAYOUT_T, KV_LAYOUT_T + uint32_t inputQType = static_cast(tilingInfo->inputQType); + uint32_t inputKType = static_cast(tilingInfo->inputKType); + uint32_t weightsType = static_cast(tilingInfo->weightsType); + uint32_t outputType = static_cast(tilingInfo->outputType); + uint32_t pageAttentionFlag = static_cast(tilingInfo->pageAttentionFlag); + uint32_t inputQLayout = static_cast(tilingInfo->inputQLayout); + uint32_t inputKLayout = static_cast(tilingInfo->inputKLayout); + uint32_t weightTypeFlag = (weightsType == ge::DT_FLOAT) ? 1 : 0; + uint64_t tilingKey = + GET_TPL_TILING_KEY(inputQType, inputKType, outputType, pageAttentionFlag, inputQLayout, inputKLayout, weightTypeFlag); + context_->SetTilingKey(tilingKey); + context_->SetScheduleMode(1); // 1: batchmode模式 + + return ge::GRAPH_SUCCESS; +} + +// --------------------------Tiling函数定义--------------------------- +ge::graphStatus TilingForLightningIndexer(gert::TilingContext *context) +{ + OP_CHECK_IF(context == nullptr, OPS_REPORT_VECTOR_INNER_ERR("LightningIndexer", "Tiling context is null."), + return ge::GRAPH_FAILED); + LITilingInfo liInfo; + LIInfoParser LIInfoParser(context); + if (LIInfoParser.ParseAndCheck(liInfo) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + LightningIndexerTiling liTiling(context); + return liTiling.DoTiling(&liInfo); +} + +// --------------------------Tiling函数及TilingPrepare函数注册-------- +IMPL_OP_OPTILING(LightningIndexer) + .Tiling(TilingForLightningIndexer) + .TilingParse(TilingPrepareForLightningIndexer); + +} // namespace optiling diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_tiling.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_tiling.h new file mode 100644 index 0000000000000000000000000000000000000000..5c2e6340147840eb8ed7ad300bf32f73f26b3369 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/lightning_indexer_tiling.h @@ -0,0 +1,250 @@ +/** + * 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 lightning_indexer_tiling.h + * \brief + */ + +#ifndef LIGHTNING_INDEXER_TILING_H_ +#define LIGHTNING_INDEXER_TILING_H_ + +#include "exe_graph/runtime/tiling_context.h" +#include "tiling/platform/platform_ascendc.h" +#include "register/op_def_registry.h" +#include "register/tilingdata_base.h" +#include "tiling/tiling_api.h" +#include "err/ops_err.h" +#include "platform/platform_info.h" +#include "op_host/tiling_util.h" +namespace optiling { +// ------------------公共定义-------------------------- +enum class DataLayout : uint32_t { + BSND = 0, + TND = 1, + BnBsND = 2 +}; + +struct TilingRequiredParaInfo { + const gert::CompileTimeTensorDesc *desc; + const gert::StorageShape *shape; +}; + +struct TilingOptionalParaInfo { + const gert::CompileTimeTensorDesc *desc; + const gert::Tensor *tensor; +}; + +// ------------------算子原型索引常量定义---------------- +// Inputs Index +constexpr uint32_t QUERY_INDEX = 0; +constexpr uint32_t KEY_INDEX = 1; +constexpr uint32_t WEIGTHS_INDEX = 2; +constexpr uint32_t ACTUAL_SEQ_Q_INDEX = 3; +constexpr uint32_t ACTUAL_SEQ_K_INDEX = 4; +constexpr uint32_t BLOCK_TABLE_INDEX = 5; +//Outputs Index +constexpr uint32_t LIGHTNING_INDEXER = 0; +constexpr uint32_t LIGHTNING_VALUES = 1; +// Attributes Index +constexpr uint32_t ATTR_QUERY_LAYOUT_INDEX = 0; +constexpr uint32_t ATTR_KEY_LAYOUT_INDEX = 1; +constexpr uint32_t ATTR_SPARSE_COUNT_INDEX = 2; +constexpr uint32_t ATTR_SPARSE_MODE_INDEX = 3; +constexpr uint32_t ATTR_PRE_TOKENS_INDEX = 4; +constexpr uint32_t ATTR_NEXT_TOKENS_INDEX = 5; +constexpr uint32_t ATTR_RETURN_VALUE_INDEX = 6; +// Dim Index +constexpr uint32_t DIM_IDX_ONE = 1; +constexpr uint32_t DIM_IDX_TWO = 2; +constexpr uint32_t DIM_IDX_THREE = 3; +// Dim Num +constexpr uint32_t DIM_NUM_TWO = 2; +constexpr uint32_t DIM_NUM_THREE = 3; +constexpr uint32_t DIM_NUM_FOUR = 4; +// 入参限制常量 +constexpr uint32_t HEAD_DIM_LIMIT = 128; +constexpr uint32_t SPARSE_LIMIT = 2048; +constexpr uint32_t SPARSE_MODE_LOWER = 3; +constexpr uint32_t QUERY_HEAD_NUM_LIMIT = 64; +constexpr uint32_t QUERY_HEAD_NUM_LIMIT_950_64 = 64; +constexpr uint32_t QUERY_HEAD_NUM_LIMIT_950_32 = 32; +constexpr uint32_t QUERY_HEAD_NUM_LIMIT_950_24 = 24; +constexpr uint32_t QUERY_HEAD_NUM_LIMIT_950_16 = 16; +constexpr uint32_t QUERY_HEAD_NUM_LIMIT_950_8 = 8; + +// -----------算子TilingData定义--------------- +BEGIN_TILING_DATA_DEF(LITilingData) +TILING_DATA_FIELD_DEF(uint32_t, bSize) +TILING_DATA_FIELD_DEF(uint32_t, n2Size) +TILING_DATA_FIELD_DEF(uint32_t, gSize) +TILING_DATA_FIELD_DEF(uint32_t, s1Size) +TILING_DATA_FIELD_DEF(uint32_t, s2Size) +TILING_DATA_FIELD_DEF(uint32_t, sparseCount) +TILING_DATA_FIELD_DEF(uint32_t, usedCoreNum) +TILING_DATA_FIELD_DEF(uint32_t, blockSize) +TILING_DATA_FIELD_DEF(uint32_t, maxBlockNumPerBatch) +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, returnValue) +END_TILING_DATA_DEF +REGISTER_TILING_DATA_CLASS(LightningIndexer, LITilingData) + +// -----------算子CompileInfo定义------------------- +struct LICompileInfo {}; + +// -----------算子Tiling入参结构体定义--------------- +struct LiParaInfo { + TilingRequiredParaInfo query = {nullptr, nullptr}; + TilingRequiredParaInfo key = {nullptr, nullptr}; + TilingRequiredParaInfo weights = {nullptr, nullptr}; + TilingOptionalParaInfo actualSeqLengthsQ = {nullptr, nullptr}; + TilingOptionalParaInfo actualSeqLengths = {nullptr, nullptr}; + TilingOptionalParaInfo blockTable = {nullptr, nullptr}; + TilingRequiredParaInfo attenOut = {nullptr, nullptr}; + TilingRequiredParaInfo valuesOut = {nullptr, nullptr}; + + const char *layOut = nullptr; + const char *layOutKey = nullptr; + const int32_t *blockSize = nullptr; + const int32_t *sparseMode = nullptr; + const int32_t *sparseCount = nullptr; + const int64_t *preTokens = nullptr; + const int64_t *nextTokens = nullptr; + const bool *returnValue = nullptr; +}; + +// -----------算子Tiling入参信息类--------------- +class LITilingInfo { +public: + const char *opName = nullptr; + fe::PlatFormInfos *platformInfo = nullptr; + LiParaInfo opParamInfo; + // Base Param + NpuArch npuArch = NpuArch::DAV_2201; + platform_ascendc::SocVersion socVersion = platform_ascendc::SocVersion::ASCEND910B; + 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 gSize = 0; + // Mask + int32_t sparseMode = 0; + // PageAttention + bool pageAttentionFlag = false; + int32_t blockSize = 0; + uint32_t maxBlockNumPerBatch = 0; + // Others Flag + uint32_t sparseCount = 0; + int64_t preTokens = INT64_MAX; + int64_t nextTokens = INT64_MAX; + bool returnValue = false; + // DType + ge::DataType inputQType = ge::DT_FLOAT16; + ge::DataType inputKType = ge::DT_FLOAT16; + ge::DataType weightsType = ge::DT_FLOAT16; + ge::DataType outputType = ge::DT_INT32; + // Layout + DataLayout inputQLayout = DataLayout::BSND; + DataLayout inputKLayout = DataLayout::BnBsND; +}; + +// -----------算子Tiling入参信息解析及Check类--------------- +class LIInfoParser { +public: + explicit LIInfoParser(gert::TilingContext *context) : context_(context) + { + } + ~LIInfoParser() = default; + + ge::graphStatus CheckRequiredInOutExistence() const; + ge::graphStatus CheckTensorShapes() const; + ge::graphStatus CheckTensorDescriptions() const; + ge::graphStatus CheckRequiredAttrExistence() const; + ge::graphStatus CheckRequiredParaExistence() const; + ge::graphStatus GetActualSeqLenSize(uint32_t &liSize, const gert::Tensor *liTensor, + const std::string &liSeqLenName) const; + ge::graphStatus GetOpName(); + ge::graphStatus GetNpuInfo(); + void GetOptionalInputParaInfo(); + void GetInputParaInfo(); + void GetOutputParaInfo(); + ge::graphStatus GetAndCheckAttrParaInfo(); + ge::graphStatus GetOpParaInfo(); + ge::graphStatus ValidateInputShapesMatchQbsnd(); + ge::graphStatus ValidateInputShapesMatchQtnd(); + ge::graphStatus ValidateInputShapesMatch(); + ge::graphStatus GetAndCheckInOutDataType(); + ge::graphStatus GetBatchSize(); + ge::graphStatus GetHeadDim(); + ge::graphStatus GetS1Size(); + ge::graphStatus GetAndCheckOptionalInput(); + ge::graphStatus CheckShapeDim(); + ge::graphStatus GetAndCheckBlockSize(); + ge::graphStatus CheckBlockCount(); + ge::graphStatus GetS2SizeForPageAttention(); + ge::graphStatus GetS2Size(); + ge::graphStatus GetQueryKeyAndOutLayout(); + ge::graphStatus GetN1Size(); + ge::graphStatus GetAndCheckN2Size(); + ge::graphStatus GetGSize(); + ge::graphStatus CheckFeatureMlaNoQuantShape() const; + ge::graphStatus GetAttenMaskInfo(); + ge::graphStatus GetActualSeqInfo(); + void GenerateInfo(LITilingInfo &liInfo); + ge::graphStatus ParseAndCheck(LITilingInfo &liInfo); + +public: + gert::TilingContext *context_ = nullptr; + const char *opName_; + fe::PlatFormInfos *platformInfo_; + LiParaInfo opParamInfo_; + + // BaseParams + 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 headDim_ = 0; + // Layout + DataLayout qLayout_ = DataLayout::BSND; + DataLayout kLayout_ = DataLayout::BnBsND; + // PageAttention + uint32_t maxBlockNumPerBatch_ = 0; + int32_t blockSize_ = 0; + NpuArch npuArch_ = NpuArch::DAV_2201; + platform_ascendc::SocVersion socVersion_ = platform_ascendc::SocVersion::ASCEND910B; + ge::DataType inputQType_ = ge::DT_FLOAT16; + ge::DataType inputKType_ = ge::DT_FLOAT16; + ge::DataType weightsType_ = ge::DT_FLOAT16; + ge::DataType blockTableType_ = ge::DT_FLOAT16; + ge::DataType inputKRopeType_ = ge::DT_FLOAT16; + ge::DataType outputType_ = ge::DT_FLOAT16; + ge::DataType valuesOutType_ = ge::DT_FLOAT16; +}; + +// ---------------算子Tiling类--------------- +class LightningIndexerTiling { +public: + explicit LightningIndexerTiling(gert::TilingContext *context) : context_(context){}; + ge::graphStatus DoTiling(LITilingInfo *tilingInfo); + +private: + gert::TilingContext *context_ = nullptr; + LITilingData tilingData_; +}; + +} // namespace optiling +#endif // LIGHTNING_INDEXER_TILING_H_ \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/op_api/aclnn_lightning_indexer.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/op_api/aclnn_lightning_indexer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b898ba0b4979d7c41db65c40ad16d7b60a642c8c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/op_api/aclnn_lightning_indexer.cpp @@ -0,0 +1,138 @@ +/** + * 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_lightning_indexer.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 aclnnInnerLightningIndexerGetWorkspaceSize( + const aclTensor *query, const aclTensor *key, const aclTensor *weights, + const aclTensor *actualSeqLengthsQueryOptional, const aclTensor *actualSeqLengthsKeyOptional, + const aclTensor *blockTableOptional, char *layoutQueryOptional, + char *layoutKeyOptional, int64_t sparseCount, int64_t sparseMode, + int64_t preTokens, int64_t nextTokens, bool returnValues, + const aclTensor *sparseIndicesOut, const aclTensor *sparseValuesOut, + uint64_t *workspaceSize, aclOpExecutor **executor); + +extern aclnnStatus aclnnInnerLightningIndexer(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 aclnnLightningIndexerGetWorkspaceSize( + const aclTensor *query, + const aclTensor *key, + const aclTensor *weights, + const aclTensor *actualSeqLengthsQueryOptional, + const aclTensor *actualSeqLengthsKeyOptional, + const aclTensor *blockTableOptional, + char *layoutQueryOptional, + char *layoutKeyOptional, + int64_t sparseCount, + int64_t sparseMode, + int64_t preTokens, + int64_t nextTokens, + bool returnValues, + const aclTensor *sparseIndicesOut, + const aclTensor *sparseValuesOut, + uint64_t *workspaceSize, + aclOpExecutor **executor) +{ + if (query == nullptr) { + OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "Query pointer is null, cannot get data type!"); + return ge::GRAPH_FAILED; + } + DataType queryDataType = query->GetDataType(); + aclDataType queryAclDataType = ToAclDataType(queryDataType); + if (returnValues) { + if (sparseValuesOut == nullptr) { + OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "sparseValuesOut cannot be nullptr."); + return ge::GRAPH_FAILED; + } + } + auto sparseValuesOutHolder = TensorHolder(sparseValuesOut, queryAclDataType, std::string("sparseValuesOut")); + if (sparseValuesOut == nullptr) { + OP_LOGE(ACLNN_ERR_PARAM_NULLPTR, "Failed to create the holder of tensor sparseValuesOut!"); + return ge::GRAPH_FAILED; + } + + return aclnnInnerLightningIndexerGetWorkspaceSize( + query, key, weights, actualSeqLengthsQueryOptional, actualSeqLengthsKeyOptional, blockTableOptional, + layoutQueryOptional, layoutKeyOptional, sparseCount, sparseMode, preTokens, nextTokens, returnValues, + sparseIndicesOut, sparseValuesOut, workspaceSize, executor); +} + +aclnnStatus aclnnLightningIndexer(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + const aclrtStream stream) +{ + return aclnnInnerLightningIndexer(workspace, workspaceSize, executor, stream); +} + +} // namespace + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/op_api/aclnn_lightning_indexer.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/op_api/aclnn_lightning_indexer.h new file mode 100644 index 0000000000000000000000000000000000000000..4b50f094471609b414c28b1ab1d8a8145700b75e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_host/op_api/aclnn_lightning_indexer.h @@ -0,0 +1,59 @@ +/** + * 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_LIGHTNING_INDEXER_H +#define ACLNN_LIGHTNING_INDEXER_H + +#include "aclnn/acl_meta.h" +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief The first interface of aclnnLightningIndexerGetWorkspaceSize calculates the workspace size based on the specific calculation process. + * @domain aclnn_ops_infer + */ +__attribute__((visibility("default"))) +aclnnStatus aclnnLightningIndexerGetWorkspaceSize( + const aclTensor *query, + const aclTensor *key, + const aclTensor *weights, + const aclTensor *actualSeqLengthsQueryOptional, + const aclTensor *actualSeqLengthsKeyOptional, + const aclTensor *blockTableOptional, + char *layoutQueryOptional, + char *layoutKeyOptional, + int64_t sparseCount, + int64_t sparseMode, + int64_t preTokens, + int64_t nextTokens, + bool returnValues, + const aclTensor *sparseIndicesOut, + const aclTensor *sparseValuesOut, + uint64_t *workspaceSize, + aclOpExecutor **executor); + +/** + * @brief The second interface of aclnnLightningIndexer is used to perform calculations. + */ +__attribute__((visibility("default"))) +aclnnStatus aclnnLightningIndexer( + void *workspace, + uint64_t workspaceSize, + aclOpExecutor *executor, + const aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // ACLNN_LIGHTNING_INDEXER_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_kernel.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..013b7d62d29845c9b34a04a94dc0ac5f95f60404 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_kernel.h @@ -0,0 +1,692 @@ +/** + * 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 lightning_indexer_kernel.h + * \brief + */ + +#ifndef LIGHTNING_INDEXER_KERNEL_H +#define LIGHTNING_INDEXER_KERNEL_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 "../lightning_indexer_common.h" +#include "lightning_indexer_service_vector.h" +#include "lightning_indexer_service_cube.h" + +namespace LIKernel { +using namespace LICommon; +using namespace LIServiceVec; +using namespace matmul; +using AscendC::CacheMode; +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +// 由于S2循环前,RunInfo还没有赋值,使用TempLoopInfo临时存放B、N、S1轴相关的信息;同时减少重复计算 +struct TempLoopInfo { + uint32_t bN2Idx = 0; + uint32_t bIdx = 0U; + uint32_t n2Idx = 0U; + uint32_t gS1Idx = 0U; + uint32_t gS1LoopEnd = 0U; // gS1方向循环的结束Idx + uint32_t s2LoopEnd = 0U; // S2方向循环的结束Idx + uint32_t actS1Size = 1ULL; // 当前Batch循环处理的S1轴的实际大小 + uint32_t actS2Size = 0ULL; + bool curActSeqLenIsZero = false; + bool needDealActS1LessThanS1 = false; // S1的实际长度小于shape的S1长度时,是否需要清理输出 + uint32_t actMBaseSize = 0U; // m轴(gS1)方向实际大小 + uint32_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小 + uint32_t s2BasicSizeTail = 0U; // S2方向循环的尾基本块大小 +}; + +template +class LightningIndexerKernel { +public: + __aicore__ inline LightningIndexerKernel(){}; + __aicore__ inline void Init(__gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *weights, + __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths, + __gm__ uint8_t *blockTable, __gm__ uint8_t *sparseIndices, __gm__ uint8_t *sparseValues, + __gm__ uint8_t *workspace, const LITilingData *__restrict tiling, TPipe *tPipe); + __aicore__ inline void Process(); + + // =================================类型定义区================================= + static constexpr bool DT_W_FLAG = LIT::weightsTypeFlag; + using Q_T = typename LIT::queryType; + using K_T = typename LIT::keyType; + using OUT_T = typename LIT::outputType; + static constexpr bool PAGE_ATTENTION = LIT::pageAttention; + static constexpr LI_LAYOUT LAYOUT_T = LIT::layout; + static constexpr LI_LAYOUT K_LAYOUT_T = LIT::keyLayout; + // 编译期条件选择模板第二个参数的类型,直接声明W_T + // 第一个模板参数:固定为Q_T;第二个模板参数:编译期选float/void + using W_T = typename LightningIndexerTypeTraits::type>::weightsType; + + using MM1_OUT_T = float; + + LightningIndexerServiceCube matmulService; + LightningIndexerServiceVector vectorService; + + // =================================常量区================================= + static constexpr uint32_t SYNC_C1_V1_FLAG = 4; + static constexpr uint32_t SYNC_V1_C1_FLAG = 5; + + static constexpr uint32_t M_BASE_SIZE = 512; + static constexpr uint32_t S2_BASE_SIZE = 512; + static constexpr uint32_t HEAD_DIM = 128; + static constexpr uint32_t K_HEAD_NUM = 1; + static constexpr uint32_t GM_ALIGN_BYTES = 512; + static constexpr uint32_t SPARSE_COUNT_8K = 8192; + static constexpr uint32_t BLOCK_CUBE_SIZE = 16; + + static constexpr int64_t LD_PREFETCH_LEN = 2; + // for workspace double + static constexpr uint32_t WS_DOUBLE = 2; + +protected: + TPipe *pipe = nullptr; + + // offset + uint64_t queryCoreOffset = 0ULL; + uint64_t keyCoreOffset = 0ULL; + uint64_t weightsCoreOffset = 0ULL; + uint64_t indiceOutCoreOffset = 0ULL; + + // ================================Global Buffer区================================= + GlobalTensor queryGm; + GlobalTensor keyGm; + GlobalTensor weightsGm; + + GlobalTensor indiceOutGm; + GlobalTensor valueOutGm; + GlobalTensor blockTableGm; + + GlobalTensor actualSeqLengthsGmQ; + GlobalTensor actualSeqLengthsGm; + // workspace + GlobalTensor mm1ResGm; // 存放S + GlobalTensor vec1ResGm; // 存放TopK计算中间结果 + GlobalTensor vec1ParamGm; // 存放LD参数信息 + + // ================================类成员变量==================================== + // aic、aiv核信息 + uint32_t tmpBlockIdx = 0U; + uint32_t aiCoreIdx = 0U; + uint32_t usedCoreNum = 0U; + + LICommon::ConstInfo constInfo{}; + TempLoopInfo tempLoopInfo{}; + LICommon::SplitCoreInfo splitCoreInfo{}; + + // ================================Init functions================================== + __aicore__ inline void InitTilingData(const LITilingData *__restrict tilingData); + __aicore__ inline void InitBuffers(); + __aicore__ inline void InitActualSeqLen(__gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths); + // ================================Split Core================================ + __aicore__ inline void SplitCore(uint32_t curCoreIdx, uint32_t &coreNum, LICommon::SplitCoreInfo &info); + __aicore__ inline uint32_t GetS2BaseBlockNumOnMask(uint32_t s1gIdx, uint32_t actS1Size, uint32_t actS2Size); + __aicore__ inline uint32_t GetTotalBaseBlockNum(); + // ================================Process functions================================ + __aicore__ inline void ProcessMain(); + __aicore__ inline void ProcessBaseBlock(uint32_t loop, uint64_t s2LoopIdx, LICommon::RunInfo &runInfo); + __aicore__ inline void ProcessDecode(); + __aicore__ inline void ProcessInvalid(); + // ================================Params Calc===================================== + __aicore__ inline void CalcGS1LoopParams(uint32_t bN2Idx); + __aicore__ inline void GetBN2Idx(uint32_t bN2Idx); + __aicore__ inline uint32_t GetActualSeqLen(uint32_t bIdx, uint32_t actualLenDims, bool isAccumSeq, + GlobalTensor &actualSeqLengthsGm, uint32_t defaultSeqLen); + __aicore__ inline void GetS1S2ActualSeqLen(uint32_t bIdx, uint32_t &actS1Size, uint32_t &actS2Size); + __aicore__ inline void CalcS2LoopParams(uint32_t bN2LoopIdx, uint32_t gS1LoopIdx); + __aicore__ inline void CalcRunInfo(uint32_t loop, uint32_t s2LoopIdx, LICommon::RunInfo &runInfo); + __aicore__ inline void DealActSeqLenIsZero(uint32_t bIdx, uint32_t n2Idx, uint32_t s1Start); +}; + +template +__aicore__ inline void LightningIndexerKernel::InitTilingData(const LITilingData *__restrict tilingData) +{ + usedCoreNum = tilingData->usedCoreNum; + constInfo.batchSize = tilingData->bSize; + constInfo.qHeadNum = constInfo.gSize = tilingData->gSize; + constInfo.kSeqSize = tilingData->s2Size; + constInfo.qSeqSize = tilingData->s1Size; + constInfo.attenMaskFlag = (tilingData->sparseMode == 3); + constInfo.kCacheBlockSize = tilingData->blockSize; + constInfo.maxBlockNumPerBatch = tilingData->maxBlockNumPerBatch; + constInfo.sparseCount = tilingData->sparseCount; + constInfo.preTokens = tilingData->preTokens; + constInfo.nextTokens = tilingData->nextTokens; + constInfo.returnValue = tilingData->returnValue; + + constInfo.outputLayout = LAYOUT_T; // 输出和输入形状一致 + if (LAYOUT_T == LI_LAYOUT::TND) { + constInfo.isAccumSeqS1 = true; + } + if (K_LAYOUT_T == LI_LAYOUT::TND) { + constInfo.isAccumSeqS2 = true; + } + + constInfo.kHeadNum = K_HEAD_NUM; + constInfo.headDim = HEAD_DIM; + constInfo.s2BaseSize = S2_BASE_SIZE; + constInfo.isSparseCountOver2K = (constInfo.sparseCount <= BASE_TOPK) ? false : true; + + constInfo.s1BaseSize = constInfo.isSparseCountOver2K ? SPARSE_COUNT_8K / constInfo.sparseCount * 2 : 8; + constInfo.mBaseSize = constInfo.s1BaseSize * constInfo.gSize; + constInfo.mBaseSizeAlign = LICommon::Align(constInfo.mBaseSize, BLOCK_CUBE_SIZE); +} + +template +__aicore__ inline void LightningIndexerKernel::InitBuffers() +{ + if ASCEND_IS_AIV { + vectorService.InitBuffers(pipe); + } else { + matmulService.InitBuffers(pipe); + } +} + +template +__aicore__ inline void LightningIndexerKernel::InitActualSeqLen(__gm__ uint8_t *actualSeqLengthsQ, + __gm__ uint8_t *actualSeqLengths) +{ + if (actualSeqLengthsQ == nullptr) { + constInfo.actualLenQDims = 0; + } else { + constInfo.actualLenQDims = constInfo.batchSize; + actualSeqLengthsGmQ.SetGlobalBuffer((__gm__ uint32_t *)actualSeqLengthsQ, constInfo.actualLenQDims); + } + if (actualSeqLengths == nullptr) { + constInfo.actualLenDims = 0; + } else { + constInfo.actualLenDims = constInfo.batchSize; + actualSeqLengthsGm.SetGlobalBuffer((__gm__ uint32_t *)actualSeqLengths, constInfo.actualLenDims); + } +} + +template +__aicore__ inline uint32_t LightningIndexerKernel::GetActualSeqLen(uint32_t bIdx, + uint32_t actualLenDims, bool isAccumSeq, + GlobalTensor &actualSeqLengthsGm, + uint32_t defaultSeqLen) +{ + if (actualLenDims == 0) { + return defaultSeqLen; + } else if (isAccumSeq && bIdx > 0) { + return actualSeqLengthsGm.GetValue(bIdx) - actualSeqLengthsGm.GetValue(bIdx - 1); + } else { + return actualSeqLengthsGm.GetValue(bIdx); + } +} + +template +__aicore__ inline void LightningIndexerKernel::GetS1S2ActualSeqLen(uint32_t bIdx, + uint32_t &actS1Size, uint32_t &actS2Size) +{ + actS1Size = GetActualSeqLen(bIdx, constInfo.actualLenQDims, constInfo.isAccumSeqS1, actualSeqLengthsGmQ, + constInfo.qSeqSize); + actS2Size = + GetActualSeqLen(bIdx, constInfo.actualLenDims, constInfo.isAccumSeqS2, actualSeqLengthsGm, constInfo.kSeqSize); +} + +template +__aicore__ inline uint32_t LightningIndexerKernel::GetS2BaseBlockNumOnMask(uint32_t s1gIdx, uint32_t actS1Size, + uint32_t actS2Size) +{ + if (actS2Size == 0) { + return 0; + } + uint32_t s1Offset = constInfo.s1BaseSize * s1gIdx; + int32_t validS2LenBase = static_cast(actS2Size) - static_cast(actS1Size); + int32_t validS2Len = s1Offset + validS2LenBase + constInfo.s1BaseSize; + validS2Len = Min(validS2Len, static_cast(actS2Size)); + validS2Len = Max(validS2Len, 1); + return (validS2Len + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; +} + +template +__aicore__ inline uint32_t LightningIndexerKernel::GetTotalBaseBlockNum() +{ + uint32_t totalBlockNum = 0; + uint32_t actS1Size, actS2Size; + uint32_t s1GBaseNum, s2BaseNum; + for (uint32_t bIdx = 0; bIdx < constInfo.batchSize; bIdx++) { + GetS1S2ActualSeqLen(bIdx, actS1Size, actS2Size); + s1GBaseNum = CeilDiv(actS1Size, constInfo.s1BaseSize); + if (!constInfo.attenMaskFlag) { + s2BaseNum = constInfo.isSparseCountOver2K + ? (actS2Size > 0 ? 1 : 0) + : CeilDiv(actS2Size, constInfo.s2BaseSize); + totalBlockNum += s1GBaseNum * s2BaseNum * constInfo.kHeadNum; + continue; + } + for (uint32_t s1gIdx = 0; s1gIdx < s1GBaseNum; s1gIdx++) { + s2BaseNum = constInfo.isSparseCountOver2K + ? (actS2Size > 0 ? 1 : 0) + : GetS2BaseBlockNumOnMask(s1gIdx, actS1Size, actS2Size); + totalBlockNum += s2BaseNum * constInfo.kHeadNum; + } + } + return totalBlockNum; +} + +// 多核版本,双闭区间 +template +__aicore__ void inline LightningIndexerKernel::SplitCore(uint32_t curCoreIdx, + uint32_t &coreNum, LICommon::SplitCoreInfo &info) +{ + // 计算每个核最少处理的块数, 剩余的部分前面的核每个核多处理一块 + uint32_t totalBlockNum = GetTotalBaseBlockNum(); + uint32_t minBlockPerCore = totalBlockNum / coreNum; + uint32_t deal1MoreBlockCoreNum = totalBlockNum % coreNum; + uint32_t coreIdx = 0; + uint32_t lastGS1RemainBlockCnt = 0; + uint32_t coreDealBlockCnt = coreIdx < deal1MoreBlockCoreNum ? minBlockPerCore + 1 : minBlockPerCore; + coreNum = minBlockPerCore == 0 ? deal1MoreBlockCoreNum : coreNum; + + bool findLastCoreEnd = true; + uint32_t actS1Size, actS2Size; + uint32_t s1GBaseNum, s2BaseNum, s2Loop; + for (uint32_t bN2Idx = 0; bN2Idx < constInfo.batchSize * constInfo.kHeadNum; bN2Idx++) { + uint32_t bIdx = bN2Idx / constInfo.kHeadNum; + if (bN2Idx % constInfo.kHeadNum == 0) { + GetS1S2ActualSeqLen(bIdx, actS1Size, actS2Size); + s1GBaseNum = CeilDiv(actS1Size, constInfo.s1BaseSize); + s2BaseNum = CeilDiv(actS2Size, constInfo.s2BaseSize); + } + if constexpr (LAYOUT_T == LI_LAYOUT::BSND) { + if (findLastCoreEnd && (s1GBaseNum == 0U || s2BaseNum == 0U)) { + info.bN2Start = bN2Idx; + info.gS1Start = 0; + info.s2Start = 0; + findLastCoreEnd = false; + } + } + for (uint32_t gS1Idx = 0; gS1Idx < s1GBaseNum; gS1Idx++) { + if (constInfo.attenMaskFlag) { + s2BaseNum = GetS2BaseBlockNumOnMask(gS1Idx, actS1Size, actS2Size); + } + if (findLastCoreEnd && s2BaseNum == 0U) { + info.bN2Start = bN2Idx; + info.gS1Start = gS1Idx; + info.s2Start = 0; + findLastCoreEnd = false; + } + s2Loop = constInfo.isSparseCountOver2K ? (actS2Size > 0 ? 1 : 0) : s2BaseNum; + for (uint32_t s2Idx = 0; s2Idx < s2Loop;) { + if (findLastCoreEnd) { + info.bN2Start = bN2Idx; + info.gS1Start = gS1Idx; + info.s2Start = s2Idx; + findLastCoreEnd = false; + } + uint32_t s2RemainBaseNum = s2Loop - s2Idx; + if (lastGS1RemainBlockCnt + s2RemainBaseNum >= coreDealBlockCnt) { + info.bN2End = bN2Idx; + info.gS1End = gS1Idx; + info.s2End = constInfo.isSparseCountOver2K + ? s2BaseNum - 1 + : s2Idx + coreDealBlockCnt - lastGS1RemainBlockCnt - 1; + + if (coreIdx == curCoreIdx) { + // S2被切N核,那么只有第一个核需要处理LD,其他核不用 + if (s2Idx == 0 && info.s2End + 1 < s2BaseNum) { + info.isLD = true; + } + // 最后一个核处理的不是最后一个Batch,表明后面的Batch为空块(S2=0), 调整终点坐标以便清理输出 + if (coreIdx == coreNum - 1 && info.bN2End != constInfo.batchSize -1) { + info.bN2End = constInfo.batchSize -1; + info.gS1End = 0; + info.s2End = 0; + } + return; + } + coreIdx++; + findLastCoreEnd = true; + s2Idx = info.s2End + 1; + lastGS1RemainBlockCnt = 0; + coreDealBlockCnt = coreIdx < deal1MoreBlockCoreNum ? minBlockPerCore + 1 : minBlockPerCore; + } else { + lastGS1RemainBlockCnt += s2RemainBaseNum; + break; + } + } + } + } +} + +template +__aicore__ inline void LightningIndexerKernel::DealActSeqLenIsZero(uint32_t bIdx, uint32_t n2Idx, uint32_t s1Start) +{ + if ASCEND_IS_AIV { + if (constInfo.outputLayout == LI_LAYOUT::TND) { + uint32_t tSize = actualSeqLengthsGmQ.GetValue(constInfo.batchSize - 1); + uint32_t tBase = bIdx == 0 ? 0 : actualSeqLengthsGmQ.GetValue(bIdx - 1); + uint32_t s1Count = tempLoopInfo.actS1Size; + + for (uint32_t s1Idx = s1Start; s1Idx < s1Count; s1Idx++) { + uint64_t indiceOutOffset = + (tBase + s1Idx) * constInfo.kHeadNum * constInfo.sparseCount + // T轴、s1轴偏移 + n2Idx * constInfo.sparseCount; // N2轴偏移 + vectorService.CleanInvalidOutput(indiceOutOffset); + } + } else if (constInfo.outputLayout == LI_LAYOUT::BSND) { + for (uint32_t s1Idx = s1Start; s1Idx < constInfo.qSeqSize; s1Idx++) { + // B,S1,N2,K + uint64_t indiceOutOffset = bIdx * constInfo.qSeqSize * constInfo.kHeadNum * constInfo.sparseCount + + s1Idx * constInfo.kHeadNum * constInfo.sparseCount + // B轴、S1轴偏移 + n2Idx * constInfo.sparseCount; // N2轴偏移 + vectorService.CleanInvalidOutput(indiceOutOffset); + } + } + } +} + +template +__aicore__ inline void LightningIndexerKernel::Init(__gm__ uint8_t *query, + __gm__ uint8_t *key, __gm__ uint8_t *weights, + __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths, + __gm__ uint8_t *blockTable, __gm__ uint8_t *sparseIndices, + __gm__ uint8_t *sparseValues, + __gm__ uint8_t *workspace, const LITilingData *__restrict tiling, + TPipe *tPipe) +{ + if ASCEND_IS_AIV { + tmpBlockIdx = GetBlockIdx(); // vec:0-47 + aiCoreIdx = tmpBlockIdx / 2; + } else { + tmpBlockIdx = GetBlockIdx(); // cube:0-23 + aiCoreIdx = tmpBlockIdx; + } + + InitTilingData(tiling); + InitActualSeqLen(actualSeqLengthsQ, actualSeqLengths); + + // 计算分核 + SplitCore(aiCoreIdx, usedCoreNum, splitCoreInfo); + + pipe = tPipe; + // workspace 内存排布 + // |mm1ResGm(存S)|vec1ResGm(存LD中间结果)|vec1ParamGm(存LD参数) + // |Core0_mm1ResDB0-Core0_mm1ResDB1-Core1_mm1ResDB0....Core23_mm1ResDB0-Core23_mm1ResDB1|Core0_vec1Res... + uint64_t offset = 0; + + // mm1开DoubleBuffer + uint64_t singleCoreMm1ResSize = WS_DOUBLE * constInfo.mBaseSizeAlign * constInfo.s2BaseSize * sizeof(MM1_OUT_T); + mm1ResGm.SetGlobalBuffer((__gm__ MM1_OUT_T *)(workspace + offset + aiCoreIdx * singleCoreMm1ResSize)); + offset += GetBlockNum() * singleCoreMm1ResSize; + + // ld流程需要ws大小: [aicnum, 2, CeilDiv(constInfo.mBaseSize, constInfo.gSize), topkOut_*2] + // (aic, 8, 2, 2, 2048) + // (aic, s1_cube, 头尾, idx/value, K) + vec1ResGm.SetGlobalBuffer((__gm__ float *)(workspace + offset)); + offset += GetBlockNum() * constInfo.s1BaseSize * WS_DOUBLE * WS_DOUBLE * BASE_TOPK * sizeof(float); + + // (aic, 8, 2, 16) + // (aic, s1_cube, 头尾,16ele) + vec1ParamGm.SetGlobalBuffer((__gm__ int64_t *)(workspace + offset)); + offset += GetBlockNum() * constInfo.s1BaseSize * WS_DOUBLE * LD_PARAM_NUM * sizeof(int64_t); + + if ASCEND_IS_AIV { + vectorService.InitParams(constInfo, tiling); + indiceOutGm.SetGlobalBuffer((__gm__ int32_t *)sparseIndices); + valueOutGm.SetGlobalBuffer((__gm__ K_T *)sparseValues); + weightsGm.SetGlobalBuffer((__gm__ W_T *)weights); + vectorService.InitVec1GlobalTensor(mm1ResGm, vec1ResGm, vec1ParamGm, weightsGm, indiceOutGm, valueOutGm); + } else { + matmulService.InitParams(constInfo); + queryGm.SetGlobalBuffer((__gm__ Q_T *)query); + if constexpr (PAGE_ATTENTION) { + blockTableGm.SetGlobalBuffer((__gm__ int32_t *)blockTable); + } + keyGm.SetGlobalBuffer((__gm__ K_T *)key); + matmulService.InitMm1GlobalTensor(blockTableGm, keyGm, queryGm, mm1ResGm); + } + InitBuffers(); +} + +template +__aicore__ inline void LightningIndexerKernel::GetBN2Idx(uint32_t bN2Idx) +{ + tempLoopInfo.bN2Idx = bN2Idx; + tempLoopInfo.bIdx = bN2Idx / constInfo.kHeadNum; + tempLoopInfo.n2Idx = bN2Idx % constInfo.kHeadNum; +} + +template +__aicore__ inline void LightningIndexerKernel::CalcS2LoopParams(uint32_t bN2LoopIdx, uint32_t gS1LoopIdx) +{ + tempLoopInfo.gS1Idx = gS1LoopIdx; + tempLoopInfo.actMBaseSize = constInfo.mBaseSize; + uint32_t remainedGS1Size = tempLoopInfo.actS1Size * constInfo.gSize - tempLoopInfo.gS1Idx * constInfo.mBaseSize; + if (remainedGS1Size <= constInfo.mBaseSize && remainedGS1Size > 0) { + tempLoopInfo.actMBaseSize = tempLoopInfo.mBasicSizeTail; + } + + bool isEnd = (bN2LoopIdx == splitCoreInfo.bN2End) && (gS1LoopIdx == splitCoreInfo.gS1End); + uint32_t s2BlockNum; + if (constInfo.attenMaskFlag) { + s2BlockNum = GetS2BaseBlockNumOnMask(gS1LoopIdx, tempLoopInfo.actS1Size, tempLoopInfo.actS2Size); + } else { + s2BlockNum = (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; + } + tempLoopInfo.s2LoopEnd = isEnd ? splitCoreInfo.s2End : s2BlockNum - 1; +} + +template +__aicore__ inline void LightningIndexerKernel::CalcGS1LoopParams(uint32_t bN2LoopIdx) +{ + GetBN2Idx(bN2LoopIdx); + GetS1S2ActualSeqLen(tempLoopInfo.bIdx, tempLoopInfo.actS1Size, tempLoopInfo.actS2Size); + if ((tempLoopInfo.actS2Size == 0) || (tempLoopInfo.actS1Size == 0)) { + tempLoopInfo.curActSeqLenIsZero = true; + return; + } + tempLoopInfo.curActSeqLenIsZero = false; + tempLoopInfo.s2BasicSizeTail = tempLoopInfo.actS2Size % constInfo.s2BaseSize; + tempLoopInfo.s2BasicSizeTail = + (tempLoopInfo.s2BasicSizeTail == 0) ? constInfo.s2BaseSize : tempLoopInfo.s2BasicSizeTail; + tempLoopInfo.mBasicSizeTail = (tempLoopInfo.actS1Size * constInfo.gSize) % constInfo.mBaseSize; + tempLoopInfo.mBasicSizeTail = + (tempLoopInfo.mBasicSizeTail == 0) ? constInfo.mBaseSize : tempLoopInfo.mBasicSizeTail; + + uint32_t gS1SplitNum = (tempLoopInfo.actS1Size * constInfo.gSize + constInfo.mBaseSize - 1) / constInfo.mBaseSize; + tempLoopInfo.gS1LoopEnd = (bN2LoopIdx == splitCoreInfo.bN2End) ? splitCoreInfo.gS1End : gS1SplitNum - 1; + if constexpr (LAYOUT_T == LI_LAYOUT::BSND) { + if (tempLoopInfo.gS1LoopEnd == gS1SplitNum - 1 && constInfo.qSeqSize > tempLoopInfo.actS1Size) { + tempLoopInfo.needDealActS1LessThanS1 = true; + } + } +} + +template +__aicore__ inline void LightningIndexerKernel::CalcRunInfo(uint32_t loop, + uint32_t s2LoopIdx, LICommon::RunInfo &runInfo) +{ + runInfo.loop = loop; + runInfo.bIdx = tempLoopInfo.bIdx; + runInfo.gS1Idx = tempLoopInfo.gS1Idx; + runInfo.s2Idx = s2LoopIdx; + runInfo.bN2Idx = tempLoopInfo.bN2Idx; + + runInfo.actS1Size = tempLoopInfo.actS1Size; + runInfo.actS2Size = tempLoopInfo.actS2Size; + // 计算实际基本块size + runInfo.actMBaseSize = tempLoopInfo.actMBaseSize; + runInfo.actualSingleProcessSInnerSize = constInfo.s2BaseSize; + uint32_t s2SplitNum = (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; + if (runInfo.s2Idx == s2SplitNum - 1) { + runInfo.actualSingleProcessSInnerSize = tempLoopInfo.s2BasicSizeTail; + } + runInfo.actualSingleProcessSInnerSizeAlign = + LICommon::Align((uint32_t)runInfo.actualSingleProcessSInnerSize, LICommon::ConstInfo::BUFFER_SIZE_BYTE_32B); + + runInfo.isFirstS2InnerLoop = s2LoopIdx == splitCoreInfo.s2Start; + runInfo.isLastS2InnerLoop = s2LoopIdx == tempLoopInfo.s2LoopEnd; + runInfo.isAllLoopEnd = (runInfo.bN2Idx == splitCoreInfo.bN2End) && (runInfo.gS1Idx == splitCoreInfo.gS1End) && + (runInfo.s2Idx == splitCoreInfo.s2End); + + if (runInfo.isFirstS2InnerLoop) { + uint64_t actualSeqQPrefixSum; + uint64_t actualSeqKPrefixSum; + if constexpr (LAYOUT_T == LI_LAYOUT::TND) { + actualSeqQPrefixSum = (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsGmQ.GetValue(runInfo.bIdx - 1); + actualSeqKPrefixSum = (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsGm.GetValue(runInfo.bIdx - 1); + } else { // BSND + actualSeqQPrefixSum = (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.qSeqSize; + actualSeqKPrefixSum = (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.kSeqSize; + } + uint64_t tndBIdxOffset = actualSeqQPrefixSum * constInfo.qHeadNum * constInfo.headDim; + uint64_t tndKeyBIdxOffset = actualSeqKPrefixSum * constInfo.kHeadNum * constInfo.headDim; + // B,S1,N1(N2,G),D + queryCoreOffset = tndBIdxOffset + runInfo.gS1Idx * constInfo.mBaseSize * constInfo.headDim; + keyCoreOffset = tndKeyBIdxOffset + runInfo.n2Idx * constInfo.headDim; + // B,S1,N1(N2,G)/T,N1(N2,G) + weightsCoreOffset = actualSeqQPrefixSum * constInfo.qHeadNum + runInfo.n2Idx * constInfo.gSize; + // B,S1,N2,k/T,N2,k + indiceOutCoreOffset = actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount + + runInfo.n2Idx * constInfo.sparseCount; + } + runInfo.tensorQueryOffset = queryCoreOffset; + runInfo.tensorKeyOffset = keyCoreOffset + runInfo.s2Idx * constInfo.s2BaseSize * constInfo.kHeadNum + * constInfo.headDim; + runInfo.tensorWeightsOffset = weightsCoreOffset; + runInfo.indiceOutOffset = indiceOutCoreOffset; +} + +template +__aicore__ inline void LightningIndexerKernel::Process() +{ + if (usedCoreNum == 0) { + // 没有计算任务,直接清理输出 + ProcessInvalid(); + return; + } + ProcessMain(); + ProcessDecode(); +} + +template +__aicore__ inline void LightningIndexerKernel::ProcessInvalid() +{ + if ASCEND_IS_AIV { + uint32_t aivCoreNum = GetBlockNum() * 2; // 2 means c:v = 1:2 + uint64_t totalOutputSize = + constInfo.batchSize * constInfo.qSeqSize * constInfo.kHeadNum * constInfo.sparseCount; + uint64_t singleCoreSize = + LICommon::Align((totalOutputSize + aivCoreNum - 1) / aivCoreNum, GM_ALIGN_BYTES / sizeof(OUT_T)); + uint64_t baseSize = tmpBlockIdx * singleCoreSize; + if (baseSize < totalOutputSize) { + uint64_t dealSize = + (baseSize + singleCoreSize <= totalOutputSize) ? singleCoreSize : totalOutputSize - baseSize; + GlobalTensor output = indiceOutGm[baseSize]; + AscendC::InitGlobalMemory(output, dealSize, constInfo.INVALID_IDX); + if (constInfo.returnValue) { + event_t eventIDMTE3ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_V)); + SetFlag(eventIDMTE3ToV); + WaitFlag(eventIDMTE3ToV); + + GlobalTensor valueOutGmTmp; + valueOutGmTmp.SetGlobalBuffer((__gm__ uint16_t *)valueOutGm.GetPhyAddr()); + GlobalTensor valueOut = valueOutGmTmp[baseSize]; + + uint16_t negInf = 0; + if constexpr(std::is_same::value) { + negInf = 0xFC00; + } else { + negInf = 0xFF80; + } + AscendC::InitGlobalMemory(valueOut, dealSize, negInf); + } + } + } +} + +template +__aicore__ inline void LightningIndexerKernel::ProcessMain() +{ + if (aiCoreIdx >= usedCoreNum) { + // 无任务核直接返回 + return; + } + + if ASCEND_IS_AIV { + vectorService.AllocEventID(); + CrossCoreSetFlag(constInfo.syncV1C1); + CrossCoreSetFlag(constInfo.syncV1C1); + } else { + matmulService.AllocEventID(); + } + + LICommon::RunInfo runInfo; + uint32_t gloop = 0; + for (uint32_t bN2LoopIdx = splitCoreInfo.bN2Start; bN2LoopIdx <= splitCoreInfo.bN2End; bN2LoopIdx++) { + CalcGS1LoopParams(bN2LoopIdx); + if (tempLoopInfo.curActSeqLenIsZero) { + DealActSeqLenIsZero(tempLoopInfo.bIdx, tempLoopInfo.n2Idx, 0U); + continue; + } + for (uint32_t gS1LoopIdx = splitCoreInfo.gS1Start; gS1LoopIdx <= tempLoopInfo.gS1LoopEnd; gS1LoopIdx++) { + CalcS2LoopParams(bN2LoopIdx, gS1LoopIdx); + for (int s2LoopIdx = splitCoreInfo.s2Start; s2LoopIdx <= tempLoopInfo.s2LoopEnd; s2LoopIdx++) { + ProcessBaseBlock(gloop, s2LoopIdx, runInfo); + ++gloop; + } + splitCoreInfo.s2Start = 0; + } + if (tempLoopInfo.needDealActS1LessThanS1) { + DealActSeqLenIsZero(tempLoopInfo.bIdx, tempLoopInfo.n2Idx, tempLoopInfo.actS1Size); + } + splitCoreInfo.gS1Start = 0; + } + + if ASCEND_IS_AIV { + vectorService.FreeEventID(); + } else { + matmulService.FreeEventID(); + CrossCoreWaitFlag(constInfo.syncV1C1); + CrossCoreWaitFlag(constInfo.syncV1C1); + } +} + +template +__aicore__ inline void LightningIndexerKernel::ProcessBaseBlock(uint32_t loop, + uint64_t s2LoopIdx, LICommon::RunInfo &runInfo) +{ + CalcRunInfo(loop, s2LoopIdx, runInfo); + if ASCEND_IS_AIC { + CrossCoreWaitFlag(constInfo.syncV1C1); + matmulService.ComputeMm1(runInfo); + CrossCoreSetFlag(constInfo.syncC1V1); + } else { + CrossCoreWaitFlag(constInfo.syncC1V1); + vectorService.ProcessVec(runInfo); + CrossCoreSetFlag(constInfo.syncV1C1); + } +} + +template +__aicore__ inline void LightningIndexerKernel::ProcessDecode() +{ + if ASCEND_IS_AIV { + vectorService.InitLDBuffers(pipe); + ICachePreLoad(LD_PREFETCH_LEN); + SyncAll(); + if (splitCoreInfo.isLD) { + vectorService.ProcessLD(); + } + } +} +} // namespace LIKernel +#endif // LIGHTNING_INDEXER_KERNEL_H \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_service_cube.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_service_cube.h new file mode 100644 index 0000000000000000000000000000000000000000..329ecc546b68c722164cfb9d383760e38dafa288 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_service_cube.h @@ -0,0 +1,425 @@ +/** + * 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 lightning_indexer_service_cube.h + * \brief use 5 buffer for matmul l1, better pipeline + */ +#ifndef LIGHTNING_INDEXER_SERVICE_CUBE_H +#define LIGHTNING_INDEXER_SERVICE_CUBE_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 "../lightning_indexer_common.h" + +namespace LIKernel { +using namespace LICommon; +template +class LightningIndexerServiceCube { +public: + using Q_T = typename LIT::queryType; + using K_T = typename LIT::keyType; + + __aicore__ inline LightningIndexerServiceCube(){}; + __aicore__ inline void InitBuffers(TPipe *pipe); + __aicore__ inline void InitMm1GlobalTensor(const GlobalTensor &blkTableGm, const GlobalTensor &keyGm, + const GlobalTensor &queryGm, const GlobalTensor &mm1ResGm); + __aicore__ inline void InitParams(const ConstInfo &constInfo); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void ComputeMm1(const LICommon::RunInfo &runInfo); + + static constexpr IsResetLoad3dConfig LOAD3DV2_CONFIG = {true, true}; // isSetFMatrix isSetPadding; + static constexpr uint64_t KEY_BUF_NUM = 3; + static constexpr uint64_t QUERY_BUF_NUM = 2; + static constexpr uint64_t L0_BUF_NUM = 2; + + static constexpr uint32_t KEY_MTE1_MTE2_EVENT = EVENT_ID2; + static constexpr uint32_t QUERY_MTE1_MTE2_EVENT = EVENT_ID5; // KEY_MTE1_MTE2_EVENT + KEY_BUF_NUM; + static constexpr uint32_t M_MTE1_EVENT = EVENT_ID3; + + static constexpr uint32_t MTE2_MTE1_EVENT = EVENT_ID2; + static constexpr uint32_t MTE1_M_EVENT = EVENT_ID2; + + static constexpr uint64_t M_BASIC_BLOCK = 256; + static constexpr uint64_t D_BASIC_BLOCK = 128; + static constexpr uint64_t S2_BASIC_BLOCK = 256; + + static constexpr uint64_t M_BASIC_BLOCK_L0 = 128; + static constexpr uint64_t D_BASIC_BLOCK_L0 = 128; + static constexpr uint64_t S2_BASIC_BLOCK_L0 = 128; + + static constexpr uint64_t QUERY_BUFFER_OFFSET = M_BASIC_BLOCK * D_BASIC_BLOCK; + static constexpr uint64_t KEY_BUFFER_OFFSET = S2_BASIC_BLOCK * D_BASIC_BLOCK; + static constexpr uint64_t L0AB_BUFFER_OFFSET = M_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0; + static constexpr uint64_t L0C_BUFFER_OFFSET = M_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0; + +protected: + __aicore__ inline void Fixp(uint64_t s1gGmOffset, uint64_t s2GmOffset, uint64_t s1gL0RealSize, + uint64_t s2L0RealSize, const LICommon::RunInfo &runInfo); + __aicore__ inline void ComuteL0c(uint64_t s1gL0RealSize, uint64_t s2L0RealSize, const LICommon::RunInfo &runInfo); + __aicore__ inline void LoadKeyToL0b(uint64_t s2L0Offset, uint64_t s2L1RealSize, uint64_t s2L0RealSize, + const LICommon::RunInfo &runInfo); + __aicore__ inline void LoadQueryToL0a(uint64_t s1gL1Offset, uint64_t s1gL0Offset, uint64_t s1gL1RealSize, + uint64_t s1gL0RealSize, const LICommon::RunInfo &runInfo); + __aicore__ inline void QueryNd2Nz(uint64_t s1gL1RealSize, uint64_t s1gL1Offset, const LICommon::RunInfo &runInfo); + __aicore__ inline void KeyNd2Nz(uint64_t s2L1RealSize, uint64_t s2GmOffset, const LICommon::RunInfo &runInfo); + __aicore__ inline void KeyNd2NzForPA(uint64_t s2L1RealSize, uint64_t s2GmOffset, const LICommon::RunInfo &runInfo); + GlobalTensor blkTableGm_; + GlobalTensor keyGm_; + GlobalTensor queryGm_; + GlobalTensor mm1ResGm_; + + TBuf bufQL1_; + LocalTensor queryL1_; + TBuf bufKeyL1_; + LocalTensor keyL1_; + + TBuf bufQL0_; + LocalTensor queryL0_; + TBuf bufKeyL0_; + LocalTensor keyL0_; + + TBuf bufL0C_; + LocalTensor cL0_; + + uint64_t keyL1BufIdx_ = 0; + uint64_t queryL1Mte2BufIdx_ = 0; + uint64_t queryL1Mte1BufIdx_ = 0; + uint64_t l0BufIdx_ = 0; + + ConstInfo constInfo_; + +private: + static constexpr bool PAGE_ATTENTION = LIT::pageAttention; +}; + +template +__aicore__ inline void LightningIndexerServiceCube::InitParams(const ConstInfo &constInfo) +{ + constInfo_ = constInfo; +} + +template +__aicore__ inline void LightningIndexerServiceCube::InitBuffers(TPipe *pipe) +{ + pipe->InitBuffer(bufQL1_, QUERY_BUF_NUM * M_BASIC_BLOCK * D_BASIC_BLOCK * sizeof(Q_T)); + queryL1_ = bufQL1_.Get(); + pipe->InitBuffer(bufKeyL1_, KEY_BUF_NUM * S2_BASIC_BLOCK * D_BASIC_BLOCK * sizeof(K_T)); + keyL1_ = bufKeyL1_.Get(); + + pipe->InitBuffer(bufQL0_, L0_BUF_NUM * M_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0 * sizeof(Q_T)); + queryL0_ = bufQL0_.Get(); + pipe->InitBuffer(bufKeyL0_, L0_BUF_NUM * D_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0 * sizeof(K_T)); + keyL0_ = bufKeyL0_.Get(); + + pipe->InitBuffer(bufL0C_, L0_BUF_NUM * M_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0 * sizeof(float)); + cL0_ = bufL0C_.Get(); +} + +template +__aicore__ inline void +LightningIndexerServiceCube::InitMm1GlobalTensor(const GlobalTensor &blkTableGm, + const GlobalTensor &keyGm, + const GlobalTensor &queryGm, const GlobalTensor &mm1ResGm) +{ + blkTableGm_ = blkTableGm; + keyGm_ = keyGm; + queryGm_ = queryGm; + mm1ResGm_ = mm1ResGm; +} + +template +__aicore__ inline void LightningIndexerServiceCube::ComputeMm1(const LICommon::RunInfo &runInfo) +{ + uint64_t s2GmBaseOffset = runInfo.s2Idx * constInfo_.s2BaseSize; + uint64_t s1gProcessSize = runInfo.actMBaseSize; + uint64_t s2ProcessSize = runInfo.actualSingleProcessSInnerSize; + for (uint64_t s2GmOffset = 0; s2GmOffset < s2ProcessSize; s2GmOffset += S2_BASIC_BLOCK) { + WaitFlag(KEY_MTE1_MTE2_EVENT + keyL1BufIdx_ % KEY_BUF_NUM); + uint64_t s2L1RealSize = + s2GmOffset + S2_BASIC_BLOCK > s2ProcessSize ? s2ProcessSize - s2GmOffset : S2_BASIC_BLOCK; + if (PAGE_ATTENTION) { + KeyNd2NzForPA(s2L1RealSize, s2GmBaseOffset + s2GmOffset, runInfo); + }else { + KeyNd2Nz(s2L1RealSize, s2GmOffset, runInfo); + } + + SetFlag(MTE2_MTE1_EVENT); + WaitFlag(MTE2_MTE1_EVENT); + // s1gProcessSize当前必定不会超过2倍的s1g basic block + for (uint64_t s1gGmOffset = 0; s1gGmOffset < s1gProcessSize; s1gGmOffset += M_BASIC_BLOCK) { + uint64_t s1gL1RealSize = + s1gGmOffset + M_BASIC_BLOCK > s1gProcessSize ? s1gProcessSize - s1gGmOffset : M_BASIC_BLOCK; + if (runInfo.isFirstS2InnerLoop && s2GmOffset == 0) { + queryL1Mte2BufIdx_++; + queryL1Mte1BufIdx_ = queryL1Mte2BufIdx_; + WaitFlag(QUERY_MTE1_MTE2_EVENT + queryL1Mte2BufIdx_ % QUERY_BUF_NUM); + QueryNd2Nz(s1gL1RealSize, s1gGmOffset, runInfo); + SetFlag(MTE2_MTE1_EVENT); + WaitFlag(MTE2_MTE1_EVENT); + } else { + queryL1Mte1BufIdx_ = + queryL1Mte2BufIdx_ - (CeilDiv(s1gProcessSize, M_BASIC_BLOCK) - 1 - (s1gGmOffset > 0)); + } + for (uint64_t s2L1Offset = 0; s2L1Offset < s2L1RealSize; s2L1Offset += S2_BASIC_BLOCK_L0) { + uint64_t s2L0RealSize = + s2L1Offset + S2_BASIC_BLOCK_L0 > s2L1RealSize ? s2L1RealSize - s2L1Offset : S2_BASIC_BLOCK_L0; + for (uint64_t s1gL1Offset = 0; s1gL1Offset < s1gL1RealSize; s1gL1Offset += M_BASIC_BLOCK_L0) { + WaitFlag(M_MTE1_EVENT + l0BufIdx_ % L0_BUF_NUM); + uint64_t s1gL0RealSize = + s1gL1Offset + M_BASIC_BLOCK_L0 > s1gL1RealSize ? s1gL1RealSize - s1gL1Offset : M_BASIC_BLOCK_L0; + LoadQueryToL0a(s1gGmOffset, s1gL1Offset, s1gL1RealSize, s1gL0RealSize, runInfo); + LoadKeyToL0b(s2L1Offset, s2L1RealSize, s2L0RealSize, runInfo); + + SetFlag(MTE1_M_EVENT); + WaitFlag(MTE1_M_EVENT); + + ComuteL0c(s1gL0RealSize, s2L0RealSize, runInfo); + + SetFlag(M_MTE1_EVENT + l0BufIdx_ % L0_BUF_NUM); + + Fixp(s1gGmOffset + s1gL1Offset, s2GmOffset + s2L1Offset, s1gL0RealSize, s2L0RealSize, runInfo); + l0BufIdx_++; + } + } + if (s2GmOffset + S2_BASIC_BLOCK >= s2ProcessSize && runInfo.isLastS2InnerLoop) { + SetFlag(QUERY_MTE1_MTE2_EVENT + queryL1Mte1BufIdx_ % QUERY_BUF_NUM); + } + } + + SetFlag(KEY_MTE1_MTE2_EVENT + keyL1BufIdx_ % KEY_BUF_NUM); + keyL1BufIdx_++; + } +} + +template +__aicore__ inline void LightningIndexerServiceCube::KeyNd2Nz(uint64_t s2L1RealSize, uint64_t s2GmOffset, + const LICommon::RunInfo &runInfo) +{ + uint64_t s2L1Offset = 0; + while (s2L1Offset < s2L1RealSize) { + uint64_t keyGmOffset = runInfo.tensorKeyOffset + (s2GmOffset + s2L1Offset) * constInfo_.headDim; + // 搬运按照S2_BASIC_BLOCK_L0*D_BASIC_BLOCK_L0的方式在l1上排布, 方便后续mte1 + // 根据s2的offset判断当前属于前一个L0分型还是后一个L0分型,暂时只支持两个分型 + uint64_t s2Mte2Size = (s2L1RealSize <= S2_BASIC_BLOCK_L0 || s2L1Offset >= S2_BASIC_BLOCK_L0) ? + s2L1RealSize - s2L1Offset : + S2_BASIC_BLOCK_L0 - s2L1Offset; + + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s2Mte2Size; // 行数 + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = constInfo_.headDim; + nd2nzPara.dstNzC0Stride = s2L1Offset >= S2_BASIC_BLOCK_L0 ? + CeilAlign(s2L1RealSize - S2_BASIC_BLOCK_L0, (uint64_t)BLOCK_CUBE) : + (s2L1RealSize > S2_BASIC_BLOCK_L0 ? + S2_BASIC_BLOCK_L0 : + CeilAlign(s2L1RealSize, (uint64_t)BLOCK_CUBE)); // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(keyL1_[(keyL1BufIdx_ % KEY_BUF_NUM) * KEY_BUFFER_OFFSET + + (s2L1Offset >= S2_BASIC_BLOCK_L0 ? + S2_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0 + (s2L1Offset - S2_BASIC_BLOCK_L0) * BLOCK_CUBE : + s2L1Offset * BLOCK_CUBE)], + keyGm_[keyGmOffset], nd2nzPara); + + s2L1Offset += s2Mte2Size; + } +} + +// blkNum, blkSize, N2, D +template +__aicore__ inline void LightningIndexerServiceCube::KeyNd2NzForPA(uint64_t s2L1RealSize, uint64_t s2GmOffset, + const LICommon::RunInfo &runInfo) +{ + uint64_t s2L1Offset = 0; + while (s2L1Offset < s2L1RealSize) { + uint64_t s2BlkId = (s2L1Offset + s2GmOffset) / constInfo_.kCacheBlockSize; + uint64_t s2BlkOffset = (s2L1Offset + s2GmOffset) % constInfo_.kCacheBlockSize; + uint64_t keyGmOffset = blkTableGm_.GetValue(runInfo.bIdx * constInfo_.maxBlockNumPerBatch + s2BlkId) * + constInfo_.kCacheBlockSize * constInfo_.kHeadNum * constInfo_.headDim + + s2BlkOffset * constInfo_.headDim; + // 搬运按照S2_BASIC_BLOCK_L0*D_BASIC_BLOCK_L0的方式在l1上排布, 方便后续mte1 + // 根据s2的offset判断当前属于前一个L0分型还是后一个L0分型,暂时只支持两个分型 + uint64_t s2Mte2Size = (s2L1RealSize <= S2_BASIC_BLOCK_L0 || s2L1Offset >= S2_BASIC_BLOCK_L0) ? + s2L1RealSize - s2L1Offset : + S2_BASIC_BLOCK_L0 - s2L1Offset; + s2Mte2Size = s2BlkOffset + s2Mte2Size >= constInfo_.kCacheBlockSize ? constInfo_.kCacheBlockSize - s2BlkOffset : + s2Mte2Size; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s2Mte2Size; // 行数 + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = constInfo_.headDim; + nd2nzPara.dstNzC0Stride = s2L1Offset >= S2_BASIC_BLOCK_L0 ? + CeilAlign(s2L1RealSize - S2_BASIC_BLOCK_L0, (uint64_t)BLOCK_CUBE) : + (s2L1RealSize > S2_BASIC_BLOCK_L0 ? + S2_BASIC_BLOCK_L0 : + CeilAlign(s2L1RealSize, (uint64_t)BLOCK_CUBE)); // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(keyL1_[(keyL1BufIdx_ % KEY_BUF_NUM) * KEY_BUFFER_OFFSET + + (s2L1Offset >= S2_BASIC_BLOCK_L0 ? + S2_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0 + (s2L1Offset - S2_BASIC_BLOCK_L0) * BLOCK_CUBE : + s2L1Offset * BLOCK_CUBE)], + keyGm_[keyGmOffset], nd2nzPara); + + s2L1Offset += s2Mte2Size; + } +} + +// batch, s1, n2, g, d +template +__aicore__ inline void LightningIndexerServiceCube::QueryNd2Nz(uint64_t s1gL1RealSize, uint64_t s1gGmOffset, + const LICommon::RunInfo &runInfo) +{ + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s1gL1RealSize; // 行数 + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = constInfo_.headDim; + nd2nzPara.dstNzC0Stride = CeilAlign(s1gL1RealSize, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + // 默认一块buf最多放两份 + DataCopy(queryL1_[(queryL1Mte2BufIdx_ % QUERY_BUF_NUM) * QUERY_BUFFER_OFFSET], + queryGm_[runInfo.tensorQueryOffset + s1gGmOffset * constInfo_.headDim], nd2nzPara); +} + +template +__aicore__ inline void LightningIndexerServiceCube::LoadQueryToL0a(uint64_t s1gGmOffset, + uint64_t s1gL1Offset, uint64_t s1gL1RealSize, + uint64_t s1gL0RealSize, const LICommon::RunInfo &runInfo) +{ + LoadData3DParamsV2 loadData3DParams; + // SetFmatrixParams + loadData3DParams.l1H = CeilDiv(s1gL1RealSize, BLOCK_CUBE); // Hin=M1=8 + loadData3DParams.l1W = BLOCK_CUBE; // Win=M0 + loadData3DParams.channelSize = constInfo_.headDim; // Cin=K + + loadData3DParams.padList[0] = 0; + loadData3DParams.padList[1] = 0; + loadData3DParams.padList[2] = 0; + loadData3DParams.padList[3] = 255; // 尾部数据不影响滑窗的结果 + + // SetLoadToA0Params + loadData3DParams.mExtension = CeilAlign(s1gL0RealSize, BLOCK_CUBE); // M height维度目的 + loadData3DParams.kExtension = constInfo_.headDim; // K width维度目的 + loadData3DParams.mStartPt = s1gL1Offset; + loadData3DParams.kStartPt = 0; + loadData3DParams.strideW = 1; + loadData3DParams.strideH = 1; + loadData3DParams.filterW = 1; + loadData3DParams.filterSizeW = (1 >> 8) & 255; + loadData3DParams.filterH = 1; + loadData3DParams.filterSizeH = (1 >> 8) & 255; + loadData3DParams.dilationFilterW = 1; + loadData3DParams.dilationFilterH = 1; + loadData3DParams.enTranspose = 0; + loadData3DParams.fMatrixCtrl = 0; + + LoadData(queryL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET], + queryL1_[(queryL1Mte1BufIdx_ % QUERY_BUF_NUM) * QUERY_BUFFER_OFFSET], + loadData3DParams); +} + +template +__aicore__ inline void LightningIndexerServiceCube::LoadKeyToL0b(uint64_t s2L1Offset, + uint64_t s2L1RealSize, uint64_t s2L0RealSize, + const LICommon::RunInfo &runInfo) +{ + uint64_t keyL1Offset = s2L1Offset >= S2_BASIC_BLOCK_L0 ? S2_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0 : 0; + LoadData2DParams loadData2DParams; + loadData2DParams.startIndex = 0; + loadData2DParams.repeatTimes = CeilDiv(s2L0RealSize, BLOCK_CUBE) * CeilDiv(constInfo_.headDim, BLOCK_CUBE); + loadData2DParams.srcStride = 1; + loadData2DParams.dstGap = 0; + loadData2DParams.ifTranspose = false; + LoadData(keyL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET], + keyL1_[(keyL1BufIdx_ % KEY_BUF_NUM) * KEY_BUFFER_OFFSET + keyL1Offset], loadData2DParams); +} + +template +__aicore__ inline void LightningIndexerServiceCube::ComuteL0c(uint64_t s1gL0RealSize, uint64_t s2L0RealSize, + const LICommon::RunInfo &runInfo) +{ + MmadParams mmadParams; + mmadParams.m = CeilAlign(s1gL0RealSize, BLOCK_CUBE); + mmadParams.n = s2L0RealSize; + mmadParams.k = constInfo_.headDim; + mmadParams.cmatrixInitVal = true; + mmadParams.cmatrixSource = false; + mmadParams.unitFlag = 0b11; + Mmad(cL0_[(l0BufIdx_ % L0_BUF_NUM) * L0C_BUFFER_OFFSET], queryL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET], + keyL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET], mmadParams); + if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { + PipeBarrier(); + } +} + +template +__aicore__ inline void LightningIndexerServiceCube::Fixp(uint64_t s1gGmOffset, + uint64_t s2GmOffset, uint64_t s1gL0RealSize, + uint64_t s2L0RealSize, const LICommon::RunInfo &runInfo) +{ + AscendC::DataCopyCO12DstParams intriParams; + intriParams.mSize = CeilAlign(s1gL0RealSize, BLOCK_CUBE); + intriParams.nSize = s2L0RealSize; + intriParams.dstStride = runInfo.actualSingleProcessSInnerSizeAlign; + intriParams.srcStride = CeilAlign(s1gL0RealSize, BLOCK_CUBE); + // set mode according to dtype + intriParams.quantPre = QuantMode_t::NoQuant; + intriParams.nz2ndEn = true; + intriParams.unitFlag = 0b11; // 3 unitflag + intriParams.reluPre = 1; + AscendC::SetFixpipeNz2ndFlag(1, 1, 1); + AscendC::DataCopy(mm1ResGm_[(runInfo.loop % 2) * constInfo_.mBaseSizeAlign * constInfo_.s2BaseSize + + s1gGmOffset * intriParams.dstStride + s2GmOffset], + cL0_[(l0BufIdx_ % L0_BUF_NUM) * L0C_BUFFER_OFFSET], intriParams); +} + +template +__aicore__ inline void LightningIndexerServiceCube::AllocEventID() +{ + SetMMLayoutTransform(true); + SetFlag(KEY_MTE1_MTE2_EVENT + 0); + SetFlag(KEY_MTE1_MTE2_EVENT + 1); + SetFlag(KEY_MTE1_MTE2_EVENT + 2); + + SetFlag(QUERY_MTE1_MTE2_EVENT + 0); + SetFlag(QUERY_MTE1_MTE2_EVENT + 1); + + SetFlag(M_MTE1_EVENT + 0); + SetFlag(M_MTE1_EVENT + 1); +} + +template +__aicore__ inline void LightningIndexerServiceCube::FreeEventID() +{ + SetMMLayoutTransform(false); + WaitFlag(KEY_MTE1_MTE2_EVENT + 0); + WaitFlag(KEY_MTE1_MTE2_EVENT + 1); + WaitFlag(KEY_MTE1_MTE2_EVENT + 2); + + WaitFlag(QUERY_MTE1_MTE2_EVENT + 0); + WaitFlag(QUERY_MTE1_MTE2_EVENT + 1); + + WaitFlag(M_MTE1_EVENT + 0); + WaitFlag(M_MTE1_EVENT + 1); +} +} // namespace LIKernel +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_service_vector.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_service_vector.h new file mode 100644 index 0000000000000000000000000000000000000000..77890fe76d7fe26ce203f3cc246ed14602cf557d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_service_vector.h @@ -0,0 +1,706 @@ +/** + * 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 lightning_indexer_service_vector.h + * \brief + */ +#ifndef LIGHTNING_INDEXER_SERVICE_VECTOR_H +#define LIGHTNING_INDEXER_SERVICE_VECTOR_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 "../lightning_indexer_common.h" +#include "lightning_indexer_vector.h" + +namespace LIKernel { +using namespace LICommon; +using namespace LIServiceVec; +constexpr uint32_t BASE_TOPK = 2048; +constexpr uint32_t SPARSE_COUNT_4K = 4096; +constexpr uint32_t LD_PARAM_NUM = 16; +constexpr uint32_t EVENTID_V_TO_MTE2_PING = 0; +constexpr uint32_t EVENTID_V_TO_MTE2_PONG = 1; +constexpr uint32_t EVENTID_V_TO_MTE2_TMPUB = 2; + +// 主模板:Q_T必选,W_T可选(默认void),无论W_T传什么,默认weightsType=Q_T +template +struct LightningIndexerTypeTraits { + using weightsType = Q_T; // 默认:weightsType绑定Q_T +}; + +// 偏特化1:固定第二个参数W_T=float,Q_T保留泛型 +template +struct LightningIndexerTypeTraits { + using weightsType = float; // W_T=float时,强制weightsType为float +}; + +template +class LightningIndexerServiceVector { +public: + // =================================类型定义区================================= + // 中间计算数据类型为float,高精度模式 + static constexpr bool DT_W_FLAG = LIT::weightsTypeFlag; + using Q_T = typename LIT::queryType; + using K_T = typename LIT::keyType; + static constexpr LI_LAYOUT LAYOUT_T = LIT::layout; + using W_T = typename LightningIndexerTypeTraits::type>::weightsType; + + // MM输出数据类型, 当前只支持float + using MM1_OUT_T = float; + + __aicore__ inline LightningIndexerServiceVector(){}; + __aicore__ inline void ProcessVec(const LICommon::RunInfo &info); + __aicore__ inline void ProcessLD(); + __aicore__ inline void InitBuffers(TPipe *pipe); + __aicore__ inline void InitParams(const struct LICommon::ConstInfo &constInfo, + const LITilingData *__restrict tilingData); + __aicore__ inline void InitVec1GlobalTensor(GlobalTensor mm1ResGm, GlobalTensor vec1ResGm, + GlobalTensor vec1ParamGm, GlobalTensor weightsGm, + GlobalTensor indiceOutGm, GlobalTensor valueOutGm); + __aicore__ inline void CleanInvalidOutput(int64_t invalidS1offset); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void InitLDBuffers(TPipe *pipe); + +protected: + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor vec1ParamGm; + GlobalTensor weightsGm; + GlobalTensor indiceOutGm; + GlobalTensor valueOutGm; + // =================================常量区================================= + +private: + // ================================Local Buffer区==================================== + // queue + TQue outQueue_; + + // tmp buff for vector + TBuf sortOutBuf_; + TBuf tmpBuf_; + TBuf indexBuf_; + TBuf reduceOutBuf_; + TBuf brcBuf_; + TBuf paramBuf_; + + // tmp buff for LD + TBuf<> ldToBeMrgBuf_; + TBuf<> ldTmpBuf_; + TBuf<> ldOutValueBuf_; + TBuf<> ldOutIdxBuf_; + + LocalTensor tmpUb_; + LocalTensor globalTopkIndice_; + LocalTensor globalTopkUb_; + LocalTensor SortedBasicBlock_; + + int32_t blockId_ = -1; + // para for vector + int32_t groupInner_ = 0; + int32_t globalTopkNum_ = 0; + int64_t blockS2StartIdx_ = 0; + int32_t gSize_ = 0; + int32_t kHeadNum_ = 0; + int32_t s1BaseSize_ = 0; + int32_t s2BaseSize_ = 0; + + // para for LD + uint32_t mrgListNum_ = 4; + uint32_t paramNum_ = 16; + int32_t virTopK = 0; + + constexpr static uint32_t REDUCE_BANK_CONFLICT_OFFSETS = 256; + constexpr static uint32_t REDUCE_BANK_CONFLICT_NUM = REDUCE_BANK_CONFLICT_OFFSETS / sizeof(float); + + struct LICommon::ConstInfo constInfo_; +}; + +template +__aicore__ inline void LightningIndexerServiceVector::InitBuffers(TPipe *pipe) +{ + uint32_t outNeedBufSize = (BASE_TOPK * 2) * 2 * sizeof(float); + uint32_t reduceCacheSize = REDUCE_BANK_CONFLICT_OFFSETS + groupInner_ * s2BaseSize_ * sizeof(float); + outNeedBufSize = reduceCacheSize > outNeedBufSize ? reduceCacheSize : outNeedBufSize; + virTopK = constInfo_.isSparseCountOver2K ? constInfo_.sparseCount : BASE_TOPK; + + pipe->InitBuffer(outQueue_, 1, outNeedBufSize); // 32KB extract + // 68KB 在搬运cube核计算得到的结果和weight时,分成两块34KB,用于db;在mrgsort时,用作临时UB + pipe->InitBuffer(tmpBuf_, (groupInner_ * s2BaseSize_ + s2BaseSize_) * 2 * sizeof(float)); + pipe->InitBuffer(sortOutBuf_, CeilDiv(s1BaseSize_, 2) * virTopK * 2 * sizeof(float)); // 64KB + pipe->InitBuffer(indexBuf_, s2BaseSize_ * sizeof(int32_t)); // 2KB + pipe->InitBuffer(reduceOutBuf_, s2BaseSize_ * 2 * sizeof(float)); // 4KB + pipe->InitBuffer(brcBuf_, groupInner_ * 8 * sizeof(float)); + pipe->InitBuffer(paramBuf_, LD_PARAM_NUM * sizeof(int64_t)); + + tmpUb_ = tmpBuf_.Get(); + globalTopkIndice_ = indexBuf_.Get(); + globalTopkUb_ = sortOutBuf_.Get(); + SortedBasicBlock_ = globalTopkUb_[virTopK * 2 * 2]; + globalTopkNum_ = 0; + + // 基本块执行前初始化UB和GM + // step1. 初始化一个有序索引 0 - s2BaseSize_ + ArithProgression(globalTopkIndice_, 0, 1, s2BaseSize_); + // step2. globalTopkUb_ [CeilDiv(s1BaseSize_, 2), BASE_TOPK, 2] -inf,-1 + InitSortOutBuf(globalTopkUb_, CeilDiv(s1BaseSize_, 2) * virTopK * 2); + + // step3. 初始化vec1ParamGm,是否进行LD的标志位设为-1(needFd=-1) + // vec1ResIn32Gm = [aic, 2, s1BaseSize_, 16] int32 + // ws清零 [needFd, s2AcSeq, s2Start, s2End, isS2End, bn2idx, s1Idx, ......] + LocalTensor tmpBuff = outQueue_.AllocTensor(); + Duplicate(tmpBuff.template ReinterpretCast(), -1, 2 * (s1BaseSize_ / 2) * paramNum_ * 2); + outQueue_.EnQue(tmpBuff); + tmpBuff = outQueue_.DeQue(); + int64_t wsInfoOffset = (blockId_ / 2) * s1BaseSize_ * 2 * paramNum_ + // 2个AIV共同地址偏移 + (blockId_ % 2) * (s1BaseSize_ / 2) * 2 * paramNum_; // 每个AIV的地址偏移,S1方向 + DataCopyPad(vec1ParamGm[wsInfoOffset], tmpBuff.template ReinterpretCast(), + {1, static_cast((s1BaseSize_ / 2) * 2 * paramNum_ * sizeof(int64_t)), 0, 0}); + outQueue_.FreeTensor(tmpBuff); +} + +template +__aicore__ inline void LightningIndexerServiceVector::InitLDBuffers(TPipe *pipe) +{ + pipe->Reset(); + pipe->InitBuffer(ldToBeMrgBuf_, 2 * BASE_TOPK * mrgListNum_ * sizeof(float)); // 2:value + index + pipe->InitBuffer(ldTmpBuf_, 2 * BASE_TOPK * mrgListNum_ * sizeof(float)); // 2:value + index + pipe->InitBuffer(ldOutValueBuf_, BASE_TOPK * sizeof(float)); + pipe->InitBuffer(ldOutIdxBuf_, BASE_TOPK * sizeof(int32_t)); +} + +template +__aicore__ inline void LightningIndexerServiceVector::InitParams(const struct LICommon::ConstInfo &constInfo, + const LITilingData *__restrict tilingData) +{ + this->constInfo_ = constInfo; + blockS2StartIdx_ = 0; + gSize_ = constInfo.gSize; + // define N2 para + kHeadNum_ = constInfo.kHeadNum; + // define MMBase para + s1BaseSize_ = constInfo.s1BaseSize; + s2BaseSize_ = constInfo.s2BaseSize; + + // group ub 切分因子当前按照UB空间强制为16 + groupInner_ = 16; + + blockId_ = GetBlockIdx(); +} + +template +__aicore__ inline void +LightningIndexerServiceVector::InitVec1GlobalTensor(GlobalTensor mm1ResGm, + GlobalTensor vec1ResGm, + GlobalTensor vec1ParamGm, GlobalTensor weightsGm, + GlobalTensor indiceOutGm, GlobalTensor valueOutGm) +{ + this->mm1ResGm = mm1ResGm; + this->vec1ResGm = vec1ResGm; + this->vec1ParamGm = vec1ParamGm; + this->weightsGm = weightsGm; + this->indiceOutGm = indiceOutGm; + this->valueOutGm = valueOutGm; +} + +template +__aicore__ inline void LightningIndexerServiceVector::AllocEventID() +{ + SetFlag(EVENTID_V_TO_MTE2_PING); + SetFlag(EVENTID_V_TO_MTE2_PONG); + SetFlag(EVENTID_V_TO_MTE2_TMPUB); +} + +template +__aicore__ inline void LightningIndexerServiceVector::FreeEventID() +{ + WaitFlag(EVENTID_V_TO_MTE2_PING); + WaitFlag(EVENTID_V_TO_MTE2_PONG); + WaitFlag(EVENTID_V_TO_MTE2_TMPUB); +} + +template +__aicore__ inline void LightningIndexerServiceVector::CleanInvalidOutput(int64_t invalidS1offset) +{ + // init -1 and copy to output + LocalTensor valueULocal = outQueue_.AllocTensor(); + LocalTensor idxULocal1 = valueULocal.template ReinterpretCast(); + Duplicate(idxULocal1, constInfo_.INVALID_IDX, constInfo_.sparseCount); + outQueue_.EnQue(valueULocal); + valueULocal = outQueue_.DeQue(); + LIServiceVec::CopyOut(indiceOutGm[invalidS1offset], idxULocal1, constInfo_.sparseCount); + outQueue_.FreeTensor(valueULocal); + + if (constInfo_.returnValue) { + uint16_t negInf = 0; + if constexpr(std::is_same::value) { + negInf = 0xFC00; + } else { + negInf = 0xFF80; + } + LocalTensor valueULocal = outQueue_.AllocTensor(); + Duplicate(valueULocal, negInf, constInfo_.sparseCount); + outQueue_.EnQue(valueULocal); + valueULocal = outQueue_.DeQue(); + GlobalTensor valueOutGmTmp; + valueOutGmTmp.SetGlobalBuffer((__gm__ uint16_t *)valueOutGm.GetPhyAddr()); + LIServiceVec::CopyOut(valueOutGmTmp[invalidS1offset], valueULocal, constInfo_.sparseCount); + outQueue_.FreeTensor(valueULocal); + } +} + +template +__aicore__ inline void LightningIndexerServiceVector::ProcessVec(const LICommon::RunInfo &info) +{ + int32_t cuBaseS1Idx = info.gS1Idx * s1BaseSize_; + int32_t cuBaseS2Idx = info.s2Idx * s2BaseSize_; + + // 计算基本块基地址偏移 偶数循环 -> 0 + aic_offset 奇数循环 -> 512*512 + aic_offset + int64_t mmGmOffset = (info.loop % 2) * (constInfo_.mBaseSizeAlign * s2BaseSize_); + // (B,S1,N1,1);(T,N1,1) -> (B,S1,N2,G,1) 当前只切分到S1轴 + int64_t weightGmOffset = info.tensorWeightsOffset + cuBaseS1Idx * kHeadNum_ * gSize_; + + PipeBarrier(); + // cuS1BeginIdxPerAiv: 每个AIV的S1起始偏移 + int32_t cuS1BeginIdxPerAiv = cuBaseS1Idx; + int32_t cuS1ProcNum = + cuS1BeginIdxPerAiv + s1BaseSize_ > info.actS1Size ? info.actS1Size % s1BaseSize_ : s1BaseSize_; + // cuS1ProcNumPerAiv: 每个AIv的S1计算量 + int32_t cuS1ProcNumPerAiv = blockId_ % 2 == 0 ? CeilDiv(cuS1ProcNum, 2) : (cuS1ProcNum / 2); + cuS1BeginIdxPerAiv += (blockId_ % 2) * CeilDiv(cuS1ProcNum, 2); + + // 基本块基地址偏移奇数核加一个S1地址偏移 + weightGmOffset += (blockId_ % 2) * CeilDiv(cuS1ProcNum, 2) * kHeadNum_ * gSize_; + mmGmOffset += (blockId_ % 2) * CeilDiv(cuS1ProcNum, 2) * gSize_ * info.actualSingleProcessSInnerSizeAlign; + + // cut G + int32_t outerG = CeilDiv(gSize_, groupInner_); + + // 非首个基本块, M(S1)轴发生切换需要初始化 + if (info.loop != 0 && info.s2Idx == 0) { + // globalTopkUb_ value,index=-inf,-1 + InitSortOutBuf(globalTopkUb_, CeilDiv(s1BaseSize_, 2) * virTopK * 2); + blockS2StartIdx_ = 0; + } else if (info.loop == 0) { + blockS2StartIdx_ = info.s2Idx; + } + // cuRealAcSeq: 当前基本块S1对应的AcSeq + int32_t cuRealAcSeq = info.actS2Size; + if (constInfo_.attenMaskFlag) { + // attenMask true场景 + cuRealAcSeq = info.actS2Size - (info.actS1Size - cuS1BeginIdxPerAiv); + } + LocalTensor reduceOutBuff = reduceOutBuf_.Get(); + LocalTensor brcBuf = brcBuf_.Get(); + // LD输出S1方向偏移,保证2个Vector输出的内容连续 + uint32_t ldS1Offset = (blockId_ % 2 == 0) ? s1BaseSize_ / 2 - cuS1ProcNumPerAiv : 0; + for (int innerS1Idx = 0; innerS1Idx < cuS1ProcNumPerAiv; innerS1Idx++) { + if (constInfo_.attenMaskFlag) { + cuRealAcSeq += 1; + } + int32_t cuS2Len = cuBaseS2Idx + s2BaseSize_ >= cuRealAcSeq ? cuRealAcSeq - cuBaseS2Idx : s2BaseSize_; + int32_t cuS1Idx = cuS1BeginIdxPerAiv + innerS1Idx; + if (cuRealAcSeq > 0 && cuS2Len > 0) { + int32_t cuS2LenVecAlign = CeilDiv(cuS2Len, s2BaseSize_) * s2BaseSize_; + int32_t mmUbStride = (cuS2LenVecAlign - info.actualSingleProcessSInnerSizeAlign) / B32_BLOCK_ALIGN_NUM; + LocalTensor reduceOutInner = reduceOutBuff[s2BaseSize_]; + PipeBarrier(); + LocalTensor reduceCacheBuf = outQueue_.AllocTensor(); + if (constInfo_.isSparseCountOver2K) { + WaitFlag(EVENTID_V_TO_MTE2_TMPUB); + } + for (int outerGidx = 0; outerGidx < outerG; outerGidx++) { + int32_t procGnum = outerGidx != outerG - 1 ? groupInner_ : gSize_ - outerGidx * groupInner_; + + int32_t pingpong = outerGidx % 2; + LocalTensor dbTmpUb = tmpUb_[pingpong * (groupInner_ * s2BaseSize_ + s2BaseSize_)]; + LocalTensor weightsInUb = dbTmpUb[procGnum * s2BaseSize_]; + WaitFlag(pingpong); + LocalTensor weightsInTUb = weightsInUb.template ReinterpretCast(); + if constexpr (!IsSameType::value) { + weightsInTUb = weightsInTUb[groupInner_]; + } + int64_t mmGmAllOffet = mmGmOffset + innerS1Idx * gSize_ * info.actualSingleProcessSInnerSizeAlign + + outerGidx * groupInner_ * info.actualSingleProcessSInnerSizeAlign; + int64_t weightGmAllOffset = weightGmOffset + innerS1Idx * gSize_ + outerGidx * groupInner_; + + LIServiceVec::CopyIn(dbTmpUb, weightsInTUb, mm1ResGm, weightsGm, mmGmAllOffet, weightGmAllOffset, + procGnum, info.actualSingleProcessSInnerSizeAlign, mmUbStride); + + SetFlag(pingpong); + WaitFlag(pingpong); + LIServiceVec::DoScale(reduceCacheBuf[REDUCE_BANK_CONFLICT_NUM], dbTmpUb, weightsInUb, weightsInTUb, + brcBuf, procGnum, s2BaseSize_, outerGidx); + // confused reduceOp in DoScale + // neednot use LIServiceVec::doReduce(mmInUb, reduceOutInner, procGnum, (s2BaseSize_+8)); + SetFlag(pingpong); + } + + int32_t gRedCnt = groupInner_ > gSize_ ? gSize_ : groupInner_; + bool isS2End = cuBaseS2Idx + s2BaseSize_ >= cuRealAcSeq; + LIServiceVec::DoReduce(reduceCacheBuf[REDUCE_BANK_CONFLICT_NUM], reduceOutInner, gRedCnt, s2BaseSize_); + outQueue_.FreeTensor(reduceCacheBuf); + + LocalTensor sortScoreUb = reduceOutBuff; + LocalTensor sortIndiceUb = reduceOutBuff[cuS2LenVecAlign]; + Duplicate(sortScoreUb.template ReinterpretCast(), LIServiceVec::NEG_INF, cuS2LenVecAlign); + PipeBarrier(); + Adds(sortScoreUb, reduceOutInner, 0.0f, cuS2Len); + PipeBarrier(); + LocalTensor sortIndiceUbInt = sortIndiceUb.template ReinterpretCast(); + // 无效数据索引填充为-1 + if (cuS2LenVecAlign != cuS2Len) { + Duplicate(sortIndiceUbInt, -1, cuS2LenVecAlign); + } + PipeBarrier(); + Adds(sortIndiceUbInt, globalTopkIndice_, static_cast(cuBaseS2Idx), cuS2Len); + PipeBarrier(); + + LocalTensor tmpSortBuf = outQueue_.AllocTensor(); + if (info.actS1Size > 4 || constInfo_.isSparseCountOver2K) { + // info.actS1Size > 4 则单个vector核内处理的 s1>2,缓存方案无法处理 + LIServiceVec::SortAll(reduceOutBuff, tmpSortBuf, + cuS2LenVecAlign); // cuS2LenVecAlign <= s2BaseSize_, fill -inf + PipeBarrier(); + LocalTensor UbTmpSort = constInfo_.isSparseCountOver2K ? tmpUb_ : tmpSortBuf; + LIServiceVec::MergeSort(globalTopkUb_[innerS1Idx * virTopK * 2], virTopK, reduceOutBuff, + cuS2LenVecAlign, UbTmpSort); + } else { + int64_t globalTopkUbCacheIdx = (info.s2Idx - blockS2StartIdx_) % 4; + Sort( + SortedBasicBlock_[innerS1Idx * BASE_TOPK * 2 + globalTopkUbCacheIdx * s2BaseSize_ * 2], + reduceOutBuff, sortIndiceUbInt.template ReinterpretCast(), tmpSortBuf, + cuS2LenVecAlign / 32); + AscendC::PipeBarrier(); + // 缓存4块512或者S2结束, 需要进行精排 + if (globalTopkUbCacheIdx == 3 || isS2End || info.isAllLoopEnd) { + LocalTensor tt = SortedBasicBlock_[innerS1Idx * BASE_TOPK * 2]; + // 前4块直接精排覆盖到globalTopkUb_ + if (info.s2Idx - blockS2StartIdx_ < 4) { + MrgBasicBlock(globalTopkUb_[innerS1Idx * BASE_TOPK * 2], tt, + static_cast(globalTopkUbCacheIdx + 1), s2BaseSize_); + } else { // 后面缓存在 SortedBasicBlock_, 先精排, 再merge到globalTopkUb_ + if (globalTopkUbCacheIdx > 0) { + MrgBasicBlock(tmpSortBuf, tt, static_cast(globalTopkUbCacheIdx + 1), s2BaseSize_); + PipeBarrier(); + DataCopy(SortedBasicBlock_[innerS1Idx * BASE_TOPK * 2], tmpSortBuf, + (globalTopkUbCacheIdx + 1) * s2BaseSize_ * 2); + } + PipeBarrier(); + SparseTopK(globalTopkUb_[innerS1Idx * BASE_TOPK * 2], + SortedBasicBlock_[innerS1Idx * BASE_TOPK * 2], tmpSortBuf, BASE_TOPK, + s2BaseSize_ * (globalTopkUbCacheIdx + 1)); + } + } + } + if (constInfo_.isSparseCountOver2K) { + SetFlag(EVENTID_V_TO_MTE2_TMPUB); + } + + PipeBarrier(); + outQueue_.FreeTensor(tmpSortBuf); + + bool needCopyOutGm = blockS2StartIdx_ == 0 && isS2End; + + // 中间结果保存 + bool needCopyWsGm = info.isAllLoopEnd || isS2End; + + if (needCopyOutGm) { + int64_t offset = (constInfo_.sparseCount <= SPARSE_COUNT_4K) ? virTopK : constInfo_.sparseCount / 2; + int64_t copyLen = (constInfo_.sparseCount <= SPARSE_COUNT_4K) + ? constInfo_.sparseCount + : constInfo_.sparseCount / 2; + int64_t copyNum = (constInfo_.sparseCount <= SPARSE_COUNT_4K) ? 1 : 2; + for (int64_t i = 0; i < copyNum; i++) { + LocalTensor outValueUb = outQueue_.AllocTensor(); + LocalTensor outIdxUb = outValueUb[offset].template ReinterpretCast(); + Extract(outValueUb, outIdxUb, + globalTopkUb_[innerS1Idx * virTopK * 2 + 2 * i * offset], (offset /32)); + + LocalTensor valueULocal1 = outValueUb.template ReinterpretCast(); + if (constInfo_.returnValue) { + PipeBarrier(); + Cast(valueULocal1, outValueUb, RoundMode::CAST_ROUND, copyLen); + } + + LocalTensor idxULocal1 = outValueUb[offset].template ReinterpretCast(); + outQueue_.EnQue(outValueUb); + outValueUb = outQueue_.DeQue(); + + LIServiceVec::CopyOut(indiceOutGm[info.indiceOutOffset + cuS1Idx * + constInfo_.sparseCount + i * offset], + idxULocal1, copyLen); + if (constInfo_.returnValue) { + LIServiceVec::CopyOut(valueOutGm[info.indiceOutOffset + cuS1Idx * + constInfo_.sparseCount + i * offset], + valueULocal1, copyLen); + } + outQueue_.FreeTensor(outValueUb); + } + } else if (needCopyWsGm) { + // vec1Res Gm = [aic, s1BaseSize_, 2, 2, topkOut_] float32 + // vec1Param Gm = [aic, s1BaseSize_, 2, 16] int64 + // 16 = [needFd, s2AcSeq, s2Start, s2End, isS2End, bn2idx, s1Idx, S1ProcNum, ......] + + int64_t wsOffset = (blockId_ / 2) * s1BaseSize_ * 2 * 2 * BASE_TOPK + // 2个AIV共同地址偏移 + (blockId_ % 2) * (s1BaseSize_ / 2) * 2 * 2 * BASE_TOPK + // 每个AIV的地址偏移,S1方向 + (ldS1Offset + innerS1Idx) * 2 * 2 * BASE_TOPK; + int64_t wsInfoOffset = (blockId_ / 2) * s1BaseSize_ * 2 * paramNum_ + // 2个AIV共同地址偏移 + (blockId_ % 2) * (s1BaseSize_ / 2) * 2 * paramNum_ + // 每个AIV的地址偏移,S1方向 + (ldS1Offset + innerS1Idx) * 2 * paramNum_; + + LocalTensor tmpiBuff = paramBuf_.Get(); + SetWaitFlag(HardEvent::MTE3_S); + tmpiBuff.SetValue(0, static_cast(1)); + tmpiBuff.SetValue(1, static_cast(cuRealAcSeq)); + tmpiBuff.SetValue(2, static_cast(blockS2StartIdx_)); + tmpiBuff.SetValue(3, static_cast(cuBaseS2Idx + cuS2Len)); + tmpiBuff.SetValue(4, static_cast(isS2End)); + tmpiBuff.SetValue(5, static_cast(info.bN2Idx)); + tmpiBuff.SetValue(6, static_cast(cuS1Idx)); + tmpiBuff.SetValue(7, static_cast(cuS1ProcNum)); + tmpiBuff.SetValue(8, static_cast(info.indiceOutOffset + cuS1Idx * constInfo_.sparseCount)); + // 写入头尾判断 + // [head, tail] + // head: 与前面规约,与前后规约 + // tail: 与后面规约 + bool isTailReduce = blockS2StartIdx_ == 0; // 一定是isLastTile + // WS偏移规则 blockS2StartIdx_ != 0 + // 跟前面块做规约 写到0偏移 不用做计算 blockS2StartIdx_ == 0 and !isS2End + // 跟后面块做规约 写到1偏移 需要 + s1BaseSize_, BASE_TOPK*2 + if (isTailReduce) { // S2不是最后结束的数据就需要往后做规约,放入第二块ws + wsInfoOffset += paramNum_; + wsOffset += 2 * BASE_TOPK; + } + SetWaitFlag(HardEvent::S_MTE3); + LIServiceVec::CopyOut(vec1ParamGm[wsInfoOffset], tmpiBuff, 16); + SetWaitFlag(HardEvent::V_MTE3); + LIServiceVec::CopyOut(vec1ResGm[wsOffset], globalTopkUb_[innerS1Idx * BASE_TOPK * 2], 2 * BASE_TOPK); + SetWaitFlag(HardEvent::MTE3_V); + } + } else if (cuRealAcSeq <= 0) { + CleanInvalidOutput(info.indiceOutOffset + cuS1Idx * constInfo_.sparseCount); + } + } + + // BNSD场景无效S1 输出-1 + if (LAYOUT_T == LI_LAYOUT::BSND) { + // 最后一个S1的基本块, 需要 >= info.actS1Size + bool isS1LoopEnd = (cuBaseS1Idx + s1BaseSize_) >= info.actS1Size; + int32_t invalidS1Num = constInfo_.qSeqSize - info.actS1Size; + // blockS2StartIdx_ == 0 控制S2从开始的核去做冗余清理 + if (invalidS1Num > 0 && isS1LoopEnd && blockS2StartIdx_ == 0) { + int32_t s1NumPerAiv = blockId_ % 2 == 0 ? CeilDiv(invalidS1Num, 2) : (invalidS1Num / 2); + int32_t s1OffsetPerAiv = info.actS1Size + (blockId_ % 2) * CeilDiv(invalidS1Num, 2); + for (int innerS1Idx = 0; innerS1Idx < s1NumPerAiv; innerS1Idx++) { + CleanInvalidOutput(info.indiceOutOffset + (s1OffsetPerAiv + innerS1Idx) * constInfo_.sparseCount); + } + } + + int32_t invalidS1Num2 = info.actS1Size - info.actS2Size; + if (invalidS1Num2 > 0 && isS1LoopEnd && blockS2StartIdx_ == 0 && constInfo_.attenMaskFlag) { + int32_t s1NumPerAiv = blockId_ % 2 == 0 ? CeilDiv(invalidS1Num2, 2) : (invalidS1Num2 / 2); + int32_t s1OffsetPerAiv = (blockId_ % 2) * CeilDiv(invalidS1Num2, 2); + for (int innerS1Idx = 0; innerS1Idx < s1NumPerAiv; innerS1Idx++) { + CleanInvalidOutput((info.bN2Idx * constInfo_.qSeqSize + s1OffsetPerAiv + innerS1Idx) * + constInfo_.sparseCount); + } + } + } + + if (info.isLastS2InnerLoop) { + // S2最后一个Loop后, 下一个基本块初始从0开始 + blockS2StartIdx_ = 0; + } +} + +template +__aicore__ inline void LightningIndexerServiceVector::ProcessLD() +{ + int32_t curCubeId = blockId_ / 2; + int32_t tmpCubeId = curCubeId; + + int64_t s2ActSeq; + int64_t s2Start; + int64_t s2End; + int64_t isS2End; + int64_t bn2Idx; + int64_t s1Idx; + uint32_t acc_list_num = 0; + int64_t bIdx = 0; + int64_t needFd; + int64_t wsOffset; + int64_t wsInfoOffset = 0; + int64_t nextneedFd; + int64_t valueOffset = 0; + int64_t outOffset = 0; + + LocalTensor curValueIdxUb = ldToBeMrgBuf_.Get(); + LocalTensor tmpUb = ldTmpBuf_.Get(); + + // S2开头信息 + // 开始必然没有头规约,因此从尾规约开始处理,while循环读取下一个核的头规约 + // 存满4个list或者遇到S2结尾,则做merge,直到做完S2 + // 每个核都忽略自己的头规约,因为必然由前面的核做完 + uint32_t s1LdStartIdx = 0; + uint32_t s1ProcNum = 0; + uint64_t paramGmCoreOffset = tmpCubeId * s1BaseSize_ * 2 * paramNum_; + for (uint32_t innerS1Idx = 0; innerS1Idx < s1BaseSize_; innerS1Idx++) { + needFd = vec1ParamGm.GetValue(paramGmCoreOffset + innerS1Idx * 2 * paramNum_ + paramNum_); + if (needFd == 1) { + s1LdStartIdx = (s1ProcNum == 0) ? innerS1Idx : s1LdStartIdx; + s1ProcNum++; + } + } + + if (s1ProcNum == 0) { + return; + } + + // S1逐行计算 + uint32_t s1VecNum = CeilDiv(s1ProcNum, 2); + if (blockId_ % 2 == 1) { + s1LdStartIdx = s1LdStartIdx + s1VecNum; + s1VecNum = s1ProcNum - s1VecNum; + } + for (uint32_t innerS1Idx = s1LdStartIdx; innerS1Idx < s1LdStartIdx + s1VecNum; innerS1Idx++) { + // 重置偏移 + tmpCubeId = curCubeId; + acc_list_num = 0; + valueOffset = 0; + + // 搬入数据 + wsOffset = tmpCubeId * s1BaseSize_ * 2 * 2 * BASE_TOPK + // 2个AIV共同地址偏移 + innerS1Idx * 2 * 2 * BASE_TOPK + 2 * BASE_TOPK; + SetWaitFlag(HardEvent::V_MTE2); + SetWaitFlag(HardEvent::S_MTE2); + DataCopyPad(curValueIdxUb, vec1ResGm[wsOffset], + {1, static_cast(2 * BASE_TOPK * sizeof(int32_t)), 0, 0}, {true, 0, 0, 0}); + acc_list_num++; + valueOffset += 2 * BASE_TOPK; + + // 获取下一个核规约信息 + tmpCubeId++; + wsInfoOffset = tmpCubeId * s1BaseSize_ * 2 * paramNum_ + innerS1Idx * 2 * paramNum_; + needFd = vec1ParamGm.GetValue(wsInfoOffset); + isS2End = vec1ParamGm.GetValue(wsInfoOffset + 4); + s1Idx = vec1ParamGm.GetValue(wsInfoOffset + 6); + outOffset = vec1ParamGm.GetValue(wsInfoOffset + 8); + + while (needFd == 1) { + // 搬入头规约数据 + wsOffset = tmpCubeId * s1BaseSize_ * 2 * 2 * BASE_TOPK + // 2个AIV共同地址偏移 + innerS1Idx * 2 * 2 * BASE_TOPK; + SetWaitFlag(HardEvent::V_MTE2); + SetWaitFlag(HardEvent::S_MTE2); + DataCopyPad(curValueIdxUb[valueOffset], vec1ResGm[wsOffset], + {1, static_cast(2 * BASE_TOPK * sizeof(int32_t)), 0, 0}, {true, 0, 0, 0}); + valueOffset += 2 * BASE_TOPK; + acc_list_num++; + + // 每满4个list,聚合 前2K为mrg结果 + if (acc_list_num == mrgListNum_) { + // MrgSort 四条2048的队列,Mrg成一条 + AscendC::MrgSort4Info params; + params.elementLengths[0] = BASE_TOPK; + params.elementLengths[1] = BASE_TOPK; + params.elementLengths[2] = BASE_TOPK; + params.elementLengths[3] = BASE_TOPK; + params.ifExhaustedSuspension = true; + params.validBit = 0b1111; + params.repeatTimes = 1; + + AscendC::MrgSortSrcList srcList; + srcList.src1 = curValueIdxUb[0]; + srcList.src2 = curValueIdxUb[2 * BASE_TOPK]; + srcList.src3 = curValueIdxUb[4 * BASE_TOPK]; + srcList.src4 = curValueIdxUb[6 * BASE_TOPK]; + SetWaitFlag(HardEvent::MTE2_V); + MrgSort(tmpUb, srcList, params); + PipeBarrier(); + DataCopy(curValueIdxUb, tmpUb, 2 * BASE_TOPK); + PipeBarrier(); + acc_list_num = 1; + valueOffset = 2 * BASE_TOPK; + } + + // reduce到S2末尾,则跳出 + if (isS2End == 1) { + break; + } + + tmpCubeId++; + wsInfoOffset = tmpCubeId * s1BaseSize_ * 2 * paramNum_ + innerS1Idx * 2 * paramNum_; + needFd = vec1ParamGm.GetValue(wsInfoOffset); + isS2End = vec1ParamGm.GetValue(wsInfoOffset + 4); + } + + // mrg不足4个list的数据 + if (acc_list_num != 1) { + AscendC::MrgSort4Info params; + params.elementLengths[0] = BASE_TOPK; + params.elementLengths[1] = BASE_TOPK; + params.elementLengths[2] = BASE_TOPK; + params.elementLengths[3] = BASE_TOPK; + params.ifExhaustedSuspension = true; + if (acc_list_num == 2) { + params.validBit = 0b0011; + } else if (acc_list_num == 3) { + params.validBit = 0b0111; + } + params.repeatTimes = 1; + + AscendC::MrgSortSrcList srcList; + srcList.src1 = curValueIdxUb[0]; + srcList.src2 = curValueIdxUb[2 * BASE_TOPK]; + srcList.src3 = curValueIdxUb[4 * BASE_TOPK]; + srcList.src4 = curValueIdxUb[6 * BASE_TOPK]; + SetWaitFlag(HardEvent::MTE2_V); + MrgSort(tmpUb, srcList, params); + PipeBarrier(); + DataCopy(curValueIdxUb, tmpUb, 2 * BASE_TOPK); + PipeBarrier(); + } + + // 搬出 + LocalTensor outValueUb = ldOutValueBuf_.Get(); + LocalTensor outIdxUb = ldOutIdxBuf_.Get(); + if (!constInfo_.returnValue) { + Extract(outValueUb, outIdxUb, curValueIdxUb, (BASE_TOPK / 32)); + LocalTensor idxULocal1 = outIdxUb.template ReinterpretCast(); + SetWaitFlag(HardEvent::V_MTE3); + SetWaitFlag(HardEvent::S_MTE3); + DataCopyPad(indiceOutGm[outOffset], idxULocal1, + {1, static_cast(constInfo_.sparseCount * sizeof(int32_t)), 0, 0}); + SetWaitFlag(HardEvent::MTE3_V); + } else { + Extract(outValueUb, outIdxUb, curValueIdxUb, (BASE_TOPK / 32)); + PipeBarrier(); + LocalTensor idxULocal1 = outIdxUb.template ReinterpretCast(); + LocalTensor valueULocal1 = outValueUb.template ReinterpretCast(); + Cast(valueULocal1, outValueUb, RoundMode::CAST_ROUND, constInfo_.sparseCount); + PipeBarrier(); + SetWaitFlag(HardEvent::V_MTE3); + SetWaitFlag(HardEvent::S_MTE3); + DataCopyPad(indiceOutGm[outOffset], idxULocal1, + {1, static_cast(constInfo_.sparseCount * sizeof(int32_t)), 0, 0}); + DataCopyPad(valueOutGm[outOffset], valueULocal1, + {1, static_cast(constInfo_.sparseCount * sizeof(K_T)), 0, 0}); + SetWaitFlag(HardEvent::MTE3_V); + } + } +} +} // namespace LIKernel +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_vector.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_vector.h new file mode 100644 index 0000000000000000000000000000000000000000..337be7b63e36a23562b81b40e885bf514f29f2f3 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch22/lightning_indexer_vector.h @@ -0,0 +1,424 @@ +/** + * 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 lightning_indexer_vector.h + * \brief + */ +#ifndef LIGHTNING_INDEXER_VECTOR_H +#define LIGHTNING_INDEXER_VECTOR_H + +#include "lightning_indexer_vector.h" +#include "kernel_operator.h" + +namespace LIServiceVec { +using namespace AscendC; + +constexpr int32_t NEG_INF = 0xFF800000; +constexpr int32_t INVALID_INDEX = -1; +constexpr uint8_t VEC_REPEAT_MAX = 255; +constexpr uint8_t B32_VEC_ELM_NUM = 64; +constexpr uint8_t B32_BLOCK_ALIGN_NUM = 8; +constexpr uint8_t B32_VEC_REPEAT_STRIDE = 8; +constexpr uint64_t VEC_REPEAT_BYTES = 256; +constexpr int32_t CONST_TWO = 2; +constexpr int64_t VALUE_AND_INDEX_NUM = 2; +constexpr int64_t BLOCK_BYTES = 32; +constexpr int64_t MRG_QUE_0 = 0; +constexpr int64_t MRG_QUE_1 = 1; +constexpr int64_t MRG_QUE_2 = 2; +constexpr int64_t MRG_QUE_3 = 3; +constexpr int64_t MRG_BLOCK_2 = 2; +constexpr int64_t MRG_BLOCK_3 = 3; +constexpr int64_t MRG_BLOCK_4 = 4; + +template +__aicore__ inline void CopyIn(LocalTensor &mmOutUb, LocalTensor &weightsUb, GlobalTensor &mMoutGm, + GlobalTensor &weightScaleGm, int64_t MMout_gmoffset, int64_t weights_gmoffset, + int64_t groupInner, int64_t s2Inner, int64_t mmUbStride) +{ + // 将MMout_gmoffset copy到UB上 + AscendC::DataCopyPadExtParams padParams{false, 0, 0, 0}; + AscendC::DataCopyExtParams dataCopymMoutParams; + dataCopymMoutParams.blockCount = groupInner; + dataCopymMoutParams.blockLen = s2Inner * sizeof(float); + dataCopymMoutParams.srcStride = 0; + dataCopymMoutParams.dstStride = mmUbStride; + dataCopymMoutParams.rsv = 0; + AscendC::DataCopyPad(mmOutUb, mMoutGm[MMout_gmoffset], dataCopymMoutParams, padParams); + + // 将weights_gmoffset copy到UB + AscendC::DataCopyPadExtParams padTParams{false, 0, 0, 0}; + AscendC::DataCopyExtParams dataCopyweightParams; + dataCopyweightParams.blockCount = 1; + dataCopyweightParams.blockLen = groupInner * sizeof(T); + dataCopyweightParams.srcStride = 0; + dataCopyweightParams.dstStride = 0; + dataCopyweightParams.rsv = 0; + AscendC::DataCopyPad(weightsUb, weightScaleGm[weights_gmoffset], dataCopyweightParams, padTParams); +} + + +template +__aicore__ inline void CopyOut(const GlobalTensor &dstGm, const LocalTensor &srcUb, int64_t copyCount) +{ + AscendC::DataCopyParams dataCopyOutyParams; + dataCopyOutyParams.blockCount = 1; + dataCopyOutyParams.blockLen = copyCount * sizeof(T); + dataCopyOutyParams.srcStride = 0; + dataCopyOutyParams.dstStride = 0; + AscendC::DataCopyPad(dstGm, srcUb, dataCopyOutyParams); +} + + +template +__aicore__ inline void DoScale(const LocalTensor &reduceCacheBuf, LocalTensor &mmOutUb, + LocalTensor &weightsUb, LocalTensor &weightsTUb, LocalTensor &tmpBuff, + int64_t groupInner, int64_t s2Inner, int32_t outerGidx) +{ + // cast bfloat16_t to float + if constexpr (!IsSameType::value) { + AscendC::Cast(weightsUb, weightsTUb, RoundMode::CAST_NONE, groupInner); + AscendC::PipeBarrier(); + } + + // weight broadcast: [groupInner, 1] -> [groupInner, 8] + AscendC::Brcb(tmpBuff, weightsUb, LICommon::CeilDiv(groupInner, static_cast(B32_BLOCK_ALIGN_NUM)), + {1, B32_VEC_REPEAT_STRIDE}); + AscendC::PipeBarrier(); + + // do scale: [groupInner, 8] * [groupInner, s2Inner] + uint64_t countPerRepeat = VEC_REPEAT_BYTES / sizeof(float); + uint64_t repeatTimes = s2Inner / countPerRepeat; + for (int32_t i = 0; i < groupInner; i++) { + if (outerGidx == 0) { + AscendC::Mul(reduceCacheBuf[i * s2Inner], mmOutUb[i * s2Inner], tmpBuff[i * B32_BLOCK_ALIGN_NUM], + countPerRepeat, repeatTimes, {1, 1, 0, B32_VEC_REPEAT_STRIDE, B32_VEC_REPEAT_STRIDE, 0}); + } else { + AscendC::Mul(mmOutUb[i * s2Inner], mmOutUb[i * s2Inner], tmpBuff[i * B32_BLOCK_ALIGN_NUM], countPerRepeat, + repeatTimes, {1, 1, 0, B32_VEC_REPEAT_STRIDE, B32_VEC_REPEAT_STRIDE, 0}); + } + } + + if (outerGidx != 0) { + AscendC::PipeBarrier(); + AscendC::Add(reduceCacheBuf, mmOutUb, reduceCacheBuf, groupInner * s2Inner); + } + AscendC::PipeBarrier(); +} + + +__aicore__ inline uint64_t FindNearestPower2(uint64_t value) +{ + if (value <= CONST_TWO) { + return value; + } else { + const uint64_t pow = 63 - AscendC::ScalarCountLeadingZero(value); // 返回前导0的个数,对于64位整数,最大有效位位置 = 63 - 前导0个数 + return (1 << pow); + } +} + + +// dstTensor 需要初始化0 +__aicore__ inline void DoReduce(const LocalTensor &srcTensor, LocalTensor &dstTensor, int32_t rNum, + int32_t aNum) +{ + if (rNum == 1) { + AscendC::Adds(dstTensor, srcTensor, 0, aNum); + AscendC::PipeBarrier(); + return; + } + + uint32_t dichotomizeAddPow = FindNearestPower2(rNum); + uint32_t dichotomizeAddDiffSize = rNum - dichotomizeAddPow; + if (dichotomizeAddDiffSize != 0) { + AscendC::Add(srcTensor, srcTensor, srcTensor[dichotomizeAddPow * aNum], dichotomizeAddDiffSize * aNum); + AscendC::PipeBarrier(); + } + int32_t nowRows = dichotomizeAddPow; + while (nowRows > CONST_TWO) { + nowRows = nowRows / CONST_TWO; + AscendC::Add(srcTensor, srcTensor, srcTensor[nowRows * aNum], nowRows * aNum); + AscendC::PipeBarrier(); + } + AscendC::Add(dstTensor, srcTensor, srcTensor[aNum], aNum); + AscendC::PipeBarrier(); +} + + +/** + src: 传入的初始化空间 + eleNum: 需要初始化的元素个数需为64整数倍,元素将被初始化为交错排布的-inf,-1 + */ +__aicore__ inline void InitSortOutBuf(const LocalTensor &src, int64_t eleNum) +{ + uint64_t mask1[2] = {0x5555555555555555, 0}; + uint64_t mask0[2] = {0xaaaaaaaaaaaaaaaa, 0}; + int64_t repeatNum = eleNum / B32_VEC_ELM_NUM; + int64_t forLoop = repeatNum / VEC_REPEAT_MAX; + int64_t forRemain = repeatNum % VEC_REPEAT_MAX; + for (int i = 0; i < forLoop; i++) { + AscendC::Duplicate(src.template ReinterpretCast(), NEG_INF, mask1, VEC_REPEAT_MAX, 1, + B32_VEC_REPEAT_STRIDE); + AscendC::PipeBarrier(); + AscendC::Duplicate(src.template ReinterpretCast(), INVALID_INDEX, mask0, VEC_REPEAT_MAX, 1, + B32_VEC_REPEAT_STRIDE); + } + if (forRemain > 0) { + AscendC::Duplicate(src.template ReinterpretCast()[forLoop * VEC_REPEAT_MAX * B32_VEC_ELM_NUM], NEG_INF, + mask1, forRemain, 1, B32_VEC_REPEAT_STRIDE); + AscendC::PipeBarrier(); + AscendC::Duplicate(src.template ReinterpretCast()[forLoop * VEC_REPEAT_MAX * B32_VEC_ELM_NUM], + INVALID_INDEX, mask0, forRemain, 1, B32_VEC_REPEAT_STRIDE); + } + AscendC::PipeBarrier(); +} + + +/** + src: logits和索引,前logitsNum为logits,后logitsNum为索引 + tmp: 计算使用到的临时空间,大小与src一致 + logitsNum: 排序的元素个数, 暂只支持[128,256,384,512,1024,2048] + */ +__aicore__ inline void SortAll(LocalTensor &src, LocalTensor &tmp, int64_t logitsNum) +{ + int64_t sort32Repeats = logitsNum / BLOCK_BYTES; + AscendC::Sort32(tmp, src, src[logitsNum].ReinterpretCast(), sort32Repeats); + AscendC::PipeBarrier(); + + int64_t mrgGroups = sort32Repeats; + int64_t mrgElements = BLOCK_BYTES; + int64_t i = 0; + AscendC::LocalTensor srcTensor; + AscendC::LocalTensor dstTensor; + while (true) { + if (i % CONST_TWO == 0) { + srcTensor = tmp; + dstTensor = src; + } else { + srcTensor = src; + dstTensor = tmp; + } + AscendC::MrgSort4Info params; + params.elementLengths[0] = mrgElements; + params.elementLengths[MRG_QUE_1] = mrgElements; + params.elementLengths[MRG_QUE_2] = mrgElements; + params.elementLengths[MRG_QUE_3] = mrgElements; + params.ifExhaustedSuspension = false; + params.validBit = 0b1111; + + AscendC::MrgSortSrcList srcList; + srcList.src1 = srcTensor[0]; + srcList.src2 = srcTensor[MRG_QUE_1 * VALUE_AND_INDEX_NUM * mrgElements]; + srcList.src3 = srcTensor[MRG_QUE_2 * VALUE_AND_INDEX_NUM * mrgElements]; + srcList.src4 = srcTensor[MRG_QUE_3 * VALUE_AND_INDEX_NUM * mrgElements]; + if (mrgGroups <= MRG_BLOCK_4) { + params.repeatTimes = 1; + if (mrgGroups == 1) { + break; + } else if (mrgGroups == MRG_BLOCK_2) { + params.validBit = 0b0011; + } else if (mrgGroups == MRG_BLOCK_3) { + params.validBit = 0b0111; + } else if (mrgGroups == MRG_BLOCK_4) { + params.validBit = 0b1111; + } + AscendC::MrgSort(dstTensor, srcList, params); + i += 1; + AscendC::PipeBarrier(); + break; + } else { + params.repeatTimes = mrgGroups / MRG_BLOCK_4; + AscendC::MrgSort(dstTensor, srcList, params); + i += 1; + mrgElements = mrgElements * MRG_BLOCK_4; + mrgGroups = mrgGroups / MRG_BLOCK_4; + } + AscendC::PipeBarrier(); + } + if (i % CONST_TWO == 0) { + AscendC::DataCopy(src, tmp, logitsNum * VALUE_AND_INDEX_NUM); + AscendC::PipeBarrier(); + } +} + + +/** + dst: 输出全排序的结果,排布方式为value,index + srcValue:输入的待排序浮点数 + srcIndex:浮点数的索引 + tmp: 计算使用到的临时空间,大小为srcValue+srcIndex + logitsNum: 排序的元素个数 + */ +__aicore__ inline void SortAll(LocalTensor &dst, LocalTensor &srcValue, LocalTensor &srcIndex, + LocalTensor &tmpTensor, int64_t logitsNum) +{ + int64_t sort32Repeats = logitsNum / BLOCK_BYTES; + AscendC::Sort(dst, srcValue, srcIndex, tmpTensor, sort32Repeats); + AscendC::PipeBarrier(); +} + + +/** + mrgDst: 合并进的Tensor + mrgSrc: 待合并的Tensor + tmpTensor:空间为mrgDst+mrgSrc + */ +__aicore__ inline void MergeSort(const LocalTensor &mrgDst, int32_t mrgDstNum, LocalTensor &mrgSrc, + int32_t mrgSrcNum, LocalTensor &tmpTensor) +{ + if (mrgDstNum <= 3072) { // 3072: threshold of data size for different processing strategy + AscendC::MrgSort4Info params; + params.elementLengths[MRG_QUE_0] = mrgSrcNum; + params.elementLengths[MRG_QUE_1] = mrgDstNum; + params.ifExhaustedSuspension = false; + params.validBit = 0b0011; + params.repeatTimes = 1; + + AscendC::MrgSortSrcList srcList; + srcList.src1 = mrgSrc; + srcList.src2 = mrgDst; + + AscendC::MrgSort(tmpTensor, srcList, params); + AscendC::PipeBarrier(); + AscendC::DataCopy(mrgDst, tmpTensor, mrgDstNum * VALUE_AND_INDEX_NUM); + AscendC::PipeBarrier(); + } else { + int64_t unitElements = 1024; + int64_t segNum = mrgDstNum / unitElements; + int64_t mrgQuelen_1 = (segNum + 2) / 3; + int64_t mrgQuelen_2 = ((segNum - mrgQuelen_1) + 1) / 2; + int64_t mrgQuelen_3 = segNum - mrgQuelen_1 - mrgQuelen_2; + + AscendC::MrgSort4Info params; + params.elementLengths[MRG_QUE_0] = mrgQuelen_1 * unitElements; + params.elementLengths[MRG_QUE_1] = mrgQuelen_2 * unitElements; + params.elementLengths[MRG_QUE_2] = mrgQuelen_3 * unitElements; + params.elementLengths[MRG_QUE_3] = mrgSrcNum; + + params.ifExhaustedSuspension = false; + params.validBit = 0b1111; + params.repeatTimes = 1; + + AscendC::MrgSortSrcList srcList; + srcList.src1 = mrgDst[0]; + srcList.src2 = mrgDst[mrgQuelen_1 * VALUE_AND_INDEX_NUM * unitElements]; + srcList.src3 = mrgDst[(mrgQuelen_1 + mrgQuelen_2) * VALUE_AND_INDEX_NUM * unitElements]; + srcList.src4 = mrgSrc; + + AscendC::MrgSort(tmpTensor, srcList, params); + AscendC::PipeBarrier(); + AscendC::DataCopy(mrgDst, tmpTensor, mrgDstNum * VALUE_AND_INDEX_NUM); + AscendC::PipeBarrier(); + } +} + + +/** + * @brief 合并基础块函数 + * @param dst 归并后的输出, 大小为blockNum * basicBlockSize * 2 * sizeof(float) + * @param src 基本块输入 + * @param blockNum 基本块的数量 + * @param basicBlockSize 基础块的大小 + * @return 无 + */ +__aicore__ inline void MrgBasicBlock(const LocalTensor &dst, const LocalTensor &src, int64_t blockNum, + int64_t basicBlockSize) +{ + // 初始化合并排序参数 + AscendC::MrgSort4Info params; + params.elementLengths[MRG_QUE_0] = basicBlockSize; + params.elementLengths[MRG_QUE_1] = basicBlockSize; + params.elementLengths[MRG_QUE_2] = basicBlockSize; + params.elementLengths[MRG_QUE_3] = basicBlockSize; + params.ifExhaustedSuspension = false; + // 根据块的数量设置有效位 + if (blockNum == MRG_BLOCK_2) { + params.validBit = 0b0011; + } else if (blockNum == MRG_BLOCK_3) { + params.validBit = 0b0111; + } else if (blockNum == MRG_BLOCK_4) { + params.validBit = 0b1111; + } else { + AscendC::DataCopy(dst, src, basicBlockSize * VALUE_AND_INDEX_NUM); + return; + } + // 初始化源列表 + AscendC::MrgSortSrcList srcList; + srcList.src1 = src[0]; + srcList.src2 = src[basicBlockSize * VALUE_AND_INDEX_NUM * MRG_QUE_1]; + srcList.src3 = src[basicBlockSize * VALUE_AND_INDEX_NUM * MRG_QUE_2]; + srcList.src4 = src[basicBlockSize * VALUE_AND_INDEX_NUM * MRG_QUE_3]; + // 执行合并排序 + AscendC::MrgSort(dst, srcList, params); +} + + +/** + * @brief 从两个队列中选择topk + * @param dst 已经归并好的topk数据 + * @param needsMerging 需要合并的有序数据 + * @param tmp 临时空间 + * @param topk topk的元素个数 + * @param mergSize 待合并的元素个数 + * @return 无 + */ +template +__aicore__ inline void SparseTopK(const LocalTensor &dst, const LocalTensor &needsMerging, + const LocalTensor &tmp, int64_t topk, int64_t mergSize) +{ + // 如果不需要合并,则直接复制数据 + if (!needMrg) { + AscendC::DataCopy(dst, needsMerging, mergSize * VALUE_AND_INDEX_NUM); + return; + } + // 初始化合并排序参数 + AscendC::MrgSort4Info params; + params.elementLengths[0] = topk; + params.elementLengths[1] = mergSize; + params.ifExhaustedSuspension = (topk == mergSize); + params.validBit = 0b0011; + // 初始化源列表 + AscendC::MrgSortSrcList srcList; + srcList.src1 = dst; + srcList.src2 = needsMerging; + // 执行合并排序 + AscendC::MrgSort(tmp, srcList, params); + AscendC::PipeBarrier(); + // 将结果复制到目标张量 + AscendC::DataCopy(dst, tmp, topk * VALUE_AND_INDEX_NUM); +} + + +__aicore__ inline void ExtractIndex(const LocalTensor &idxULocal, const LocalTensor &sortLocal, + int64_t extractNum) +{ + AscendC::GatherMaskParams gatherMaskParams; + gatherMaskParams.repeatTimes = Ceil(extractNum * sizeof(float) * VALUE_AND_INDEX_NUM, VEC_REPEAT_BYTES); + gatherMaskParams.src0BlockStride = 1; + gatherMaskParams.src0RepeatStride = B32_VEC_REPEAT_STRIDE; + gatherMaskParams.src1RepeatStride = 0; + uint64_t rsvdCnt = 0; // 用于保存筛选后保留下来的元素个数 + uint8_t src1Pattern = 2; // 固定模式2,表示筛选出奇数索引的数 + AscendC::GatherMask(idxULocal, sortLocal, src1Pattern, false, static_cast(0), gatherMaskParams, rsvdCnt); + AscendC::PipeBarrier(); +} + + +template +__aicore__ inline void SetWaitFlag(HardEvent evt) +{ + event_t eventId = static_cast(GetTPipePtr()->FetchEventID(evt)); + AscendC::SetFlag(eventId); + AscendC::WaitFlag(eventId); +} + +} // namespace LIServiceVec +#endif // LIGHTNING_INDEXER_VECTOR_H \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_kernel.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..f230105fb2006076087f839d91703c35ccc0bf01 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_kernel.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 lightning_indexer_kernel.h + * \brief + */ + +#ifndef LIGHTNING_INDEXER_KERNEL_H +#define LIGHTNING_INDEXER_KERNEL_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 "../lightning_indexer_common.h" +#include "lightning_indexer_service_vector.h" +#include "lightning_indexer_service_cube.h" + +namespace LIKernel { +using namespace LICommon; +using namespace matmul; +using AscendC::CacheMode; +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +// 由于S2循环前,RunInfo还没有赋值,使用TempLoopInfo临时存放B、N、S1轴相关的信息;同时减少重复计算 +struct TempLoopInfo { + uint32_t bIdx = 0U; + uint32_t bN2Idx = 0; + uint32_t n2Idx = 0U; + uint32_t gS1Idx = 0U; + uint32_t gS1LoopEnd = 0U; // gS1方向循环的结束Idx + uint32_t s2LoopEnd = 0U; // S2方向循环的结束Idx + uint32_t actS1Size = 1U; // 当前Batch循环处理的S1轴的实际大小 + uint32_t actS2Size = 0U; + uint32_t actS2SizeOrig = 0U; // 压缩前s2 + bool curActSeqLenIsZero = false; + bool needDealActS1LessThanS1 = false; // S1的实际长度小于shape的S1长度时,是否需要清理输出 + uint32_t actMBaseSize = 0U; // m轴(gS1)方向实际大小 + uint32_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小 + uint32_t s2BasicSizeTail = 0U; // S2方向循环的尾基本块大小 +}; + +template +class LightningIndexerKernel { +public: + __aicore__ inline LightningIndexerKernel(){}; + __aicore__ inline void Init(__gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *weights, + __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengthsK, + __gm__ uint8_t *blockTable, __gm__ uint8_t *sparseIndices, __gm__ uint8_t *sparseValues, + __gm__ uint8_t *workspace, const LITilingData *__restrict tiling, TPipe *tPipe); + __aicore__ inline void Process(); + + // =================================类型定义区================================= + static constexpr bool DT_W_FLAG = LIT::weightsTypeFlag; + using Q_T = typename LIT::queryType; + using K_T = typename LIT::keyType; + using OUT_T = typename LIT::outputType; + using SCORE_T = uint32_t; + static constexpr bool PAGE_ATTENTION = LIT::pageAttention; + static constexpr LI_LAYOUT LAYOUT_T = LIT::layout; + static constexpr LI_LAYOUT K_LAYOUT_T = LIT::keyLayout; + using W_T = + typename LightningIndexerTypeTraits::type>::weightsType; + + LightningIndexerServiceCube matmulService; + LightningIndexerServiceVector vectorService; + + // =================================常量区================================= + static constexpr uint32_t SYNC_C1_V1_FLAG = 4; + static constexpr uint32_t SYNC_V1_C1_FLAG = 5; + + static constexpr uint32_t M_BASE_SIZE = 256; + static constexpr uint32_t S1_BASE_SIZE = 4; + static constexpr uint32_t S1_BASE_SIZE_SMALL = 2; + static constexpr uint32_t S2_BASE_SIZE = 128; + static constexpr uint32_t HEAD_DIM = 128; + static constexpr uint32_t K_HEAD_NUM = 1; + static constexpr uint32_t GM_ALIGN_BYTES = 512; + + static constexpr int64_t LD_PREFETCH_LEN = 2; + +protected: + TPipe *pipe = nullptr; + + // offset + uint64_t queryCoreOffset = 0ULL; + uint64_t keyCoreOffset = 0ULL; + uint64_t weightsCoreOffset = 0ULL; + uint64_t indiceOutCoreOffset = 0ULL; + uint64_t valueOutCoreOffset = 0ULL; + // ================================Global Buffer区================================= + GlobalTensor queryGm; + GlobalTensor keyGm; + GlobalTensor weightsGm; + + GlobalTensor indiceOutGm; + GlobalTensor valueOutGm; + GlobalTensor blockTableGm; + + GlobalTensor actualSeqLengthsGmQ; + GlobalTensor actualSeqLengthsGmKv; + + // ================================类成员变量==================================== + // aic、aiv核信息 + uint32_t tmpBlockIdx = 0U; + uint32_t aiCoreIdx = 0U; + uint32_t usedCoreNum = 0U; + + LICommon::ConstInfo constInfo{}; + TempLoopInfo tempLoopInfo{}; + LICommon::SplitCoreInfo splitCoreInfo{}; + + // ================================Init functions================================== + __aicore__ inline void InitTilingData(const LITilingData *__restrict tilingData); + __aicore__ inline void InitBuffers(); + __aicore__ inline void InitActualSeqLen(__gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengthsK); + // ================================Split Core================================ + __aicore__ inline void SplitCore(uint32_t curCoreIdx, uint32_t &coreNum, LICommon::SplitCoreInfo &info); + __aicore__ inline uint32_t GetTotalBaseBlockNum(); + __aicore__ inline uint32_t GetS2BaseBlockNumOnMask(uint32_t s1gIdx, uint32_t actS1Size, uint32_t actS2SizeOrig); + // ================================Process functions================================ + __aicore__ inline void ProcessMain(); + __aicore__ inline void ProcessBaseBlock(uint32_t loop, uint64_t s2LoopIdx, + LICommon::RunInfo runInfo); + __aicore__ inline void ProcessInvalid(); + // ================================Params Calc===================================== + __aicore__ inline void CalcGS1LoopParams(uint32_t bN2Idx); + __aicore__ inline void GetBN2Idx(uint32_t bN2Idx); + __aicore__ inline uint32_t GetActualSeqLen(uint32_t bIdx, uint32_t actualLenDims, bool isAccumSeq, + GlobalTensor &actualSeqLengthsGmKv, uint32_t defaultSeqLen); + __aicore__ inline void GetS1S2ActualSeqLen(uint32_t bIdx, uint32_t &actS1Size, + uint32_t &actS2Size, uint32_t &actS2SizeOrig); + __aicore__ inline void CalcS2LoopParams(uint32_t bN2LoopIdx, uint32_t gS1LoopIdx); + __aicore__ inline void CalcRunInfo(uint32_t loop, uint32_t s2LoopIdx, LICommon::RunInfo &runInfo); + __aicore__ inline void DealActSeqLenIsZero(uint32_t bIdx, uint32_t n2Idx, uint32_t s1Start); +}; + +template +__aicore__ inline void LightningIndexerKernel::InitTilingData(const LITilingData *__restrict tilingData) +{ + usedCoreNum = tilingData->usedCoreNum; + constInfo.batchSize = tilingData->bSize; + constInfo.qHeadNum = constInfo.gSize = tilingData->gSize; + constInfo.qSeqSize = tilingData->s1Size; + constInfo.kSeqSize = tilingData->s2Size; + constInfo.attenMaskFlag = (tilingData->sparseMode == 3); + constInfo.kCacheBlockSize = tilingData->blockSize; + constInfo.maxBlockNumPerBatch = tilingData->maxBlockNumPerBatch; + constInfo.sparseCount = tilingData->sparseCount; + constInfo.outputLayout = LAYOUT_T; // 输出和输入形状一致 + if constexpr (std::is_same_v) { + constInfo.INVALID_VAL = 0xFC00; + }else { + constInfo.INVALID_VAL = 0xFF80; + } + if constexpr (LAYOUT_T == LI_LAYOUT::TND) { + constInfo.isAccumSeqS1 = true; + } + if constexpr (K_LAYOUT_T == LI_LAYOUT::TND) { + constInfo.isAccumSeqS2 = true; + } + + constInfo.kHeadNum = K_HEAD_NUM; + constInfo.headDim = HEAD_DIM; + + if (constInfo.sparseCount > 2048) { + constInfo.mBaseSize = S1_BASE_SIZE_SMALL * constInfo.gSize; + constInfo.s1BaseSize = S1_BASE_SIZE_SMALL; + } else { + constInfo.mBaseSize = S1_BASE_SIZE * constInfo.gSize; + constInfo.s1BaseSize = S1_BASE_SIZE; + } + constInfo.s2BaseSize = S2_BASE_SIZE; + constInfo.returnValueFlag = tilingData->returnValue; + constInfo.splitMFlag = (constInfo.gSize == 64 && constInfo.sparseCount <= 2048); +} + +template +__aicore__ inline void LightningIndexerKernel::InitBuffers() +{ + if ASCEND_IS_AIV { + vectorService.InitBuffers(pipe); + } else { + matmulService.InitBuffers(pipe); + } +} + +template +__aicore__ inline void LightningIndexerKernel::InitActualSeqLen(__gm__ uint8_t *actualSeqLengthsQ, + __gm__ uint8_t *actualSeqLengthsK) +{ + if (actualSeqLengthsQ == nullptr) { + constInfo.actualLenQDims = 0; + } else { + constInfo.actualLenQDims = constInfo.batchSize; + actualSeqLengthsGmQ.SetGlobalBuffer((__gm__ uint32_t *)actualSeqLengthsQ, + constInfo.actualLenQDims); + } + if (actualSeqLengthsK == nullptr) { + constInfo.actualLenDims = 0; + } else { + constInfo.actualLenDims = constInfo.batchSize; + actualSeqLengthsGmKv.SetGlobalBuffer((__gm__ uint32_t *)actualSeqLengthsK, constInfo.actualLenDims); + } +} + +template +__aicore__ inline uint32_t LightningIndexerKernel::GetActualSeqLen(uint32_t bIdx, + uint32_t actualLenDims, bool isAccumSeq, + GlobalTensor &actualSeqLengthsGmKv, + uint32_t defaultSeqLen) +{ + if (actualLenDims == 0) { + return defaultSeqLen; + } else if (isAccumSeq && bIdx > 0) { + return actualSeqLengthsGmKv.GetValue(bIdx) - actualSeqLengthsGmKv.GetValue(bIdx - 1); + } else { + return actualSeqLengthsGmKv.GetValue(bIdx); + } +} + +template +__aicore__ inline void LightningIndexerKernel::GetS1S2ActualSeqLen(uint32_t bIdx, uint32_t &actS1Size, + uint32_t &actS2Size, uint32_t &actS2SizeOrig) +{ + actS1Size = GetActualSeqLen(bIdx, constInfo.actualLenQDims, constInfo.isAccumSeqS1, actualSeqLengthsGmQ, + constInfo.qSeqSize); + actS2SizeOrig = + GetActualSeqLen(bIdx, constInfo.actualLenDims, + constInfo.isAccumSeqS2, actualSeqLengthsGmKv, constInfo.kSeqSize); + actS2Size = actS2SizeOrig; +} + +template +__aicore__ inline uint32_t LightningIndexerKernel::GetS2BaseBlockNumOnMask(uint32_t s1gIdx, uint32_t actS1Size, + uint32_t actS2SizeOrig) +{ + if (actS2SizeOrig == 0) { + return 0; + } + uint32_t s1Offset = constInfo.s1BaseSize * s1gIdx; + int32_t validS2LenBase = static_cast(actS2SizeOrig) - static_cast(actS1Size); + int32_t validS2Len = (static_cast(s1Offset) + validS2LenBase + static_cast(constInfo.s1BaseSize)); + validS2Len = Min(validS2Len, static_cast(actS2SizeOrig)); + validS2Len = Max(validS2Len, 1); + return (validS2Len + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; +} + +template +__aicore__ inline uint32_t LightningIndexerKernel::GetTotalBaseBlockNum() +{ + uint32_t totalBlockNum = 0; + uint32_t actS1Size, actS2Size, actS2SizeOrig; + uint32_t s1GBaseNum, s2BaseNum; + for (uint32_t bIdx = 0; bIdx < constInfo.batchSize; bIdx++) { + GetS1S2ActualSeqLen(bIdx, actS1Size, actS2Size, actS2SizeOrig); + s1GBaseNum = CeilDiv(actS1Size, constInfo.s1BaseSize); + if (!constInfo.attenMaskFlag) { + s2BaseNum = constInfo.isLDOpen ? CeilDiv(actS2Size, constInfo.s2BaseSize) : (actS2Size > 0 ? 1 : 0); + totalBlockNum += s1GBaseNum * s2BaseNum * constInfo.kHeadNum; + continue; + } + for (uint32_t s1gIdx = 0; s1gIdx < s1GBaseNum; s1gIdx++) { + s2BaseNum = constInfo.isLDOpen + ? GetS2BaseBlockNumOnMask(s1gIdx, actS1Size, actS2SizeOrig) + : (actS2Size > 0 ? 1 : 0); + totalBlockNum += s2BaseNum * constInfo.kHeadNum; + } + } + return totalBlockNum; +} + + +// 多核版本,双闭区间。基本原则:计算每个核最少处理的块数, 剩余的部分前面的核每个核多处理一块 +template +__aicore__ void inline LightningIndexerKernel::SplitCore(uint32_t curCoreIdx, uint32_t &coreNum, + LICommon::SplitCoreInfo &info) +{ + uint32_t totalBlockNum = GetTotalBaseBlockNum(); + uint32_t minBlockPerCore = totalBlockNum / coreNum; + uint32_t deal1MoreBlockCoreNum = totalBlockNum % coreNum; + uint32_t coreIdx = 0; + uint32_t lastGS1RemainBlockCnt = 0; + uint32_t coreDealBlockCnt = coreIdx < deal1MoreBlockCoreNum ? minBlockPerCore + 1 : minBlockPerCore; + coreNum = minBlockPerCore == 0 ? deal1MoreBlockCoreNum : coreNum; + if (curCoreIdx < coreNum) { + splitCoreInfo.isCoreEnable = true; + } else { + splitCoreInfo.isCoreEnable = false; + return; + } + + bool findLastCoreEnd = true; + uint32_t actS1Size, actS2Size, actS2SizeOrig; + uint32_t s1GBaseNum, s2BaseNum, s2Loop; + for (uint32_t bN2Idx = 0; bN2Idx < constInfo.batchSize * constInfo.kHeadNum; bN2Idx++) { + uint32_t bIdx = bN2Idx / constInfo.kHeadNum; + if (bN2Idx % constInfo.kHeadNum == 0) { + GetS1S2ActualSeqLen(bIdx, actS1Size, actS2Size, actS2SizeOrig); + s1GBaseNum = CeilDiv(actS1Size, constInfo.s1BaseSize); + s2BaseNum = CeilDiv(actS2Size, constInfo.s2BaseSize); + } + if constexpr (LAYOUT_T == LI_LAYOUT::BSND) { + if (findLastCoreEnd && (s1GBaseNum == 0U || s2BaseNum == 0U)) { + info.bN2Start = bN2Idx; + info.gS1Start = 0; + info.s2Start = 0; + findLastCoreEnd = false; + } + } + for (uint32_t gS1Idx = 0; gS1Idx < s1GBaseNum; gS1Idx++) { + if (constInfo.attenMaskFlag) { + s2BaseNum = GetS2BaseBlockNumOnMask(gS1Idx, actS1Size, actS2SizeOrig); + } + if (findLastCoreEnd && s2BaseNum == 0U) { + info.bN2Start = bN2Idx; + info.gS1Start = gS1Idx; + info.s2Start = 0; + findLastCoreEnd = false; + } + s2Loop = constInfo.isLDOpen ? s2BaseNum : (actS2Size > 0 ? 1 : 0); + for (uint32_t s2Idx = 0; s2Idx < s2Loop;) { + if (findLastCoreEnd) { + info.bN2Start = bN2Idx; + info.gS1Start = gS1Idx; + info.s2Start = s2Idx; + findLastCoreEnd = false; + } + uint32_t s2RemainBaseNum = s2Loop - s2Idx; + if (lastGS1RemainBlockCnt + s2RemainBaseNum >= coreDealBlockCnt) { + info.bN2End = bN2Idx; + info.gS1End = gS1Idx; + info.s2End = constInfo.isLDOpen + ? s2Idx + coreDealBlockCnt - lastGS1RemainBlockCnt - 1 + : s2BaseNum - 1; + + if (coreIdx == curCoreIdx) { + // S2被切N核,那么只有第一个核需要处理LD,其他核不用 + if (s2Idx == 0 && info.s2End + 1 < s2BaseNum) { + info.isLD = true; + } + // 最后一个核处理的不是最后一个Batch,表明后面的Batch为空块(S2=0), 调整终点坐标以便清理输出 + if (coreIdx == coreNum - 1 && info.bN2End != constInfo.batchSize - 1) { + info.bN2End = constInfo.batchSize - 1; + info.s2End = 0; + info.gS1End = 0; + } + return; + } + coreIdx++; + findLastCoreEnd = true; + s2Idx = info.s2End + 1; + lastGS1RemainBlockCnt = 0; + coreDealBlockCnt = coreIdx < deal1MoreBlockCoreNum ? + minBlockPerCore + 1 : minBlockPerCore; + } else { + lastGS1RemainBlockCnt += s2RemainBaseNum; + break; + } + } + } + } +} + +template +__aicore__ inline void LightningIndexerKernel::DealActSeqLenIsZero(uint32_t bIdx, uint32_t n2Idx, uint32_t s1Start) +{ + if ASCEND_IS_AIV { + if (constInfo.outputLayout == LI_LAYOUT::TND) { + uint32_t tSize = actualSeqLengthsGmQ.GetValue(constInfo.batchSize - 1); + uint32_t tBase = bIdx == 0 ? 0 : actualSeqLengthsGmQ.GetValue(bIdx - 1); + uint32_t s1Count = tempLoopInfo.actS1Size; + + for (uint32_t s1Idx = s1Start; s1Idx < s1Count; s1Idx++) { + uint64_t indiceOutOffset = + (tBase + s1Idx) * constInfo.kHeadNum * constInfo.sparseCount + // T轴、s1轴偏移 + n2Idx * constInfo.sparseCount; // N2轴偏移 + vectorService.CleanInvalidOutput(indiceOutOffset); + } + } else if (constInfo.outputLayout == LI_LAYOUT::BSND) { + for (uint32_t s1Idx = s1Start; s1Idx < constInfo.qSeqSize; s1Idx++) { + // B,S1,N2,K + uint64_t indiceOutOffset = bIdx * constInfo.qSeqSize * constInfo.kHeadNum * + constInfo.sparseCount + + s1Idx * constInfo.kHeadNum * constInfo.sparseCount + // B轴、S1轴偏移 + n2Idx * constInfo.sparseCount; // N2轴偏移 + vectorService.CleanInvalidOutput(indiceOutOffset); + } + } + } +} + +template +__aicore__ inline void LightningIndexerKernel::Init(__gm__ uint8_t *query, + __gm__ uint8_t *key, __gm__ uint8_t *weights, + __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengthsK, + __gm__ uint8_t *blockTable, __gm__ uint8_t *sparseIndices, + __gm__ uint8_t *sparseValues, + __gm__ uint8_t *workspace, const LITilingData *__restrict tiling, + TPipe *tPipe) +{ + if ASCEND_IS_AIV { + tmpBlockIdx = GetBlockIdx(); // vec:0-47 + aiCoreIdx = tmpBlockIdx / 2; + } else { + tmpBlockIdx = GetBlockIdx(); // cube:0-23 + aiCoreIdx = tmpBlockIdx; + } + + InitTilingData(tiling); + InitActualSeqLen(actualSeqLengthsQ, actualSeqLengthsK); + + // 获取分核信息 + SplitCore(aiCoreIdx, usedCoreNum, splitCoreInfo); + + pipe = tPipe; + + uint64_t offset = 0; + // vec 把整个s2的score存储在GM,大小为s1BaseSize * 16K * 4 + GlobalTensor scoreGm; // 存放vec核写出的score + uint64_t singleCoreScoreSize = constInfo.s1BaseSize * + LICommon::Align( + (uint64_t)constInfo.kSeqSize, + (uint64_t)constInfo.s2BaseSize) * + sizeof(SCORE_T); + scoreGm.SetGlobalBuffer((__gm__ SCORE_T *)(workspace + aiCoreIdx * singleCoreScoreSize)); + offset += GetBlockNum() * singleCoreScoreSize; + + if ASCEND_IS_AIV { + vectorService.InitParams(constInfo, tiling); + indiceOutGm.SetGlobalBuffer((__gm__ int32_t *)sparseIndices); + valueOutGm.SetGlobalBuffer((__gm__ K_T *)sparseValues); + weightsGm.SetGlobalBuffer((__gm__ W_T *)weights); + blockTableGm.SetGlobalBuffer((__gm__ int32_t *)blockTable); + vectorService.InitVecInputTensor(weightsGm, indiceOutGm, valueOutGm, blockTableGm); + vectorService.InitVecWorkspaceTensor(scoreGm); + } else { + matmulService.InitParams(constInfo); + queryGm.SetGlobalBuffer((__gm__ Q_T *)query); + if constexpr (PAGE_ATTENTION) { + blockTableGm.SetGlobalBuffer((__gm__ int32_t *)blockTable); + } + keyGm.SetGlobalBuffer((__gm__ K_T *)key); + matmulService.InitMm1GlobalTensor(blockTableGm, keyGm, queryGm); + } + InitBuffers(); +} + +template +__aicore__ inline void LightningIndexerKernel::GetBN2Idx(uint32_t bN2Idx) +{ + tempLoopInfo.bN2Idx = bN2Idx; + tempLoopInfo.bIdx = bN2Idx / constInfo.kHeadNum; + tempLoopInfo.n2Idx = bN2Idx % constInfo.kHeadNum; +} + +template +__aicore__ inline void LightningIndexerKernel::CalcS2LoopParams(uint32_t bN2LoopIdx, uint32_t gS1LoopIdx) +{ + tempLoopInfo.gS1Idx = gS1LoopIdx; + tempLoopInfo.actMBaseSize = constInfo.mBaseSize; + uint32_t remainedGS1Size = tempLoopInfo.actS1Size * + constInfo.gSize - tempLoopInfo.gS1Idx * constInfo.mBaseSize; + if (remainedGS1Size <= constInfo.mBaseSize && remainedGS1Size > 0) { + tempLoopInfo.actMBaseSize = tempLoopInfo.mBasicSizeTail; + } + + bool isEnd = (bN2LoopIdx == splitCoreInfo.bN2End) && (gS1LoopIdx == splitCoreInfo.gS1End); + uint32_t s2BlockNum; + if (constInfo.attenMaskFlag) { + s2BlockNum = GetS2BaseBlockNumOnMask(gS1LoopIdx, tempLoopInfo.actS1Size, tempLoopInfo.actS2SizeOrig); + } else { + s2BlockNum = (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; + } + tempLoopInfo.s2LoopEnd = isEnd ? splitCoreInfo.s2End : s2BlockNum - 1; +} + +template +__aicore__ inline void LightningIndexerKernel::CalcGS1LoopParams(uint32_t bN2LoopIdx) +{ + GetBN2Idx(bN2LoopIdx); + GetS1S2ActualSeqLen(tempLoopInfo.bIdx, tempLoopInfo.actS1Size, tempLoopInfo.actS2Size, tempLoopInfo.actS2SizeOrig); + if ((tempLoopInfo.actS2Size == 0) || (tempLoopInfo.actS1Size == 0)) { + tempLoopInfo.curActSeqLenIsZero = true; + return; + } + tempLoopInfo.curActSeqLenIsZero = false; + tempLoopInfo.s2BasicSizeTail = tempLoopInfo.actS2Size % constInfo.s2BaseSize; + tempLoopInfo.s2BasicSizeTail = + (tempLoopInfo.s2BasicSizeTail == 0) ? constInfo.s2BaseSize : tempLoopInfo.s2BasicSizeTail; + tempLoopInfo.mBasicSizeTail = (tempLoopInfo.actS1Size * constInfo.gSize) % constInfo.mBaseSize; + tempLoopInfo.mBasicSizeTail = + (tempLoopInfo.mBasicSizeTail == 0) ? constInfo.mBaseSize : tempLoopInfo.mBasicSizeTail; + + uint32_t gS1SplitNum = (tempLoopInfo.actS1Size * constInfo.gSize + constInfo.mBaseSize - 1) / constInfo.mBaseSize; + tempLoopInfo.gS1LoopEnd = (bN2LoopIdx == splitCoreInfo.bN2End) ? splitCoreInfo.gS1End : gS1SplitNum - 1; + if constexpr (LAYOUT_T == LI_LAYOUT::BSND) { + if (tempLoopInfo.gS1LoopEnd == gS1SplitNum - 1 && constInfo.qSeqSize > tempLoopInfo.actS1Size) { + tempLoopInfo.needDealActS1LessThanS1 = true; + } + } +} + +template +__aicore__ inline void LightningIndexerKernel::CalcRunInfo(uint32_t loop, + uint32_t s2LoopIdx, LICommon::RunInfo &runInfo) +{ + runInfo.loop = loop; + runInfo.bIdx = tempLoopInfo.bIdx; + runInfo.gS1Idx = tempLoopInfo.gS1Idx; + runInfo.s2Idx = s2LoopIdx; + runInfo.bN2Idx = tempLoopInfo.bN2Idx; + runInfo.isValid = s2LoopIdx <= tempLoopInfo.s2LoopEnd; + + if (!runInfo.isValid) { + return; + } + + runInfo.actS1Size = tempLoopInfo.actS1Size; + runInfo.actS2Size = tempLoopInfo.actS2Size; + runInfo.actS2SizeOrig = tempLoopInfo.actS2SizeOrig; + // 计算实际基本块size + runInfo.actMBaseSize = tempLoopInfo.actMBaseSize; + runInfo.actualSingleProcessSInnerSize = constInfo.s2BaseSize; + uint32_t s2SplitNum = (tempLoopInfo.actS2Size + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; + if (runInfo.s2Idx == s2SplitNum - 1) { + runInfo.actualSingleProcessSInnerSize = tempLoopInfo.s2BasicSizeTail; + } + runInfo.actualSingleProcessSInnerSizeAlign = + LICommon::Align((uint32_t)runInfo.actualSingleProcessSInnerSize, LICommon::ConstInfo::BUFFER_SIZE_BYTE_32B); + + runInfo.isFirstS2InnerLoop = s2LoopIdx == splitCoreInfo.s2Start; + runInfo.isLastS2InnerLoop = s2LoopIdx == tempLoopInfo.s2LoopEnd; + runInfo.isAllLoopEnd = (runInfo.bN2Idx == splitCoreInfo.bN2End) && (runInfo.gS1Idx == splitCoreInfo.gS1End) && + (runInfo.s2Idx == splitCoreInfo.s2End); + + if (runInfo.isFirstS2InnerLoop) { + uint64_t actualSeqQPrefixSum; + if constexpr (LAYOUT_T == LI_LAYOUT::TND) { + actualSeqQPrefixSum = (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsGmQ.GetValue(runInfo.bIdx - 1); + } else { // BSND + actualSeqQPrefixSum = (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.qSeqSize; + } + uint64_t tndBIdxOffset = actualSeqQPrefixSum * + constInfo.qHeadNum * constInfo.headDim; + // B,S1,N1(N2,G),D + queryCoreOffset = tndBIdxOffset + runInfo.gS1Idx * constInfo.mBaseSize * constInfo.headDim; + // B,S1,N1(N2,G)/T,N1(N2,G) + weightsCoreOffset = actualSeqQPrefixSum * constInfo.qHeadNum + runInfo.n2Idx * constInfo.gSize; + // B,S1,N2,k/T,N2,k + indiceOutCoreOffset = + actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount + runInfo.n2Idx * constInfo.sparseCount; + // B,S1,N2,k/T,N2,k + valueOutCoreOffset = + actualSeqQPrefixSum * constInfo.kHeadNum * constInfo.sparseCount + runInfo.n2Idx * constInfo.sparseCount; + } + uint64_t actualSeqKPrefixSum; + if constexpr (K_LAYOUT_T == LI_LAYOUT::TND) { // T N2 D + actualSeqKPrefixSum = (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsGmKv.GetValue(runInfo.bIdx - 1); + } else { + actualSeqKPrefixSum = (runInfo.bIdx <= 0) ? 0 : runInfo.bIdx * constInfo.kSeqSize; + } + uint64_t tndBIdxOffsetForK = actualSeqKPrefixSum * constInfo.kHeadNum * constInfo.headDim; + keyCoreOffset = tndBIdxOffsetForK + runInfo.s2Idx * constInfo.s2BaseSize * constInfo.kHeadNum * constInfo.headDim; + runInfo.tensorQueryOffset = queryCoreOffset; + runInfo.tensorKeyOffset = keyCoreOffset; + runInfo.tensorWeightsOffset = weightsCoreOffset; + runInfo.indiceOutOffset = indiceOutCoreOffset; + runInfo.valueOutOffset = valueOutCoreOffset; +} + +template +__aicore__ inline void LightningIndexerKernel::Process() +{ + if (usedCoreNum == 0) { + // 没有计算任务,直接清理输出 + ProcessInvalid(); + return; + } + + ProcessMain(); +} + +template +__aicore__ inline void LightningIndexerKernel::ProcessInvalid() +{ + if ASCEND_IS_AIV { + uint32_t aivCoreNum = GetBlockNum() * 2; // 2 means c:v = 1:2 + uint64_t totalOutputSize = + constInfo.batchSize * constInfo.qSeqSize * constInfo.kHeadNum * constInfo.sparseCount; + uint64_t singleCoreSize = + LICommon::Align((totalOutputSize + aivCoreNum - 1) / aivCoreNum, GM_ALIGN_BYTES / sizeof(OUT_T)); + uint64_t baseSize = tmpBlockIdx * singleCoreSize; + if (baseSize < totalOutputSize) { + uint64_t dealSize = + (baseSize + singleCoreSize <= totalOutputSize) ? singleCoreSize : totalOutputSize - baseSize; + GlobalTensor output = indiceOutGm[baseSize]; + AscendC::InitGlobalMemory(output, dealSize, constInfo.INVALID_IDX); + if (constInfo.returnValueFlag) { + GlobalTensor valueOutGmTmp; + valueOutGmTmp.SetGlobalBuffer((__gm__ uint16_t *)valueOutGm.GetPhyAddr()); + GlobalTensor valueOut = valueOutGmTmp[baseSize]; + AscendC::InitGlobalMemory(valueOut, dealSize, constInfo.INVALID_VAL); + } + } + } +} + +template +__aicore__ inline void LightningIndexerKernel::ProcessMain() +{ + if (!splitCoreInfo.isCoreEnable) { + return; + } + + if ASCEND_IS_AIV { + vectorService.AllocEventID(); + CrossCoreSetFlag(LICommon::ConstInfo::CROSS_VC_EVENT + 0); + CrossCoreSetFlag(LICommon::ConstInfo::CROSS_VC_EVENT + 1); + } else { + matmulService.AllocEventID(); + } + + LICommon::RunInfo runInfo; + uint32_t gloop = 0; + for (uint32_t bN2LoopIdx = splitCoreInfo.bN2Start; bN2LoopIdx <= splitCoreInfo.bN2End; bN2LoopIdx++) { + CalcGS1LoopParams(bN2LoopIdx); + if (tempLoopInfo.curActSeqLenIsZero) { + DealActSeqLenIsZero(tempLoopInfo.bIdx, tempLoopInfo.n2Idx, 0U); + continue; + } + for (uint32_t gS1LoopIdx = splitCoreInfo.gS1Start; gS1LoopIdx <= tempLoopInfo.gS1LoopEnd; gS1LoopIdx++) { + CalcS2LoopParams(bN2LoopIdx, gS1LoopIdx); + for (int s2LoopIdx = splitCoreInfo.s2Start; s2LoopIdx <= tempLoopInfo.s2LoopEnd; s2LoopIdx++) { + ProcessBaseBlock(gloop, s2LoopIdx, runInfo); + ++gloop; + } + splitCoreInfo.s2Start = 0; + } + if (tempLoopInfo.needDealActS1LessThanS1) { + DealActSeqLenIsZero(tempLoopInfo.bIdx, + tempLoopInfo.n2Idx, tempLoopInfo.actS1Size); + } + splitCoreInfo.gS1Start = 0; + } + + if ASCEND_IS_AIV { + vectorService.FreeEventID(); + } else { + matmulService.FreeEventID(); + CrossCoreWaitFlag(LICommon::ConstInfo::CROSS_VC_EVENT + 0); + CrossCoreWaitFlag(LICommon::ConstInfo::CROSS_VC_EVENT + 1); + } +} + +template +__aicore__ inline void LightningIndexerKernel::ProcessBaseBlock(uint32_t loop, + uint64_t s2LoopIdx, LICommon::RunInfo runInfo) +{ + CalcRunInfo(loop, s2LoopIdx, runInfo); + if ASCEND_IS_AIC { + matmulService.ComputeMm1(runInfo); + } else { + vectorService.ProcessVec1(runInfo); + if (runInfo.isLastS2InnerLoop) { // 本核s2last + vectorService.ProcessTopK(runInfo); + } + } +} + +} // namespace LIKernel +#endif // LIGHTNING_INDEXER_KERNEL_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_service_cube.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_service_cube.h new file mode 100644 index 0000000000000000000000000000000000000000..3af8c5e117715c8e4062c38ef6b5082f9a77a4b3 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_service_cube.h @@ -0,0 +1,459 @@ +/** + * 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 lightning_indexer_service_cube.h + * \brief use 5 buffer for matmul l1, better pipeline + */ +#ifndef LIGHTNING_INDEXER_SERVICE_CUBE_H +#define LIGHTNING_INDEXER_SERVICE_CUBE_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 "../lightning_indexer_common.h" + +namespace LIKernel { +using namespace LICommon; +template +class LightningIndexerServiceCube { +public: + using Q_T = typename LIT::queryType; + using K_T = typename LIT::keyType; + using SCORE_T = uint32_t; + + __aicore__ inline LightningIndexerServiceCube(){}; + __aicore__ inline void InitBuffers(TPipe *pipe); + __aicore__ inline void InitMm1GlobalTensor(const GlobalTensor &blkTableGm, const GlobalTensor &keyGm, + const GlobalTensor &queryGm); + __aicore__ inline void InitParams(const ConstInfo &constInfo); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + __aicore__ inline void ComputeMm1(const LICommon::RunInfo &runInfo); + + static constexpr uint64_t KEY_BUF_NUM = 3; + static constexpr uint64_t QUERY_BUF_NUM = 2; + static constexpr uint64_t L0_BUF_NUM = 2; + + static constexpr uint32_t KEY_MTE1_MTE2_EVENT = EVENT_ID2; + static constexpr uint32_t QUERY_MTE1_MTE2_EVENT = EVENT_ID5; // KEY_MTE1_MTE2_EVENT + KEY_BUF_NUM; + static constexpr uint32_t M_MTE1_EVENT = EVENT_ID3; + + static constexpr uint32_t MTE2_MTE1_EVENT = EVENT_ID2; + static constexpr uint32_t MTE1_M_EVENT = EVENT_ID2; + static constexpr uint32_t FIX_M_EVENT = EVENT_ID2; + static constexpr uint32_t M_FIX_EVENT = EVENT_ID3; + + static constexpr uint64_t M_BASIC_BLOCK = 256; + static constexpr uint64_t D_BASIC_BLOCK = 128; + static constexpr uint64_t S2_BASIC_BLOCK = 128; + + static constexpr uint64_t M_BASIC_BLOCK_L0 = 128; + static constexpr uint64_t D_BASIC_BLOCK_L0 = 128; + static constexpr uint64_t S2_BASIC_BLOCK_L0 = 128; + + static constexpr uint64_t FP16_BLOCK_CUBE = 16; + static constexpr FixpipeConfig LI_CFG_ROW_MAJOR_UB = {CO2Layout::ROW_MAJOR, true}; + + static constexpr uint64_t QUERY_BUFFER_OFFSET = M_BASIC_BLOCK * D_BASIC_BLOCK; + static constexpr uint64_t KEY_BUFFER_OFFSET = S2_BASIC_BLOCK * D_BASIC_BLOCK; + static constexpr uint64_t L0AB_BUFFER_OFFSET = M_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0; + static constexpr uint64_t L0C_BUFFER_OFFSET = M_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0; + +protected: + __aicore__ inline void Fixp(uint64_t s1gGmOffset, uint64_t s2GmOffset, uint64_t s1gL0RealSize, + uint64_t s2L0RealSize, const LICommon::RunInfo &runInfo); + __aicore__ inline void ComputeL0c(uint64_t s1gL0RealSize, uint64_t s2L0RealSize, const LICommon::RunInfo &runInfo); + __aicore__ inline void LoadKeyToL0b(uint64_t s2L0Offset, uint64_t s2L1RealSize, uint64_t s2L0RealSize, + const LICommon::RunInfo &runInfo); + __aicore__ inline void LoadQueryToL0a(uint64_t s1gL1Offset, uint64_t s1gL0Offset, uint64_t s1gL1RealSize, + uint64_t s1gL0RealSize, const LICommon::RunInfo &runInfo); + __aicore__ inline void QueryNd2Nz(uint64_t s1gL1RealSize, uint64_t s1gL1Offset, const LICommon::RunInfo &runInfo); + __aicore__ inline void KeyNd2Nz(uint64_t s2L1RealSize, uint64_t s2GmOffset, const LICommon::RunInfo &runInfo); + __aicore__ inline void KeyNd2NzForPA(uint64_t s2L1RealSize, uint64_t s2GmOffset, const LICommon::RunInfo &runInfo); + GlobalTensor blkTableGm_; + GlobalTensor keyGm_; + GlobalTensor queryGm_; + + TBuf bufQL1_; + LocalTensor queryL1_; + TBuf bufKeyL1_; + LocalTensor keyL1_; + + TBuf bufQL0_; + LocalTensor queryL0_; + TBuf bufKeyL0_; + LocalTensor keyL0_; + + TBuf bufL0C_; + LocalTensor cL0_; + + TBuf bufUB_; + LocalTensor mm1ResUB_; + + uint64_t keyL1BufIdx_ = 0; + uint64_t queryL1Mte2BufIdx_ = 0; + uint64_t queryL1Mte1BufIdx_ = 0; + uint64_t l0BufIdx_ = 0; + uint64_t kl0BufIdx_ = 0; + + ConstInfo constInfo_; + +private: + static constexpr bool PAGE_ATTENTION = LIT::pageAttention; +}; + +template +__aicore__ inline void LightningIndexerServiceCube::InitParams(const ConstInfo &constInfo) +{ + constInfo_ = constInfo; +} + +template +__aicore__ inline void LightningIndexerServiceCube::InitBuffers(TPipe *pipe) +{ + pipe->InitBuffer(bufUB_, 2 *CeilDiv(constInfo_.mBaseSize, 2) * + constInfo_.s2BaseSize * + sizeof(float)); // 大小:2(开dB) * 2 * 64 * 128 * 4 = 128KB + mm1ResUB_ = bufUB_.Get(); + pipe->InitBuffer(bufQL1_, QUERY_BUF_NUM * M_BASIC_BLOCK * D_BASIC_BLOCK * sizeof(Q_T)); + queryL1_ = bufQL1_.Get(); + pipe->InitBuffer(bufKeyL1_, KEY_BUF_NUM * S2_BASIC_BLOCK * D_BASIC_BLOCK * sizeof(K_T)); + keyL1_ = bufKeyL1_.Get(); + + pipe->InitBuffer(bufQL0_, L0_BUF_NUM * M_BASIC_BLOCK_L0 * D_BASIC_BLOCK_L0 * sizeof(Q_T)); + queryL0_ = bufQL0_.Get(); + pipe->InitBuffer(bufKeyL0_, L0_BUF_NUM * D_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0 * sizeof(K_T)); + keyL0_ = bufKeyL0_.Get(); + + pipe->InitBuffer(bufL0C_, L0_BUF_NUM * M_BASIC_BLOCK_L0 * S2_BASIC_BLOCK_L0 * sizeof(float)); + cL0_ = bufL0C_.Get(); +} + +template +__aicore__ inline void +LightningIndexerServiceCube::InitMm1GlobalTensor(const GlobalTensor &blkTableGm, + const GlobalTensor &keyGm, const GlobalTensor &queryGm) +{ + blkTableGm_ = blkTableGm; + keyGm_ = keyGm; + queryGm_ = queryGm; +} + +template +__aicore__ inline void LightningIndexerServiceCube::ComputeMm1(const LICommon::RunInfo &runInfo) +{ + CrossCoreWaitFlag( + LICommon::ConstInfo::CROSS_VC_EVENT + runInfo.loop % 2); + CrossCoreWaitFlag( + LICommon::ConstInfo::CROSS_VC_EVENT + + runInfo.loop % 2 + + LICommon::ConstInfo::AIV0_AIV1_OFFSET); + uint64_t s2GmBaseOffset = runInfo.s2Idx * constInfo_.s2BaseSize; + uint64_t s1gProcessSize = runInfo.actMBaseSize; + uint64_t s2ProcessSize = runInfo.actualSingleProcessSInnerSize; + for (uint64_t s2GmOffset = 0; s2GmOffset < s2ProcessSize; s2GmOffset += S2_BASIC_BLOCK) { + WaitFlag(KEY_MTE1_MTE2_EVENT + keyL1BufIdx_ % KEY_BUF_NUM); + uint64_t s2L1RealSize = + s2GmOffset + S2_BASIC_BLOCK > s2ProcessSize ? s2ProcessSize - s2GmOffset : S2_BASIC_BLOCK; + if (PAGE_ATTENTION) { + KeyNd2NzForPA(s2L1RealSize, s2GmBaseOffset + s2GmOffset, runInfo); + }else { + KeyNd2Nz(s2L1RealSize, s2GmOffset, runInfo); + } + + SetFlag(MTE2_MTE1_EVENT); + WaitFlag(MTE2_MTE1_EVENT); + // s1gProcessSize当前必定不会超过2倍的s1g basic block + for (uint64_t s1gGmOffset = 0; s1gGmOffset < s1gProcessSize; s1gGmOffset += constInfo_.mBaseSize) { + uint64_t s1gL1RealSize = + s1gGmOffset + constInfo_.mBaseSize > s1gProcessSize + ? s1gProcessSize - s1gGmOffset + : constInfo_.mBaseSize; + uint64_t s1gL1SizeAlign2G = CeilAlign(s1gL1RealSize, 2 * constInfo_.gSize); + if (runInfo.isFirstS2InnerLoop && s2GmOffset == 0) { + queryL1Mte2BufIdx_++; + queryL1Mte1BufIdx_ = queryL1Mte2BufIdx_; + WaitFlag(QUERY_MTE1_MTE2_EVENT + queryL1Mte2BufIdx_ % QUERY_BUF_NUM); + QueryNd2Nz(s1gL1RealSize, s1gGmOffset, runInfo); + SetFlag(MTE2_MTE1_EVENT); + WaitFlag(MTE2_MTE1_EVENT); + } else { + queryL1Mte1BufIdx_ = + queryL1Mte2BufIdx_ - (CeilDiv(s1gProcessSize, constInfo_.mBaseSize) - 1 - (s1gGmOffset > 0)); + } + for (uint64_t s2L1Offset = 0; s2L1Offset < s2L1RealSize; s2L1Offset += S2_BASIC_BLOCK_L0) { + uint64_t s2L0RealSize = + s2L1Offset + S2_BASIC_BLOCK_L0 > s2L1RealSize ? s2L1RealSize - s2L1Offset : S2_BASIC_BLOCK_L0; + + uint64_t l0Stride = constInfo_.mBaseSize; + if (constInfo_.splitMFlag) { + l0Stride /= 2; + } + + for (uint64_t s1gL1Offset = 0; s1gL1Offset < s1gL1SizeAlign2G; s1gL1Offset += l0Stride) { + WaitFlag(M_MTE1_EVENT + l0BufIdx_ % L0_BUF_NUM); + uint64_t s1gL0RealSize = + s1gL1Offset + constInfo_.mBaseSize > s1gL1SizeAlign2G + ? s1gL1SizeAlign2G - s1gL1Offset + : constInfo_.mBaseSize; + if (constInfo_.splitMFlag) { + s1gL0RealSize = 128; // g=64, topK=2k时固定m=128 + } + LoadQueryToL0a(s1gGmOffset, s1gL1Offset, s1gL1SizeAlign2G, s1gL0RealSize, runInfo); + if (s1gL1Offset == 0) { + LoadKeyToL0b(s2L1Offset, s2L1RealSize, s2L0RealSize, runInfo); + } + + SetFlag(MTE1_M_EVENT); + WaitFlag(MTE1_M_EVENT); + + WaitFlag(FIX_M_EVENT + l0BufIdx_ % L0_BUF_NUM); + ComputeL0c(s1gL0RealSize, s2L0RealSize, runInfo); + + SetFlag(M_MTE1_EVENT + l0BufIdx_ % L0_BUF_NUM); + + bool lastIter = s1gL1Offset + l0Stride >= s1gL1SizeAlign2G; + if (lastIter) { + kl0BufIdx_++; + } + + Fixp(s1gGmOffset + s1gL1Offset, s2GmOffset + s2L1Offset, s1gL0RealSize, s2L0RealSize, runInfo); + SetFlag(FIX_M_EVENT + l0BufIdx_ % L0_BUF_NUM); + l0BufIdx_++; + } + } + if (s2GmOffset + S2_BASIC_BLOCK >= s2ProcessSize && runInfo.isLastS2InnerLoop) { + SetFlag(QUERY_MTE1_MTE2_EVENT + queryL1Mte1BufIdx_ % QUERY_BUF_NUM); + } + } + SetFlag(KEY_MTE1_MTE2_EVENT + keyL1BufIdx_ % KEY_BUF_NUM); + keyL1BufIdx_++; + } + CrossCoreSetFlag( + LICommon::ConstInfo::CROSS_CV_EVENT + + runInfo.loop % 2); + CrossCoreSetFlag( + LICommon::ConstInfo::CROSS_CV_EVENT + + runInfo.loop % 2 + + LICommon::ConstInfo::AIV0_AIV1_OFFSET); +} + +template +__aicore__ inline void LightningIndexerServiceCube::KeyNd2Nz(uint64_t s2L1RealSize, uint64_t s2GmOffset, + const LICommon::RunInfo &runInfo) +{ + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s2L1RealSize; // 行数 + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = constInfo_.headDim; + nd2nzPara.dstNzC0Stride = CeilAlign(s2L1RealSize, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + // 默认一块buf最多放两份 + DataCopy(keyL1_[(keyL1BufIdx_ % KEY_BUF_NUM) * KEY_BUFFER_OFFSET], + keyGm_[runInfo.tensorKeyOffset + s2GmOffset * constInfo_.headDim], nd2nzPara); +} + +// blkNum, blkSize, N2, D +template +__aicore__ inline void LightningIndexerServiceCube::KeyNd2NzForPA(uint64_t s2L1RealSize, uint64_t s2GmOffset, + const LICommon::RunInfo &runInfo) +{ + uint64_t s2L1Offset = 0; + while (s2L1Offset < s2L1RealSize) { + uint64_t s2BlkId = (s2L1Offset + s2GmOffset) / constInfo_.kCacheBlockSize; + uint64_t s2BlkOffset = (s2L1Offset + s2GmOffset) % constInfo_.kCacheBlockSize; + uint64_t keyGmOffset = blkTableGm_.GetValue(runInfo.bIdx * constInfo_.maxBlockNumPerBatch + s2BlkId) * + constInfo_.kCacheBlockSize * constInfo_.kHeadNum * constInfo_.headDim + + s2BlkOffset * constInfo_.headDim; + + uint64_t s2Mte2Size = s2L1RealSize - s2L1Offset; + s2Mte2Size = s2BlkOffset + s2Mte2Size >= constInfo_.kCacheBlockSize + ? constInfo_.kCacheBlockSize - s2BlkOffset + : s2Mte2Size; + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s2Mte2Size; // 行数 + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = constInfo_.headDim; + nd2nzPara.dstNzC0Stride = CeilAlign(s2L1RealSize, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(keyL1_[(keyL1BufIdx_ % KEY_BUF_NUM) * KEY_BUFFER_OFFSET + s2L1Offset * FP16_BLOCK_CUBE], + keyGm_[keyGmOffset], nd2nzPara); + + s2L1Offset += s2Mte2Size; + } +} + +// batch, s1, n2, g, d +template +__aicore__ inline void LightningIndexerServiceCube::QueryNd2Nz(uint64_t s1gL1RealSize, uint64_t s1gGmOffset, + const LICommon::RunInfo &runInfo) +{ + uint64_t dstNzC0Stride = CeilAlign(s1gL1RealSize, 2 * constInfo_.gSize); + Nd2NzParams nd2nzPara; + nd2nzPara.ndNum = 1; + nd2nzPara.nValue = s1gL1RealSize; // 行数 + nd2nzPara.dValue = constInfo_.headDim; + nd2nzPara.srcDValue = constInfo_.headDim; + nd2nzPara.dstNzC0Stride = CeilAlign(dstNzC0Stride, (uint64_t)BLOCK_CUBE); // 对齐到16 单位block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + // 默认一块buf最多放两份 + DataCopy(queryL1_[(queryL1Mte2BufIdx_ % QUERY_BUF_NUM) * QUERY_BUFFER_OFFSET], + queryGm_[runInfo.tensorQueryOffset + s1gGmOffset * constInfo_.headDim], nd2nzPara); +} + +template +__aicore__ inline void LightningIndexerServiceCube::LoadQueryToL0a(uint64_t s1gGmOffset, + uint64_t s1gL1Offset, uint64_t s1gL1RealSize, + uint64_t s1gL0RealSize, const LICommon::RunInfo &runInfo) +{ + LoadData2DParamsV2 loadData2DParamsV2; + if (constInfo_.splitMFlag && runInfo.actMBaseSize > 128) { // 非尾块,切M + uint64_t dstOffset = 0; + loadData2DParamsV2.kStartPosition = 0; + loadData2DParamsV2.mStep = CeilDiv(64, BLOCK_CUBE); + loadData2DParamsV2.kStep = CeilDiv(constInfo_.headDim, FP16_BLOCK_CUBE); + loadData2DParamsV2.srcStride = CeilDiv(s1gL1RealSize, BLOCK_CUBE); + loadData2DParamsV2.dstStride = CeilDiv(s1gL0RealSize, BLOCK_CUBE); + loadData2DParamsV2.ifTranspose = false; + for (int i = 0; i < 2; i++) { + loadData2DParamsV2.mStartPosition = CeilDiv((s1gL1Offset / 2) + i * 128, BLOCK_CUBE); + dstOffset = i * 64 * 16; + + LoadData(queryL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET + dstOffset], + queryL1_[(queryL1Mte1BufIdx_ % QUERY_BUF_NUM) * QUERY_BUFFER_OFFSET], loadData2DParamsV2); + } + } else { + loadData2DParamsV2.mStartPosition = CeilDiv(s1gL1Offset, BLOCK_CUBE); + loadData2DParamsV2.kStartPosition = 0; + loadData2DParamsV2.mStep = CeilDiv(s1gL0RealSize, BLOCK_CUBE); + loadData2DParamsV2.kStep = CeilDiv(constInfo_.headDim, FP16_BLOCK_CUBE); + loadData2DParamsV2.srcStride = CeilDiv(s1gL1RealSize, BLOCK_CUBE); + loadData2DParamsV2.dstStride = CeilDiv(s1gL0RealSize, BLOCK_CUBE); + loadData2DParamsV2.ifTranspose = false; + + LoadData(queryL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET], + queryL1_[(queryL1Mte1BufIdx_ % QUERY_BUF_NUM) * QUERY_BUFFER_OFFSET], loadData2DParamsV2); + } +} + +template +__aicore__ inline void LightningIndexerServiceCube::LoadKeyToL0b(uint64_t s2L1Offset, + uint64_t s2L1RealSize, uint64_t s2L0RealSize, + const LICommon::RunInfo &runInfo) +{ + LoadData2DParamsV2 loadData2DParamsV2; + loadData2DParamsV2.mStartPosition = CeilDiv(s2L1Offset, BLOCK_CUBE); + loadData2DParamsV2.kStartPosition = 0; + loadData2DParamsV2.mStep = CeilDiv(s2L0RealSize, BLOCK_CUBE); + loadData2DParamsV2.kStep = CeilDiv(constInfo_.headDim, FP16_BLOCK_CUBE); + loadData2DParamsV2.srcStride = CeilDiv(s2L1RealSize, BLOCK_CUBE); + loadData2DParamsV2.dstStride = CeilDiv(s2L0RealSize, BLOCK_CUBE); + loadData2DParamsV2.ifTranspose = false; + + LoadData(keyL0_[(kl0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET], + keyL1_[(keyL1BufIdx_ % KEY_BUF_NUM) * KEY_BUFFER_OFFSET], loadData2DParamsV2); +} + +template +__aicore__ inline void LightningIndexerServiceCube::ComputeL0c(uint64_t s1gL0RealSize, uint64_t s2L0RealSize, + const LICommon::RunInfo &runInfo) +{ + MmadParams mmadParams; + mmadParams.m = CeilAlign(s1gL0RealSize, BLOCK_CUBE); + mmadParams.n = s2L0RealSize; + mmadParams.k = constInfo_.headDim; + mmadParams.cmatrixInitVal = true; + mmadParams.cmatrixSource = false; + Mmad(cL0_[(l0BufIdx_ % L0_BUF_NUM) * L0C_BUFFER_OFFSET], queryL0_[(l0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET], + keyL0_[(kl0BufIdx_ % L0_BUF_NUM) * L0AB_BUFFER_OFFSET], mmadParams); + if ((mmadParams.m / 16) * (mmadParams.n / 16) < 10) { + PipeBarrier(); + } +} + +template +__aicore__ inline void LightningIndexerServiceCube::Fixp(uint64_t s1gGmOffset, + uint64_t s2GmOffset, uint64_t s1gL0RealSize, + uint64_t s2L0RealSize, const LICommon::RunInfo &runInfo) +{ + SetFlag(M_FIX_EVENT + l0BufIdx_ % L0_BUF_NUM); + WaitFlag(M_FIX_EVENT + l0BufIdx_ % L0_BUF_NUM); + + if constexpr (std::is_same::value) { + FixpipeParamsC310 fixpipeParams; + // L0C上的bmm1结果矩阵N方向的size大小;同mmadParams.n;8个元素(32B)对齐 + fixpipeParams.nSize = (s2L0RealSize + 7) >> 3 << 3; + // 有效数据不足16行,只需输出部分行即可;L0C上的bmm1结果矩阵M方向的size大小必须是偶数 + fixpipeParams.mSize = (s1gL0RealSize + 1) >> 1 << 1; + // 源NZ矩阵中相邻Z排布的起始地址偏移 + // L0C上matmul结果相邻连续数据片断间隔(前面一个数据块的头与后面数据块的头的间隔),单位为16 *sizeof(T) + fixpipeParams.srcStride = ((fixpipeParams.mSize + 15) / 16) * 16; + // mmResUb上两行之间的间隔,单位:element + fixpipeParams.dstStride = constInfo_.s2BaseSize; + // 双目标模式,按M维度拆分, M / 2 * N写入每个UB,M必须为2的倍数 + fixpipeParams.dualDstCtl = 1; + fixpipeParams.params.ndNum = 1; + fixpipeParams.params.srcNdStride = 0; + fixpipeParams.params.dstNdStride = 0; + Fixpipe(mm1ResUB_[(runInfo.loop % 2) * + CeilDiv(constInfo_.mBaseSize, 2) * constInfo_.s2BaseSize + + CeilDiv(s1gGmOffset, 2) * fixpipeParams.dstStride + s2GmOffset], + cL0_[(l0BufIdx_ % L0_BUF_NUM) * L0C_BUFFER_OFFSET], fixpipeParams); + } +} + +template +__aicore__ inline void LightningIndexerServiceCube::AllocEventID() +{ + SetMMLayoutTransform(true); + SetFlag(KEY_MTE1_MTE2_EVENT + 0); + SetFlag(KEY_MTE1_MTE2_EVENT + 1); + SetFlag(KEY_MTE1_MTE2_EVENT + 2); + + SetFlag(QUERY_MTE1_MTE2_EVENT + 0); + SetFlag(QUERY_MTE1_MTE2_EVENT + 1); + + SetFlag(M_MTE1_EVENT + 0); + SetFlag(M_MTE1_EVENT + 1); + + SetFlag(FIX_M_EVENT + 0); + SetFlag(FIX_M_EVENT + 1); +} + +template +__aicore__ inline void LightningIndexerServiceCube::FreeEventID() +{ + SetMMLayoutTransform(false); + WaitFlag(KEY_MTE1_MTE2_EVENT + 0); + WaitFlag(KEY_MTE1_MTE2_EVENT + 1); + WaitFlag(KEY_MTE1_MTE2_EVENT + 2); + + WaitFlag(QUERY_MTE1_MTE2_EVENT + 0); + WaitFlag(QUERY_MTE1_MTE2_EVENT + 1); + + WaitFlag(M_MTE1_EVENT + 0); + WaitFlag(M_MTE1_EVENT + 1); + + WaitFlag(FIX_M_EVENT + 0); + WaitFlag(FIX_M_EVENT + 1); +} +} // namespace LIKernel +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_service_vector.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_service_vector.h new file mode 100644 index 0000000000000000000000000000000000000000..70cae0d4f7d2da759f44a4070ea3a8ef6b023223 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/lightning_indexer_service_vector.h @@ -0,0 +1,602 @@ +/** + * 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 lightning_indexer_service_vector.h + * \brief + */ +#ifndef LIGHTNING_INDEXER_SERVICE_VECTOR_H +#define LIGHTNING_INDEXER_SERVICE_VECTOR_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 "../lightning_indexer_common.h" +#include "../arch35/vf/lightning_indexer_vector1.h" +#include "../arch35/vf/lightning_indexer_topk.h" + +namespace LIKernel { +using namespace LICommon; +constexpr uint32_t TRUNK_LEN_8K = 8192; +constexpr uint32_t TRUNK_LEN_4K = 4096; +constexpr uint32_t TRUNK_LEN_2K = 2048; +constexpr uint32_t TOPK_LEN_7K = 7168; +constexpr uint32_t TOPK_LEN_5K = 5120; + +template +struct LightningIndexerTypeTraits { + using weightsType = Q_T; // 默认:weightsType绑定Q_T +}; + +template +struct LightningIndexerTypeTraits { + using weightsType = float; // W_T=float时,强制weightsType为float +}; +template +class LightningIndexerServiceVector { +public: + // =================================类型定义区================================= + static constexpr LI_LAYOUT LAYOUT_T = LIT::layout; + static constexpr LI_LAYOUT K_LAYOUT_T = LIT::keyLayout; + static constexpr bool PAGE_ATTENTION = LIT::pageAttention; + static constexpr bool DT_W_FLAG = LIT::weightsTypeFlag; + using Q_T = typename LIT::queryType; + using K_T = typename LIT::keyType; + using SCORE_T = uint32_t; + using W_T = typename LightningIndexerTypeTraits::type>::weightsType; + + __aicore__ inline LightningIndexerServiceVector(){}; + __aicore__ inline void ProcessVec1(const LICommon::RunInfo &info); + __aicore__ inline void ProcessTopK(const LICommon::RunInfo &info); + __aicore__ inline void InitBuffers(TPipe *pipe); + __aicore__ inline void InitParams(const struct LICommon::ConstInfo &constInfo, + const LITilingData *__restrict tilingData); + __aicore__ inline void InitVecWorkspaceTensor(GlobalTensor scoreGm); + __aicore__ inline void InitVecInputTensor(GlobalTensor weightsGm, GlobalTensor indiceOutGm, + GlobalTensor valueOutGm, GlobalTensor blockTableGm); + __aicore__ inline void CleanInvalidOutput(int64_t invalidS1offset); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + +protected: + GlobalTensor scoreGm; + GlobalTensor weightsGm; + GlobalTensor indiceOutGm; + GlobalTensor valueOutGm; + GlobalTensor blockTableGm; + // =================================常量区================================= + static constexpr uint32_t VEC1_V_MTE2_EVENT = EVENT_ID0; + static constexpr uint32_t VEC1_MTE2_V_EVENT = EVENT_ID1; + static constexpr uint32_t VEC1_V_MTE3_EVENT = EVENT_ID2; + static constexpr uint32_t VEC1_MTE3_V_EVENT = EVENT_ID3; + + static constexpr uint32_t TOPK_V_MTE2_EVENT = EVENT_ID4; + static constexpr uint32_t TOPK_MTE2_V_EVENT = EVENT_ID5; + static constexpr uint32_t TOPK_V_MTE3_EVENT = EVENT_ID6; + static constexpr uint32_t TOPK_MTE3_V_EVENT = EVENT_ID7; + + static constexpr uint32_t MTE3_MTE2_EVENT = EVENT_ID0; + static constexpr uint32_t V_MTE2_EVENT = EVENT_ID7; + static constexpr uint32_t V_MTE2_EVENT1 = EVENT_ID2; + static constexpr uint32_t V_MTE2_EVENT2 = EVENT_ID3; + static constexpr uint32_t V_MTE2_EVENT3 = EVENT_ID5; + +private: + // ================================Local Buffer区==================================== + + // tmp buff for vector + TBuf resMm1Buf_; + LocalTensor resMm1UB_; + // tmp buff for weight + TBuf weightBuf_; + LocalTensor weightUB_; + + // tmp buff for out + TBuf outBuf_; + LocalTensor vec1OutUB_; + + // tmp buff for returnValue K_T + TBuf valueOutBuf_; + LocalTensor valueOutLocal_; + + // tmp buff for topk + TBuf mrgValueBuf_; + LocalTensor mrgValueLocal_; + + TBuf indicesOutBuf_; + LocalTensor indicesOutLocal_; + + TBuf scoreOutBuf_; + LocalTensor scoreOutLocal_; + + TBuf topkSharedTmpBuf_; + LocalTensor topkSharedTmpLocal_; + int32_t blockId_ = -1; + // para for vector + int32_t groupInner_ = 0; + int32_t globalTopkNum_ = 0; + int64_t blockS2StartIdx_ = 0; + int32_t gSize_ = 0; + int32_t kSeqSize_ = 0; + int32_t kHeadNum_ = 0; + int32_t qHeadNum_ = 0; + int32_t s1BaseSize_ = 0; + int32_t s2BaseSize_ = 0; + int32_t kCacheBlockSize_ = 0; + int32_t maxBlockNumPerBatch_ = 0; + uint32_t topkCount_ = 0; + uint32_t topkCountAlign256_ = 0; // topkCount对齐到256(直方图需要),支持topk泛化 + uint32_t trunkLen_ = 0; + bool returnValueFlag = false; + + struct LICommon::ConstInfo constInfo_; + topk::LITopk topkOp_; +}; + +template +__aicore__ inline void LightningIndexerServiceVector::InitBuffers(TPipe *pipe) +{ + pipe->InitBuffer(resMm1Buf_, 2 * CeilDiv(constInfo_.mBaseSize, 2) * s2BaseSize_ * sizeof(float)); + resMm1UB_ = resMm1Buf_.Get(); + + pipe->InitBuffer(weightBuf_, 2 * CeilDiv(s1BaseSize_, 2) * + LICommon::Align((uint64_t)gSize_, (uint64_t)16) * sizeof(W_T)); + weightUB_ = weightBuf_.Get(); + pipe->InitBuffer(outBuf_, + 2 * CeilDiv(s1BaseSize_, 2) * s2BaseSize_ * sizeof(SCORE_T)); + vec1OutUB_ = outBuf_.Get(); // out + + // Topk + pipe->InitBuffer(mrgValueBuf_, + (topkCountAlign256_ + trunkLen_) * sizeof(SCORE_T)); + mrgValueLocal_ = mrgValueBuf_.Get(); + // returnvalue + if (topkCount_ <= 2048) { + pipe->InitBuffer(valueOutBuf_, topkCountAlign256_ * sizeof(K_T)); + valueOutLocal_ = valueOutBuf_.Get(); + } else { // sparseCount > 2k时,复用return value相关UB + valueOutLocal_ = mrgValueBuf_.Get(); // returnValue float + } + + // 大小:(topkCountAlign256_ + 64) * 4 64:duplicate刷-1需要额外空间 + pipe->InitBuffer(indicesOutBuf_, + (topkCountAlign256_ + 64) * sizeof(uint32_t)); + indicesOutLocal_ = indicesOutBuf_.Get(); + + pipe->InitBuffer(scoreOutBuf_, topkCountAlign256_ * sizeof(SCORE_T)); + scoreOutLocal_ = scoreOutBuf_.Get(); + + uint64_t topkSharedTmpSize = topkOp_.GetSharedTmpBufferSize(); + pipe->InitBuffer(topkSharedTmpBuf_, topkSharedTmpSize); + topkSharedTmpLocal_ = topkSharedTmpBuf_.Get(); + topkOp_.InitBuffers(topkSharedTmpLocal_, indicesOutLocal_); +} + +template +__aicore__ inline void LightningIndexerServiceVector::InitParams(const struct LICommon::ConstInfo &constInfo, + const LITilingData *__restrict tilingData) +{ + this->constInfo_ = constInfo; + blockS2StartIdx_ = 0; + gSize_ = constInfo.gSize; + kSeqSize_ = constInfo.kSeqSize; + // define N2 para + kHeadNum_ = constInfo.kHeadNum; + qHeadNum_ = constInfo.qHeadNum; + // define MMBase para + s1BaseSize_ = constInfo.s1BaseSize; // 4 + s2BaseSize_ = constInfo.s2BaseSize; // 128 + kCacheBlockSize_ = constInfo.kCacheBlockSize; + maxBlockNumPerBatch_ = constInfo.maxBlockNumPerBatch; + returnValueFlag = constInfo.returnValueFlag; + blockId_ = GetBlockIdx(); + trunkLen_ = constInfo.sparseCount > TOPK_LEN_5K ? + (constInfo.sparseCount > TOPK_LEN_7K ? TRUNK_LEN_2K : TRUNK_LEN_4K) : TRUNK_LEN_8K; + topkCount_ = constInfo.sparseCount; + topkOp_.Init(topkCount_, trunkLen_); + topkCountAlign256_ = LICommon::Align(constInfo.sparseCount, (uint64_t)256); // topkCount对齐到256 +} + +template +__aicore__ inline void LightningIndexerServiceVector::InitVecInputTensor(GlobalTensor weightsGm, + GlobalTensor indiceOutGm, + GlobalTensor valueOutGm, + GlobalTensor blockTableGm) +{ + this->weightsGm = weightsGm; + this->indiceOutGm = indiceOutGm; + this->valueOutGm = valueOutGm; + this->blockTableGm = blockTableGm; +} + +template +__aicore__ inline void LightningIndexerServiceVector::InitVecWorkspaceTensor(GlobalTensor scoreGm) +{ + this->scoreGm = scoreGm; // resucesum*k +} + +template +__aicore__ inline void LightningIndexerServiceVector::AllocEventID() +{ + SetFlag(VEC1_V_MTE2_EVENT + 0); + SetFlag(VEC1_V_MTE2_EVENT + 1); + SetFlag(VEC1_MTE3_V_EVENT + 0); + SetFlag(VEC1_MTE3_V_EVENT + 1); + + SetFlag(TOPK_V_MTE2_EVENT); + SetFlag(TOPK_MTE3_V_EVENT); + SetFlag(V_MTE2_EVENT1); +} + +template +__aicore__ inline void LightningIndexerServiceVector::FreeEventID() +{ + WaitFlag(VEC1_V_MTE2_EVENT + 0); + WaitFlag(VEC1_V_MTE2_EVENT + 1); + WaitFlag(VEC1_MTE3_V_EVENT + 0); + WaitFlag(VEC1_MTE3_V_EVENT + 1); + + WaitFlag(TOPK_V_MTE2_EVENT); + WaitFlag(TOPK_MTE3_V_EVENT); + WaitFlag(V_MTE2_EVENT1); +} + +template +__aicore__ inline void LightningIndexerServiceVector::CleanInvalidOutput(int64_t invalidS1Offset) +{ + // init -1 and copy to output + uint64_t dealSize = constInfo_.sparseCount; + GlobalTensor indexOutput = indiceOutGm[invalidS1Offset]; + AscendC::InitGlobalMemory(indexOutput, dealSize, constInfo_.INVALID_IDX); + if (returnValueFlag) { + SetFlag(TOPK_MTE3_V_EVENT); + WaitFlag(TOPK_MTE3_V_EVENT); + Duplicate(valueOutLocal_.template ReinterpretCast(), constInfo_.INVALID_VAL, constInfo_.sparseCount); + + SetFlag(TOPK_V_MTE3_EVENT); + WaitFlag(TOPK_V_MTE3_EVENT); + + AscendC::DataCopyParams copyOutValueParams; + copyOutValueParams.blockCount = 1; + copyOutValueParams.blockLen = constInfo_.sparseCount * sizeof(K_T); + copyOutValueParams.srcStride = 0; + copyOutValueParams.dstStride = 0; + AscendC::DataCopyPad(valueOutGm[invalidS1Offset], valueOutLocal_, copyOutValueParams); + } +} + +template +__aicore__ inline void LightningIndexerServiceVector::ProcessVec1(const LICommon::RunInfo &info) +{ + auto pingpong = (info.loop % 2); + // CV同步, V核等C核计算完mm1,mm1Res已搬运到UB + CrossCoreWaitFlag(LICommon::ConstInfo::CROSS_CV_EVENT + pingpong); + + int64_t curS1Idx = info.gS1Idx * s1BaseSize_; + int64_t curS2Idx = info.s2Idx * s2BaseSize_; + int64_t curS1ProcNum = curS1Idx + s1BaseSize_ > info.actS1Size ? info.actS1Size % s1BaseSize_ : s1BaseSize_; + int64_t curAivS1Idx = curS1Idx + (blockId_ % 2) * CeilDiv(curS1ProcNum, 2); + int64_t curAivS1ProcNum = (blockId_ % 2 == 0) ? CeilDiv(curS1ProcNum, 2) : curS1ProcNum / 2; + + if (curAivS1ProcNum == 0) { + // V核处理完,通知C核可以把mm1Res搬运到UB + CrossCoreSetFlag(LICommon::ConstInfo::CROSS_VC_EVENT + + pingpong); + return; + } + WaitFlag(VEC1_V_MTE2_EVENT + pingpong); + // weightsGm --> weightUB_ + uint64_t gSizeAlign16 = LICommon::Align((uint64_t)gSize_, (uint64_t)16); + int64_t weightGmOffset = info.tensorWeightsOffset + curAivS1Idx * kHeadNum_ * gSize_; + DataCopyPadExtParams padWeightsParams{true, 0, 0, 0}; + DataCopyExtParams qwDataCopyExtParams; + qwDataCopyExtParams.blockCount = curAivS1ProcNum; + qwDataCopyExtParams.blockLen = gSize_ * sizeof(W_T); + qwDataCopyExtParams.srcStride = 0; + qwDataCopyExtParams.dstStride = (gSizeAlign16 - gSize_) * sizeof(W_T) / 32; + DataCopyPad(weightUB_[pingpong * CeilDiv(s1BaseSize_, 2) * gSizeAlign16], + weightsGm[weightGmOffset], qwDataCopyExtParams, padWeightsParams); + + SetFlag(VEC1_MTE2_V_EVENT + pingpong); + WaitFlag(VEC1_MTE2_V_EVENT + pingpong); + WaitFlag(VEC1_MTE3_V_EVENT + pingpong); + + for (int64_t s1IdxTmp = 0; s1IdxTmp < curAivS1ProcNum; s1IdxTmp++) { + vector1::MulWeightAndReduceSum( + vec1OutUB_[pingpong * CeilDiv(s1BaseSize_, 2) * s2BaseSize_ + s1IdxTmp * s2BaseSize_], + resMm1UB_[pingpong * CeilDiv(constInfo_.mBaseSize, 2) * + s2BaseSize_ + s1IdxTmp * gSize_ * s2BaseSize_], + weightUB_[pingpong * CeilDiv(s1BaseSize_, 2) * gSizeAlign16 + s1IdxTmp * gSizeAlign16], + gSize_); + } + SetFlag(VEC1_V_MTE2_EVENT + pingpong); + SetFlag(VEC1_V_MTE3_EVENT + pingpong); + WaitFlag(VEC1_V_MTE3_EVENT + pingpong); + // outUB_ ---> scoreGm + uint64_t kSeqSizeAlign = LICommon::Align((uint64_t)constInfo_.kSeqSize, (uint64_t)s2BaseSize_); + int64_t vec1OutGmOffset = blockId_ % 2 == 0 ? curS2Idx : + CeilDiv(s1BaseSize_, 2) * kSeqSizeAlign + curS2Idx; + DataCopyExtParams copyOutParams; + copyOutParams.blockCount = curAivS1ProcNum; + copyOutParams.blockLen = s2BaseSize_ * sizeof(SCORE_T); + copyOutParams.srcStride = 0; + copyOutParams.dstStride = (kSeqSizeAlign - s2BaseSize_) * sizeof(SCORE_T); + + DataCopyPad(scoreGm[vec1OutGmOffset], + vec1OutUB_[pingpong * CeilDiv(s1BaseSize_, 2) * s2BaseSize_], + copyOutParams); + SetFlag(VEC1_MTE3_V_EVENT + pingpong); + // V核处理完,通知C核可以把mm1Res搬运到UB + CrossCoreSetFlag(LICommon::ConstInfo::CROSS_VC_EVENT + pingpong); +} + +template +__aicore__ inline void LightningIndexerServiceVector::ProcessTopK(const LICommon::RunInfo &info) +{ + SetFlag(MTE3_MTE2_EVENT); + WaitFlag(MTE3_MTE2_EVENT); + int64_t curS1Idx = info.gS1Idx * s1BaseSize_; + int64_t curS2Idx = info.s2Idx * s2BaseSize_; + int64_t curS1ProcNum = curS1Idx + s1BaseSize_ > info.actS1Size ? info.actS1Size % s1BaseSize_ : s1BaseSize_; + int64_t curAivS1Idx = curS1Idx + (blockId_ % 2) * CeilDiv(curS1ProcNum, 2); + int64_t curAivS1ProcNum = (blockId_ % 2 == 0) ? CeilDiv(curS1ProcNum, 2) : curS1ProcNum / 2; + + AscendC::DataCopyExtParams copyInParams; + copyInParams.blockCount = 1; + copyInParams.srcStride = 0; + copyInParams.dstStride = 0; + copyInParams.rsv = 0; + + AscendC::DataCopyParams copyOutParams; + copyOutParams.blockCount = 1; + copyOutParams.blockLen = topkCount_ * sizeof(uint32_t); // bytes + copyOutParams.srcStride = 0; + copyOutParams.dstStride = 0; + + int32_t cuRealAcSeq = info.actS2Size; + if (constInfo_.attenMaskFlag) { + cuRealAcSeq = info.actS2SizeOrig - info.actS1Size + curAivS1Idx + 1; + } + + int32_t validS2Len = cuRealAcSeq; + for (uint32_t i = 0; i < curAivS1ProcNum; i++) { + uint32_t rowIdx = blockId_ % 2 * CeilDiv(curS1ProcNum, 2) + i; + uint32_t vecOffset = blockId_ % 2 * CeilDiv(s1BaseSize_, 2) + i; + + SCORE_T zero = 0; + int32_t neg = -1; + if (constInfo_.attenMaskFlag) { + validS2Len = (int32_t)i + cuRealAcSeq; + } + if (validS2Len <= 0) { + WaitFlag(TOPK_MTE3_V_EVENT); + Duplicate(indicesOutLocal_.ReinterpretCast(), neg, topkCount_); + SetFlag(TOPK_V_MTE3_EVENT); + WaitFlag(TOPK_V_MTE3_EVENT); + AscendC::DataCopyPad(indiceOutGm[info.indiceOutOffset + (curS1Idx + rowIdx) * topkCount_], + indicesOutLocal_.ReinterpretCast(), + copyOutParams); + SetFlag(TOPK_MTE3_V_EVENT); + if (returnValueFlag) { + WaitFlag(TOPK_MTE3_V_EVENT); + Duplicate(valueOutLocal_.template ReinterpretCast(), constInfo_.INVALID_VAL, topkCount_); + + SetFlag(TOPK_V_MTE3_EVENT); + WaitFlag(TOPK_V_MTE3_EVENT); + + AscendC::DataCopyParams copyOutValueParams; + copyOutValueParams.blockCount = 1; + copyOutValueParams.blockLen = topkCount_ * sizeof(K_T); + copyOutValueParams.srcStride = 0; + copyOutValueParams.dstStride = 0; + AscendC::DataCopyPad( + valueOutGm[info.valueOutOffset + (curS1Idx + rowIdx) * topkCount_], + valueOutLocal_, + copyOutValueParams); + SetFlag(TOPK_MTE3_V_EVENT); + } + continue; + } + + WaitFlag(TOPK_V_MTE2_EVENT); + WaitFlag(TOPK_MTE3_V_EVENT); + + AscendC::DataCopyPadExtParams padParams{true, 0, 0, 0}; + if (validS2Len >= topkCount_) { + uint32_t s2LoopNum = (validS2Len + trunkLen_ - 1) / trunkLen_; + bool useSingleLoop = (s2LoopNum == 1) || ((topkCount_ > trunkLen_) && + (validS2Len <= (uint32_t)topkCountAlign256_)); + if (useSingleLoop) { + uint32_t validS2LenAlign = LICommon::Align(validS2Len, (int32_t)256); + Duplicate(mrgValueLocal_[validS2Len / 256 * 256], zero, validS2LenAlign - validS2Len / 256 * 256); + SetFlag(V_MTE2_EVENT); + WaitFlag(V_MTE2_EVENT); + copyInParams.blockLen = validS2Len * sizeof(SCORE_T); // byte + AscendC::DataCopyPadExtParams padParams{true, 0, 0, 0}; + AscendC::DataCopyPad( + mrgValueLocal_, + scoreGm[vecOffset * LICommon::Align((uint64_t)constInfo_.kSeqSize, (uint64_t)s2BaseSize_)], + copyInParams, padParams); + SetFlag(TOPK_MTE2_V_EVENT); + WaitFlag(TOPK_MTE2_V_EVENT); + topkOp_(mrgValueLocal_, indicesOutLocal_, scoreOutLocal_, validS2LenAlign, 0, 1, returnValueFlag); + } else { + uint32_t actS2LoopNum = 0; + if (topkCount_ > trunkLen_) { + actS2LoopNum = 1 + (validS2Len - topkCountAlign256_ + trunkLen_ - 1) / trunkLen_; + } else { + actS2LoopNum = (validS2Len + trunkLen_ - 1) / trunkLen_; + } + for (uint32_t loopIdx = 0; loopIdx < actS2LoopNum; loopIdx++) { + if (loopIdx == 0) { + if (topkCount_ > trunkLen_) { + copyInParams.blockLen = topkCountAlign256_ * sizeof(SCORE_T); // byte + AscendC::DataCopyPad(scoreOutLocal_, + scoreGm[vecOffset * + LICommon::Align((uint64_t)constInfo_.kSeqSize, + (uint64_t)s2BaseSize_)], + copyInParams, padParams); + SetFlag(TOPK_MTE2_V_EVENT); + WaitFlag(TOPK_MTE2_V_EVENT); + AscendC::CreateVecIndex(indicesOutLocal_.ReinterpretCast(), + (int32_t)zero, topkCountAlign256_); + AscendC::CreateVecIndex(topkSharedTmpLocal_.ReinterpretCast(), + (int32_t)zero, topkCountAlign256_); + } else { + copyInParams.blockLen = trunkLen_ * sizeof(SCORE_T); // byte + AscendC::DataCopyPad( + mrgValueLocal_, + scoreGm[vecOffset * LICommon::Align((uint64_t)constInfo_.kSeqSize, + (uint64_t)s2BaseSize_)], + copyInParams, padParams); + SetFlag(TOPK_MTE2_V_EVENT); + WaitFlag(TOPK_MTE2_V_EVENT); + topkOp_(mrgValueLocal_, indicesOutLocal_, + scoreOutLocal_, trunkLen_, loopIdx, + actS2LoopNum, returnValueFlag); + } + continue; + } + SetFlag(V_MTE2_EVENT2); + WaitFlag(V_MTE2_EVENT2); + uint32_t validTrunkLen = 0; + uint32_t offset = 0; + if (topkCount_ > trunkLen_) { + validTrunkLen = (topkCountAlign256_ + (loopIdx-1) * trunkLen_ + trunkLen_) > validS2Len + ? (validS2Len - topkCountAlign256_)% trunkLen_ + :trunkLen_; + offset = vecOffset * + LICommon::Align((uint64_t)constInfo_.kSeqSize, (uint64_t)s2BaseSize_) + + topkCountAlign256_ + (loopIdx - 1)* trunkLen_; + } else { + validTrunkLen = (loopIdx * trunkLen_ + trunkLen_) > validS2Len + ? validS2Len % trunkLen_ + :trunkLen_; + offset = vecOffset * + LICommon::Align((uint64_t)constInfo_.kSeqSize, (uint64_t)s2BaseSize_) + + loopIdx * trunkLen_; + } + AscendC::DataCopy(mrgValueLocal_, scoreOutLocal_, topkCountAlign256_); + // topk如果没有对齐到256,则把topkCountAlign256_ - topkCount_部分刷0 + // 如果是tok > trunklen, 第一轮每调用topk,是直接拷贝的,所以不需要刷零 + bool isZeroPadding = (topkCount_ > trunkLen_) ? (loopIdx > 1) : true; + if (topkCountAlign256_ != topkCount_ && isZeroPadding) { + uint64_t mask[1]; + mask[0] = ~0; + mask[0] = mask[0] << (topkCount_ % 64); + PipeBarrier(); + // 把topkCount_对齐到64刷0,此处由于duplicate的限制mask[0]刷64个数 + Duplicate(mrgValueLocal_[topkCount_ / 64 * 64], zero, mask, 1, 1, 0); + PipeBarrier(); + // 把topk剩余对齐到256的部分刷0 + Duplicate(mrgValueLocal_[topkCount_ / 64 * 64 + 64], zero, + topkCountAlign256_ - (topkCount_ / 64 * 64 + 64)); + SetFlag(V_MTE2_EVENT3); + WaitFlag(V_MTE2_EVENT3); + } + copyInParams.blockLen = validTrunkLen * sizeof(SCORE_T); // byte + // TOPK 直方图一次必须计算256,输入处理数据需要和256对齐 + if ((topkCountAlign256_ + validTrunkLen) % 256 != 0) { + Duplicate(mrgValueLocal_[topkCountAlign256_ + validTrunkLen / 256 * 256], + zero, LICommon::Align(validTrunkLen, + (uint32_t)256) - validTrunkLen / 256 * 256); + SetFlag(V_MTE2_EVENT); + WaitFlag(V_MTE2_EVENT); + } + WaitFlag(V_MTE2_EVENT1); + AscendC::DataCopyPad(mrgValueLocal_[topkCountAlign256_], scoreGm[offset], copyInParams, padParams); + SetFlag(TOPK_MTE2_V_EVENT); + WaitFlag(TOPK_MTE2_V_EVENT); + topkOp_(mrgValueLocal_, indicesOutLocal_, + scoreOutLocal_, + LICommon::Align(topkCountAlign256_ + validTrunkLen, (uint32_t)256), + loopIdx, actS2LoopNum, returnValueFlag); + SetFlag(V_MTE2_EVENT1); + } + } + } else { + AscendC::CreateVecIndex(indicesOutLocal_.ReinterpretCast(), (int32_t)zero, validS2Len); + if (returnValueFlag) { + copyInParams.blockLen = LICommon::Align(validS2Len, (int32_t)32) * sizeof(SCORE_T); + AscendC::DataCopyPad(scoreOutLocal_, + scoreGm[vecOffset * LICommon::Align((uint64_t)constInfo_.kSeqSize, (uint64_t)s2BaseSize_)], + copyInParams, padParams); + SetFlag(TOPK_MTE2_V_EVENT); + WaitFlag(TOPK_MTE2_V_EVENT); + } + } + + if (validS2Len < topkCount_) { + uint64_t mask[1]; + mask[0] = ~0; + mask[0] = mask[0] << (validS2Len % 8); + PipeBarrier(); + Duplicate(indicesOutLocal_.ReinterpretCast()[validS2Len / 8 * 8], neg, mask, 1, 1, 0); + } + + if (validS2Len / 8 * 8 + 64 < topkCount_) { + PipeBarrier(); + Duplicate(indicesOutLocal_.ReinterpretCast()[validS2Len / 8 * 8 + 64], + neg, topkCount_ - (validS2Len / 8 * 8 + 64)); + } + + SetFlag(TOPK_V_MTE2_EVENT); + SetFlag(TOPK_V_MTE3_EVENT); + WaitFlag(TOPK_V_MTE3_EVENT); + AscendC::DataCopyPad(indiceOutGm[info.indiceOutOffset + (curS1Idx + rowIdx) * topkCount_], + indicesOutLocal_.ReinterpretCast(), copyOutParams); + + + // // 是否返回Value值 + if (returnValueFlag) { + WaitFlag(TOPK_V_MTE2_EVENT); + // uint16_t -> bfloat16 + if (std::is_same_v) { + vector1::UIntToFloatReturnValue(valueOutLocal_.template ReinterpretCast(), + scoreOutLocal_, topkCountAlign256_); + } else { + vector1::UIntToFloatReturnValue(valueOutLocal_.template ReinterpretCast(), + scoreOutLocal_, topkCountAlign256_); + } + + if (validS2Len < topkCount_) { + uint64_t mask[1]; + mask[0] = ~0; + mask[0] = mask[0] << (validS2Len % 16); + PipeBarrier(); + Duplicate(valueOutLocal_.template ReinterpretCast()[validS2Len / 16 * 16], + constInfo_.INVALID_VAL, mask, 1, 1, 0); + } + if (validS2Len / 16 * 16 + 64 < topkCount_) { + PipeBarrier(); + Duplicate(valueOutLocal_.template ReinterpretCast()[validS2Len / 16 * 16 + 64], + constInfo_.INVALID_VAL, topkCount_ - (validS2Len / 16 * 16 + 64)); + } + SetFlag(TOPK_V_MTE2_EVENT); + SetFlag(TOPK_V_MTE3_EVENT); + WaitFlag(TOPK_V_MTE3_EVENT); + AscendC::DataCopyParams copyOutValueParams; + copyOutValueParams.blockCount = 1; + copyOutValueParams.blockLen = topkCount_ * sizeof(K_T); // bytes + copyOutValueParams.srcStride = 0; + copyOutValueParams.dstStride = 0; + // 搬运到GM + AscendC::DataCopyPad( + valueOutGm[info.valueOutOffset + (curS1Idx + rowIdx) * topkCount_], + valueOutLocal_, copyOutValueParams); + } + SetFlag(TOPK_MTE3_V_EVENT); + } +} +} // namespace LIKernel +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/common/lightning_indexer_vector1_base.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/common/lightning_indexer_vector1_base.h new file mode 100644 index 0000000000000000000000000000000000000000..6a43eddccc007aadc0f164ee358d6f022bd763ba --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/common/lightning_indexer_vector1_base.h @@ -0,0 +1,197 @@ +/** + * 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 lightning_indexer_vector1_base.h + * \brief + */ +#ifndef LIGHTNING_INDEXER_VECTOR1_BASE_H +#define LIGHTNING_INDEXER_VECTOR1_BASE_H + +#include "kernel_operator.h" + +namespace vector1 { + +template +struct FloatSortTraits; + +// fp32 +template <> +struct FloatSortTraits { + using UInt = uint32_t; + static constexpr UInt ZERO = 0x00000000; + static constexpr UInt SIGN_MASK = 0x80000000; + static constexpr UInt NAN_MASK = 0x7FC00000; + static constexpr UInt ALL_ONE = 0xFFFFFFFF; +}; + +// bf16 +template <> +struct FloatSortTraits { + using UInt = uint16_t; + static constexpr UInt ZERO = 0x0000; + static constexpr UInt SIGN_MASK = 0x8000; + static constexpr UInt NAN_MASK = 0x7FC0; + static constexpr UInt ALL_ONE = 0xFFFF; +}; + +template +struct FloatSortConstCtx { + using Traits = FloatSortTraits; + using UInt = typename Traits::UInt; + AscendC::MicroAPI::RegTensor zeros; + AscendC::MicroAPI::RegTensor allOne; + AscendC::MicroAPI::RegTensor signMask; + AscendC::MicroAPI::RegTensor nan; +}; + +template +__simd_callee__ inline void InitFloatSortConstCtx(FloatSortConstCtx& ctx, AscendC::MicroAPI::MaskReg& maskAll) +{ + using Traits = FloatSortTraits; + AscendC::MicroAPI::Duplicate(ctx.zeros, Traits::ZERO, maskAll); + AscendC::MicroAPI::Duplicate(ctx.allOne, Traits::ALL_ONE, maskAll); + AscendC::MicroAPI::Duplicate(ctx.signMask, Traits::SIGN_MASK, maskAll); + AscendC::MicroAPI::Duplicate(ctx.nan, Traits::NAN_MASK, maskAll); +} + +template +__simd_callee__ inline void FloatToSortableKey( + AscendC::MicroAPI::RegTensor::UInt>& + outKey, + AscendC::MicroAPI::RegTensor& inVal, + FloatSortConstCtx& ctx, + AscendC::MicroAPI::MaskReg& maskAll) +{ + using Traits = FloatSortTraits; + using UInt = typename Traits::UInt; + + AscendC::MicroAPI::RegTensor regTemp; + AscendC::MicroAPI::RegTensor regMask; + AscendC::MicroAPI::MaskReg regSelectNan; + AscendC::MicroAPI::MaskReg regSelectSign; + + auto& inBits = (AscendC::MicroAPI::RegTensor&)inVal; + + // 1. NaN check + AscendC::MicroAPI::Compare(regSelectNan, inBits, ctx.nan, maskAll); + + // 2. NaN -> ALL_ONE + AscendC::MicroAPI::Select(outKey, ctx.allOne, inBits, regSelectNan); + + // 3. sign bit + AscendC::MicroAPI::And(regTemp, outKey, ctx.signMask, maskAll); + + AscendC::MicroAPI::Compare(regSelectSign, regTemp, ctx.zeros, maskAll); + + // 4. xor mask + AscendC::MicroAPI::Select(regMask, ctx.allOne, ctx.signMask, regSelectSign); + AscendC::MicroAPI::Xor(outKey, outKey, regMask, maskAll); +} + +template +__simd_callee__ inline void FloatX2ToSortableKey(AscendC::MicroAPI::RegTensor::UInt>& + outKey0, + AscendC::MicroAPI::RegTensor::UInt>& + outKey1, + AscendC::MicroAPI::RegTensor& inVal0, + AscendC::MicroAPI::RegTensor& inVal1, + FloatSortConstCtx& ctx, + AscendC::MicroAPI::MaskReg& maskAll) +{ + using Traits = FloatSortTraits; + using UInt = typename Traits::UInt; + + AscendC::MicroAPI::RegTensor regTemp[2]; + AscendC::MicroAPI::RegTensor regMask[2]; + AscendC::MicroAPI::MaskReg regSelectNan[2]; + AscendC::MicroAPI::MaskReg regSelectSign[2]; + + auto& inBits0 = (AscendC::MicroAPI::RegTensor&)inVal0; + auto& inBits1 = (AscendC::MicroAPI::RegTensor&)inVal1; + + // 1. NaN check + AscendC::MicroAPI::Compare(regSelectNan[0], inBits0, ctx.nan, maskAll); + AscendC::MicroAPI::Compare(regSelectNan[1], inBits1, ctx.nan, maskAll); + + // 2. NaN -> ALL_ONE + AscendC::MicroAPI::Select(outKey0, ctx.allOne, inBits0, regSelectNan[0]); + AscendC::MicroAPI::Select(outKey1, ctx.allOne, inBits1, regSelectNan[1]); + + // 3. sign bit + AscendC::MicroAPI::And(regTemp[0], outKey0, ctx.signMask, maskAll); + AscendC::MicroAPI::And(regTemp[1], outKey1, ctx.signMask, maskAll); + + AscendC::MicroAPI::Compare(regSelectSign[0], regTemp[0], ctx.zeros, maskAll); + AscendC::MicroAPI::Compare(regSelectSign[1], regTemp[1], ctx.zeros, maskAll); + + // 4. xor mask + AscendC::MicroAPI::Select(regMask[0], ctx.allOne, ctx.signMask, regSelectSign[0]); + AscendC::MicroAPI::Select(regMask[1], ctx.allOne, ctx.signMask, regSelectSign[1]); + AscendC::MicroAPI::Xor(outKey0, outKey0, regMask[0], maskAll); + AscendC::MicroAPI::Xor(outKey1, outKey1, regMask[1], maskAll); +} + +template +__simd_callee__ inline void DuplicateZero(AscendC::MicroAPI::RegTensor (®Array)[N], + AscendC::MicroAPI::MaskReg& mask) +{ + static_assert(N <= 4, "N must be <= 4"); + // 不能用循环, 会导致fatal error: error in backend: Unsupported Inst must be hoisted. + if constexpr (N >= 1) { + AscendC::MicroAPI::Duplicate(regArray[0], static_cast(0), mask); + } + if constexpr (N >= 2) { + AscendC::MicroAPI::Duplicate(regArray[1], static_cast(0), mask); + } + if constexpr (N >= 3) { + AscendC::MicroAPI::Duplicate(regArray[2], static_cast(0), mask); + } + if constexpr (N >= 4) { + AscendC::MicroAPI::Duplicate(regArray[3], static_cast(0), mask); + } +} + +template +__simd_callee__ inline void WeightedAccum(AscendC::MicroAPI::RegTensor (&accum)[N], + AscendC::MicroAPI::RegTensor (&input)[N], + AscendC::MicroAPI::RegTensor& weight, + AscendC::MicroAPI::MaskReg& mask) +{ + static_assert(N <= 2, "N must be <= 2"); + // ---- Relu block ---- + if constexpr (ApplyRelu) { + if constexpr (N >= 1) { + AscendC::MicroAPI::Relu(input[0], input[0], mask); + } + if constexpr (N >= 2) { + AscendC::MicroAPI::Relu(input[1], input[1], mask); + } + } + // ---- MulAdd block ---- + if constexpr (N >= 1) { + AscendC::MicroAPI::MulAddDst(accum[0], input[0], weight, mask); + } + if constexpr (N >= 2) { + AscendC::MicroAPI::MulAddDst(accum[1], input[1], weight, mask); + } +} + +__simd_callee__ inline void BroadcastLane(AscendC::MicroAPI::RegTensor& dst, + AscendC::MicroAPI::RegTensor& src, + uint16_t laneIdx) +{ + AscendC::MicroAPI::RegTensor brcGatherIndex; + AscendC::MicroAPI::Duplicate(brcGatherIndex, laneIdx); + AscendC::MicroAPI::Gather(dst, src, brcGatherIndex); +} + +} +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/common/vf_topk_16_gather.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/common/vf_topk_16_gather.h new file mode 100644 index 0000000000000000000000000000000000000000..c4b76fdfbf3284f319472033cb02dbbe621a259a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/common/vf_topk_16_gather.h @@ -0,0 +1,476 @@ +/** + * 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 vf_top_k_16_gather.h +* \brief +*/ + +#ifndef VF_TOP_K_16_GATHER_H +#define VF_TOP_K_16_GATHER_H + +namespace topkb16gather { + +template +__aicore__ inline T TopKGatherAlign(T num, T rnd) +{ + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd))); +} + +template +__simd_vf__ void HistogramsHighVFImpl(__ubuf__ uint32_t* histogramsBuf, + __ubuf__ uint16_t* inputBuf, + uint16_t vfLoop, bool init) +{ + MicroAPI::MaskReg maskRegB32 = MicroAPI::CreateMask(); + MicroAPI::MaskReg maskRegB16 = MicroAPI::CreateMask(); + MicroAPI::MaskReg maskRegB8 = MicroAPI::CreateMask(); + + // 计算直方图coutReg0 0-127 coutReg1 128-255 + MicroAPI::RegTensor coutReg0; + MicroAPI::RegTensor coutReg1; + MicroAPI::Duplicate(coutReg0, 0); + MicroAPI::Duplicate(coutReg1, 0); + + MicroAPI::RegTensor coutReg0U32Even; + MicroAPI::RegTensor coutReg0U32Odd; + MicroAPI::RegTensor coutReg1U32Even; + MicroAPI::RegTensor coutReg1U32Odd; + + MicroAPI::RegTensor vregHigh; + MicroAPI::RegTensor vregLow; + + static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TO_UINT32_EVEN = {MicroAPI::RegLayout::ZERO, + MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TO_UINT32_ODD = {MicroAPI::RegLayout::ONE, + MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + for (uint16_t i = 0; i < vfLoop; ++i) { + MicroAPI::LoadAlign(vregLow, vregHigh, inputBuf + i * 256); + + MicroAPI::Histograms(coutReg0, + (MicroAPI::RegTensor&)vregHigh, + maskRegB8); + MicroAPI::Histograms(coutReg1, + (MicroAPI::RegTensor&)vregHigh, + maskRegB8); + } + + MicroAPI::Cast(coutReg0U32Even, coutReg0, maskRegB16); + MicroAPI::Cast(coutReg0U32Odd, coutReg0, maskRegB16); + MicroAPI::Cast(coutReg1U32Even, coutReg1, maskRegB16); + MicroAPI::Cast(coutReg1U32Odd, coutReg1, maskRegB16); + + MicroAPI::StoreAlign(histogramsBuf, + coutReg0U32Even, coutReg0U32Odd, maskRegB32); + MicroAPI::StoreAlign(histogramsBuf + 128, + coutReg1U32Even, coutReg1U32Odd, maskRegB32); +} + +__simd_vf__ void FindHighTargetBinVFImpl(__ubuf__ uint32_t* idxHighBuf, + __ubuf__ uint32_t* nkValueBuf, + __ubuf__ uint32_t* histogramsBuf, + uint32_t bottomK) +{ + MicroAPI::MaskReg maskRegB32 = MicroAPI::CreateMask(); + + MicroAPI::MaskReg pregGE; + + MicroAPI::ClearSpr(); + + MicroAPI::UnalignRegForStore alignIdxHigh; + + MicroAPI::RegTensor btmK; + MicroAPI::Duplicate(btmK, bottomK); + + MicroAPI::RegTensor idxC; + MicroAPI::RegTensor cout; + MicroAPI::RegTensor sqzIdxHigh; + + for (uint16_t i = 0; i < (uint16_t)(4); ++i) { + MicroAPI::Arange(idxC, i * 64); + + MicroAPI::LoadAlign(cout, histogramsBuf + i * 64); + + MicroAPI::Compare(pregGE, cout, btmK, maskRegB32); + + MicroAPI::Squeeze( + sqzIdxHigh, (MicroAPI::RegTensor&)idxC, pregGE); + MicroAPI::StoreUnAlign(idxHighBuf, sqzIdxHigh, alignIdxHigh); + } + MicroAPI::StoreUnAlignPost(idxHighBuf, alignIdxHigh); + + MicroAPI::LocalMemBar(); + + MicroAPI::RegTensor idxHigh; + MicroAPI::LoadAlign(idxHigh, idxHighBuf); + + MicroAPI::RegTensor idxAll1Reg; + MicroAPI::RegTensor idxPrev0Reg; + MicroAPI::RegTensor prevBinValueReg; + MicroAPI::Duplicate(idxAll1Reg, 1); + + MicroAPI::RegTensor zeroAllReg; + MicroAPI::Duplicate(zeroAllReg, 0); + + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + MicroAPI::Compare(preg0, idxHigh, zeroAllReg, maskRegB32); + MicroAPI::Sub(idxPrev0Reg, idxHigh, (MicroAPI::RegTensor&)idxAll1Reg, maskRegB32); + MicroAPI::ShiftRights(idxPrev0Reg, idxPrev0Reg, (int16_t)24, maskRegB32); + + MicroAPI::Gather(prevBinValueReg, histogramsBuf, idxPrev0Reg, maskRegB32); + MicroAPI::Select(prevBinValueReg, zeroAllReg, prevBinValueReg, preg0); + + MicroAPI::RegTensor nextK; + MicroAPI::Sub(nextK, btmK, prevBinValueReg, maskRegB32); + MicroAPI::StoreAlign(nkValueBuf, nextK, maskRegB32); +} + +template +__simd_vf__ void HistogramsLowVFImpl(__ubuf__ uint32_t* histogramsBuf, + __ubuf__ uint16_t* inputBuf, __ubuf__ uint32_t* idxHighBuf, + uint16_t vfLoop, bool init) +{ + MicroAPI::MaskReg maskRegB32 = MicroAPI::CreateMask(); + MicroAPI::MaskReg maskRegB16 = MicroAPI::CreateMask(); + MicroAPI::MaskReg maskRegB8 = MicroAPI::CreateMask(); + + MicroAPI::MaskReg pregEQ; + + // 计算直方图0-127 128-255 + MicroAPI::RegTensor coutReg0; + MicroAPI::RegTensor coutReg1; + MicroAPI::Duplicate(coutReg0, 0); + MicroAPI::Duplicate(coutReg1, 0); + + MicroAPI::RegTensor coutReg0U32Even; + MicroAPI::RegTensor coutReg0U32Odd; + MicroAPI::RegTensor coutReg1U32Even; + MicroAPI::RegTensor coutReg1U32Odd; + + MicroAPI::RegTensor idxHigh; + MicroAPI::LoadAlign(idxHigh, idxHighBuf); + + MicroAPI::RegTensor vregHigh; + MicroAPI::RegTensor vregLow; + + static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TO_UINT32_EVEN = {MicroAPI::RegLayout::ZERO, + MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TO_UINT32_ODD = {MicroAPI::RegLayout::ONE, + MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + for (uint16_t i = 0; i < vfLoop; ++i) { + MicroAPI::LoadAlign(vregLow, vregHigh, inputBuf + i * 256); + + MicroAPI::Compare(pregEQ, + (MicroAPI::RegTensor&)vregHigh, + (MicroAPI::RegTensor&)idxHigh, maskRegB8); + + MicroAPI::Histograms(coutReg0, + (MicroAPI::RegTensor&)vregLow, pregEQ); + MicroAPI::Histograms(coutReg1, + (MicroAPI::RegTensor&)vregLow, pregEQ); + } + + MicroAPI::Cast(coutReg0U32Even, coutReg0, maskRegB16); + MicroAPI::Cast(coutReg0U32Odd, coutReg0, maskRegB16); + MicroAPI::Cast(coutReg1U32Even, coutReg1, maskRegB16); + MicroAPI::Cast(coutReg1U32Odd, coutReg1, maskRegB16); + + MicroAPI::StoreAlign(histogramsBuf, + coutReg0U32Even, coutReg0U32Odd, maskRegB32); + MicroAPI::StoreAlign(histogramsBuf + 128, + coutReg1U32Even, coutReg1U32Odd, maskRegB32); +} + +__simd_vf__ void FindKthVFImpl(__ubuf__ uint32_t* kValue, + __ubuf__ uint32_t* histogramsBuf, __ubuf__ uint32_t* idxHighBuf, + __ubuf__ uint32_t* idxLowBuf) +{ + MicroAPI::MaskReg maskRegB32 = MicroAPI::CreateMask(); + MicroAPI::MaskReg maskRegB16 = MicroAPI::CreateMask(); + + MicroAPI::MaskReg pregGE; + + MicroAPI::ClearSpr(); + + MicroAPI::UnalignRegForStore alignIdxLow; + + MicroAPI::RegTensor btmK; + MicroAPI::LoadAlign(btmK, kValue); + + MicroAPI::RegTensor idxC; + MicroAPI::RegTensor cout; + MicroAPI::RegTensor sqzIdxLow; + + for (uint16_t i = 0; i < (uint16_t)(4); ++i) { + MicroAPI::Arange(idxC, i * 64); + + MicroAPI::LoadAlign(cout, histogramsBuf + i * 64); + + MicroAPI::Compare(pregGE, cout, btmK, maskRegB32); + + MicroAPI::Squeeze(sqzIdxLow, + (MicroAPI::RegTensor&)idxC, pregGE); + MicroAPI::StoreUnAlign(idxLowBuf, sqzIdxLow, alignIdxLow); + } + MicroAPI::StoreUnAlignPost(idxLowBuf, alignIdxLow); + + MicroAPI::LocalMemBar(); + + MicroAPI::RegTensor idxHigh; + MicroAPI::RegTensor idxLow; + MicroAPI::LoadAlign(idxHigh, idxHighBuf); + MicroAPI::LoadAlign(idxLow, idxLowBuf); + + MicroAPI::RegTensor idxTmp; + MicroAPI::Duplicate(idxTmp, 0xff00); + + MicroAPI::And(idxHigh, idxHigh, (MicroAPI::RegTensor&)idxTmp, maskRegB32); + + MicroAPI::RegTensor idxK; + MicroAPI::Add(idxK, idxHigh, idxLow, maskRegB16); + + MicroAPI::StoreAlign(kValue, idxK, maskRegB32); +} + +/** + 输出所有大于的kth-value的Index + */ +__simd_vf__ void FindIdxGTOutputVFImpl(__ubuf__ uint16_t* outputIdxBuf, + __ubuf__ uint16_t* inputValueBuf, uint16_t beginIdx, + __ubuf__ uint32_t* kValue, uint16_t vfLoop) +{ + MicroAPI::MaskReg maskRegB16 = MicroAPI::CreateMask(); + + MicroAPI::MaskReg poutGT; + + MicroAPI::ClearSpr(); + + MicroAPI::UnalignRegForStore alignIdxReg; + + MicroAPI::RegTensor kthValue; + MicroAPI::LoadAlign(kthValue, kValue); + + MicroAPI::RegTensor vregInput; + MicroAPI::RegTensor idxC; + MicroAPI::RegTensor sqzIdxOut; + + for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) { + MicroAPI::Arange(idxC, beginIdx + i * 128); + + MicroAPI::LoadAlign(vregInput, inputValueBuf + i * 128); + + MicroAPI::Compare(poutGT, vregInput, + (MicroAPI::RegTensor&)kthValue, maskRegB16); + + MicroAPI::Squeeze(sqzIdxOut, + (MicroAPI::RegTensor&)idxC, poutGT); + MicroAPI::StoreUnAlign(outputIdxBuf, sqzIdxOut, alignIdxReg); + } + MicroAPI::StoreUnAlignPost(outputIdxBuf, alignIdxReg); +} + +/** + 输出所有等于的kth-value的Index + */ +__simd_vf__ void FindIdxEQOutputVFImpl(__ubuf__ uint16_t* outputIdxBuf, + __ubuf__ uint16_t* inputValueBuf, uint16_t beginIdx, + __ubuf__ uint32_t* kValue, uint16_t vfLoop) +{ + MicroAPI::MaskReg maskRegB16 = MicroAPI::CreateMask(); + + MicroAPI::MaskReg poutEQ; + + MicroAPI::UnalignRegForStore alignIdxReg; + + MicroAPI::RegTensor kthValue; + MicroAPI::LoadAlign(kthValue, kValue); + + MicroAPI::RegTensor vregInput; + MicroAPI::RegTensor idxC; + MicroAPI::RegTensor sqzIdxOut; + + for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) { + MicroAPI::Arange(idxC, beginIdx + i * 128); + + MicroAPI::LoadAlign(vregInput, inputValueBuf + i * 128); + + MicroAPI::Compare(poutEQ, vregInput, + (MicroAPI::RegTensor&)kthValue, maskRegB16); + + MicroAPI::Squeeze(sqzIdxOut, + (MicroAPI::RegTensor&)idxC, poutEQ); + MicroAPI::StoreUnAlign(outputIdxBuf, sqzIdxOut, alignIdxReg); + } + MicroAPI::StoreUnAlignPost(outputIdxBuf, alignIdxReg); +} + +/** + 输出最终的Value + */ +__simd_vf__ void FindValueOutputVFImpl(__ubuf__ uint16_t* outputValueBuf, + __ubuf__ uint16_t* inputValueBuf, + __ubuf__ uint16_t* tmpIdxBuf, uint16_t vfLoop) +{ + MicroAPI::MaskReg maskRegB16 = MicroAPI::CreateMask(); + + MicroAPI::RegTensor tmpIdx; + MicroAPI::RegTensor outputValue; + + for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) { + MicroAPI::LoadAlign(tmpIdx, tmpIdxBuf + i * 128); + + MicroAPI::Gather(outputValue, inputValueBuf, tmpIdx, maskRegB16); + + MicroAPI::StoreAlign(outputValueBuf + i * 128, + outputValue, maskRegB16); + } +} + +/** + 输出最终的Idx + */ +__simd_vf__ void FindRealIndexVFImpl(__ubuf__ uint32_t* outputIdxBuf, + __ubuf__ uint16_t* tmpIdxBuf, __ubuf__ uint32_t* hisIdxBuf, + uint32_t topK, uint32_t loopIndex, uint16_t vfLoop) +{ + MicroAPI::MaskReg maskRegB32 = MicroAPI::CreateMask(); + + MicroAPI::MaskReg pregNow; + MicroAPI::MaskReg pregHis; + + MicroAPI::RegTensor tmpIdx; + MicroAPI::RegTensor outputGatherIdx; + MicroAPI::RegTensor outputAddsIdx; + + for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) { + MicroAPI::LoadAlign(tmpIdx, tmpIdxBuf + i * 64); + + MicroAPI::Compares(pregNow, + (MicroAPI::RegTensor&)tmpIdx, topK - 1, maskRegB32); + MicroAPI::Xor(pregHis, pregNow, maskRegB32, maskRegB32); + + MicroAPI::Gather(outputGatherIdx, hisIdxBuf, (MicroAPI::RegTensor&)tmpIdx, pregHis); + MicroAPI::Adds(outputAddsIdx, (MicroAPI::RegTensor&)tmpIdx, loopIndex, pregNow); + + MicroAPI::Add(outputGatherIdx, outputGatherIdx, outputAddsIdx, maskRegB32); + + MicroAPI::StoreAlign(outputIdxBuf + i * 64, + outputGatherIdx, maskRegB32); + } +} + +/** + * @brief LiTopKVF 对一个validLen的输入进行topk算法,输出idx_tmp + * @param tmpIdxLocal Temp阶段输出的TopKIndex;如果s2SeqLen < 16K作为最终输出 validLen * 2B + * @param outputValueLocal 如果s2SeqLen > 16K并且是首轮输出Value topK * 2B + * @param inputValueLocal 输入Value validLen * 2B + * @param histogramsLocal 直方图 256 * 4B + * @param idxHighLocal 目标桶高八位 256 * 4B + * @param idxLowLocal 目标桶低八位 256 * 4B + * @param nkValueLocal 存储next_k的值 64 * 4B + * @param topK topK元素 + * @param validLen 有效元素个数,按 256 对齐后的 topkCountAlign256_ + validTrunkLen + */ +template // 是否输出VALUE +__aicore__ inline void LiTopKVF(const LocalTensor& tmpIdxLocal, + const LocalTensor& outputValueLocal, + const LocalTensor& inputValueLocal, + const LocalTensor& histogramsLocal, + const LocalTensor& idxHighLocal, + const LocalTensor& idxLowLocal, + const LocalTensor& nkValueLocal, + uint32_t topK, + uint32_t validLen) +{ + __ubuf__ uint16_t* tmpIdxBuf = (__ubuf__ uint16_t*)tmpIdxLocal.GetPhyAddr(); + __ubuf__ uint16_t* outputValueBuf = (__ubuf__ uint16_t*)outputValueLocal.GetPhyAddr(); + __ubuf__ uint16_t* inputValueBuf = (__ubuf__ uint16_t*)inputValueLocal.GetPhyAddr(); + __ubuf__ uint32_t* histogramsBuf = (__ubuf__ uint32_t*)histogramsLocal.GetPhyAddr(); + __ubuf__ uint32_t* idxHighBuf = (__ubuf__ uint32_t*)idxHighLocal.GetPhyAddr(); + __ubuf__ uint32_t* idxLowBuf = (__ubuf__ uint32_t*)idxLowLocal.GetPhyAddr(); + __ubuf__ uint32_t* nkValueBuf = (__ubuf__ uint32_t*)nkValueLocal.GetPhyAddr(); + + uint32_t bottomK = validLen - topK + 1; + uint32_t beginIdx = 0; + bool flag = true; + + const uint16_t repeatSize8 = 256; + const uint16_t repeatSize16 = 128; + const uint16_t repeatSize32 = 64; + + uint16_t histogramsLoopNum = (validLen + repeatSize8 - 1) / repeatSize8; + uint16_t inputLoopNum = (validLen + repeatSize16 - 1) / repeatSize16; + uint16_t topkLoopNum = (topK + repeatSize32 - 1) / repeatSize32; + uint16_t topkLoopNum16 = (topK + repeatSize16 - 1) / repeatSize16; + + // find kth-value + HistogramsHighVFImpl(histogramsBuf, inputValueBuf, histogramsLoopNum, flag); + FindHighTargetBinVFImpl(idxHighBuf, nkValueBuf, histogramsBuf, bottomK); + + HistogramsLowVFImpl(histogramsBuf, inputValueBuf, idxHighBuf, histogramsLoopNum, flag); + FindKthVFImpl(nkValueBuf, histogramsBuf, idxHighBuf, idxLowBuf); + + // filter + int32_t count = TopKGatherAlign(topK, (uint32_t)128) - topK / 128 * 128; + AscendC::Duplicate(tmpIdxLocal[topK / 128 * 128], (uint16_t)(0), count); + // 输出大于k-value的值idx + FindIdxGTOutputVFImpl(tmpIdxBuf, inputValueBuf, (uint32_t)(0), nkValueBuf, inputLoopNum); + // 输出等于k-value的值idx + FindIdxEQOutputVFImpl(tmpIdxBuf, inputValueBuf, (uint32_t)(0), nkValueBuf, inputLoopNum); + + // 是否输出Value + if constexpr (ISOUTVALUE) { + FindValueOutputVFImpl(outputValueBuf, inputValueBuf, tmpIdxBuf, topkLoopNum16); + } +} + +/** + * @brief 通过idx_tmp gather出实际的TopKIndex,s2SeqLen > 16K才会执行 + * @param outputIdxLocal 输出Idx 有效:topK * 2B + * @param outputValueLocal 输出Value topK * 2B(以后需要输出实际value使用) + * @param inputValueLocal 输入Value validLen * 2B + * @param tmpIdxLocal 本轮tmpIdx输入 validLen * 2B (0 ~ validLen - 1) + * @param hisIdxLocal 上一轮实际Idx输入 有效:topK * 4B + * @param topK topK元素个数 + * @param loopBasicIdx 当前循环需要加上得基准Index + * @param validLen 有效元素个数 + */ +__aicore__ inline void LiTopKGatherVF(const LocalTensor& outputIdxLocal, + const LocalTensor& outputValueLocal, + const LocalTensor& inputValueLocal, + const LocalTensor& tmpIdxLocal, + const LocalTensor& hisIdxLocal, + uint32_t topK, + uint32_t loopBasicIdx, + uint32_t validLen) +{ + __ubuf__ uint32_t* outputIdxBuf = (__ubuf__ uint32_t*)outputIdxLocal.GetPhyAddr(); + __ubuf__ uint16_t* outputValueBuf = (__ubuf__ uint16_t*)outputValueLocal.GetPhyAddr(); + __ubuf__ uint16_t* inputValueBuf = (__ubuf__ uint16_t*)inputValueLocal.GetPhyAddr(); + __ubuf__ uint16_t* tmpIdxBuf = (__ubuf__ uint16_t*)tmpIdxLocal.GetPhyAddr(); + __ubuf__ uint32_t* hisIdxBuf = (__ubuf__ uint32_t*)hisIdxLocal.GetPhyAddr(); + + const uint16_t repeatSize32 = 64; + const uint16_t repeatSize16 = 128; + uint16_t topkLoopNum16 = (topK + repeatSize16 - 1) / repeatSize16; + uint16_t topkLoopNum32 = (topK + repeatSize32 - 1) / repeatSize32; + + FindRealIndexVFImpl(outputIdxBuf, tmpIdxBuf, hisIdxBuf, topK, loopBasicIdx, topkLoopNum32); +} +} +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/lightning_indexer_topk.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/lightning_indexer_topk.h new file mode 100644 index 0000000000000000000000000000000000000000..98ee1dc0f18b6ad03541928e8bcf9462312f8d67 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/lightning_indexer_topk.h @@ -0,0 +1,128 @@ +/** + * 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 lightning_indexer_topk.h + * \brief + */ +#ifndef LIGHTNING_INDEXER_TOPK_H +#define LIGHTNING_INDEXER_TOPK_H + +#include "kernel_operator.h" +#include "vf_topk_gather.h" + +namespace topk { +template +class LITopk { +public: + __aicore__ inline void operator()(LocalTensor& outputIdxLocal, + LocalTensor& inputLocal, + uint32_t s2SeqLen) + { + } +}; +template<> +class LITopk { +public: + __aicore__ inline uint32_t GetSharedTmpBufferSize() + { + // 2 * LICommon::Align(topK, (uint32_t)256): 两块hisIndexLocal + // 5 * 256:histogramsLocal + idxLocal[0-3] + // 64:nkValueLocal + uint64_t bufferSize1 = (2 * LICommon::Align(topK, (uint32_t)256) + 5 * 256 + 64) * sizeof(uint32_t); + // LICommon::Align(topK, (uint32_t)256) + trunkLen:tmpIndexLocal + uint64_t bufferSize2 = (LICommon::Align(topK, (uint32_t)256) + trunkLen) * sizeof(uint32_t); + uint64_t reuseBufferSize = LICommon::Align(topK, (uint32_t)256) * sizeof(uint32_t); + return bufferSize1 + bufferSize2 - reuseBufferSize; + } + + __aicore__ inline void Init(uint32_t topK, uint32_t trunkLen) + { + this->topK = topK; + this->trunkLen = trunkLen; + } + + __aicore__ inline void InitBuffers(LocalTensor& sharedTmpBuffer, LocalTensor& indicesOutLocal) + { + LocalTensor hisIndexLocal1 = indicesOutLocal; + LocalTensor hisIndexLocal2 = sharedTmpBuffer[0]; + hisIndexLocal[0] = hisIndexLocal1; + hisIndexLocal[1] = hisIndexLocal2; + histogramsLocal = hisIndexLocal2[LICommon::Align(topK, (uint32_t)256)]; // 256: 本地内存对齐基线 + idx0Local = histogramsLocal[256]; // 256: 本地内存对齐基线 + idx1Local = idx0Local[256]; // 256: 同上 + idx2Local = idx1Local[256]; // 256: 同上 + idx3Local = idx2Local[256]; // 256: 同上 + nkValueLocal = idx3Local[256]; // 256: 同上 + tmpIndexLocal = nkValueLocal[64]; // 64: 单核/单线程输出元素容量(G维度切分阈值) + } + + __aicore__ inline void operator()(LocalTensor& mrgValueLocal, LocalTensor& indicesOutLocal, + LocalTensor& hisValueLocal, uint32_t s2SeqLen, + uint32_t loopIdx, uint32_t s2LoopNum, bool returnValueFlag) + { + if (s2LoopNum == 1) { + if (returnValueFlag) { + topkb32gather::LiTopKVF(tmpIndexLocal, hisValueLocal, + mrgValueLocal, histogramsLocal, idx0Local, idx1Local, + idx2Local, idx3Local, nkValueLocal, topK, s2SeqLen); + } else { + topkb32gather::LiTopKVF(tmpIndexLocal, hisValueLocal, + mrgValueLocal, histogramsLocal, idx0Local, idx1Local, + idx2Local, idx3Local, nkValueLocal, topK, s2SeqLen); + } + PipeBarrier(); + AscendC::DataCopy(indicesOutLocal, tmpIndexLocal, LICommon::Align(topK, (uint32_t)256)); // 256: 本地内存对齐基线 + } else { + if (loopIdx == 0) { + topkb32gather::LiTopKVF(tmpIndexLocal, hisValueLocal, mrgValueLocal, + histogramsLocal, idx0Local, idx1Local, idx2Local, + idx3Local, nkValueLocal, topK, s2SeqLen); + PipeBarrier(); + AscendC::DataCopy(hisIndexLocal[(loopIdx + 1) % 2], // 2:pingpong + tmpIndexLocal, LICommon::Align(topK, (uint32_t)256)); // 256: 本地内存对齐基线 + } else { + topkb32gather::LiTopKVF(tmpIndexLocal, hisValueLocal, mrgValueLocal, + histogramsLocal, idx0Local, idx1Local, idx2Local, + idx3Local, nkValueLocal, topK, s2SeqLen); + PipeBarrier(); + uint32_t loopBasicIdx = topK < trunkLen ? + (loopIdx * trunkLen - LICommon::Align(topK, (uint32_t)256)) : + ((loopIdx - 1) * trunkLen); + topkb32gather::LiTopKGatherVF(hisIndexLocal[(loopIdx + 1) % 2], // 2:pingpong + hisValueLocal, mrgValueLocal, + tmpIndexLocal, hisIndexLocal[loopIdx % 2], // 2:pingpong + topK, + loopBasicIdx, + s2SeqLen); + if (loopIdx == s2LoopNum - 1) { + PipeBarrier(); + if ((loopIdx + 1) % 2 == 1) { // 2:pingpong + AscendC::DataCopy(indicesOutLocal, hisIndexLocal[(loopIdx + 1) % 2], // 2:pingpong + LICommon::Align(topK, (uint32_t)256)); // 256: 本地内存对齐基线 + } + } + } + } + } +private: + LocalTensor hisIndexLocal[2]; // 每trunkLen长度的s2选出的topK个索引 + LocalTensor histogramsLocal; // 直方图的临时Buf 256 * 4B + LocalTensor idx0Local; // 输入数据第1个8位Buf 256 * 4B + LocalTensor idx1Local; // 输入数据第2个8位Buf 256 * 4B + LocalTensor idx2Local; // 输入数据第3个8位Buf 256 * 4B + LocalTensor idx3Local; // 输入数据第4个8位Buf 256 * 4B + LocalTensor nkValueLocal; // next_k 暂存Buf 64 * 4B + LocalTensor tmpIndexLocal; // 每trunkLen + topK的临时index + uint32_t topK = 512; + uint32_t trunkLen = 8192; +}; +} +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/lightning_indexer_vector1.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/lightning_indexer_vector1.h new file mode 100644 index 0000000000000000000000000000000000000000..e8ca979c44d53ea422ff15dba42b4e1f07356cc6 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/lightning_indexer_vector1.h @@ -0,0 +1,252 @@ +/** + * 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 lightning_indexer_vector1.h + * \brief + */ +#ifndef LIGHTNING_INDEXER_VECTOR1_H +#define LIGHTNING_INDEXER_VECTOR1_H + +#include "kernel_operator.h" +#include "common/lightning_indexer_vector1_base.h" + +namespace vector1 { + +template +struct UIntSortTraits; + +template <> +struct UIntSortTraits { + using UInt = uint32_t; + static constexpr UInt ZERO = 0x00000000; + static constexpr UInt SIGN_MASK = 0x80000000; + static constexpr UInt NAN_MASK = 0xFFC00000; + static constexpr UInt ALL_ONE = 0xFFFFFFFF; +}; + +template +struct UIntSortConstCtx { + using Traits = UIntSortTraits; + using UInt = typename Traits::UInt; + AscendC::MicroAPI::RegTensor zeros; + AscendC::MicroAPI::RegTensor allOne; + AscendC::MicroAPI::RegTensor signMask; + AscendC::MicroAPI::RegTensor nan; +}; + +template +__simd_callee__ inline void InitUIntSortConstCtx(UIntSortConstCtx& ctx, AscendC::MicroAPI::MaskReg& maskAll) +{ + using Traits = UIntSortTraits; + AscendC::MicroAPI::Duplicate(ctx.zeros, Traits::ZERO, maskAll); + AscendC::MicroAPI::Duplicate(ctx.allOne, Traits::ALL_ONE, maskAll); + AscendC::MicroAPI::Duplicate(ctx.signMask, Traits::SIGN_MASK, maskAll); + AscendC::MicroAPI::Duplicate(ctx.nan, Traits::NAN_MASK, maskAll); +} + +template +__simd_callee__ inline void UIntToSortableKey(AscendC::MicroAPI::RegTensor& outKey, + AscendC::MicroAPI::RegTensor::UInt>& + inVal, + UIntSortConstCtx& ctx, + AscendC::MicroAPI::MaskReg& maskAll) +{ + using Traits = UIntSortTraits; + using UInt = typename Traits::UInt; + + AscendC::MicroAPI::RegTensor regTemp; + AscendC::MicroAPI::RegTensor regMask; + AscendC::MicroAPI::MaskReg regSelectZero; + AscendC::MicroAPI::MaskReg regSelectSign; + + auto& inBits = inVal; + + // 1. 0 check + AscendC::MicroAPI::Compare(regSelectZero, inBits, ctx.zeros, maskAll); + + // 2. 0 -> -NAN + AscendC::MicroAPI::Select((AscendC::MicroAPI::RegTensor&)outKey, ctx.nan, inBits, regSelectZero); + + // 3. sign bit + AscendC::MicroAPI::And(regTemp, (AscendC::MicroAPI::RegTensor&)outKey, ctx.signMask, maskAll); + + AscendC::MicroAPI::Compare(regSelectSign, regTemp, ctx.zeros, maskAll); + + // 4. xor mask + AscendC::MicroAPI::Select(regMask, ctx.signMask, ctx.allOne, regSelectSign); + AscendC::MicroAPI::Xor((AscendC::MicroAPI::RegTensor&)outKey, + (AscendC::MicroAPI::RegTensor&)outKey, regMask, maskAll); +} + +__aicore__ inline void UIntToFloatReturnValue(const LocalTensor &out_, + const LocalTensor &in, + const uint32_t topK) +{ + auto outBuf = (__local_mem__ bfloat16_t*)out_.GetPhyAddr(); + auto inBuf = (__local_mem__ uint32_t*)in.GetPhyAddr(); + + const uint16_t repeatSize32 = 128; + uint16_t topkLoopNum = (topK + repeatSize32 - 1) / repeatSize32; + + __VEC_SCOPE__ + { + AscendC::MicroAPI::RegTensor regIn[2]; + AscendC::MicroAPI::RegTensor regOut[2]; + AscendC::MicroAPI::RegTensor regOutBF16[2]; + AscendC::MicroAPI::RegTensor regOutValue; + AscendC::MicroAPI::RegTensor regInvalid; + AscendC::MicroAPI::MaskReg maskAllB32 = + AscendC::MicroAPI::CreateMask(); + AscendC::MicroAPI::MaskReg maskAllB16 = + AscendC::MicroAPI::CreateMask(); + constexpr static MicroAPI::CastTrait castTraitFP32ToBF16 = + {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::NO_SAT, + MicroAPI::MaskMergeMode::ZEROING, + RoundMode::CAST_RINT}; + for (uint16_t i = 0; i < topkLoopNum; ++i) { + AscendC::MicroAPI::LoadAlign(regIn[0], inBuf + i * repeatSize32); + AscendC::MicroAPI::LoadAlign(regIn[1], inBuf + i * repeatSize32 + 64); + UIntSortConstCtx uint32Ctx; + InitUIntSortConstCtx(uint32Ctx, maskAllB32); + UIntToSortableKey(regOut[0], regIn[0], uint32Ctx, maskAllB32); + UIntToSortableKey(regOut[1], regIn[1], uint32Ctx, maskAllB32); + + AscendC::MicroAPI::Cast(regOutBF16[0], regOut[0], maskAllB32); + AscendC::MicroAPI::Cast(regOutBF16[1], regOut[1], maskAllB32); + + AscendC::MicroAPI::DeInterleave(regOutValue, regInvalid, regOutBF16[0], regOutBF16[1]); + + AscendC::MicroAPI::StoreAlign( + outBuf + i * repeatSize32, + regOutValue, + maskAllB16); + } + } +} + +__aicore__ inline void UIntToFloatReturnValue(const LocalTensor &out_, + const LocalTensor &in, + const uint32_t topK) +{ + auto outBuf = (__local_mem__ half*)out_.GetPhyAddr(); + auto inBuf = (__local_mem__ uint32_t*)in.GetPhyAddr(); + + const uint16_t repeatSize32 = 128; + uint16_t topkLoopNum = (topK + repeatSize32 - 1) / repeatSize32; + + __VEC_SCOPE__ + { + AscendC::MicroAPI::RegTensor regIn[2]; + AscendC::MicroAPI::RegTensor regOut[2]; + AscendC::MicroAPI::RegTensor regOutFP16[2]; + AscendC::MicroAPI::RegTensor regOutValue; + AscendC::MicroAPI::RegTensor regInvalid; + AscendC::MicroAPI::MaskReg maskAllB32 = + AscendC::MicroAPI::CreateMask(); + AscendC::MicroAPI::MaskReg maskAllB16 = + AscendC::MicroAPI::CreateMask(); + constexpr static MicroAPI::CastTrait castTraitFP32ToFP16 = + {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::NO_SAT, + MicroAPI::MaskMergeMode::ZEROING, + RoundMode::CAST_RINT}; + for (uint16_t i = 0; i < topkLoopNum; ++i) { + AscendC::MicroAPI::LoadAlign(regIn[0], inBuf + i * repeatSize32); + AscendC::MicroAPI::LoadAlign(regIn[1], inBuf + i * repeatSize32 + 64); + UIntSortConstCtx uint32Ctx; + InitUIntSortConstCtx(uint32Ctx, maskAllB32); + UIntToSortableKey(regOut[0], regIn[0], uint32Ctx, maskAllB32); + UIntToSortableKey(regOut[1], regIn[1], uint32Ctx, maskAllB32); + + AscendC::MicroAPI::Cast(regOutFP16[0], regOut[0], maskAllB32); + AscendC::MicroAPI::Cast(regOutFP16[1], regOut[1], maskAllB32); + + AscendC::MicroAPI::DeInterleave(regOutValue, regInvalid, regOutFP16[0], regOutFP16[1]); + + AscendC::MicroAPI::StoreAlign( + outBuf + i * repeatSize32, + regOutValue, + maskAllB16); + } + } +} + +__simd_callee__ inline void BroadcastLane(AscendC::MicroAPI::RegTensor& dst, + __local_mem__ float* src, + uint16_t laneIdx) +{ + AscendC::MicroAPI::LoadAlign(dst, src + laneIdx); +} + +template +__aicore__ inline void MulWeightAndReduceSum(const LocalTensor &out, // out [S2Base] [128 ] 2 + const LocalTensor &qk, // q*k^t [G, S2Base] [64 128] 2 + const LocalTensor &weight, // w [G] [64 ] 1 + const int gSize) // G 64 +{ + __local_mem__ W_T* weight_ = (__local_mem__ W_T*)weight.GetPhyAddr(); + + constexpr uint32_t VL = 64; // vector length + + auto qk0 = (__local_mem__ float*)qk.GetPhyAddr(); + auto qk1 = qk0 + VL; + auto out0 = (__local_mem__ uint32_t*)out.GetPhyAddr(); + auto out1 = out0 + VL; + + __VEC_SCOPE__ + { + AscendC::MicroAPI::RegTensor brcGatherIndex; + AscendC::MicroAPI::RegTensor regQK[2]; + AscendC::MicroAPI::RegTensor regW; + AscendC::MicroAPI::RegTensor regwBrc; + AscendC::MicroAPI::RegTensor regQScale; + AscendC::MicroAPI::RegTensor regKScale[2]; + AscendC::MicroAPI::RegTensor regSum[2]; + AscendC::MicroAPI::RegTensor regWWT; + + AscendC::MicroAPI::MaskReg maskAll = + AscendC::MicroAPI::CreateMask(); + AscendC::MicroAPI::MaskReg maskAll16 = + AscendC::MicroAPI::CreateMask(); + + FloatSortConstCtx fp32Ctx; + InitFloatSortConstCtx(fp32Ctx, maskAll); + + constexpr static MicroAPI::CastTrait castTraitWTToFP32 = {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::UNKNOWN, + MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + AscendC::MicroAPI::LoadAlign(regWWT, weight_); + AscendC::MicroAPI::Cast(regW, regWWT, maskAll16); + + AscendC::MicroAPI::Duplicate(regSum[0], 0.0f, maskAll); + AscendC::MicroAPI::Duplicate(regSum[1], 0.0f, maskAll); + + for (uint16_t i = (uint16_t)(0); i < (uint16_t)(gSize); ++i) { + AscendC::MicroAPI::Duplicate(brcGatherIndex, i); + AscendC::MicroAPI::LoadAlign(regQK[0], qk0 + 128 * i); + AscendC::MicroAPI::LoadAlign(regQK[1], qk1 + 128 * i); + AscendC::MicroAPI::Gather(regwBrc, regW, brcGatherIndex); + + AscendC::MicroAPI::Relu(regQK[0], regQK[0], maskAll); + AscendC::MicroAPI::Relu(regQK[1], regQK[1], maskAll); + + AscendC::MicroAPI::MulAddDst(regSum[0], regQK[0], regwBrc, maskAll); + AscendC::MicroAPI::MulAddDst(regSum[1], regQK[1], regwBrc, maskAll); + } + + AscendC::MicroAPI::RegTensor regOut[2]; + FloatX2ToSortableKey(regOut[0], regOut[1], regSum[0], regSum[1], fp32Ctx, maskAll); + + AscendC::MicroAPI::StoreAlign(out0, regOut[0], maskAll); + AscendC::MicroAPI::StoreAlign(out1, regOut[1], maskAll); + } +} +} + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/vf_topk_gather.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/vf_topk_gather.h new file mode 100644 index 0000000000000000000000000000000000000000..816a8196e5d8b7f2ff13b8324dbb7182b231ba8d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/arch35/vf/vf_topk_gather.h @@ -0,0 +1,746 @@ +/** + * 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 vf_topk_gather.h +* \brief +*/ + +#ifndef VF_TOP_K_GATHER_H +#define VF_TOP_K_GATHER_H + +namespace topkb32gather { +template +__simd_vf__ void HistogramsFirstVFImpl(__ubuf__ uint32_t* histogramsBuf, + __ubuf__ uint32_t* inputBuf, uint16_t vfLoop, bool init) +{ + MicroAPI::MaskReg pregB32Reg0 = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregB16Reg0 = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregB8Reg0 = MicroAPI::CreateMask(); + + // 计算直方图cout0 0-127 cout1 128-255 + MicroAPI::RegTensor cout0; + MicroAPI::RegTensor cout1; + MicroAPI::Duplicate(cout0, 0); + MicroAPI::Duplicate(cout1, 0); + + MicroAPI::RegTensor cout0U32Even; + MicroAPI::RegTensor cout0U32Odd; + MicroAPI::RegTensor cout1U32Even; + MicroAPI::RegTensor cout1U32Odd; + + // 32bit 高16bit + MicroAPI::RegTensor vreg0U16; + // 32bit 低16bit + MicroAPI::RegTensor vreg1U16; + MicroAPI::RegTensor vreg2U16; + MicroAPI::RegTensor vreg3U16; + + MicroAPI::RegTensor vreg0; + MicroAPI::RegTensor vreg1; + MicroAPI::RegTensor vreg2; + MicroAPI::RegTensor vreg3; + + static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_EVEN = {MicroAPI::RegLayout::ZERO, + MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_ODD = {MicroAPI::RegLayout::ONE, + MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + for (uint16_t i = 0; i < vfLoop; ++i) { + MicroAPI::LoadAlign(vreg1U16, vreg0U16, inputBuf + i * 256); + MicroAPI::LoadAlign(vreg3U16, + vreg2U16, inputBuf + (i * 256) + 128); + + MicroAPI::DeInterleave(vreg1, vreg0, + (MicroAPI::RegTensor&)vreg0U16, + (MicroAPI::RegTensor&)vreg2U16); + + MicroAPI::Histograms(cout0, vreg0, pregB8Reg0); + MicroAPI::Histograms(cout1, vreg0, pregB8Reg0); + } + + MicroAPI::Cast(cout0U32Even, cout0, pregB16Reg0); + MicroAPI::Cast(cout0U32Odd, cout0, pregB16Reg0); + MicroAPI::Cast(cout1U32Even, cout1, pregB16Reg0); + MicroAPI::Cast(cout1U32Odd, cout1, pregB16Reg0); + + MicroAPI::StoreAlign(histogramsBuf, cout0U32Even, + cout0U32Odd, pregB32Reg0); + MicroAPI::StoreAlign(histogramsBuf + 128, cout1U32Even, + cout1U32Odd, pregB32Reg0); +} + +__simd_vf__ void FindFirstTargetBinVFImpl(__ubuf__ uint32_t* idx0Buf, __ubuf__ uint32_t* nkValueBuf, + __ubuf__ uint32_t* histogramsBuf, uint32_t bottomK) +{ + MicroAPI::MaskReg pregB32Reg1 = MicroAPI::CreateMask(); + + MicroAPI::ClearSpr(); + + MicroAPI::UnalignRegForStore alignIdx0; + + MicroAPI::RegTensor btmK; + MicroAPI::Duplicate(btmK, bottomK); + + for (uint16_t i = 0; i < (uint16_t)(4); ++i) { + MicroAPI::RegTensor idxC; + MicroAPI::RegTensor cout; + MicroAPI::RegTensor sqzIdx0; + + MicroAPI::MaskReg pregGE = MicroAPI::CreateMask(); + + MicroAPI::Arange(idxC, i * 64); + MicroAPI::LoadAlign(cout, histogramsBuf + i * 64); + MicroAPI::Compare(pregGE, cout, btmK, pregB32Reg1); + MicroAPI::Squeeze(sqzIdx0, + (MicroAPI::RegTensor&)idxC, pregGE); + MicroAPI::StoreUnAlign(idx0Buf, sqzIdx0, alignIdx0); + } + MicroAPI::StoreUnAlignPost(idx0Buf, alignIdx0); + + MicroAPI::LocalMemBar(); + + MicroAPI::RegTensor idx0; + MicroAPI::LoadAlign(idx0, idx0Buf); + + MicroAPI::RegTensor idxAll1; + MicroAPI::RegTensor idxPrev0; + MicroAPI::RegTensor prevBinValue; + MicroAPI::Duplicate(idxAll1, 1); + + MicroAPI::RegTensor zeroAll; + MicroAPI::Duplicate(zeroAll, 0); + + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + MicroAPI::Compare(preg0, idx0, zeroAll, pregB32Reg1); + MicroAPI::Sub(idxPrev0, idx0, (MicroAPI::RegTensor&)idxAll1, pregB32Reg1); + MicroAPI::ShiftRights(idxPrev0, idxPrev0, (int16_t)24, pregB32Reg1); + + MicroAPI::Gather(prevBinValue, histogramsBuf, idxPrev0, pregB32Reg1); + MicroAPI::Select(prevBinValue, zeroAll, prevBinValue, preg0); + + MicroAPI::RegTensor nextK; + MicroAPI::Sub(nextK, btmK, prevBinValue, pregB32Reg1); + MicroAPI::StoreAlign(nkValueBuf, nextK, pregB32Reg1); +} + +template +__simd_vf__ void HistogramsSecondVFImpl(__ubuf__ uint32_t* histogramsBuf, + __ubuf__ uint32_t* inputBuf, __ubuf__ uint32_t* idx0Buf, + uint16_t vfLoop, bool init) +{ + MicroAPI::MaskReg pregB32Reg2 = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregB16Reg1 = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregB8Reg1 = MicroAPI::CreateMask(); + + // 计算直方图0-127 128-255 + MicroAPI::RegTensor cout0; + MicroAPI::RegTensor cout1; + MicroAPI::Duplicate(cout0, 0); + MicroAPI::Duplicate(cout1, 0); + + MicroAPI::RegTensor cout0U32Even; + MicroAPI::RegTensor cout0U32Odd; + MicroAPI::RegTensor cout1U32Even; + MicroAPI::RegTensor cout1U32Odd; + + MicroAPI::RegTensor idx0; + // 0x000000fc -> 0xfcfcfcfc + MicroAPI::LoadAlign(idx0, idx0Buf); + + MicroAPI::RegTensor vreg0U16; + MicroAPI::RegTensor vreg1U16; + MicroAPI::RegTensor vreg2U16; + MicroAPI::RegTensor vreg3U16; + + MicroAPI::RegTensor vreg0; + MicroAPI::RegTensor vreg1; + MicroAPI::RegTensor vreg2; + MicroAPI::RegTensor vreg3; + + static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_EVEN = {MicroAPI::RegLayout::ZERO, + MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_ODD = {MicroAPI::RegLayout::ONE, + MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + for (uint16_t i = 0; i < vfLoop; ++i) { + MicroAPI::LoadAlign(vreg1U16, vreg0U16, inputBuf + i * 256); + MicroAPI::LoadAlign(vreg3U16, vreg2U16, + inputBuf + (i * 256) + 128); + + MicroAPI::DeInterleave(vreg1, vreg0, (MicroAPI::RegTensor&)vreg0U16, + (MicroAPI::RegTensor&)vreg2U16); + + MicroAPI::MaskReg pregEQ = MicroAPI::CreateMask(); + MicroAPI::Compare(pregEQ, vreg0, (MicroAPI::RegTensor&)idx0, pregB8Reg1); + + MicroAPI::Histograms(cout0, vreg1, pregEQ); + MicroAPI::Histograms(cout1, vreg1, pregEQ); + } + + MicroAPI::Cast(cout0U32Even, cout0, pregB16Reg1); + MicroAPI::Cast(cout0U32Odd, cout0, pregB16Reg1); + MicroAPI::Cast(cout1U32Even, cout1, pregB16Reg1); + MicroAPI::Cast(cout1U32Odd, cout1, pregB16Reg1); + + MicroAPI::StoreAlign(histogramsBuf, + cout0U32Even, cout0U32Odd, pregB32Reg2); + MicroAPI::StoreAlign(histogramsBuf + 128, + cout1U32Even, cout1U32Odd, pregB32Reg2); +} + +// kValue新的bottomK +__simd_vf__ void FindSecondTargetBinVFImpl(__ubuf__ uint32_t* idx1Buf, __ubuf__ uint32_t* nkValueBuf, + __ubuf__ uint32_t* kValue, __ubuf__ uint32_t* histogramsBuf) +{ + MicroAPI::MaskReg pregB32Reg3 = MicroAPI::CreateMask(); + + MicroAPI::ClearSpr(); + + MicroAPI::UnalignRegForStore alignIdx1; + + MicroAPI::RegTensor btmK1; + MicroAPI::LoadAlign(btmK1, kValue); + + for (uint16_t i = 0; i < (uint16_t)(4); ++i) { + MicroAPI::RegTensor idxC; + MicroAPI::RegTensor cout; + MicroAPI::RegTensor sqzIdx1; + + MicroAPI::MaskReg pregGE = MicroAPI::CreateMask(); + + MicroAPI::Arange(idxC, i * 64); + MicroAPI::LoadAlign(cout, histogramsBuf + i * 64); + MicroAPI::Compare(pregGE, cout, btmK1, pregB32Reg3); + MicroAPI::Squeeze(sqzIdx1, + (MicroAPI::RegTensor&)idxC, pregGE); + MicroAPI::StoreUnAlign(idx1Buf, sqzIdx1, alignIdx1); + } + MicroAPI::StoreUnAlignPost(idx1Buf, alignIdx1); + + MicroAPI::LocalMemBar(); + + MicroAPI::RegTensor idx1; + MicroAPI::LoadAlign(idx1, idx1Buf); + + MicroAPI::RegTensor idxAll1; + MicroAPI::RegTensor idxPrev1; + MicroAPI::RegTensor prevBinValue; + MicroAPI::Duplicate(idxAll1, 1); + + MicroAPI::RegTensor zeroAll; + MicroAPI::Duplicate(zeroAll, 0); + + MicroAPI::MaskReg preg1 = MicroAPI::CreateMask(); + MicroAPI::Compare(preg1, idx1, zeroAll, pregB32Reg3); + MicroAPI::Sub(idxPrev1, idx1, (MicroAPI::RegTensor&)idxAll1, pregB32Reg3); + MicroAPI::ShiftRights(idxPrev1, idxPrev1, (int16_t)24, pregB32Reg3); + + MicroAPI::Gather(prevBinValue, histogramsBuf, idxPrev1, pregB32Reg3); + MicroAPI::Select(prevBinValue, zeroAll, prevBinValue, preg1); + + MicroAPI::RegTensor nextK; + MicroAPI::Sub(nextK, btmK1, prevBinValue, pregB32Reg3); + MicroAPI::StoreAlign(nkValueBuf, nextK, pregB32Reg3); +} + +template +__simd_vf__ void HistogramsThirdVFImpl(__ubuf__ uint32_t* histogramsBuf, __ubuf__ uint32_t* inputBuf, + __ubuf__ uint32_t* idx0Buf, __ubuf__ uint32_t* idx1Buf, + uint16_t vfLoop, bool init) +{ + MicroAPI::MaskReg pregB32Reg4 = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregB16Reg2 = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregB8Reg2 = MicroAPI::CreateMask(); + + // 计算直方图0-127 128-255 + MicroAPI::RegTensor cout0, cout1; + MicroAPI::Duplicate(cout0, 0); + MicroAPI::Duplicate(cout1, 0); + + MicroAPI::RegTensor cout0U32Even, cout0U32Odd, cout1U32Even, cout1U32Odd; + + MicroAPI::RegTensor idx0; + MicroAPI::RegTensor idx1; + // 0x000000fc -> 0xfcfcfcfc + MicroAPI::LoadAlign(idx0, idx0Buf); + MicroAPI::LoadAlign(idx1, idx1Buf); + + MicroAPI::RegTensor vreg0U16, vreg1U16, vreg2U16, vreg3U16; + + MicroAPI::RegTensor vreg0, vreg1, vreg2, vreg3; + + static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_EVEN = {MicroAPI::RegLayout::ZERO, + MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_ODD = {MicroAPI::RegLayout::ONE, + MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + for (uint16_t i = 0; i < vfLoop; ++i) { + MicroAPI::LoadAlign(vreg1U16, vreg0U16, + inputBuf + i * 256); + MicroAPI::LoadAlign(vreg3U16, vreg2U16, + inputBuf + (i * 256) + 128); + + MicroAPI::DeInterleave(vreg1, vreg0, (MicroAPI::RegTensor&)vreg0U16, + (MicroAPI::RegTensor&)vreg2U16); + MicroAPI::DeInterleave(vreg3, vreg2, (MicroAPI::RegTensor&)vreg1U16, + (MicroAPI::RegTensor&)vreg3U16); + + MicroAPI::MaskReg pregEQ0 = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregEQ1 = MicroAPI::CreateMask(); + MicroAPI::Compare(pregEQ0, vreg0, (MicroAPI::RegTensor&)idx0, pregB8Reg2); + MicroAPI::Compare(pregEQ1, vreg1, (MicroAPI::RegTensor&)idx1, pregB8Reg2); + + MicroAPI::MaskReg pregEQ = MicroAPI::CreateMask(); + MicroAPI::And(pregEQ, pregEQ0, pregEQ1, pregB8Reg2); + + MicroAPI::Histograms(cout0, vreg2, pregEQ); + MicroAPI::Histograms(cout1, vreg2, pregEQ); + } + + MicroAPI::Cast(cout0U32Even, cout0, pregB16Reg2); + MicroAPI::Cast(cout0U32Odd, cout0, pregB16Reg2); + MicroAPI::Cast(cout1U32Even, cout1, pregB16Reg2); + MicroAPI::Cast(cout1U32Odd, cout1, pregB16Reg2); + + MicroAPI::StoreAlign(histogramsBuf, + cout0U32Even, cout0U32Odd, pregB32Reg4); + MicroAPI::StoreAlign(histogramsBuf + 128, + cout1U32Even, cout1U32Odd, pregB32Reg4); +} + +__simd_vf__ void FindThirdTargetBinVFImpl(__ubuf__ uint32_t* idx2Buf, __ubuf__ uint32_t* nkValueBuf, + __ubuf__ uint32_t* kValue, __ubuf__ uint32_t* histogramsBuf) +{ + MicroAPI::MaskReg pregB32Reg5 = MicroAPI::CreateMask(); + + MicroAPI::ClearSpr(); + + MicroAPI::UnalignRegForStore alignIdx2; + + MicroAPI::RegTensor btmK2; + MicroAPI::LoadAlign(btmK2, kValue); + + for (uint16_t i = 0; i < (uint16_t)(4); ++i) { + MicroAPI::RegTensor idxC; + MicroAPI::RegTensor cout; + MicroAPI::RegTensor sqzIdx2; + + MicroAPI::MaskReg pregGE = MicroAPI::CreateMask(); + + MicroAPI::Arange(idxC, i * 64); + MicroAPI::LoadAlign(cout, histogramsBuf + i * 64); + MicroAPI::Compare(pregGE, cout, btmK2, pregB32Reg5); + MicroAPI::Squeeze(sqzIdx2, + (MicroAPI::RegTensor&)idxC, pregGE); + MicroAPI::StoreUnAlign(idx2Buf, sqzIdx2, alignIdx2); + } + MicroAPI::StoreUnAlignPost(idx2Buf, alignIdx2); + + MicroAPI::LocalMemBar(); + + MicroAPI::RegTensor idx2; + MicroAPI::LoadAlign(idx2, idx2Buf); + + MicroAPI::RegTensor idxAll1; + MicroAPI::RegTensor idxPrev2; + MicroAPI::RegTensor prevBinValue; + MicroAPI::Duplicate(idxAll1, 1); + + MicroAPI::RegTensor zeroAll; + MicroAPI::Duplicate(zeroAll, 0); + + MicroAPI::MaskReg preg2 = MicroAPI::CreateMask(); + MicroAPI::Compare(preg2, idx2, zeroAll, pregB32Reg5); + MicroAPI::Sub(idxPrev2, idx2, (MicroAPI::RegTensor&)idxAll1, pregB32Reg5); + MicroAPI::ShiftRights(idxPrev2, idxPrev2, (int16_t)24, pregB32Reg5); + + MicroAPI::Gather(prevBinValue, histogramsBuf, idxPrev2, pregB32Reg5); + MicroAPI::Select(prevBinValue, zeroAll, prevBinValue, preg2); + + MicroAPI::RegTensor nextK; + MicroAPI::Sub(nextK, btmK2, prevBinValue, pregB32Reg5); + MicroAPI::StoreAlign(nkValueBuf, nextK, pregB32Reg5); +} + +template +__simd_vf__ void HistogramsLastVFImpl(__ubuf__ uint32_t* histogramsBuf, __ubuf__ uint32_t* inputBuf, + __ubuf__ uint32_t* idx0Buf, __ubuf__ uint32_t* idx1Buf, + __ubuf__ uint32_t* idx2Buf, uint16_t vfLoop, bool init) +{ + MicroAPI::MaskReg pregB32Reg6 = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregB16Reg3 = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregB8Reg3 = MicroAPI::CreateMask(); + + // 计算直方图0-127 128-255 + MicroAPI::RegTensor cout0, cout1; + MicroAPI::Duplicate(cout0, 0); + MicroAPI::Duplicate(cout1, 0); + + MicroAPI::RegTensor cout0U32Even, cout0U32Odd, cout1U32Even, cout1U32Odd; + + MicroAPI::RegTensor idx0, idx1, idx2; + // 0x000000fc -> 0xfcfcfcfc + MicroAPI::LoadAlign(idx0, idx0Buf); + MicroAPI::LoadAlign(idx1, idx1Buf); + MicroAPI::LoadAlign(idx2, idx2Buf); + + MicroAPI::RegTensor vreg0U16, vreg1U16, vreg2U16, vreg3U16; + + MicroAPI::RegTensor vreg0, vreg1, vreg2, vreg3; + + static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_EVEN = {MicroAPI::RegLayout::ZERO, + MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + static constexpr MicroAPI::CastTrait CAST_TRAIT_UINT16_TOUINT32_ODD = {MicroAPI::RegLayout::ONE, + MicroAPI::SatMode::UNKNOWN, MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + for (uint16_t i = 0; i < vfLoop; ++i) { + MicroAPI::LoadAlign(vreg1U16, vreg0U16, inputBuf + i * 256); + MicroAPI::LoadAlign(vreg3U16, vreg2U16, + inputBuf + (i * 256) + 128); + + MicroAPI::DeInterleave(vreg1, vreg0, (MicroAPI::RegTensor&)vreg0U16, + (MicroAPI::RegTensor&)vreg2U16); + MicroAPI::DeInterleave(vreg3, vreg2, (MicroAPI::RegTensor&)vreg1U16, + (MicroAPI::RegTensor&)vreg3U16); + + MicroAPI::MaskReg pregEQ0 = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregEQ1 = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregEQ2 = MicroAPI::CreateMask(); + MicroAPI::Compare(pregEQ0, vreg0, (MicroAPI::RegTensor&)idx0, pregB8Reg3); + MicroAPI::Compare(pregEQ1, vreg1, (MicroAPI::RegTensor&)idx1, pregB8Reg3); + MicroAPI::Compare(pregEQ2, vreg2, (MicroAPI::RegTensor&)idx2, pregB8Reg3); + + MicroAPI::MaskReg pregEQ0And1 = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregEQAll = MicroAPI::CreateMask(); + MicroAPI::And(pregEQ0And1, pregEQ0, pregEQ1, pregB8Reg3); + MicroAPI::And(pregEQAll, pregEQ0And1, pregEQ2, pregB8Reg3); + + MicroAPI::Histograms(cout0, vreg3, pregEQAll); + MicroAPI::Histograms(cout1, vreg3, pregEQAll); + } + + MicroAPI::Cast(cout0U32Even, cout0, pregB16Reg3); + MicroAPI::Cast(cout0U32Odd, cout0, pregB16Reg3); + MicroAPI::Cast(cout1U32Even, cout1, pregB16Reg3); + MicroAPI::Cast(cout1U32Odd, cout1, pregB16Reg3); + + MicroAPI::StoreAlign(histogramsBuf, cout0U32Even, + cout0U32Odd, pregB32Reg6); + MicroAPI::StoreAlign(histogramsBuf + 128, cout1U32Even, + cout1U32Odd, pregB32Reg6); +} + +__simd_vf__ void FindKthVFImpl(__ubuf__ uint32_t* kValue, __ubuf__ uint32_t* histogramsBuf, + __ubuf__ uint32_t* idx0Buf, __ubuf__ uint32_t* idx1Buf, + __ubuf__ uint32_t* idx2Buf, __ubuf__ uint32_t* idx3Buf) +{ + MicroAPI::MaskReg pregB32Reg7 = MicroAPI::CreateMask(); + + MicroAPI::ClearSpr(); + + MicroAPI::UnalignRegForStore alignIdx3; + + MicroAPI::RegTensor btmK3; + MicroAPI::LoadAlign(btmK3, kValue); + + for (uint16_t i = 0; i < (uint16_t)(4); ++i) { + MicroAPI::RegTensor idxC; + MicroAPI::RegTensor cout; + MicroAPI::RegTensor sqzIdx3; + + MicroAPI::MaskReg pregGE = MicroAPI::CreateMask(); + + MicroAPI::Arange(idxC, i * 64); + MicroAPI::LoadAlign(cout, histogramsBuf + i * 64); + MicroAPI::Compare(pregGE, cout, btmK3, pregB32Reg7); + MicroAPI::Squeeze(sqzIdx3, (MicroAPI::RegTensor&)idxC, + pregGE); + MicroAPI::StoreUnAlign(idx3Buf, sqzIdx3, alignIdx3); + } + MicroAPI::StoreUnAlignPost(idx3Buf, alignIdx3); + + MicroAPI::LocalMemBar(); + + MicroAPI::RegTensor idx0; + MicroAPI::RegTensor idx1; + MicroAPI::RegTensor idx2; + MicroAPI::RegTensor idx3; + MicroAPI::LoadAlign(idx0, idx0Buf); + MicroAPI::LoadAlign(idx1, idx1Buf); + MicroAPI::LoadAlign(idx2, idx2Buf); + MicroAPI::LoadAlign(idx3, idx3Buf); + + MicroAPI::ShiftLefts(idx0, idx0, (int16_t)24, pregB32Reg7); + MicroAPI::ShiftLefts(idx1, idx1, (int16_t)16, pregB32Reg7); + MicroAPI::ShiftLefts(idx2, idx2, (int16_t)8, pregB32Reg7); + + // ADD + MicroAPI::Add(idx0, idx0, idx1, pregB32Reg7); + MicroAPI::Add(idx0, idx0, idx2, pregB32Reg7); + MicroAPI::Add(idx0, idx0, idx3, pregB32Reg7); + + MicroAPI::StoreAlign(kValue, idx0, pregB32Reg7); +} + +__simd_vf__ void FindIdxGTOutputVFImpl(__ubuf__ uint32_t* outputIdxBuf, __ubuf__ uint32_t* inputBuf, + uint32_t beginIdx, __ubuf__ uint32_t* kValue, uint16_t vfLoop) +{ + MicroAPI::MaskReg pregB32Reg8 = MicroAPI::CreateMask(); + + MicroAPI::ClearSpr(); + + MicroAPI::UnalignRegForStore alignIdx; + + MicroAPI::RegTensor kthValue; + MicroAPI::LoadAlign(kthValue, kValue); + + MicroAPI::RegTensor vregInput; + + for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) { + MicroAPI::RegTensor idxC; + MicroAPI::Arange(idxC, beginIdx + i * 64); + + MicroAPI::LoadAlign(vregInput, inputBuf + i * 64); + + MicroAPI::MaskReg poutGT = MicroAPI::CreateMask(); + + MicroAPI::RegTensor sqzIdxOut; + MicroAPI::Compare(poutGT, vregInput, kthValue, pregB32Reg8); + + MicroAPI::Squeeze(sqzIdxOut, + (MicroAPI::RegTensor&)idxC, poutGT); + MicroAPI::StoreUnAlign(outputIdxBuf, sqzIdxOut, alignIdx); + } + MicroAPI::StoreUnAlignPost(outputIdxBuf, alignIdx); +} + +__simd_vf__ void FindIdxEQOutputVFImpl(__ubuf__ uint32_t* outputIdxBuf, __ubuf__ uint32_t* inputBuf, + uint32_t beginIdx, __ubuf__ uint32_t* kValue, uint16_t vfLoop) +{ + MicroAPI::MaskReg pregB32Reg9 = MicroAPI::CreateMask(); + + MicroAPI::MaskReg poutEQ; + + MicroAPI::UnalignRegForStore alignIdx; + + MicroAPI::RegTensor kthValue; + MicroAPI::LoadAlign(kthValue, kValue); + + MicroAPI::RegTensor vregInput; + MicroAPI::RegTensor idxC; + MicroAPI::RegTensor sqzIdxOut; + + for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) { + MicroAPI::Arange(idxC, beginIdx + i * 64); + + MicroAPI::LoadAlign(vregInput, inputBuf + i * 64); + + MicroAPI::Compare(poutEQ, vregInput, kthValue, pregB32Reg9); + + MicroAPI::Squeeze(sqzIdxOut, + (MicroAPI::RegTensor&)idxC, poutEQ); + MicroAPI::StoreUnAlign(outputIdxBuf, sqzIdxOut, alignIdx); + } + MicroAPI::StoreUnAlignPost(outputIdxBuf, alignIdx); +} + +/** + 输出最终的Value + */ +__simd_vf__ void FindValueOutputVFImpl(__ubuf__ uint32_t* outputValueBuf, __ubuf__ uint32_t* inputValueBuf, + __ubuf__ uint32_t* tmpIdxBuf, uint16_t vfLoop) +{ + MicroAPI::MaskReg pregB32Reg10 = MicroAPI::CreateMask(); + + MicroAPI::RegTensor tmpIdx; + MicroAPI::RegTensor outputValue; + + for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) { + MicroAPI::LoadAlign(tmpIdx, tmpIdxBuf + i * 64); + + MicroAPI::Gather(outputValue, inputValueBuf, tmpIdx, pregB32Reg10); + + MicroAPI::StoreAlign(outputValueBuf + i * 64, + outputValue, pregB32Reg10); + } +} + +/** + 输出最终的Idx + */ +__simd_vf__ void FindRealIndexVFImpl(__ubuf__ uint32_t* outputIdxBuf, __ubuf__ uint32_t* tmpIdxBuf, + __ubuf__ uint32_t* hisIdxBuf, uint32_t topK, uint32_t loopIndex, + uint16_t vfLoop) +{ + MicroAPI::MaskReg pregB32Reg11 = MicroAPI::CreateMask(); + + MicroAPI::MaskReg pregNow; + MicroAPI::MaskReg pregHis; + + MicroAPI::RegTensor tmpIdx; + MicroAPI::RegTensor outputGatherIdx; + MicroAPI::RegTensor outputAddsIdx; + + for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) { + MicroAPI::LoadAlign(tmpIdx, tmpIdxBuf + i * 64); + + MicroAPI::Compares(pregNow, tmpIdx, topK - 1, pregB32Reg11); + MicroAPI::Xor(pregHis, pregNow, pregB32Reg11, pregB32Reg11); + + MicroAPI::Gather(outputGatherIdx, hisIdxBuf, tmpIdx, pregHis); + MicroAPI::Adds(outputAddsIdx, tmpIdx, loopIndex, pregNow); + + MicroAPI::Add(outputGatherIdx, outputGatherIdx, outputAddsIdx, pregB32Reg11); + + MicroAPI::StoreAlign(outputIdxBuf + i * 64, + outputGatherIdx, pregB32Reg11); + } +} + +__simd_vf__ void IndicesAddOffsetVF(__ubuf__ uint32_t* indicesOutBuf, uint32_t outputIdxOffset, uint32_t vfLoop) +{ + MicroAPI::MaskReg pregB32Reg12 = MicroAPI::CreateMask(); + + MicroAPI::RegTensor outIndices; + + for (uint16_t i = 0; i < (uint16_t)(vfLoop); ++i) { + MicroAPI::LoadAlign(outIndices, indicesOutBuf + i * 64); + MicroAPI::Adds(outIndices, outIndices, outputIdxOffset, pregB32Reg12); + MicroAPI::StoreAlign(indicesOutBuf + i * 64, + outIndices, pregB32Reg12); + } +} + +/** + * @brief LiTopKVF 对一个validLen的输入进行topk算法,输出idx_tmp + * @param tmpIdxLocal Temp阶段输出的TopKIndex;如果s2SeqLen < 8K作为最终输出 validLen * 4B + * @param outputValueLocal 如果s2SeqLen > 8K并且是首轮输出Value topK * 4B + * @param inputValueLocal 输入Value validLen * 4B + * @param histogramsLocal 直方图 256 * 4B + * @param idx0Local 目标桶第一个八位 256 * 4B + * @param idx1Local 目标桶第二个八位 256 * 4B + * @param idx2Local 目标桶第三个八位 256 * 4B + * @param idx3Local 目标桶第四个八位 256 * 4B + * @param nkValueLocal 存储next_k的值 64 * 4B + * @param topK topK元素 + * @param validLen 有效元素个数:QLICommon::Align(topkCountAlign256_ + validTrunkLen, (uint32_t)256) + */ +template +__aicore__ inline void LiTopKVF(const LocalTensor& tmpIdxLocal, + const LocalTensor& outputValueLocal, + const LocalTensor& inputValueLocal, + const LocalTensor& histogramsLocal, + const LocalTensor& idx0Local, + const LocalTensor& idx1Local, + const LocalTensor& idx2Local, + const LocalTensor& idx3Local, + const LocalTensor& nkValueLocal, + uint32_t topK, + uint32_t validLen) +{ + __ubuf__ uint32_t* tmpIdxBuf = (__ubuf__ uint32_t*)tmpIdxLocal.GetPhyAddr(); + __ubuf__ uint32_t* outputValueBuf = (__ubuf__ uint32_t*)outputValueLocal.GetPhyAddr(); + __ubuf__ uint32_t* inputValueBuf = (__ubuf__ uint32_t*)inputValueLocal.GetPhyAddr(); + __ubuf__ uint32_t* histogramsBuf = (__ubuf__ uint32_t*)histogramsLocal.GetPhyAddr(); + __ubuf__ uint32_t* idx0Buf = (__ubuf__ uint32_t*)idx0Local.GetPhyAddr(); + __ubuf__ uint32_t* idx1Buf = (__ubuf__ uint32_t*)idx1Local.GetPhyAddr(); + __ubuf__ uint32_t* idx2Buf = (__ubuf__ uint32_t*)idx2Local.GetPhyAddr(); + __ubuf__ uint32_t* idx3Buf = (__ubuf__ uint32_t*)idx3Local.GetPhyAddr(); + __ubuf__ uint32_t* nkValueBuf = (__ubuf__ uint32_t*)nkValueLocal.GetPhyAddr(); + + uint32_t bottomK = validLen - topK + 1; + uint32_t beginIdx = 0; + bool flag = true; + + const uint16_t repeatSize8 = 256; + const uint16_t repeatSize32 = 64; + + uint16_t histogramsLoopNum = (validLen + repeatSize8 - 1) / repeatSize8; + uint16_t inputLoopNum = (validLen + repeatSize32 - 1) / repeatSize32; + uint16_t topkLoopNum = (topK + 64 - 1) / 64; + + // find kth-value + HistogramsFirstVFImpl(histogramsBuf, inputValueBuf, histogramsLoopNum, flag); + FindFirstTargetBinVFImpl(idx0Buf, nkValueBuf, histogramsBuf, bottomK); + HistogramsSecondVFImpl(histogramsBuf, inputValueBuf, idx0Buf, histogramsLoopNum, flag); + FindSecondTargetBinVFImpl(idx1Buf, nkValueBuf, nkValueBuf, histogramsBuf); + HistogramsThirdVFImpl(histogramsBuf, inputValueBuf, idx0Buf, idx1Buf, histogramsLoopNum, flag); + FindThirdTargetBinVFImpl(idx2Buf, nkValueBuf, nkValueBuf, histogramsBuf); + HistogramsLastVFImpl(histogramsBuf, inputValueBuf, idx0Buf, idx1Buf, idx2Buf, histogramsLoopNum, flag); + FindKthVFImpl(nkValueBuf, histogramsBuf, idx0Buf, idx1Buf, idx2Buf, idx3Buf); + + // filter + int32_t count = LICommon::Align(topK, (uint32_t)64) - topK / 64 * 64; + AscendC::Duplicate(tmpIdxLocal[topK / 64 * 64], (uint32_t)(0), count); + // 输出大于k-value的值idx + FindIdxGTOutputVFImpl(tmpIdxBuf, inputValueBuf, (uint32_t)(0), nkValueBuf, inputLoopNum); + // 输出等于k-value的值idx + FindIdxEQOutputVFImpl(tmpIdxBuf, inputValueBuf, (uint32_t)(0), nkValueBuf, inputLoopNum); + + if constexpr (ISOUTVALUE) { + FindValueOutputVFImpl(outputValueBuf, inputValueBuf, tmpIdxBuf, topkLoopNum); + } +} + +/** + * @brief 通过idx_tmp gather出实际的TopKIndex,s2SeqLen > 8K才会执行 + * @param outputIdxLocal 输出Idx 有效:topK * 4B + * @param outputValueLocal 输出Value topK * 4B(以后需要输出实际value使用) + * @param inputValueLocal 输入Value validLen * 4B + * @param tmpIdxLocal 本轮tmpIdx输入 validLen * 4B (0 ~ validLen - 1) + * @param hisIdxLocal 上一轮实际Idx输入 有效:topK * 4B + * @param topK topK元素个数 + * @param loopBasicIdx 当前循环需要加上得基准Index + * @param validLen 有效元素个数 + */ +__aicore__ inline void LiTopKGatherVF(const LocalTensor& outputIdxLocal, + const LocalTensor& outputValueLocal, + const LocalTensor& inputValueLocal, + const LocalTensor& tmpIdxLocal, + const LocalTensor& hisIdxLocal, + uint32_t topK, + uint32_t loopBasicIdx, + uint32_t validLen) +{ + __ubuf__ uint32_t* outputIdxBuf = (__ubuf__ uint32_t*)outputIdxLocal.GetPhyAddr(); + __ubuf__ uint32_t* outputValueBuf = (__ubuf__ uint32_t*)outputValueLocal.GetPhyAddr(); + __ubuf__ uint32_t* inputValueBuf = (__ubuf__ uint32_t*)inputValueLocal.GetPhyAddr(); + __ubuf__ uint32_t* tmpIdxBuf = (__ubuf__ uint32_t*)tmpIdxLocal.GetPhyAddr(); + __ubuf__ uint32_t* hisIdxBuf = (__ubuf__ uint32_t*)hisIdxLocal.GetPhyAddr(); + + const uint16_t repeatSize32 = 64; + uint16_t topkLoopNum32 = (topK + repeatSize32 - 1) / repeatSize32; + + FindRealIndexVFImpl(outputIdxBuf, tmpIdxBuf, hisIdxBuf, topK, loopBasicIdx, topkLoopNum32); +} + +__aicore__ inline void IndicesAddOffset(const LocalTensor& indicesOutLocal, + uint32_t outputIdxOffset, uint32_t topK) +{ + __ubuf__ uint32_t* indicesOutBuf = (__ubuf__ uint32_t*)indicesOutLocal.GetPhyAddr(); + const uint16_t repeatSize32 = 64; + uint16_t topkLoopNum32 = (topK + repeatSize32 - 1) / repeatSize32; + IndicesAddOffsetVF(indicesOutBuf, outputIdxOffset, topkLoopNum32); +} +} +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ddb3f29fca512273557ca45423c7c4fe56b957b1 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer.cpp @@ -0,0 +1,66 @@ +/** + * 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 lightning_indexer.cpp + * \brief + */ + +#include "kernel_operator.h" +#include "lib/matmul_intf.h" +#include "lightning_indexer_template_tiling_key.h" + +#if (__CCE_AICORE__ == 310) + #include "arch35/lightning_indexer_kernel.h" + +#else + #include "arch22/lightning_indexer_kernel.h" +#endif + +using namespace LIKernel; + +#define INVOKE_LI_NO_KFC_OP_IMPL(templateClass, ...) \ + do { \ + templateClass> op; \ + GET_TILING_DATA_WITH_STRUCT(LITilingData, tiling_data_in, tiling); \ + const LITilingData *__restrict tiling_data = &tiling_data_in; \ + op.Init(query, key, weights, actualSeqLengthsQ, actualSeqLengths, blocktable, sparseIndices, sparseValues, user, \ + tiling_data, &tPipe); \ + op.Process(); \ + } while (0) + +template +__global__ __aicore__ void lightning_indexer(__gm__ uint8_t *query, __gm__ uint8_t *key, __gm__ uint8_t *weights, + __gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths, + __gm__ uint8_t *blocktable, __gm__ uint8_t *sparseIndices, + __gm__ uint8_t *sparseValues, __gm__ uint8_t *workspace, + __gm__ uint8_t *tiling) +{ + TPipe tPipe; + __gm__ uint8_t *user = GetUserWorkspace(workspace); + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); +#if (__CCE_AICORE__ == 310) || (defined __DAV_310R6__) || (__CCE_AICORE__ == 200) + if (ORIG_DTYPE_QUERY == DT_BF16) { + INVOKE_LI_NO_KFC_OP_IMPL(LightningIndexerKernel, bfloat16_t, bfloat16_t, int32_t, + PAGE_ATTENTION, LI_LAYOUT(LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), DT_W_FLAG); + } else if (ORIG_DTYPE_QUERY == DT_FLOAT16) { + INVOKE_LI_NO_KFC_OP_IMPL(LightningIndexerKernel, half, half, int32_t, + PAGE_ATTENTION, LI_LAYOUT(LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), DT_W_FLAG); + } +#else + if constexpr (DT_Q == LI_TPL_FP16 && DT_K == LI_TPL_FP16 && DT_OUT == LI_TPL_INT32) { + INVOKE_LI_NO_KFC_OP_IMPL(LightningIndexerKernel, half, half, int32_t, PAGE_ATTENTION, + LI_LAYOUT(LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), DT_W_FLAG); + } else { + INVOKE_LI_NO_KFC_OP_IMPL(LightningIndexerKernel, bfloat16_t, bfloat16_t, int32_t, PAGE_ATTENTION, + LI_LAYOUT(LAYOUT_T), LI_LAYOUT(K_LAYOUT_T), DT_W_FLAG); + } +#endif +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer_common.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer_common.h new file mode 100644 index 0000000000000000000000000000000000000000..bb49441984c7d856365910f5c6f52f9dbe4276f9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer_common.h @@ -0,0 +1,175 @@ +/** + * 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 lightning_indexer_common.h + * \brief + */ +#ifndef LIGHTNING_INDEXER_COMMON_H +#define LIGHTNING_INDEXER_COMMON_H +using namespace AscendC; +namespace LICommon { + +// 与tiling的layout保持一致 +enum class LI_LAYOUT { + BSND = 0, + TND = 1, + PA_BSND = 2 +}; + +template +struct LIType { + static constexpr bool weightsTypeFlag = DT_W_FLAG; // weight的dtype是否为FP32 + using queryType = Q_T; + using keyType = K_T; + using outputType = OUT_T; + static constexpr bool pageAttention = PAGE_ATTENTION; + static constexpr LI_LAYOUT layout = LAYOUT_T; + static constexpr LI_LAYOUT keyLayout = K_LAYOUT_T; +}; + +struct RunInfo { + uint32_t loop; + uint32_t bN2Idx; + uint32_t bIdx; + uint32_t n2Idx = 0; + uint32_t gS1Idx; + uint32_t s2Idx; + + uint32_t actS1Size = 1; + uint32_t actS2Size = 1; + uint32_t actS2SizeOrig = 1; + uint32_t actMBaseSize; + uint32_t actualSingleProcessSInnerSize; + uint32_t actualSingleProcessSInnerSizeAlign; + + uint64_t tensorQueryOffset; + uint64_t tensorKeyOffset; + uint64_t tensorWeightsOffset; + uint64_t indiceOutOffset; + uint64_t valueOutOffset; + + bool isFirstS2InnerLoop; + bool isLastS2InnerLoop; + bool isAllLoopEnd = false; + bool isValid = false; +}; + +struct ConstInfo { + // CUBE与VEC核间同步的模式 + static constexpr uint32_t FIA_SYNC_MODE2 = 2; + static constexpr uint32_t LI_SYNC_MODE4 = 4; + static constexpr uint32_t AIV0_AIV1_OFFSET = 16; + static constexpr uint32_t CROSS_VC_EVENT = 0; + static constexpr uint32_t CROSS_CV_EVENT = 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; + // 无效索引 + static constexpr int INVALID_IDX = -1; + uint16_t INVALID_VAL = 0; + // CUBE和VEC的核间同步EventID + uint32_t syncC1V1 = 0U; + uint32_t syncC1V0 = 2U; + uint32_t syncV1C1 = 0U; + uint32_t syncV0C1 = 1U; + + // 基本块大小 + uint32_t mBaseSize = 1ULL; + uint32_t mBaseSizeAlign = 1ULL; + uint32_t s1BaseSize = 1ULL; + uint32_t s2BaseSize = 1ULL; + + uint64_t batchSize = 0ULL; + uint64_t gSize = 0ULL; + uint64_t qHeadNum = 0ULL; + uint64_t kHeadNum; + uint64_t headDim; + uint64_t sparseCount; // topK选取大小 + uint64_t kSeqSize = 0ULL; // kv最大S长度 + uint64_t qSeqSize = 1ULL; // q最大S长度 + uint32_t kCacheBlockSize = 0; // PA场景的block size + uint32_t maxBlockNumPerBatch = 0; // PA场景的最大单batch block number + LI_LAYOUT outputLayout; // 输出的格式 + bool attenMaskFlag = false; + int64_t preTokens = INT64_MAX; + int64_t nextTokens = INT64_MAX; + bool returnValue = false; + + uint32_t actualLenQDims = 0U; // query的actualSeqLength 的维度 + uint32_t actualLenDims = 0U; // KV 的actualSeqLength 的维度 + bool isAccumSeqS1 = false; // 是否累加模式 + bool isAccumSeqS2 = false; // 是否累加模式 + bool isSparseCountOver2K = false; //sparseCount小于等于2048为false + bool isLDOpen = false; + bool returnValueFlag = false; + bool splitMFlag = false; +}; + +struct SplitCoreInfo { + uint32_t s2Start = 0U; // S2的起始位置 + uint32_t s2End = 0U; // S2循环index上限 + uint32_t bN2Start = 0U; + uint32_t bN2End = 0U; + uint32_t gS1Start = 0U; + uint32_t gS1End = 0U; + bool isLD = false; // 当前核是否需要进行Decode归约任务 + bool isCoreEnable = false; +}; + +template +__aicore__ inline T Align(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 T1 Max(T1 a, T2 b) +{ + return (a > b) ? (a) : (b); +} + +template +__aicore__ inline T CeilDiv(T num, T rnd) +{ + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd))); +} +} // namespace LICommon + +// bank冲突优化 +// david 256KB bank layout +// shape ( bank_depth ( banks bank_groups block)) (512 ( 2 8 32)) +// stride (banks*bank_groups*block (bank_groups*block block 1)) (512 (256 32 1)) +#define UB_BLOCK 32 // 32B +#define UB_BANK_GROUPS 8 +#define UB_BANKS 2 +#define UB_BANK_DEPTH 512 + +#define UB_BANK_GROUP_STRIDE UB_BLOCK // 32B +#define UB_BANK_STRIDE (UB_BANK_GROUPS * UB_BLOCK) // 256B +#define UB_BANK_DEPTH_STRIDE (UB_BANKS * UB_BANK_GROUPS * UB_BLOCK) // 512B + +#endif // LIGHTNING_INDEXER_COMMON_H \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer_template_tiling_key.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer_template_tiling_key.h new file mode 100644 index 0000000000000000000000000000000000000000..b9640d70e546992afc8122e9053a1b357fd24907 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/op_kernel/lightning_indexer_template_tiling_key.h @@ -0,0 +1,88 @@ +/** + * 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 lightning_indexer_template_tiling_key.h + * \brief + */ + +#ifndef TEMPLATE_TILING_KEY_LI_H_ +#define TEMPLATE_TILING_KEY_LI_H_ + +#include "ascendc/host_api/tiling/template_argument.h" + +#define LI_TPL_FP32 0 +#define LI_TPL_FP16 1 +#define LI_TPL_INT32 3 +#define LI_TPL_BF16 27 + +#define LI_LAYOUT_BSND 0 +#define LI_LAYOUT_TND 1 +#define LI_LAYOUT_PA_BSND 2 + +#define ASCENDC_TPL_4_BW 4 + +// 模板参数支持的范围定义 +ASCENDC_TPL_ARGS_DECL(LightningIndexer, // 算子OpType + ASCENDC_TPL_DTYPE_DECL(DT_Q, LI_TPL_FP16, LI_TPL_BF16), + ASCENDC_TPL_DTYPE_DECL(DT_K, LI_TPL_FP16, LI_TPL_BF16), + ASCENDC_TPL_DTYPE_DECL(DT_OUT, LI_TPL_INT32), ASCENDC_TPL_BOOL_DECL(PAGE_ATTENTION, 0, 1), + ASCENDC_TPL_UINT_DECL(LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND, + LI_LAYOUT_TND), + ASCENDC_TPL_UINT_DECL(K_LAYOUT_T, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, + LI_LAYOUT_BSND, LI_LAYOUT_TND, LI_LAYOUT_PA_BSND), + ASCENDC_TPL_BOOL_DECL(DT_W_FLAG, 0, 1), ); + +// 支持的模板参数组合 +// 用于调用GET_TPL_TILING_KEY获取TilingKey时,接口内部校验TilingKey是否合法 +ASCENDC_TPL_SEL( + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, LI_TPL_FP16), ASCENDC_TPL_DTYPE_SEL(DT_K, LI_TPL_FP16), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, LI_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND, LI_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_PA_BSND), + ASCENDC_TPL_BOOL_SEL(DT_W_FLAG, 0, 1), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, LI_TPL_BF16), ASCENDC_TPL_DTYPE_SEL(DT_K, LI_TPL_BF16), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, LI_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 1), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND, LI_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_PA_BSND), + ASCENDC_TPL_BOOL_SEL(DT_W_FLAG, 0, 1), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, LI_TPL_FP16), ASCENDC_TPL_DTYPE_SEL(DT_K, LI_TPL_FP16), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, LI_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND), + ASCENDC_TPL_BOOL_SEL(DT_W_FLAG, 0, 1), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, LI_TPL_FP16), ASCENDC_TPL_DTYPE_SEL(DT_K, LI_TPL_FP16), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, LI_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_TND), + ASCENDC_TPL_BOOL_SEL(DT_W_FLAG, 0, 1), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, LI_TPL_BF16), ASCENDC_TPL_DTYPE_SEL(DT_K, LI_TPL_BF16), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, LI_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_BSND), + ASCENDC_TPL_BOOL_SEL(DT_W_FLAG, 0, 1), ), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_DTYPE_SEL(DT_Q, LI_TPL_BF16), ASCENDC_TPL_DTYPE_SEL(DT_K, LI_TPL_BF16), + ASCENDC_TPL_DTYPE_SEL(DT_OUT, LI_TPL_INT32), + ASCENDC_TPL_BOOL_SEL(PAGE_ATTENTION, 0), + ASCENDC_TPL_UINT_SEL(LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_TND), + ASCENDC_TPL_UINT_SEL(K_LAYOUT_T, ASCENDC_TPL_UI_LIST, LI_LAYOUT_TND), + ASCENDC_TPL_BOOL_SEL(DT_W_FLAG, 0, 1), ), ); + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/test_data/cases_manifest.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/test_data/cases_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..939ca5f24a3fdc442df085a0ad7bc3a3fe44c7a6 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/test_data/cases_manifest.json @@ -0,0 +1,217 @@ +{ + "op_name": "lightning_indexer", + "op_camel": "LightningIndexer", + "output_keys": [ + "sparse_indices", + "sparse_values" + ], + "cases": [ + { + "id": 0, + "dtype": "float16", + "q_layout": "BSND", + "k_layout": "BSND", + "shape": [ + 1, + 4, + 1 + ], + "attrs": { + "B": 1, + "S1": 4, + "N1": 1, + "S2": 64, + "sc": 64, + "sm": 0, + "rv": true + } + }, + { + "id": 1, + "dtype": "bfloat16", + "q_layout": "BSND", + "k_layout": "BSND", + "shape": [ + 2, + 16, + 8 + ], + "attrs": { + "B": 2, + "S1": 16, + "N1": 8, + "S2": 128, + "sc": 2048, + "sm": 3, + "rv": false + } + }, + { + "id": 2, + "dtype": "float16", + "q_layout": "BSND", + "k_layout": "BSND", + "shape": [ + 1, + 8, + 32 + ], + "attrs": { + "B": 1, + "S1": 8, + "N1": 32, + "S2": 128, + "sc": 128, + "sm": 3, + "rv": false + } + }, + { + "id": 3, + "dtype": "float16", + "q_layout": "BSND", + "k_layout": "BSND", + "shape": [ + 2, + 16, + 4 + ], + "attrs": { + "B": 2, + "S1": 16, + "N1": 4, + "S2": 64, + "sc": 64, + "sm": 0, + "rv": true, + "weights_dtype": "float32" + } + }, + { + "id": 4, + "dtype": "bfloat16", + "q_layout": "BSND", + "k_layout": "PA_BSND", + "shape": [ + 2, + 32, + 8 + ], + "attrs": { + "B": 2, + "S1": 32, + "N1": 8, + "blocks": 16, + "blk": 16, + "max_blocks": 8, + "sc": 128, + "sm": 3, + "rv": false + } + }, + { + "id": 5, + "dtype": "float16", + "q_layout": "TND", + "k_layout": "TND", + "shape": [ + 1, + 64, + 2 + ], + "attrs": { + "B": 1, + "T": 64, + "N1": 2, + "sc": 64, + "sm": 0, + "rv": true + } + }, + { + "id": 6, + "dtype": "bfloat16", + "q_layout": "TND", + "k_layout": "TND", + "shape": [ + 1, + 64, + 4 + ], + "attrs": { + "B": 1, + "T": 64, + "N1": 4, + "sc": 128, + "sm": 3, + "rv": false + } + }, + { + "id": 7, + "dtype": "float16", + "q_layout": "TND", + "k_layout": "TND", + "shape": [ + 3, + 48, + 8 + ], + "attrs": { + "B": 3, + "T": 48, + "N1": 8, + "sc": 16, + "sm": 0, + "rv": false, + "weights_dtype": "float32", + "seq": "[16, 32, 48]" + } + }, + { + "id": 8, + "dtype": "float16", + "q_layout": "TND", + "k_layout": "PA_BSND", + "shape": [ + 1, + 16, + 2 + ], + "attrs": { + "B": 1, + "T": 16, + "N1": 2, + "blocks": 2, + "blk": 16, + "max_blocks": 2, + "seq": "[16]", + "seq_key": "[32]", + "block_table_override": "[[0, 1]]", + "sc": 64, + "sm": 3, + "rv": false + } + }, + { + "id": 9, + "dtype": "float16", + "q_layout": "BSND", + "k_layout": "BSND", + "shape": [ + 1, + 1, + 64 + ], + "attrs": { + "B": 1, + "S1": 1, + "N1": 64, + "S2": 16, + "sc": 16, + "sm": 0, + "rv": true + } + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..fee487bccb8c03e66930cadb2d0e7d2db150c6c9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/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/lightning_indexer/tests/assets/impl/compare.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..8609ef0cb5f8c84aa4f7a02b88723b8aabd848af --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/compare.py @@ -0,0 +1,231 @@ +#!/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. +# ----------------------------------------------------------------------------------------------------------- + +"""TopK compare helpers for LightningIndexer TestSpec adapters.""" + +import numpy as np + +# Match the pytest boundary-score policy for non-identical TopK index sets. +_TOPK_REL_TOL = 0.0001 +_VALUE_RTOL = 0.005 +_VALUE_ATOL = 0.000025 +_VALUE_FAIL_RATIO = 0.05 + + +def as_numpy(value): + if hasattr(value, "detach"): + value = value.detach().cpu().numpy() + return np.asarray(value) + + +def row_set_diff_positions(output_row, golden_row): + golden_set = {int(x) for x in golden_row if x >= 0} + bad_positions = [idx for idx, value in enumerate(output_row) if value >= 0 and int(value) not in golden_set] + output_set = {int(x) for x in output_row if x >= 0} + missing_count = max(len(output_set - golden_set), len(golden_set - output_set)) + if missing_count <= 0: + return [] + if len(bad_positions) >= missing_count: + return bad_positions[:missing_count] + positional = [idx for idx, (out, gold) in enumerate(zip(output_row, golden_row)) if out != gold] + return (bad_positions + positional)[:missing_count] + + +def score_relative_diff(score, boundary): + score_diff = abs(float(score) - float(boundary)) + denom = max(abs(float(boundary)), 1e-10) + return abs(score_diff / denom) + + +def is_score_close_to_boundary(score, boundary): + return score_relative_diff(score, boundary) <= _TOPK_REL_TOL + + +def row_score_diff_to_boundary(output_indices, golden_indices, score_row): + if len(golden_indices) == 0: + return 0.0, 0.0 + boundary_idx = int(golden_indices[-1]) + if boundary_idx < 0 or boundary_idx >= score_row.shape[-1]: + return 0.0, 0.0 + boundary = float(score_row[boundary_idx]) + candidates = {int(x) for x in output_indices} ^ {int(x) for x in golden_indices} + max_abs = 0.0 + max_rel = 0.0 + for idx in candidates: + if 0 <= idx < score_row.shape[-1]: + abs_diff = abs(float(score_row[idx]) - boundary) + max_abs = max(max_abs, abs_diff) + max_rel = max(max_rel, score_relative_diff(score_row[idx], boundary)) + return max_abs, max_rel + + +def is_row_equivalent_by_score(output_indices, golden_indices, score_row): + if len(output_indices) != len(golden_indices) or len(golden_indices) == 0: + return False + output_set = {int(x) for x in output_indices} + golden_set = {int(x) for x in golden_indices} + if output_set == golden_set: + return True + only_output = list(output_set - golden_set) + only_golden = list(golden_set - output_set) + if len(only_output) != len(only_golden): + return False + + boundary_idx = int(golden_indices[-1]) + if boundary_idx < 0 or boundary_idx >= score_row.shape[-1]: + return False + boundary = float(score_row[boundary_idx]) + for idx in only_output + only_golden: + if idx < 0 or idx >= score_row.shape[-1]: + return False + if not is_score_close_to_boundary(score_row[idx], boundary): + return False + return True + + +def topk_index_compare(npu_out, golden_out, scores): + npu = as_numpy(npu_out) + golden = as_numpy(golden_out) + if npu.shape != golden.shape: + return { + "pass": False, + "precision": "shape_mismatch", + "error_info": f"index shape mismatch: npu={npu.shape}, golden={golden.shape}", + } + if npu.size == 0: + return {"pass": True, "precision": 100.0, "metrics": {"rows": 0}} + + scores_np = None if scores is None else as_numpy(scores) + if scores_np is None or tuple(scores_np.shape[:-1]) != tuple(golden.shape[:-1]): + sorted_npu = np.sort(npu, axis=-1).reshape(-1) + sorted_golden = np.sort(golden, axis=-1).reshape(-1) + diff_idx = np.where(sorted_npu != sorted_golden)[0].tolist() + precision = (sorted_golden.size - len(diff_idx)) / sorted_golden.size * 100 + reason = "score context missing" if scores_np is None else f"score shape {scores_np.shape} vs index shape {golden.shape}" + return { + "pass": len(diff_idx) == 0, + "precision": precision, + "diff_indices": diff_idx[:1000], + "error_info": None if not diff_idx else f"TopK fallback sorted-index compare failed: {reason}", + "metrics": {"fallback": reason, "diff_positions": len(diff_idx)}, + } + + row_count = int(np.prod(golden.shape[:-1])) if golden.shape[:-1] else 1 + k_count = golden.shape[-1] + output_rows = npu.reshape(row_count, k_count) + golden_rows = golden.reshape(row_count, k_count) + score_rows = scores_np.reshape(row_count, scores_np.shape[-1]) + + diff_indices = [] + set_equal_rows = 0 + score_equiv_rows = 0 + failed_rows = 0 + max_failed_abs_diff = 0.0 + max_failed_rel_diff = 0.0 + for row_idx, (output_row, golden_row, score_row) in enumerate(zip(output_rows, golden_rows, score_rows)): + output_valid = output_row[output_row >= 0].astype(np.int64) + golden_valid = golden_row[golden_row >= 0].astype(np.int64) + if np.array_equal(np.sort(output_valid), np.sort(golden_valid)): + set_equal_rows += 1 + continue + if is_row_equivalent_by_score(output_valid, golden_valid, score_row): + score_equiv_rows += 1 + continue + failed_rows += 1 + abs_diff, rel_diff = row_score_diff_to_boundary(output_valid, golden_valid, score_row) + max_failed_abs_diff = max(max_failed_abs_diff, abs_diff) + max_failed_rel_diff = max(max_failed_rel_diff, rel_diff) + base = row_idx * k_count + diff_indices.extend(base + i for i in row_set_diff_positions(output_row, golden_row)) + + precision = (golden.size - len(diff_indices)) / golden.size * 100 + fail_ratio = len(diff_indices) / golden.size + passed = failed_rows == 0 + error_info = None + if failed_rows: + verdict = "tolerated" if passed else "failed" + error_info = ( + f"TopK index compare {verdict} rows={failed_rows}, diff_positions={len(diff_indices)}, " + f"fail_ratio={fail_ratio:.6g}, max_failed_abs_score_diff={max_failed_abs_diff:.6g}, " + f"max_failed_rel_score_diff={max_failed_rel_diff:.6g}" + ) + return { + "pass": passed, + "precision": precision, + "diff_indices": diff_indices[:1000], + "error_info": error_info, + "metrics": { + "rows": row_count, + "set_equal_rows": set_equal_rows, + "score_equivalent_rows": score_equiv_rows, + "failed_rows": failed_rows, + "diff_positions": len(diff_indices), + "fail_ratio": fail_ratio, + "topk_rel_tol": _TOPK_REL_TOL, + "max_failed_abs_score_diff": max_failed_abs_diff, + "max_failed_rel_score_diff": max_failed_rel_diff, + }, + } + + +def expected_values_from_scores(scores, value_shape): + if scores is None: + return None + scores_np = as_numpy(scores).astype(np.float32) + if tuple(scores_np.shape[:-1]) != tuple(value_shape[:-1]): + return None + k_count = value_shape[-1] + sorted_scores = np.sort(scores_np, axis=-1)[..., ::-1] + if sorted_scores.shape[-1] < k_count: + pad_shape = sorted_scores.shape[:-1] + (k_count - sorted_scores.shape[-1],) + sorted_scores = np.concatenate( + [sorted_scores, np.full(pad_shape, -np.inf, dtype=np.float32)], axis=-1) + return sorted_scores[..., :k_count] + + +def value_compare(npu_out, golden_out, scores=None): + npu = as_numpy(npu_out).astype(np.float32) + expected = expected_values_from_scores(scores, npu.shape) + if expected is None: + expected = np.sort(as_numpy(golden_out).astype(np.float32), axis=-1) + npu = np.sort(npu, axis=-1) + if npu.size != expected.size: + return { + "pass": False, + "precision": "size_mismatch", + "error_info": f"value size mismatch: npu={npu.size}, golden={expected.size}", + } + if expected.size == 0: + return {"pass": True, "precision": 100.0} + diff = ~np.isclose(npu.reshape(-1), expected.reshape(-1), rtol=_VALUE_RTOL, atol=_VALUE_ATOL, equal_nan=True) + diff_idx = np.where(diff)[0].tolist() + precision = (expected.size - len(diff_idx)) / expected.size * 100 + return { + "pass": (len(diff_idx) / expected.size) <= _VALUE_FAIL_RATIO, + "precision": precision, + "diff_indices": diff_idx[:1000], + "error_info": None if not diff_idx else f"value compare mismatches={len(diff_idx)}", + "metrics": {"rtol": _VALUE_RTOL, "atol": _VALUE_ATOL, "fail_ratio": _VALUE_FAIL_RATIO}, + } + + +def compare(*outputs, scores=None): + """Compare NPU outputs against golden references using TopK index and value tolerance policies.""" + 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 = [topk_index_compare(npu_outputs[0], golden_outputs[0], scores)] + for idx in range(1, half): + results.append(value_compare(npu_outputs[idx], golden_outputs[idx], scores=scores)) + return results[0] if len(results) == 1 else results diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/golden.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/golden.py new file mode 100644 index 0000000000000000000000000000000000000000..faa74fc02bb50ab68a5369ba9061a63ffda0202d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/golden.py @@ -0,0 +1,195 @@ +#!/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 importlib.util +import math +import sys +from pathlib import Path + +import torch + + +PYTEST_GOLDEN_MODULE = None + + +def load_pytest_golden_module(): + """Load tests/pytest/lightning_indexer_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 / "lightning_indexer_golden.py" + sys.path.insert(0, str(pytest_dir)) + try: + spec = importlib.util.spec_from_file_location( + f"li_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 + + +# ========================= TTK e2e adapter ========================= +# The CPU reference is loaded from tests/pytest; assets keeps only the TTK adapter layer. +# The adapter below maps torch_npu API-style tensors to GeneralizedLI and normalizes return_value semantics. +_TTK_V3_TOPK_SCORES = None + + +def clear_topk_scores(): + global _TTK_V3_TOPK_SCORES + _TTK_V3_TOPK_SCORES = None + + +def set_topk_scores(scores): + global _TTK_V3_TOPK_SCORES + _TTK_V3_TOPK_SCORES = scores + + +def get_topk_scores(): + return _TTK_V3_TOPK_SCORES + + +__golden__ = { + "e2e": { + "torch_npu.npu_lightning_indexer": "cpu_lightning_indexer" + } +} + + +def ttk_tensor_to_list(value): + if value is None: + return [] + if torch.is_tensor(value): + return [int(x) for x in value.detach().cpu().reshape(-1).tolist()] + if isinstance(value, (list, tuple)): + return [int(x) for x in value] + return [int(value)] + + +def ttk_per_batch_from_prefix(prefix): + prefix = ttk_tensor_to_list(prefix) + if not prefix: + return [] + out = [prefix[0]] + for i in range(len(prefix) - 1): + out.append(prefix[i + 1] - prefix[i]) + return out + + +def ttk_scores_to_layout(golden_obj, scores_bnsd, layout_query, act_q_per_batch): + shape = list(scores_bnsd.shape) + return golden_obj.trans_bnsd_to_layout(scores_bnsd, shape, layout_query, act_q_per_batch) + + +def ttk_restore_pa_bsnd(paged_tensor, block_table, act_k, block_size): + if paged_tensor is None or block_table is None: + return paged_tensor + act_k = [int(x) for x in act_k] + page_table = block_table.detach().cpu() if torch.is_tensor(block_table) else torch.tensor(block_table) + src = paged_tensor.detach().cpu() + batch = len(act_k) + num_heads = src.shape[2] + tail_shape = src.shape[3:] + max_k = max(act_k) if act_k else 0 + restored = torch.zeros((batch, num_heads, max_k) + tail_shape, dtype=src.dtype) + for b_idx, cur_k in enumerate(act_k): + if cur_k <= 0: + continue + pages = int(math.ceil(cur_k / block_size)) + copied = 0 + for page_idx in range(min(pages, page_table.shape[1])): + block_id = int(page_table[b_idx, page_idx].item()) + if block_id < 0: + continue + take = min(block_size, cur_k - copied) + restored[b_idx, :, copied:copied + take, ...] = src[ + block_id, :take, :, ... + ].permute(1, 0, *range(2, src.dim() - 1)) + copied += take + if copied >= cur_k: + break + return restored + + +def cpu_lightning_indexer(query, key, weights, *, actual_seq_lengths_query=None, + actual_seq_lengths_key=None, block_table=None, + layout_query="BSND", layout_key="BSND", sparse_count=2048, + sparse_mode=3, pre_tokens=(1 << 63) - 1, + next_tokens=(1 << 63) - 1, return_value=False, **kwargs): + """Golden reference implementation for LightningIndexer attention with TopK scoring.""" + clear_topk_scores() + q_shape = list(query.shape) + k_shape = list(key.shape) + act_q = ttk_tensor_to_list(actual_seq_lengths_query) + act_k = ttk_tensor_to_list(actual_seq_lengths_key) + + if layout_query == "TND": + batch_size = len(act_q) if act_q else 1 + q_t_size, q_head_num, head_dim = q_shape + q_seq = max(ttk_per_batch_from_prefix(act_q) or [q_t_size]) + act_q_forward = act_q + else: + batch_size, q_seq, q_head_num, head_dim = q_shape + act_q_forward = act_q or [q_seq] * batch_size + q_t_size = sum(act_q_forward) + + if layout_key == "TND": + k_t_size, k_head_num, _ = k_shape + k_seq = max(ttk_per_batch_from_prefix(act_k) or [k_t_size]) + act_k_forward = act_k + elif layout_key == "PA_BSND": + block_num, block_size, k_head_num, _ = k_shape + k_t_size = sum(act_k) if act_k else block_num * block_size + k_seq = max(act_k or [block_size]) + act_k_forward = act_k or [k_seq] * batch_size + else: + _, k_seq, k_head_num, _ = k_shape + k_t_size = sum(act_k) if act_k else k_seq * batch_size + act_k_forward = act_k or [k_seq] * batch_size + block_size = int(kwargs.get("block_size", 16)) + block_num = int(kwargs.get("block_num", 0)) + + block_size = int(kwargs.get("block_size", locals().get("block_size", 16))) + block_num = int(kwargs.get("block_num", locals().get("block_num", 0))) + + golden_key = key + if layout_key == "PA_BSND": + golden_key = ttk_restore_pa_bsnd(key, block_table, act_k_forward, block_size) + + golden_cls = load_pytest_golden_module().GeneralizedLI + golden = golden_cls(batch_size, q_seq, k_seq, q_t_size, k_t_size, + q_head_num, k_head_num, head_dim, block_size, block_num, + query.dtype, weights.dtype, torch.int32, + act_q_forward, act_k_forward, layout_query, layout_key, + int(sparse_count), int(sparse_mode)) + fwd_act_q = act_q_forward if layout_query == "TND" else torch.tensor(act_q_forward, dtype=torch.int32) + fwd_act_k = act_k_forward if layout_key == "TND" else torch.tensor(act_k_forward, dtype=torch.int32) + indices, full_scores_bnsd = golden.forward(query, golden_key, weights, + fwd_act_q, fwd_act_k, block_table) + + act_q_per_batch = ttk_per_batch_from_prefix(act_q_forward) if layout_query == "TND" else act_q_forward + scores_layout = ttk_scores_to_layout(golden, full_scores_bnsd, layout_query, act_q_per_batch) + set_topk_scores(scores_layout) + + return_value = bool(return_value or kwargs.get("return_values", False)) + if return_value: + gather_idx = indices.clamp_min(0).to(torch.long) + values = torch.gather(scores_layout, -1, gather_idx).to(query.dtype) + values = torch.where(indices < 0, torch.full_like(values, -float('inf')), values) + return indices, values + return indices, torch.zeros(0, dtype=scores_layout.dtype) diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/inputs.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/inputs.py new file mode 100644 index 0000000000000000000000000000000000000000..eb5f282c6ade1dd83277f12065e7a2cf6db7a1fd --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/impl/inputs.py @@ -0,0 +1,73 @@ +#!/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__ = { + "e2e": { + "torch_npu.npu_lightning_indexer": "generate_li_inputs" + } +} + +import math +import torch + + +def to_list(value): + if value is None: + return [] + if torch.is_tensor(value): + return value.detach().cpu().tolist() + if isinstance(value, (list, tuple)): + return list(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 generate_li_inputs(query, key, weights, *, + actual_seq_lengths_query=None, + actual_seq_lengths_key=None, + block_table=None, + layout_query="BSND", layout_key="BSND", + sparse_count=2048, sparse_mode=3, **kwargs): + """Generate and preprocess NPU inputs for LightningIndexer, handling BSND/TND/PA_BSND layouts.""" + fill_tensor_from_value(actual_seq_lengths_query, actual_seq_lengths_query) + fill_tensor_from_value(actual_seq_lengths_key, actual_seq_lengths_key) + fill_tensor_from_value(block_table, block_table) + + act_q = to_list(actual_seq_lengths_query) + act_k = to_list(actual_seq_lengths_key) + + if layout_query == "BSND": + B = query.shape[0] + else: + B = len(act_q) if act_q else 1 + + if not act_q: + act_q = [query.shape[1] if layout_query == "BSND" else max(query.shape[0] // B, 1)] * B + if not act_k: + act_k = [key.shape[1] if layout_key == "BSND" else max(key.shape[0] // B, 1)] * B + + if block_table is not None and torch.is_tensor(block_table) and layout_key == "PA_BSND": + block_size = kwargs.get('block_size', 256) + key_block_num_per_batch = [math.ceil(k / block_size) for k in act_k] + new_bt = torch.full(tuple(block_table.shape), -1, dtype=torch.int32) + cur_block_id = 0 + for batch_idx, cur_threshold in enumerate(key_block_num_per_batch): + for i_block in range(min(cur_threshold, block_table.shape[1])): + new_bt[batch_idx, i_block] = cur_block_id + cur_block_id += 1 + block_table[:] = new_bt.to(block_table.device) diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/spec.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/spec.py new file mode 100644 index 0000000000000000000000000000000000000000..936afbfef8e4fa30cb7a89ed481e8139b3cb0e89 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/assets/spec.py @@ -0,0 +1,49 @@ +#!/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 LightningIndexer 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"li_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 LightningIndexerSpec: + golden = golden_module.cpu_lightning_indexer + customize_inputs = inputs_module.generate_li_inputs + tolerance = { + "float16": {"standard": "stat_rel_err"}, + "bfloat16": {"standard": "stat_rel_err"}, + } + + def compare(*outputs, **kwargs): + return compare_module.compare(*outputs, scores=golden_module.get_topk_scores()) + + +__spec__ = { + "torch_npu.npu_lightning_indexer": "LightningIndexerSpec", +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/README.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c073731263dc85fea739078ce40f6da919ee9f98 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/README.md @@ -0,0 +1,77 @@ +# lightning_indexer算子测试框架 + +## 功能说明 + +基于pytest测试框架,实现lightning_indexer算子的功能验证: + +- **CPU侧**:复现算子功能用以生成golden数据 +- **NPU侧**:通过TorchNPU进行算子直调获取实际数据 +- **精度对比**:进行CPU与NPU结果的精度对比验证算子功能 + +## 当前实现范围 + +### 参数限制 + +- **数据格式**: + - **query_layout**:BSND、TND + - **key_layout**: PA_BSND + +### 环境配置 + +#### 前置要求 + +1. 完成环境安装和环境变量配置。 +2. 安装与当前 CANN、PyTorch 环境兼容的 TorchNPU 软件包。 + +#### custom包调用 + +支持custom包调用 + +## 文件结构 + +#### pytest文件结构说明 + +- test_run_sh # 执行脚本 +- lightning_indexer_golden.py # cpu侧算子golden实现 +- result_compare_method.py # cpu golden与npu输出精度对比 +- pytest.ini # 创建测试标记 + +单用例测试: + +- test_lightning_indexer_single.py # pytest测试单用例运行主程序 +- test_lightning_indexer_paramset.py # 单用例入参配置 + +批量测试: + +- test_lightning_indexer_batch.py # 用例批量测试主程序并生成excel文件保存结果 +- ./batch/lightning_indexer_pt_loadprocess.py # 读取pt文件并调用算子获取npu输出 +- ./batch/lightning_indexer_pt_save.py # 读取excel表格批量生成用例pt文件 +- ./batch/replace_path.py # test_lightning_indexer_batch.py占位符替换 + +## 使用方法 + +在pytest文件夹路径下执行: + +### 运行测试用例 + +#### 单用例调测 + +1、手动配置test_lightning_indexer_paramset.py的参数 + +2、执行指令: + +``` bash +bash test_run.sh single +``` + +#### 用例的批量生成与测试 + +1、excel路径下存放用例excel表格 + +2、test_run.sh中设置读取的用例excel表格路径和pt文件存放路径 + +3、执行指令: + +``` bash +bash test_run.sh batch +``` diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/lightning_indexer_pt_loadprocess.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/lightning_indexer_pt_loadprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..d0262b6d1f1be63c34e31c1fb0a56fc68888fc1a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/lightning_indexer_pt_loadprocess.py @@ -0,0 +1,69 @@ +#!/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 pandas as pd +import numpy as np +import torch +import torch_npu +import pytest +import random +import math +import ast + +def test_li_process(filepath, device_id=0): + # 加载测试数据 + test_data = torch.load(filepath, map_location="cpu") + + params = test_data['params'] + cpu_result = test_data['cpu_result'] + topk_value = test_data['topk_value'] + print("执行用例:", filepath) + torch_npu.npu.set_device(device_id) + + if params[10] == 'FLOAT8_E4M3FN': + query = test_data['query'].to(dtype=torch.float8_e4m3fn).npu() + key = test_data['key'].to(dtype=torch.float8_e4m3fn).npu() + else: + query = test_data['query'].npu() + key = test_data['key'].npu() + + + weights =test_data['weights'].npu() + actual_seq_lengths_query = test_data['actual_seq_lengths_query'].npu() + actual_seq_lengths_key = test_data['actual_seq_lengths_key'].npu() + block_table = test_data['block_table'] + if isinstance(block_table, torch.Tensor): + block_table = block_table.npu() + layout_query = test_data['layout_query'] + layout_key = test_data['layout_key'] + sparse_count = test_data['sparse_count'] + sparse_mode = test_data['sparse_mode'] + return_value = test_data['return_value'] + #调用LI算子 + npu_result, sparse_value = torch_npu.npu_lightning_indexer(query, key, weights, + actual_seq_lengths_query=actual_seq_lengths_query, + actual_seq_lengths_key=actual_seq_lengths_key, + block_table=block_table, + layout_query=layout_query, + layout_key=layout_key, + sparse_count=sparse_count, + sparse_mode=sparse_mode, + pre_tokens = (1<<63)-1, + next_tokens = (1<<63)-1, + return_value = return_value + ) + + torch.npu.synchronize() + sparse_value, _ = sparse_value.sort(dim=-1, descending=True) + return cpu_result, npu_result, topk_value, sparse_value, params + diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/lightning_indexer_pt_save.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/lightning_indexer_pt_save.py new file mode 100644 index 0000000000000000000000000000000000000000..4a50129188bf26a7a739f60b6e881420c6305bfb --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/lightning_indexer_pt_save.py @@ -0,0 +1,295 @@ +#!/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 functools import partial +from lightning_indexer_golden import GeneralizedLI +import pandas as pd +import numpy as np +import torch +import torch_npu +import pytest +import random +import math +import ast +import argparse + +def load_excel_test_cases(excel_file_path: str, sheetname: str): + + """ + 从 Excel 文件加载测试用例。 + + 参数: + excel_file_path (str): Excel 文件的路径。 + sheetname (str, optional): 工作表名称。若未提供,则默认 'Sheet1'。 + + 返回: + list[tuple]: 测试用例元组列表,每个元组包含 20+ 个字段。 + 若失败或跳过,则返回空列表。 + """ + # 优先使用传入的 sheetname,否则尝试从环境变量获取 + if sheetname is None: + sheetname = 'Sheet1' + + # 检查文件是否存在 + if not os.path.exists(excel_file_path): + pytest.skip(f"Excel file not found: {excel_file_path}", allow_module_level=True) + + try: + # 读取 Excel 文件的指定 sheet + df = pd.read_excel(excel_file_path, sheet_name=sheetname) + df = df.replace({np.nan: None, pd.NA: None}) + + # 定义必需的列名 + required_columns = [ + 'Testcase_Name', 'batch_size', 'q_seq','k_seq','q_t_size', 'k_t_size', + 'q_head_num', 'k_head_num', 'head_dim', 'block_size', 'block_num', + 'qk_dtype','weight_dtype', 'actual_seq_dtype', 'act_seq_q', 'act_seq_k', + 'layout_query','layout_key','sparse_count', + 'sparse_mode', 'query_datarange','key_datarange','weights_datarange', + 'return_value' + ] + + # 检查是否缺少必要列 + missing_cols = [col for col in required_columns if col not in df.columns] + if missing_cols: + pytest.skip(f"Missing required columns in Excel: {missing_cols}", allow_module_level=True) + + # 构建测试用例列表 + test_cases = [] + for _, row in df.iterrows(): + test_cases.append(( + row['Testcase_Name'], + row['batch_size'], + row['q_seq'], + row['k_seq'], + row['q_t_size'], + row['k_t_size'], + row['q_head_num'], + row['k_head_num'], + row['head_dim'], + row['block_size'], + row['block_num'], + row['qk_dtype'], + row['weight_dtype'], + row['actual_seq_dtype'], + row['act_seq_q'], + row['act_seq_k'], + row['layout_query'], + row['layout_key'], + row['sparse_count'], + row['sparse_mode'], + row['query_datarange'], + row['key_datarange'], + row['weights_datarange'], + row['return_value'], + )) + + return test_cases + + except Exception as e: + pytest.skip(f"Failed to read Excel file: {e}", allow_module_level=True) + return None + + +def li_output_single(data_case): + casename = data_case[0] + params = data_case[1:] + + batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num, \ + qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, \ + layout_key, sparse_count, sparse_mode, query_datarange, key_datarange, weights_datarange, \ + return_value = params + batch_size = int(batch_size) + q_seq = int(q_seq) + k_seq = int(k_seq) + if q_t_size is not None: + q_t_size = int(q_t_size) + if k_t_size is not None: + k_t_size = int(k_t_size) + if qk_dtype == 'FP16': + qk_dtype = torch.float16 + elif qk_dtype == 'BF16': + qk_dtype = torch.bfloat16 + q_head_num = int(q_head_num) + k_head_num = int(k_head_num) + head_dim = int(head_dim) + if block_size is not None: + block_size = int(block_size) + if block_num is not None: + block_num = int(block_num) + sparse_count = int(sparse_count) + sparse_mode = int(sparse_mode) + return_value = bool(return_value) if return_value is not None else False + if weight_dtype == 'FP16': + weight_dtype = torch.float16 + elif weight_dtype == 'BF16': + weight_dtype = torch.bfloat16 + + if actual_seq_dtype == 'INT32': + actual_seq_dtype = torch.int32 + + # 处理B+1 + if isinstance(act_seq_q, int): + act_seq_q = [act_seq_q] + elif isinstance(act_seq_q, list): + act_seq_q = act_seq_q + else: + act_seq_q = [int(x.strip()) for x in act_seq_q.split(',')] + if layout_query == 'TND': + if len(act_seq_q) == batch_size + 1: + act_seq_q = act_seq_q[1:] + if isinstance(act_seq_k, int): + act_seq_k = [act_seq_k] + elif isinstance(act_seq_k, list): + act_seq_k = act_seq_k + else: + act_seq_k = [int(x.strip()) for x in act_seq_k.split(',')] + if layout_key == 'TND': + if len(act_seq_k) == batch_size + 1: + act_seq_k = act_seq_k[1:] + query_datarange = [float(x.strip()) for x in query_datarange.split(',')] + key_datarange = [float(x.strip()) for x in key_datarange.split(',')] + weights_datarange = [float(x.strip()) for x in weights_datarange.split(',')] + + + test_li = GeneralizedLI(batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num, + qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, + layout_query, layout_key, sparse_count, sparse_mode) + actual_seq_lengths_query = torch.tensor(np.random.uniform(q_seq, q_seq, batch_size)).to(actual_seq_dtype).npu() \ + if act_seq_q is None else torch.tensor(act_seq_q).to(actual_seq_dtype).npu() + actual_seq_lengths_key = torch.tensor(np.random.uniform(k_seq, k_seq, batch_size)).to(actual_seq_dtype).npu() \ + if act_seq_k is None else torch.tensor(act_seq_k).to(actual_seq_dtype).npu() + if layout_query == "BSND": + query = torch.tensor(np.random.uniform(query_datarange[0], query_datarange[1],(batch_size, q_seq, q_head_num, head_dim))).to(qk_dtype).npu() + weights = torch.tensor(np.random.uniform(weights_datarange[0], weights_datarange[1], (batch_size, q_seq, q_head_num))).to(weight_dtype).npu() + + elif layout_query == "TND": + query = torch.tensor(np.random.uniform(query_datarange[0], query_datarange[1], (q_t_size, q_head_num, head_dim))).to(qk_dtype).npu() + weights = torch.tensor(np.random.uniform(weights_datarange[0], weights_datarange[1], (q_t_size, q_head_num))).to(weight_dtype).npu() + + if layout_key == "BSND": + key = torch.tensor(np.random.uniform(key_datarange[0], key_datarange[1], (batch_size, k_seq, k_head_num, head_dim))).to(qk_dtype).npu() + block_table = None + cpu_result, topk_value = test_li.forward(query, key, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table) + + elif layout_key == "TND": + key = torch.tensor(np.random.uniform(key_datarange[0], key_datarange[1], (k_t_size, k_head_num, head_dim))).to(qk_dtype).npu() + block_table = None + cpu_result, topk_value = test_li.forward(query, key, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table) + + elif layout_key == "PA_BSND": + # 以不同batch中最大seq为标准初始化key(bnsd) + k_max_s2 = math.floor(max(act_seq_k)) + k_max_block_num_per_batch = math.ceil(k_max_s2 / block_size) #遍历batch得到的最大的block num + key_bnsd = torch.tensor(np.random.uniform(key_datarange[0], key_datarange[1],(batch_size, k_head_num, k_max_s2, head_dim))).to(qk_dtype) + + key_block_num_per_batch = [] + key_block_num_sum = 0 + for cur_act_k in act_seq_k: + cur_cmp_act_k = math.floor(cur_act_k) + cur_key_block_num = math.ceil(cur_cmp_act_k / block_size) + key_block_num_per_batch.append(cur_key_block_num) + key_block_num_sum += cur_key_block_num + if block_num < key_block_num_sum: + raise ValueError(f"key actual block num < needed block num") + + # 构建block table + block_id_list = np.arange(block_num) + block_id_list = np.random.permutation(block_id_list).astype(np.int32) + cur_block_id = 0 + block_table = np.full((batch_size, k_max_block_num_per_batch), fill_value = -1, dtype=np.int32) + batch_idx = 0 + for cur_block_id_threshold in key_block_num_per_batch: + for i_block_id in range(cur_block_id_threshold): + block_table[batch_idx][i_block_id] = block_id_list[cur_block_id] + cur_block_id += 1 + batch_idx += 1 + + # 构建PA场景的key + # [batch_size, s2, k_head_num, head_dim] expand to [batch_size, k_max_block_num_per_batch * block_size, k_head_num, head_dim] + key_expand = torch.zeros((batch_size, k_head_num, k_max_block_num_per_batch * block_size, head_dim), dtype = qk_dtype) + key_expand[:,:,:k_max_s2,:] = key_bnsd + key = torch.zeros((block_num, block_size, k_head_num, head_dim), dtype = qk_dtype) + for i_batch in range(batch_size): + for i_block, cur_block_id in enumerate(block_table[i_batch]): + block_start_pos = i_block * block_size + if cur_block_id == -1: + continue + else: + for i_n in range(k_head_num): + key[cur_block_id, :, i_n, :] = key_expand[i_batch, i_n, block_start_pos:block_start_pos+block_size,:] + key = key.npu() + + cpu_result, topk_value = test_li.forward(query, key_bnsd, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table) + block_table = torch.from_numpy(block_table).to(dtype=torch.int32).npu() + max_seqlen_q = actual_seq_lengths_query.max().item() + max_seqlen_k = actual_seq_lengths_key.max().item() + + if qk_dtype == torch.float8_e4m3fn: + query = query.to(dtype=torch.float16) + key = key.to(dtype=torch.float16) + + output_tensors = { + "params":(batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num, + qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, + layout_key, sparse_count, sparse_mode, query_datarange, key_datarange, weights_datarange, + return_value), + "cpu_result": cpu_result, + "topk_value": topk_value, + "query": query, + "key":key, + "weights": weights, + "actual_seq_lengths_query": actual_seq_lengths_query, + "actual_seq_lengths_key": actual_seq_lengths_key, + "block_table": block_table, + "layout_query":layout_query, + "layout_key":layout_key, + "sparse_count":sparse_count, + "sparse_mode":sparse_mode, + "return_value":return_value, + } + return casename, output_tensors + +def save_test_case(test_cases, file_path): + print("正在保存pt文件...") + # 创建输出目录 + os.makedirs(file_path, exist_ok=True) + + for idx, case in enumerate(test_cases): + try: + case_name, output_tensors = li_output_single(case) + # 生成文件名 + input_filename = f"{case_name}.pt" + input_filepath = os.path.join(file_path, input_filename) + + # 保存数据 + torch.save(output_tensors, input_filepath) + print(f"测试用例已保存到: {input_filepath}") + + except Exception as e: + print(f"[失败] 生成 pt 文件失败: {case[0]} (索引: {idx})") + print(f"错误详情: {e}") + +def main(): + parser = argparse.ArgumentParser(description='li_pt_save.py 接收路径参数') + parser.add_argument('path1', type=str, help='第一个路径') + parser.add_argument('path2', type=str, help='第二个路径') + args = parser.parse_args() + path1 = args.path1 + path2 = args.path2 + testcase = load_excel_test_cases(path1, "Sheet1") + save_test_case(testcase, path2) + +if __name__ == "__main__": + main() + diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/replace_path.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/replace_path.py new file mode 100644 index 0000000000000000000000000000000000000000..c65f79edf93bf4f7f6d1c3e21650c8bee8f775a6 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/batch/replace_path.py @@ -0,0 +1,38 @@ +#!/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 fileinput +import sys + +def replace_paths_in_test_file(test_file_path, path): + """ + 替换test_li_batch.py中的占位符为实际路径 + :param test_file_path: test_li_batch.py的路径 + :param path1: 实际路径 + """ + try: + # 逐行替换占位符 + with fileinput.FileInput(test_file_path, inplace=True, backup='.bak') as f: + for line in f: + # 替换__PATH__为实际路径 + line = line.replace('__PATH__', path) + # 输出替换后的行(inplace=True会自动写回文件) + print(line, end='') + print(f" 已成功替换 {test_file_path} 中的路径") + except Exception as e: + print(f" 替换路径失败:{e}") + sys.exit(1) + +if __name__ == '__main__': + test_file = sys.argv[1] + path = sys.argv[2] + replace_paths_in_test_file(test_file, path) \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/lightning_indexer_acl_graph.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/lightning_indexer_acl_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..11f856ae15417b1dbc5bc771a0637f06b6a8e377 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/lightning_indexer_acl_graph.py @@ -0,0 +1,142 @@ +#!/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 test +import torch +import torch_npu +import pytest +import random +import numpy as np +import math +import ctypes +import copy +import torchair +import torch.nn as nn +from torchair.configs.compiler_config import CompilerConfig +import lightning_indexer_golden + +class LINetwork(nn.Module): + def __init__(self): + super(LINetwork, self).__init__() + + def forward(self, query, key, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table, + layout_query, layout_key, sparse_count, sparse_mode, pre_tokens, next_tokens): + return torch_npu.npu_lightning_indexer(query, key, weights, + actual_seq_lengths_query = actual_seq_lengths_query, + actual_seq_lengths_key = actual_seq_lengths_key, + block_table = block_table, + layout_query = layout_query, + layout_key = layout_key, + sparse_count = sparse_count, + sparse_mode = sparse_mode, + pre_tokens = pre_tokens, + next_tokens = next_tokens) + +def li_output_acl_graph(params): + batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num, \ + qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, layout_key, sparse_count, \ + sparse_mode, query_datarange, key_datarange, weights_datarange = params + import ml_dtypes + + test_li = lightning_indexer_golden.GeneralizedLI(batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num, + qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, layout_key, sparse_count, sparse_mode) + + actual_seq_lengths_query = torch.tensor(np.random.uniform(q_seq, q_seq, batch_size)).to(actual_seq_dtype).npu() \ + if act_seq_q is None else torch.tensor(act_seq_q).to(actual_seq_dtype).npu() + actual_seq_lengths_key = torch.tensor(np.random.uniform(k_seq, k_seq, batch_size)).to(actual_seq_dtype).npu() \ + if act_seq_k is None else torch.tensor(act_seq_k).to(actual_seq_dtype).npu() + + # shape推导 + if layout_query == "BSND": + query_shape = [batch_size, q_seq, q_head_num, head_dim] + weights_shape = [batch_size, q_seq, q_head_num] + elif layout_query == "TND": + query_shape = [q_t_size, q_head_num, head_dim] + weights_shape = [q_t_size, q_head_num] + + if layout_key == "BSND": + key_shape = [batch_size, k_seq, k_head_num, head_dim] + elif layout_key == "TND": + key_shape = [k_t_size, k_head_num, head_dim] + elif layout_key == "PA_BSND": + # 以不同batch中最大seq为标准初始化key(bnsd) + k_max_s2 = math.floor(max(act_seq_k)) + key_shape = [batch_size, k_head_num, k_max_s2, head_dim] + + # 随机数据生成 + query = torch.tensor(np.random.uniform(query_datarange[0], query_datarange[1], query_shape)).to(qk_dtype).npu() + weights = torch.tensor(np.random.uniform(weights_datarange[0], weights_datarange[1], weights_shape)).to(weight_dtype).npu() + key = torch.tensor(np.random.uniform(key_datarange[0], key_datarange[1], key_shape)).to(qk_dtype).npu() + block_table = None + key_cpu = key + + if layout_key == "PA_BSND": + k_max_block_num_per_batch = math.ceil(k_max_s2 / block_size) #遍历batch得到的最大的block num + key_block_num_per_batch = [] + key_block_num_sum = 0 + for cur_act_k in act_seq_k: + cur_cmp_act_k = math.floor(cur_act_k) + cur_key_block_num = math.ceil(cur_cmp_act_k / block_size) + key_block_num_per_batch.append(cur_key_block_num) + key_block_num_sum += cur_key_block_num + if block_num < key_block_num_sum: + raise ValueError(f"key actual block num < needed block num") + # 构建block table + block_id_list = np.arange(block_num) + block_id_list = np.random.permutation(block_id_list).astype(np.int32) + cur_block_id = 0 + block_table = np.full((batch_size, k_max_block_num_per_batch), fill_value = -1, dtype=np.int32) + batch_idx = 0 + for cur_block_id_threshold in key_block_num_per_batch: + for i_block_id in range(cur_block_id_threshold): + block_table[batch_idx][i_block_id] = block_id_list[cur_block_id] + cur_block_id += 1 + batch_idx += 1 + # 构建PA场景的key + key_expand = torch.zeros((batch_size, k_head_num, k_max_block_num_per_batch * block_size, head_dim), dtype = qk_dtype) + key_expand[:,:,:k_max_s2,:] = key_cpu + key = torch.zeros((block_num, block_size, k_head_num, head_dim), dtype = qk_dtype) + for i_batch in range(batch_size): + for i_block, cur_block_id in enumerate(block_table[i_batch]): + block_start_pos = i_block * block_size + if cur_block_id == -1: + continue + else: + for i_n in range(k_head_num): + key[cur_block_id, :, i_n, :] = key_expand[i_batch, i_n, block_start_pos:block_start_pos+block_size,:] + key = key.npu() + block_table = torch.from_numpy(block_table).to(dtype=torch.int32).npu() + + # cpu golden生成 + cpu_result, topk_value = test_li.forward(query, key_cpu, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table) + cpu_result, _ = torch.sort(cpu_result) + + print("acl_graph") + + config = CompilerConfig() + npu_backend = torchair.get_npu_backend(compiler_config=config) + torch._dynamo.reset() + config.mode = "reduce-overhead" + npu_mode = torch.compile(LINetwork().npu(), fullgraph=True, backend=npu_backend, dynamic=False) + npu_result, _ = npu_mode(query, key, weights, + actual_seq_lengths_query = actual_seq_lengths_query, + actual_seq_lengths_key = actual_seq_lengths_key, + block_table = block_table, + layout_query = layout_query, + layout_key = layout_key, + sparse_count = sparse_count, + sparse_mode = sparse_mode, + pre_tokens = (1<<63)-1, + next_tokens = (1<<63)-1) + torch.npu.synchronize() + npu_result, _ = torch.sort(npu_result) + return cpu_result, npu_result, topk_value diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/lightning_indexer_golden.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/lightning_indexer_golden.py new file mode 100644 index 0000000000000000000000000000000000000000..17b6de04ccf3d89844e7f07e5f0c82de3ee7eac2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/lightning_indexer_golden.py @@ -0,0 +1,468 @@ +#!/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 test +import torch +import torch_npu +import pytest +import random +import numpy as np +import math +import ctypes +import copy + +class GeneralizedLI: + def __init__(self, batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num, qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, layout_key, sparse_count, sparse_mode): + self.batch_size = batch_size + self.q_seq = q_seq + self.k_seq = k_seq + self.q_t_size = q_t_size + self.k_t_size = k_t_size + self.q_head_num = q_head_num + self.k_head_num = k_head_num + self.group_size = q_head_num // k_head_num + self.head_dim = head_dim + self.block_size = block_size + self.block_num = block_num + self.qk_dtype = qk_dtype + self.weight_dtype = weight_dtype + self.actual_seq_dtype = actual_seq_dtype + self.act_seq_q = act_seq_q + self.act_seq_k = act_seq_k + self.layout_query = layout_query + self.layout_key = layout_key + self.sparse_count = sparse_count + self.sparse_mode = sparse_mode + + if layout_query == "BSND": + self.out_shape = [batch_size, q_seq, k_head_num, sparse_count] + elif layout_query == "TND": + self.out_shape = [q_t_size, k_head_num, sparse_count] + + def cal_atten_bnsd(self): + batch_size = self.batch_size + qs = self.q_seq + ks = self.k_seq + n1 = self.q_head_num + n2 = self.k_head_num + actualSeqLengths_q = self.actual_seq_lengths_query + actualSeqLengths_k = self.actual_seq_lengths_key + q_bnsd_tensor = self.q_bnsd_tensor + k_bnsd_tensor = self.k_bnsd_tensor + wt_bnsd_tensor = self.wt_bnsd_tensor + mask_tensor = self.m_tensor + out_shape_bnsd = list(q_bnsd_tensor.shape) + out_shape_bnsd[1] = n2 + out_shape_bnsd[-1] = self.sparse_count + + out_shape_bnss = list(q_bnsd_tensor.shape) + out_shape_bnss[1] = n2 + out_shape_bnss[-1] = math.floor(max(actualSeqLengths_k)) + + y = torch.full(out_shape_bnsd,-1,dtype = torch.int32) + y_value = torch.full(out_shape_bnss,-float('inf'), dtype=torch.float32) + + for b_idx in range(batch_size): + curr_actualSeq_q = actualSeqLengths_q[b_idx] + curr_actualSeq_k = math.floor(actualSeqLengths_k[b_idx]) + self.cur_actseq_q = curr_actualSeq_q + self.cur_actseq_k = curr_actualSeq_k + self.cur_q = q_bnsd_tensor[b_idx:(b_idx + 1), :, :curr_actualSeq_q, :] + self.cur_k = k_bnsd_tensor[b_idx:(b_idx + 1), :, :curr_actualSeq_k, :] + self.cur_wt = wt_bnsd_tensor[b_idx:(b_idx + 1), :, :curr_actualSeq_q, :] + if self.sparse_mode != 0: + self.cur_m = mask_tensor[b_idx:(b_idx + 1), :curr_actualSeq_q, :curr_actualSeq_k] + self.cur_b_idx = b_idx + + if curr_actualSeq_q != 0: + actual_selected_count = min(curr_actualSeq_k, self.sparse_count) + y[b_idx:(b_idx + 1), :, :curr_actualSeq_q, :actual_selected_count], y_value[b_idx:(b_idx + 1), + :, :curr_actualSeq_q, :curr_actualSeq_k] = self.cal_atten_per_batch_b16(b_idx) + else: + pass + return y, y_value + + def trans_shape_to_bnsd(self, tensor, layout, headnums=None, act_seq=None, tensor_name=None): + if layout == "BSND": + B = tensor.shape[0] + S = tensor.shape[1] + N = tensor.shape[2] + D = 1 + if len(tensor.shape) == 3: + tensor = torch.unsqueeze(tensor, dim=-1) + else: + D = tensor.shape[3] + tensor = tensor.reshape(B, S, N, D).permute(0, 2, 1, 3) + return tensor + elif layout == "TND": + T = tensor.shape[0] + N = tensor.shape[1] + D = 1 + if len(tensor.shape) == 2: + tensor = torch.unsqueeze(tensor, dim=-1) + else: + D = tensor.shape[2] + B = len(act_seq) + S = max(act_seq) + new_tensor = torch.zeros((B, N, S, D), dtype=tensor.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, :] = tensor[t_start:t_end, n_index, :] + t_start += act_s + return new_tensor + elif layout == "PA_BSND": + if len(tensor.shape) == 3: + tensor = torch.unsqueeze(tensor, dim=-1) + return tensor + else: + return tensor + + def trans_tnd_actseq(self,list): + list_len = len(list) + if list_len == 0: + raise ValueError(f'TND情况下 act_seq需要必传') + 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: + raise ValueError(f'TND情况下 act_seq_len 为非递减数列 act_seq_len={list}') + return list_new + + def cal_atten_per_batch_b16(self,b_idx): + cur_q = self.cur_q.to(dtype=torch.float32) + cur_k = self.cur_k.to(dtype=torch.float32) + cur_wt = self.cur_wt.to(dtype=torch.float32) + + sparse_count = self.sparse_count + sparse_mode = self.sparse_mode + + qk_bmm_res = torch.bmm( + cur_q.squeeze(0), + cur_k.permute(0, 1, 3, 2).squeeze(0) + ).unsqueeze(0) + + qk_relu_out = (qk_bmm_res.to(dtype=torch.float32)).clamp_min(0.0) + + brc_vmul = torch.bmm( + cur_wt.permute(0, 2, 3, 1).to(dtype=torch.float32).squeeze(0), + qk_relu_out.permute(0, 2, 1, 3).to(dtype=torch.float32).squeeze(0) + ).unsqueeze(0) + + temp_b, temp_s1, temp_n1, temp_s2 = brc_vmul.shape + temp_g = self.group_size + temp_n2 = self.k_head_num + temp_b_idx = self.cur_b_idx + actual_selected_count = min(temp_s2, sparse_count) + reduce_sum = brc_vmul.reshape(temp_b, temp_n2, temp_s1, temp_s2) + + if sparse_mode == 3: + cur_m = self.cur_m + cur_m_broadcasted = cur_m.reshape(1, 1, temp_s1, temp_s2) + cur_m_broadcasted = torch.broadcast_to(cur_m_broadcasted, (1, temp_n2, temp_s1, temp_s2)) + # 根据布尔矩阵置-inf + reduce_sum[cur_m_broadcasted.to(dtype = torch.bool)] = -torch.inf + to_be_sort_ele = reduce_sum.clone() + to_be_sort_ele = to_be_sort_ele.to(torch.bfloat16) + # 稳定排序 + b_sorted_indices = torch.full(to_be_sort_ele.shape, -1, dtype=torch.int32) + if sparse_mode == 3: + for i in range(temp_s1): + row_mask = cur_m_broadcasted[0, 0, i, :].to(dtype = torch.bool) + true_indices = torch.where(~row_mask)[0] + row_ele = to_be_sort_ele[0, 0, i, true_indices] + indices = torch.arange(len(row_ele), device = row_ele.device) + + sorted_vals, sorted_idx = torch.sort( + torch.stack([-row_ele, indices],dim=1), + dim=0, + stable=True + ) + b_sorted_indices[0, 0, i, true_indices] = true_indices[sorted_idx[:, 0]].to(torch.int32) + else: + for i in range(temp_s1): + row_ele = to_be_sort_ele[0, 0, i, :] + indices = torch.arange(len(row_ele),device = row_ele.device) + sorted_vals, sorted_idx = torch.sort( + torch.stack([-row_ele, indices],dim=1), + dim=0, + stable=True + ) + b_sorted_indices[0, 0, i, :] = sorted_idx[:,0] + topk_indices = b_sorted_indices[..., :actual_selected_count] + return topk_indices, to_be_sort_ele + + def trans_bnsd_to_layout(self,tensor, shape, layout, act_q=None): + # 此时的输出D轴是K轴 + if layout == "BSH": + output = tensor.permute(0, 2, 1, 3).contiguous().view(shape) + return output + elif layout == "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.full(size=(T, N, D), fill_value=-1, 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 broadcast_n_axis(self, n1, n2, temp_tensor): + g = n1 // n2 + temp_shape = temp_tensor.shape + B = temp_shape[0] + S = temp_shape[2] + D = temp_shape[3] + modify_tensor = torch.zeros([B, n1, S, D], dtype=temp_tensor.dtype) + for i in range(n1): + j = i // g + modify_tensor[:, i:i + 1, :, :] = temp_tensor[:, j:j + 1, :, :] + return modify_tensor + + def create_mask(self, m_shape, act_k, S1): + atten_masks = torch.zeros(tuple(m_shape), dtype=torch.uint8) + tmp_pos_orig = act_k - S1 + + for i in range(S1): + if((tmp_pos_orig+i+1) < 0): + atten_masks[i,:] = 1 + else: + atten_masks[i, math.floor(tmp_pos_orig+i+1):] = 1 + return atten_masks + + def create_mask_right_down(self, m_shape, actualSeqLengthsQ, actualSeqLengthsK, batch): + mask_s_q = m_shape[0] + mask_s_kv = m_shape[1] + next_tokens_list = [] + re_mask_batch = [] + pre_tokens = 214748647 + for i in range(batch): + if len(actualSeqLengthsQ) == 0: + S1 = mask_s_q + else: + S1 = actualSeqLengthsQ[i] + + if len(actualSeqLengthsK) == 0: + S2 = mask_s_kv + else: + S2 = math.floor(actualSeqLengthsK[i]) + next_tokens = S2-S1 + next_tokens_list.append(next_tokens) + act_k = actualSeqLengthsK[i] + atten_masks = self.create_mask(m_shape, act_k, S1) + re_mask_batch.append(atten_masks) + re_mask_np = torch.stack(re_mask_batch, dim=0).numpy().astype(np.bool_) + cpu_mask = torch.from_numpy(re_mask_np) + return cpu_mask, next_tokens_list + + def forward(self, query, key, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table): + print("cpu执行中...") + + # 参数的初始化 + batch_size = self.batch_size + q_seq = self.q_seq + k_seq = self.k_seq + layout_query = self.layout_query + layout_key = self.layout_key + sparse_count = self.sparse_count + sparse_mode = self.sparse_mode + out_shape = self.out_shape + head_dim = self.head_dim + q_head_num = self.q_head_num + k_head_num = self.k_head_num + q_t_size = self.q_t_size + k_t_size = self.k_t_size + block_size = self.block_size + block_num = self.block_num + q_dtype = self.qk_dtype + weight_dtype = self.weight_dtype + k_dtype = self.qk_dtype + actual_seq_dtype = self.actual_seq_dtype + + if layout_query == "TND": + actual_seq_lengths_query = self.trans_tnd_actseq(actual_seq_lengths_query) + self.actual_seq_lengths_query = torch.tensor(actual_seq_lengths_query) + actualSeqLengths_q = self.actual_seq_lengths_query + + elif layout_query == "BSND": + self.actual_seq_lengths_query = actual_seq_lengths_query + actualSeqLengths_q = self.actual_seq_lengths_query + + if layout_key == "TND": + actual_seq_lengths_key = self.trans_tnd_actseq(actual_seq_lengths_key) + self.actual_seq_lengths_key = torch.tensor(actual_seq_lengths_key) + actualSeqLengths_k = self.actual_seq_lengths_key + + elif layout_key == "BSND": + self.actual_seq_lengths_key = actual_seq_lengths_key + actualSeqLengths_k = self.actual_seq_lengths_key + + elif layout_key == "PA_BSND": + self.actual_seq_lengths_key = actual_seq_lengths_key + actualSeqLengths_k = self.actual_seq_lengths_key + k_max_s2 = math.floor(max(actualSeqLengths_k)) + query = query.cpu() + key = key.cpu() + weights = weights.cpu() + + # 将输入转化为BNSD + ## BSND / TND -> BNSD + q_bnsd_tensor = self.trans_shape_to_bnsd(query, + layout_query, q_head_num, actualSeqLengths_q) + + ## BSND/TND/ -> BNSD + k_bnsd_tensor = self.trans_shape_to_bnsd(key, + layout_key, k_head_num, torch.floor(actualSeqLengths_k).to(actual_seq_dtype)) + + ## BSN1 -> BNS1 TN1 -> BNS1 + wt_bnsd_tensor = self.trans_shape_to_bnsd(weights, + layout_query, q_head_num, actualSeqLengths_q) + + # 将 k n2轴 广播为 n1 + if q_head_num != k_head_num: + k_bnsd_tensor = self.broadcast_n_axis(q_head_num, k_head_num, k_bnsd_tensor) + self.q_bnsd_tensor = q_bnsd_tensor + self.k_bnsd_tensor = k_bnsd_tensor + self.wt_bnsd_tensor = wt_bnsd_tensor + # 生成mask, sparse_mode=3时使能 + m_shape_std = [q_bnsd_tensor.shape[2], k_bnsd_tensor.shape[2]] #m_shape应该是[s1,s2] + batch = q_bnsd_tensor.shape[0] + m_tensor = [] + if sparse_mode == 3: + m_tensor, next_tokens_list = self.create_mask_right_down(m_shape_std, actualSeqLengths_q, actualSeqLengths_k, batch) + elif sparse_mode == 0: + pass + else: + raise ValueError("unsupported sparse_mode!") + self.m_tensor = m_tensor + y, y_value = self.cal_atten_bnsd() + # TND & PA 需要传入out_shape为BNSD + out_shape_bnsd = list(q_bnsd_tensor.shape) + out_shape_bnsd[1] = k_head_num + out_shape_bnsd[-1] = sparse_count + y = self.trans_bnsd_to_layout(y, out_shape_bnsd, layout_query, actualSeqLengths_q) + return y, y_value + +def li_output_single(params): + batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num, \ + qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, layout_key, sparse_count, \ + sparse_mode, query_datarange, key_datarange, weights_datarange, return_value = params + import ml_dtypes + + test_li = GeneralizedLI(batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num, + qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query, layout_key, sparse_count, sparse_mode) + + actual_seq_lengths_query = torch.tensor(np.random.uniform(q_seq, q_seq, batch_size)).to(actual_seq_dtype).npu() \ + if act_seq_q is None else torch.tensor(act_seq_q).to(actual_seq_dtype).npu() + actual_seq_lengths_key = torch.tensor(np.random.uniform(k_seq, k_seq, batch_size)).to(actual_seq_dtype).npu() \ + if act_seq_k is None else torch.tensor(act_seq_k).to(actual_seq_dtype).npu() + + # shape推导 + if layout_query == "BSND": + query_shape = [batch_size, q_seq, q_head_num, head_dim] + weights_shape = [batch_size, q_seq, q_head_num] + elif layout_query == "TND": + query_shape = [q_t_size, q_head_num, head_dim] + weights_shape = [q_t_size, q_head_num] + + if layout_key == "BSND": + key_shape = [batch_size, k_seq, k_head_num, head_dim] + elif layout_key == "TND": + key_shape = [k_t_size, k_head_num, head_dim] + elif layout_key == "PA_BSND": + # 以不同batch中最大seq为标准初始化key(bnsd) + k_max_s2 = math.floor(max(act_seq_k)) + key_shape = [batch_size, k_head_num, k_max_s2, head_dim] + + # 随机数据生成 + query = torch.tensor(np.random.uniform(query_datarange[0], query_datarange[1], query_shape)).to(qk_dtype).npu() + weights = torch.tensor(np.random.uniform(weights_datarange[0], weights_datarange[1], weights_shape)).to(weight_dtype).npu() + key = torch.tensor(np.random.uniform(key_datarange[0], key_datarange[1], key_shape)).to(qk_dtype).npu() + block_table = None + key_cpu = key + + if layout_key == "PA_BSND": + k_max_block_num_per_batch = math.ceil(k_max_s2 / block_size) #遍历batch得到的最大的block num + key_block_num_per_batch = [] + key_block_num_sum = 0 + for cur_act_k in act_seq_k: + cur_cmp_act_k = math.floor(cur_act_k) + cur_key_block_num = math.ceil(cur_cmp_act_k / block_size) + key_block_num_per_batch.append(cur_key_block_num) + key_block_num_sum += cur_key_block_num + if block_num < key_block_num_sum: + raise ValueError(f"key actual block num < needed block num") + # 构建block table + block_id_list = np.arange(block_num) + block_id_list = np.random.permutation(block_id_list).astype(np.int32) + cur_block_id = 0 + block_table = np.full((batch_size, k_max_block_num_per_batch), fill_value = -1, dtype=np.int32) + batch_idx = 0 + for cur_block_id_threshold in key_block_num_per_batch: + for i_block_id in range(cur_block_id_threshold): + block_table[batch_idx][i_block_id] = block_id_list[cur_block_id] + cur_block_id += 1 + batch_idx += 1 + # 构建PA场景的key + key_expand = torch.zeros((batch_size, k_head_num, k_max_block_num_per_batch * block_size, head_dim), dtype = qk_dtype) + key_expand[:,:,:k_max_s2,:] = key_cpu + key = torch.zeros((block_num, block_size, k_head_num, head_dim), dtype = qk_dtype) + for i_batch in range(batch_size): + for i_block, cur_block_id in enumerate(block_table[i_batch]): + block_start_pos = i_block * block_size + if cur_block_id == -1: + continue + else: + for i_n in range(k_head_num): + key[cur_block_id, :, i_n, :] = key_expand[i_batch, i_n, block_start_pos:block_start_pos+block_size,:] + key = key.npu() + block_table = torch.from_numpy(block_table).to(dtype=torch.int32).npu() + + # cpu golden生成 + cpu_result, topk_value = test_li.forward(query, key_cpu, weights, actual_seq_lengths_query, actual_seq_lengths_key, block_table) + cpu_result, _ = torch.sort(cpu_result) + + npu_result, sparse_value = torch_npu.npu_lightning_indexer(query, key, weights, + actual_seq_lengths_query = actual_seq_lengths_query, + actual_seq_lengths_key = actual_seq_lengths_key, + block_table = block_table, + layout_query = layout_query, + layout_key = layout_key, + sparse_count = sparse_count, + sparse_mode = sparse_mode) + torch.npu.synchronize() + npu_result, _ = torch.sort(npu_result) + return cpu_result, npu_result, topk_value, sparse_value diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/pytest.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..4b80d76c8ccca6f85933a5742916a3c485509dbb --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/pytest.ini @@ -0,0 +1,4 @@ +[pytest] +markers = + ci: mark a test as a CI test + graph: marks tests as graph mode compilation tests \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/result_compare_method.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/result_compare_method.py new file mode 100644 index 0000000000000000000000000000000000000000..5c9787f6a5ecf992d7e9be57f3de32564e220214 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/result_compare_method.py @@ -0,0 +1,443 @@ +#!/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 +from time import time +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 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( + '---------------------------------------------------------------------------------------') +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 find_batch_and_position(act_q, x): + """ + 判断x属于哪个batch以及在该batch中的位置 + + 参数: + act_q: 前缀和列表,act_q[b_idx]表示前(b_idx+1)个batch的总长度 + x: 需要判断的数值 + + 返回: + tuple: (batch_idx, position) + - batch_idx: 所属的batch索引(从0开始),超出范围则为-1 + - position: 在该batch中的位置(从0开始),超出范围则为-1 + """ + if not act_q: + return (-1, -1) + # 遍历前缀和列表查找所属批次 + for batch_idx in range(len(act_q)): + # 计算当前批次的起始位置 + start = act_q[batch_idx - 1] if batch_idx > 0 else 0 + # 判断是否在当前批次范围内 + if start <= x < act_q[batch_idx]: + # 计算在当前批次中的位置(偏移量) + position = x - start + return (batch_idx, position) + # 超出所有批次范围 + return (-1, -1) + +def judge_value_by_isclose(real_data, data_compe): + atol = 2.5e-05 + rtol = 0.005 + pct_thd = 0.005 + diff_thd = 0.005 + start = 0 + end = real_data.size - 1 + if end < start: + end = start + split_count = int(end - start + 1) if end != start else 1 + + if str(real_data.dtype) == 'bfloat16': + atol = 0.0001 + diff_result = np.isclose(real_data.astype(np.float32), data_compe.astype(np.float32), 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] + 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 + pct_thd = (1 - pct_thd) * 100.0 + result = True if (fulfill_percent >= pct_thd) else False + return result + +def compare_topk_valid(cur_npu, cur_cpu, topk_value, bsn, diff_npu, diff_cpu, + cur_npu_output_value=None, cur_cpu_output_value=None, thres=0.0001, return_value_flag=False): + b_idx, s1_idx, n2_idx = bsn + max_re = 0.0 + npu_pass = True + npu_set = set(cur_npu) + cpu_set = set(cur_cpu) + + is_equivalent = npu_set == cpu_set + if is_equivalent: + pass + else: + value_bm = topk_value[b_idx, n2_idx, s1_idx, cur_cpu[-1]] + element_list = topk_value[b_idx, n2_idx, s1_idx, :] + only_in_npu = npu_set - cpu_set + only_in_cpu = cpu_set - npu_set + only_in_npu_list = list(only_in_npu) + only_in_cpu_list = list(only_in_cpu) + for diff_idx in range(len(only_in_npu_list)): + element_npu = element_list[only_in_npu_list[diff_idx]] + element_cpu = element_list[only_in_cpu_list[diff_idx]] + npu_ae = abs(element_npu - value_bm) + cpu_ae = abs(element_cpu - value_bm) + if value_bm == 0: + if npu_ae == 0: + npu_re = 0.0 + else: + npu_re = float("inf") + if cpu_ae == 0: + cpu_re = 0.0 + else: + cpu_re = float("inf") + else: + npu_re = abs(npu_ae / value_bm) + cpu_re = abs(cpu_ae / value_bm) + if npu_re > thres or cpu_re > thres: + if return_value_flag: + if not judge_value_by_isclose(cur_npu_output_value, cur_cpu_output_value): + npu_pass = False + diff_npu.append(element_npu) + diff_cpu.append(element_cpu) + max_re = max(max_re, npu_re, cpu_re) + else: + npu_pass = False + diff_npu.append(element_npu) + diff_cpu.append(element_cpu) + max_re = max(max_re, npu_re) + return npu_pass, max_re + +def trans_tnd_actseq(list): + list_len = len(list) + if list_len == 0: + raise ValueError(f'TND情况下 act_seq需要必传') + 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: + raise ValueError(f'TND情况下 act_seq_len 为非递减数列 act_seq_len={list}') + return list_new + +def check_result(expect, result, topk_value, sparse_value, params): + batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num,\ + qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query,\ + layout_key, sparse_count, sparse_mode, query_datarange, key_datarange, weights_datarange,\ + return_value = params + # 处理B+1 + if isinstance(act_seq_q, int): + act_seq_q = [act_seq_q] + elif isinstance(act_seq_q, list): + act_seq_q = act_seq_q + else: + act_seq_q = [int(x.strip()) for x in act_seq_q.split(',')] + if isinstance(act_seq_k, int): + act_seq_k = [act_seq_k] + elif isinstance(act_seq_k, list): + act_seq_k = act_seq_k + else: + act_seq_k = [int(x.strip()) for x in act_seq_k.split(',')] + + if layout_query == 'TND': + if len(act_seq_q) == batch_size + 1: + act_seq_q = act_seq_q[1:] + if layout_key == 'TND': + if len(act_seq_k) == batch_size + 1: + act_seq_k = act_seq_k[1:] + + npu_pass = True + max_error = 0 + max_re = 0 + thres = 0.0001 + diff_thd=0.01 + pct_thd=0.05 + max_diff_hd=0.1 + rtol=0.005 + atol=0.000025 + max_error_idx = 10000000 + return_value_flag = True + cpu_output = expect.cpu().numpy() + npu_output = result.cpu().numpy() + real_data = result.cpu().numpy() + data_compe = expect.cpu().numpy() + real_data = npu_output.flatten() + data_compe = cpu_output.flatten() + diff_cpu = [] + diff_npu = [] + + if layout_query in ["BSND"]: + sp = (batch_size, q_seq, k_head_num) + total_rows = batch_size * q_seq * k_head_num + elif layout_query in ["TND"]: + sp = (q_t_size, k_head_num) + total_rows = q_t_size * k_head_num + else: + total_rows = 0 + sp = (0, 0) + print(f"total_line is {total_rows}") + npu_reshape = npu_output.reshape([total_rows, sparse_count]) + cpu_reshape = cpu_output.reshape([total_rows, sparse_count]) + start_time = time() + invalid_data = cpu_reshape != -1 + valid_lens = invalid_data.sum(axis=-1) # (total_rows,) + # 判断有效值部分集合是否相同 + cpu_output_sorted = np.sort(cpu_reshape, axis=1) + npu_output_sorted = np.sort(npu_reshape, axis=1) + diff_rows = np.zeros(total_rows, dtype=bool) + diff_rows |= np.any(cpu_output_sorted != npu_output_sorted, axis=1) #标记存在差异的行 + test_id = [] + rows = [] + if np.any(diff_rows): + rows = np.where(diff_rows)[0] + num_rows = len(rows) + if num_rows: + print(f"需要进行第二步比较的batch有{num_rows}") + else: + print(f"有效值集合相同,无需进行比较") + for t_id in rows: + bsn = np.unravel_index(t_id, sp) + if layout_query == "TND": + b_idx, s1_idx = find_batch_and_position(act_seq_q, bsn[0]) + bsn = (b_idx, s1_idx, bsn[-1]) + cur_cpu_output_value = cpu_reshape[t_id, :] + cur_npu_output_value = npu_reshape[t_id, :] + npu_pass_t = True + max_re_t = 0 + valid_len = valid_lens[t_id] + npu_pass_t, max_re_t = compare_topk_valid(npu_reshape[t_id, :valid_len], cpu_reshape[t_id, :valid_len], + topk_value, bsn, diff_npu, diff_cpu, + cur_npu_output_value, + cur_cpu_output_value, thres, + return_value_flag) + if not npu_pass_t: + npu_pass = False + end_time = time() + print(f"耗时:{end_time - start_time:.6f} 秒") + topk_precision = not diff_npu and not diff_cpu + if topk_precision: + print(f'[success]TopK精度通过, idx不同的地方的value误差在阈值之内') + else: + print(f'[fail]TopK精度失败') + print(f"npu_pass is {npu_pass}") + 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 + 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] + 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] + 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)) + 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 (npu_pass or topk_precision) else "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]) + + if return_value : + print_log('=================== Value Compare (topk_value vs sparse_value) ===================') + # topk_value: BNSD [B, N2, S1, max(S2)], float32 — golden的完整注意力分数 + # sparse_value: 输出layout (BSND/TND), qk_dtype — NPU输出的top-k值,已降序排列 + # Step 1: 对topk_value降序排序并取前sparse_count个值 + topk_sorted, _ = topk_value.sort(dim=-1, descending=True) + # 当max(act_seq_k) < sparse_count时,topk_value最后一维不足,需要用-inf填充 + if topk_sorted.shape[-1] < sparse_count: + pad_size = sparse_count - topk_sorted.shape[-1] + pad_tensor = torch.full((*topk_sorted.shape[:-1], pad_size), -float('inf'), dtype=topk_sorted.dtype) + topk_sorted = torch.cat([topk_sorted, pad_tensor], dim=-1) + topk_selected = topk_sorted[..., :sparse_count] # [B, N2, S1, sparse_count] + # Step 2: 将BNSD转换为输出layout,与sparse_value对齐 + if layout_query == "BSND": + topk_selected = topk_selected.permute(0, 2, 1, 3) # [B, S1, N2, sparse_count] + elif layout_query == "TND": + topk_selected = topk_selected.permute(0, 2, 1, 3) # [B, S1, N2, sparse_count] + tnd_list = [] + for b_idx in range(batch_size): + seq_len = int(act_seq_q[b_idx]) - (int(act_seq_q[b_idx - 1]) if b_idx > 0 else 0) + tnd_list.append(topk_selected[b_idx, :seq_len, :, :]) + topk_selected = torch.cat(tnd_list, dim=0) # [T, N2, sparse_count] + # Step 3: 转换为float numpy进行精度比较 + if qk_dtype == torch.bfloat16: + topk_val_np = topk_selected.cpu().to(torch.bfloat16).float().numpy().flatten() + elif qk_dtype == torch.float16: + topk_val_np = topk_selected.cpu().to(torch.float16).float().numpy().flatten() + else: + topk_val_np = topk_selected.cpu().float().numpy().flatten() + sparse_val_np = sparse_value.cpu().float().numpy().flatten() + val_start = 0 + val_end = topk_val_np.size - 1 + if val_end < val_start: + val_end = val_start + val_split_count = int(val_end - val_start + 1) if val_end != val_start else 1 + + val_diff_result = np.isclose(topk_val_np, sparse_val_np, rtol=rtol, atol=atol, equal_nan=True) + val_err_idx = np.where(val_diff_result != np.array((True,)))[0] + val_diff_abs = abs(sparse_val_np - topk_val_np) + val_b1 = np.maximum(np.abs(topk_val_np), np.abs(sparse_val_np)) + val_b2 = float((1.0 / (1 << 14)) / diff_thd) + val_b = np.add(np.maximum(val_b1, val_b2), 10e-10) + val_err_diff = val_diff_abs / (val_b + eps) + val_err_diff = val_err_diff[val_err_idx] + + val_fulfill_percent = float(val_split_count - val_err_idx.size) / float(val_split_count) * 100.0 + display_output_np_isclose(topk_val_np, sparse_val_np, val_start, val_end) + val_result = "Pass" if (val_fulfill_percent >= pct_thd) else "Failed" + if len(val_err_diff) > 0: + val_max_error = max(val_err_diff[0:max_error_idx]) + if val_max_error >= max_diff_hd: + val_result = "Failed" + else: + val_max_error = 0 + + print_log('---------------------------------------------------------------------------------------') + print_log('Value Compare: 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, val_fulfill_percent, val_result)) + if len(val_err_diff) > 0: + print_log('Value Max-RelativeError is: %s. Threshold is: %s.' % + (val_max_error, max_diff_hd)) + if val_result == "Failed": + display_error_output(topk_val_np, sparse_val_np, + val_err_idx, val_err_diff[0:max_error_idx]) + result = "Failed" + return result, fulfill_percent \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_batch.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..add724186341fedbf9b3024e10bf8eb957721246 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_batch.py @@ -0,0 +1,119 @@ +#!/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 itertools +import torch +import result_compare_method +from batch import lightning_indexer_pt_loadprocess +import pytest +import random +import pandas as pd +from pathlib import Path +import numpy as np +import math +import os +import multiprocessing as mp +from concurrent.futures import ProcessPoolExecutor, as_completed + +TEST_INPUT_PATH = "__PATH__" +pt_dir = TEST_INPUT_PATH +result_path = Path('result.xlsx') # 或使用传入的result_path + +# 生成所有的组合,并转换为字典列表 +locals()["testcase_files"] = [] +if os.path.isdir(pt_dir): + pt_files = [f for f in os.listdir(pt_dir) if f.endswith('.pt')] + if not pt_files: + print(f"错误: 目录中没有找到.pt文件: {pt_dir}") + else: + print(f"找到 {len(pt_files)} 个测试用例文件") + for pt_file in pt_files: + filepath = os.path.join(pt_dir, pt_file) + locals()["testcase_files"].append(filepath) +else: + print(f"错误: 输出目录不存在: {pt_dir}") + +def li(testcase_files): # 初始化参数和tensor + cpu_result, npu_result, topk_value, sparse_value, params = lightning_indexer_pt_loadprocess.test_li_process(testcase_files, device_id=0) + if npu_result is not None: + result, fulfill_percent = result_compare_method.check_result(cpu_result, npu_result, topk_value, sparse_value, params) + else: + result = "Failed" + fulfill_percent = 0 + + if result != "Pass": + pytest.fail(f"用例执行失败") + + row_data = { + "Testcase_Name": Path(testcase_files).stem, + "batch_size": params[0], + "q_seq": params[1], + "k_seq": params[2], + "q_t_size": params[3], + "k_t_size": params[4], + "q_head_num": params[5], + "k_head_num": params[6], + "head_dim": params[7], + "block_size": params[8], + "block_num": params[9], + "qk_dtype": params[10], + "weight_dtype": params[11], + "actual_seq_dtype": params[12], + "act_seq_q": params[13], + "act_seq_k": params[14], + "layout_query": params[15], + "layout_key": params[16], + "sparse_count":params[17], + "sparse_mode":params[18], + "query_datarange":params[19], + "key_datarange":params[20], + "weights_datarange":params[21], + "result":result, + "fulfill_percent":fulfill_percent + } + + # 检查文件是否存在 + if result_path.exists(): + # 读取现有数据 + df = pd.read_excel(result_path) + + # 检查列名是否一致 + if set(df.columns) != set(row_data.keys()): + print("警告:变量名与Excel列名不匹配!") + print(f"Excel列名: {list(df.columns)}") + print(f"变量名: {list(row_data.keys())}") + print("请检查变量名或Excel文件") + return False + + # 追加新行 + new_df = pd.DataFrame([row_data]) + df = pd.concat([df, new_df], ignore_index=True) + else: + # 文件不存在,创建新的DataFrame + df = pd.DataFrame([row_data]) + + # 保存到Excel + df.to_excel(result_path, index=False) + +@pytest.mark.ci +@pytest.mark.parametrize("testcase_files", locals()["testcase_files"]) +def test_li(testcase_files): # 初始化参数和tensor + with ProcessPoolExecutor(max_workers=1) as executor: + # 创建当前用例子进程 + future1 = executor.submit(li, testcase_files) + # 检查退出码 + for future in as_completed([future1]): + try: + result = future.result() + except Exception as e: + pytest.fail(f"❌ 当前用例子进程执行失败:{e}") + diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_paramset.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_paramset.py new file mode 100644 index 0000000000000000000000000000000000000000..16b78a1c35caf9e0377847250c85dcb82146e593 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_paramset.py @@ -0,0 +1,59 @@ +#!/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 + +# 定义测试参数组合 +TEST_PARAMS = { + "li_default_a2":{ # 1 + "batch_size": [18], + "q_seq": [3], + "k_seq": [3072], + "q_t_size":[1], + "k_t_size":[1],#压缩后的值 + "q_head_num": [16], + "k_head_num": [1], + "head_dim": [128], + "block_size": [128], # 取16的整数倍,最多支持到1024 + "block_num":[469], + "qk_dtype": [torch.bfloat16], + "weight_dtype":[torch.bfloat16], + "actual_seq_dtype": [torch.int32], + "act_seq_q": [[3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3]], + "act_seq_k": [[3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3016,3072]], #PA场景非前缀和,表示每个batch_size的实际token数 + "layout_query": ["BSND"], + "layout_key":["PA_BSND"], + "sparse_count": [2048], + "sparse_mode": [3], + "query_datarange":[[-1,1]], + "key_datarange":[[-1,1]], + "weights_datarange":[[-130,130]] + }, + "li_default_a3": {}, + "li_default_a5": {}, +} + +# 按需选择要启用的测试参数(例如默认启用所有) +properties = torch.npu.get_device_properties() +# 定义设备映射 +device_configs = { + "Ascend910_93": "li_default_a3", + "Ascend950": "li_default_a5", + "Ascend910B": "li_default_a2" +} +# 选择配置 key +config_key = device_configs.get(properties.name) +if config_key: + ENABLED_PARAMS = [TEST_PARAMS[config_key]] +else: + print(f"未知设备: {properties.name}, 使用默认配置(li_default_a2)") + ENABLED_PARAMS = [TEST_PARAMS["li_default_a2"]] diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_single.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_single.py new file mode 100644 index 0000000000000000000000000000000000000000..305769055738d5d8fbe2fc12f54d72f6443a8c36 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_lightning_indexer_single.py @@ -0,0 +1,102 @@ +#!/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 itertools +import torch +import torch_npu +from test_lightning_indexer_paramset import ENABLED_PARAMS +import result_compare_method +import lightning_indexer_golden +import lightning_indexer_acl_graph +import pytest + +for _, params in enumerate(ENABLED_PARAMS): + # 将params的所有字段注册为局部变量 + for key, value in params.items(): + locals()[f"param_{key}"] = value + param_names = [ + "batch_size", "q_seq", "k_seq", "q_t_size", "k_t_size", "q_head_num", "k_head_num","head_dim", + "block_size", "block_num", "qk_dtype", "weight_dtype", "actual_seq_dtype", "act_seq_q","act_seq_k", + "layout_query","layout_key", "sparse_count", "sparse_mode", + "query_datarange","key_datarange","weights_datarange" + ] + param_values = [ + locals()["param_batch_size"], + locals()["param_q_seq"], + locals()["param_k_seq"], + locals()["param_q_t_size"], + locals()["param_k_t_size"], + locals()["param_q_head_num"], + locals()["param_k_head_num"], + locals()["param_head_dim"], + locals()["param_block_size"], + locals()["param_block_num"], + locals()["param_qk_dtype"], + locals()["param_weight_dtype"], + locals()["param_actual_seq_dtype"], + locals()["param_act_seq_q"], + locals()["param_act_seq_k"], + locals()["param_layout_query"], + locals()["param_layout_key"], + locals()["param_sparse_count"], + locals()["param_sparse_mode"], + locals()["param_query_datarange"], + locals()["param_key_datarange"], + locals()["param_weights_datarange"] + ] + + #生成所有的组合,并转换为字典列表 + locals()["param_combinations"] = [] + for combo in itertools.product(*param_values): + param_dict = dict(zip(param_names, combo)) + locals()["param_combinations"].append(param_dict) + + @pytest.mark.ci + @pytest.mark.parametrize("param_combinations", locals()["param_combinations"]) + def test_li(param_combinations): # 初始化参数和tensor + batch_size = param_combinations['batch_size'] + q_seq = param_combinations['q_seq'] + k_seq = param_combinations['k_seq'] + q_t_size = param_combinations['q_t_size'] + k_t_size = param_combinations['k_t_size'] + q_head_num = param_combinations['q_head_num'] + k_head_num = param_combinations['k_head_num'] + head_dim = param_combinations['head_dim'] + block_size = param_combinations['block_size'] + block_num = param_combinations['block_num'] + qk_dtype= param_combinations['qk_dtype'] + weight_dtype= param_combinations['weight_dtype'] + actual_seq_dtype = param_combinations['actual_seq_dtype'] + act_seq_q = param_combinations['act_seq_q'] + act_seq_k = param_combinations['act_seq_k'] + layout_query = param_combinations['layout_query'] + layout_key = param_combinations['layout_key'] + sparse_count = param_combinations['sparse_count'] + sparse_mode = param_combinations['sparse_mode'] + query_datarange = param_combinations['query_datarange'] + key_datarange = param_combinations['key_datarange'] + weights_datarange = param_combinations['weights_datarange'] + torch_npu.npu.set_device(0) + test_data = batch_size, q_seq, k_seq, q_t_size, k_t_size, q_head_num, k_head_num, head_dim, block_size, block_num,\ + qk_dtype, weight_dtype, actual_seq_dtype, act_seq_q, act_seq_k, layout_query,\ + layout_key, sparse_count, sparse_mode, query_datarange, key_datarange, weights_datarange, None + + # 获得cpu结果(真值)和算子结果(测试值) + cpu_result, npu_result, topk_value, sparse_value = lightning_indexer_golden.li_output_single(test_data) + # acl_graph + # cpu_result, npu_result, topk_value = lightning_indexer_acl_graph.li_output_acl_graph(test_data) + # 结果精度对比 + result, fulfill_percent = result_compare_method.check_result(cpu_result, npu_result, topk_value, sparse_value, test_data) + print("result", result) + print("result", fulfill_percent) + if result != "Pass": + pytest.fail(f"用例执行失败") \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_run.sh b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_run.sh new file mode 100644 index 0000000000000000000000000000000000000000..b8098796b36d54744fbcf9b63239e901cba3695e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/pytest/test_run.sh @@ -0,0 +1,100 @@ +#!/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 + +# ====================== 配置区====================== +# 需要读取的用例excel表格路径,如下: +PATH1="./excel/*" +# 用例pt的文件存放路径,如下: +PATH2="./pt_path" + +# 脚本路径 +LI_PT_SAVE_SCRIPT="./batch/lightning_indexer_pt_save.py" +TEST_LI_BATCH_SCRIPT="test_lightning_indexer_batch.py" +REPLACE_PATH_SCRIPT="./batch/replace_path.py" +TEST_LI_SINGLE_SCRIPT="test_lightning_indexer_single.py" + +# ====================== 执行区====================== + +# 单用例算子调测 +run_single() { + echo "===== 执行单用例算子调测 =====" + python3 -m pytest -rA -s $TEST_LI_SINGLE_SCRIPT -v -m ci -W ignore::UserWarning -W ignore::DeprecationWarning +} + +# 用例批量生成调试 +run_batch() { + echo "===== 执行用例批量生成测试 =====" + + echo -e "\n===== 第一步:执行lightning_indexer_pt_save.py =====" + python3 $LI_PT_SAVE_SCRIPT $PATH1 $PATH2 + if [ $? -ne 0 ]; then + echo "lightning_indexer_pt_save.py 执行失败,退出" + exit 1 + fi + + echo -e "\n===== 第二步:替换test_lightning_indexer_batch.py中的路径 =====" + python3 $REPLACE_PATH_SCRIPT $TEST_LI_BATCH_SCRIPT $PATH2 + if [ $? -ne 0 ]; then + echo "替换路径失败,退出" + exit 1 + fi + + echo -e "\n===== 第三步:执行pytest命令 =====" + python3 -m pytest -rA -s $TEST_LI_BATCH_SCRIPT -v -m ci + if [ $? -ne 0 ]; then + echo "pytest执行失败" + exit 1 + fi + + cp test_lightning_indexer_batch.py.bak test_lightning_indexer_batch.py + + echo -e "\n=====执行完成!=====" +} + +# 显示帮助信息 +show_help() { + echo "用法: $0 [参数]" + echo "参数说明:" + echo " single 执行单算子用例调测" + echo " batch 执行用例批量生成调试" + echo " help 显示本帮助信息" + echo "示例:" + echo " $0 single # 执行single模式" + echo " $0 batch # 执行batch模式" +} + +# ====================== 主逻辑 ====================== +# 检查传入的参数数量 +if [ $# -ne 1 ]; then + echo "错误:必须传入且仅传入一个参数(single/batch/help)" + show_help + exit 1 +fi + +# 根据参数执行对应函数 +case "$1" in + single) + run_single + ;; + batch) + run_batch + ;; + help) + show_help + ;; + *) + echo "错误:未知参数 '$1',仅支持 single/batch/help" + show_help + exit 1 + ;; +esac diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..dec9194060f736294e21476ce3ee8ba354a2bb94 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/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.lightning_indexer.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/lightning_indexer/tests/ut/op_api/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_api/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..77e0ca1492477d95e9c595e7e2199f437e80b511 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/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/lightning_indexer/tests/ut/op_api/test_aclnn_lightning_indexer.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_api/test_aclnn_lightning_indexer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4da948ee87cbd5552b9d842a034fedff95613ce0 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_api/test_aclnn_lightning_indexer.cpp @@ -0,0 +1,147 @@ +/** + * 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 "gtest/gtest.h" +#include "../../../op_host/op_api/aclnn_lightning_indexer.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 lightning_indexer_opapi_ut : public testing::Test +{ +protected: + static void SetUpTestCase() + { + op::SetPlatformSocVersion(op::SocVersion::ASCEND910B); + cout << "lightning_indexer_opapi_ut SetUp" << endl; + } + + static void TearDownTestCase() + { + cout << "lightning_indexer_opapi_ut TearDown" << endl; + } +}; + +// Null query +TEST_F(lightning_indexer_opapi_ut, lightning_indexer_aclnn_0) +{ + char layoutQuery[] = "BSND"; + char layoutKey[] = "BSND"; + uint64_t workspaceSize = 0; + aclOpExecutor *executor = nullptr; + + aclnnStatus aclRet = aclnnLightningIndexerGetWorkspaceSize( + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + layoutQuery, + layoutKey, + 4, + 3, + INT64_MAX, + INT64_MAX, + true, + nullptr, + nullptr, + &workspaceSize, + &executor); + + EXPECT_NE(aclRet, ACL_SUCCESS); + EXPECT_EQ(executor, nullptr); +} + +// Missing sparse values +TEST_F(lightning_indexer_opapi_ut, lightning_indexer_aclnn_1) +{ + char layoutQuery[] = "BSND"; + char layoutKey[] = "BSND"; + auto query = unique_ptr( + TensorDesc({1, 8, 8, 128}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto key = unique_ptr( + TensorDesc({1, 64, 1, 128}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto weights = unique_ptr( + TensorDesc({1, 8, 8}, ACL_FLOAT, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto sparseIndicesOut = unique_ptr( + TensorDesc({1, 8, 1, 4}, ACL_INT32, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + uint64_t workspaceSize = 0; + aclOpExecutor *executor = nullptr; + + aclnnStatus aclRet = aclnnLightningIndexerGetWorkspaceSize( + query.get(), + key.get(), + weights.get(), + nullptr, + nullptr, + nullptr, + layoutQuery, + layoutKey, + 4, + 3, + INT64_MAX, + INT64_MAX, + true, + sparseIndicesOut.get(), + nullptr, + &workspaceSize, + &executor); + + EXPECT_NE(aclRet, ACL_SUCCESS); + EXPECT_EQ(executor, nullptr); +} + +// Holder fallback +TEST_F(lightning_indexer_opapi_ut, lightning_indexer_aclnn_2) +{ + char layoutQuery[] = "BSND"; + char layoutKey[] = "BSND"; + auto query = unique_ptr( + TensorDesc({1, 8, 8, 128}, ACL_FLOAT16, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto weights = unique_ptr( + TensorDesc({1, 8, 8}, ACL_FLOAT, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + auto sparseIndicesOut = unique_ptr( + TensorDesc({1, 8, 1, 4}, ACL_INT32, ACL_FORMAT_ND).ToAclTypeRawPtr(), DestroyAclTensor); + uint64_t workspaceSize = 0; + aclOpExecutor *executor = nullptr; + + aclnnStatus aclRet = aclnnLightningIndexerGetWorkspaceSize( + query.get(), + nullptr, + weights.get(), + nullptr, + nullptr, + nullptr, + layoutQuery, + layoutKey, + 4, + 3, + INT64_MAX, + INT64_MAX, + false, + sparseIndicesOut.get(), + nullptr, + &workspaceSize, + &executor); + + EXPECT_NE(aclRet, ACL_SUCCESS); + EXPECT_EQ(executor, nullptr); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..0393ee8c2854860db422698b798a6d9f2e742e97 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/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/lightning_indexer/tests/ut/op_host/arch22/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/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/lightning_indexer/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/lightning_indexer/tests/ut/op_host/arch22/test_lightning_indexer_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_host/arch22/test_lightning_indexer_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7220272cfab58bc9e953bd2da6a9e9e0115f872c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_host/arch22/test_lightning_indexer_tiling.cpp @@ -0,0 +1,263 @@ +/** + * 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 LightningIndexerTiling : public testing::Test { +protected: + static void SetUpTestCase() + { + std::cout << "LightningIndexerTiling SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "LightningIndexerTiling TearDown" << std::endl; + } +}; + +// when key layout is not PA_BSND, input block_table must be null +TEST_F(LightningIndexerTiling, LightningIndexer_910b_tiling_0) +{ + struct LightningIndexerCompileInfo {} compileInfo; + int64_t actual_seq_qlist[] = {509}; + int64_t actual_seq_kvlist[] = {1111}; + gert::TilingContextPara tilingContextPara( + "LightningIndexer", + { + {{{1, 1856, 8, 128}, {1, 1856, 8, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{1, 131072, 1, 128}, {1, 131072, 1, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{1, 1856, 8}, {1, 1856, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, // weights input2 + {{{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_key + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND} // block_table input3 + }, + { + {{{1, 1856, 1, 1024}, {1, 1856, 1, 1024}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices + {{{1, 1856, 1, 1024}, {1, 1856, 1, 1024}}, ge::DT_BF16, ge::FORMAT_ND} // sparse_values + }, + { + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_key", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"sparse_count", Ops::Transformer::AnyValue::CreateFrom(1024)}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"return_values", Ops::Transformer::AnyValue::CreateFrom(true)} + }, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// key shape[2] is numhead, only support 1. +TEST_F(LightningIndexerTiling, LightningIndexer_910b_tiling_1) +{ + struct LightningIndexerCompileInfo {} compileInfo; + int64_t* actual_seq_qlist = nullptr; + int64_t actual_seq_kvlist[] = {16484, 16484, 16484, 16484}; + gert::TilingContextPara tilingContextPara( + "LightningIndexer", + { + {{{4, 16484, 64, 128}, {4, 16484, 64, 128}}, ge::DT_FLOAT16, ge::FORMAT_ND}, // query input0 + {{{4, 1, 16484, 128}, {4, 1, 16484, 128}}, ge::DT_FLOAT16, ge::FORMAT_ND}, // key input1 + {{{4, 16484, 64}, {4, 16484, 64}}, ge::DT_FLOAT, ge::FORMAT_ND}, // weights input2 + {{{0}, {0}}, 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_key + {{{4, 129}, {4, 129}}, ge::DT_INT32, ge::FORMAT_ND} // block_table input3 + }, + { + {{{4, 16484, 1, 3072}, {4, 16484, 1, 3072}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices + {{{0}, {0}}, ge::DT_FLOAT16, ge::FORMAT_ND} // sparse_values + }, + { + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_key", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_count", Ops::Transformer::AnyValue::CreateFrom(3072)}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"return_values", Ops::Transformer::AnyValue::CreateFrom(false)} + }, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// when key layout is not PA_BSND, input block_table must be null +TEST_F(LightningIndexerTiling, LightningIndexer_910b_tiling_2) +{ + struct LightningIndexerCompileInfo {} compileInfo; + int64_t actual_seq_qlist[] = {64, 128, 192, 256, 320, 384, 448, 512}; + int64_t actual_seq_kvlist[] = {64, 128, 192, 256, 320, 384, 448, 512}; + gert::TilingContextPara tilingContextPara( + "LightningIndexer", + { + {{{512, 8, 128}, {420, 64, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{512, 1, 128}, {1344, 1, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{512, 8}, {420, 64}}, ge::DT_FLOAT, ge::FORMAT_ND}, // weights input2 + {{{8}, {8}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{8}, {8}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_key + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND} // block_table input3 + }, + { + {{{512, 1, 3072}, {512, 1, 3072}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices + {{{512, 1, 3072}, {512, 1, 3072}}, ge::DT_BF16, ge::FORMAT_ND} // sparse_values + }, + { + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"layout_key", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"sparse_count", Ops::Transformer::AnyValue::CreateFrom(3072)}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"return_values", Ops::Transformer::AnyValue::CreateFrom(true)} + }, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// key shape[2] is numhead, only support 1. +TEST_F(LightningIndexerTiling, LightningIndexer_910b_tiling_3) +{ + struct LightningIndexerCompileInfo {} compileInfo; + int64_t actual_seq_qlist[] = {8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192}; + int64_t actual_seq_kvlist[] = {8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192, 8192}; + gert::TilingContextPara tilingContextPara( + "LightningIndexer", + { + {{{24, 8192, 64, 128}, {24, 8192, 64, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{24, 1, 8192, 128}, {24, 1, 8192, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{24, 8192, 64}, {24, 8192, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // weights input2 + {{{24}, {24}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{24}, {24}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_key + {{{24, 32}, {24, 32}}, ge::DT_INT32, ge::FORMAT_ND} // block_table input3 + }, + { + {{{24, 8192, 1, 2048}, {24, 8192, 1, 2048}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices + {{{0}, {0}}, ge::DT_BF16, ge::FORMAT_ND} // sparse_values + }, + { + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_key", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_count", Ops::Transformer::AnyValue::CreateFrom(2048)}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"return_values", Ops::Transformer::AnyValue::CreateFrom(false)} + }, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// when key layout is not PA_BSND, input block_table must be null +TEST_F(LightningIndexerTiling, LightningIndexer_910b_tiling_4) +{ + struct LightningIndexerCompileInfo {} compileInfo; + int64_t actual_seq_qlist[] = {33, 33}; + int64_t actual_seq_kvlist[] = {137, 2304}; + gert::TilingContextPara tilingContextPara( + "LightningIndexer", + { + {{{2, 3072, 64, 128}, {2, 3072, 64, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{2, 2304, 1, 128}, {2, 2304, 1, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{2, 3072, 64}, {2, 3072, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // weights input2 + {{{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_key + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND} // block_table input3 + }, + { + {{{2, 3072, 1, 2048}, {2, 3072, 1, 2048}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices + {{{0}, {0}}, ge::DT_BF16, ge::FORMAT_ND} // sparse_values + }, + { + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_key", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"sparse_count", Ops::Transformer::AnyValue::CreateFrom(2048)}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"return_values", Ops::Transformer::AnyValue::CreateFrom(false)} + }, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// input key's block_size must be a multiple of 16 and belong to (0, 1024]. +TEST_F(LightningIndexerTiling, LightningIndexer_910b_tiling_5) +{ + struct LightningIndexerCompileInfo {} compileInfo; + int64_t actual_seq_qlist[] = {39, 39}; + int64_t actual_seq_kvlist[] = {1, 1}; + gert::TilingContextPara tilingContextPara( + "LightningIndexer", + { + {{{2, 39, 64, 128}, {2, 39, 64, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{2, 1, 1, 128}, {2, 1, 1, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{2, 39, 64}, {2, 39, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // weights input2 + {{{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_key + {{{2, 1}, {2, 1}}, ge::DT_INT32, ge::FORMAT_ND} // block_table input3 + }, + { + {{{2, 39, 1, 2048}, {2, 39, 1, 2048}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices + {{{0}, {0}}, ge::DT_BF16, ge::FORMAT_ND} // sparse_values + }, + { + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_key", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_count", Ops::Transformer::AnyValue::CreateFrom(2048)}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"return_values", Ops::Transformer::AnyValue::CreateFrom(false)} + }, + &compileInfo, "Ascend910B", 64, 262144, 16384); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED); +} + +// key Dim(2)=1 Dim(1)=16 success +TEST_F(LightningIndexerTiling, LightningIndexer_910b_tiling_6) +{ + struct LightningIndexerCompileInfo {} compileInfo; + int64_t actual_seq_qlist[] = {39, 39}; + int64_t actual_seq_kvlist[] = {1, 1}; + gert::TilingContextPara tilingContextPara( + "LightningIndexer", + { + {{{2, 39, 64, 128}, {2, 39, 64, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{2, 16, 1, 128}, {2, 16, 1, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{2, 39, 64}, {2, 39, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // weights input2 + {{{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_key + {{{2, 1}, {2, 1}}, ge::DT_INT32, ge::FORMAT_ND} // block_table input3 + }, + { + {{{2, 39, 1, 2048}, {2, 39, 1, 2048}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices + {{{0}, {0}}, ge::DT_BF16, ge::FORMAT_ND} // sparse_values + }, + { + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_key", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_count", Ops::Transformer::AnyValue::CreateFrom(2048)}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"return_values", Ops::Transformer::AnyValue::CreateFrom(false)} + }, + &compileInfo, "Ascend910B", 64, 262144, 16384); + int64_t expectTilingKey = 1090722587; + std::string expectTilingData = + "2 167503724608 8796093022224 68719476800 12884901889 " + "9223372036854775807 9223372036854775807 0 "; + std::vector expectWorkspaces = {167903232}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_host/test_lightning_indexer_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_host/test_lightning_indexer_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3c3c53ba54f21e666931c4bb4dabd9130a8c36bc --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/lightning_indexer/tests/ut/op_host/test_lightning_indexer_infershape.cpp @@ -0,0 +1,181 @@ +/** + * 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 LightningIndexerProto : public testing::Test { +protected: + static void SetUpTestCase() + { + std::cout << "LightningIndexerProto SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "LightningIndexerProto TearDown" << std::endl; + } +}; + +// BSND_BSND +TEST_F(LightningIndexerProto, LightningIndexer_infershape_0) +{ + int64_t actual_seq_qlist[] = {509}; + int64_t actual_seq_kvlist[] = {1111}; + gert::InfershapeContextPara infershapeContextPara( + "LightningIndexer", + // 输入Tensor + { + {{{1, 1856, 8, 128}, {1, 1856, 8, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{1, 131072, 1, 128}, {1, 131072, 1, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{1, 1856, 8}, {1, 1856, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, // weights input2 + {{{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_key + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND} // block_table input3 + }, + {// 输出Tensor + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND} // sparse_values + }, + {// 属性 + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"layout_key", Ops::Transformer::AnyValue::CreateFrom("BSND")}, + {"sparse_count", Ops::Transformer::AnyValue::CreateFrom(1024)}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"return_values", Ops::Transformer::AnyValue::CreateFrom(true)} + } + ); + + std::vector> expectOutputShape = { // 预期输出 + {1, 1856, 1, 1024}, + {1, 1856, 1, 1024} + }; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); // 比对成功返回SUCCESS +} + +// PA_TND +TEST_F(LightningIndexerProto, LightningIndexer_infershape_1) +{ + int64_t actual_seq_qlist[] = {1}; + int64_t actual_seq_kvlist[] = {8191}; + gert::InfershapeContextPara infershapeContextPara( + "LightningIndexer", + // 输入Tensor + { + {{{1, 64, 128}, {1, 64, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{1, 1, 8191, 128}, {1, 1, 8191, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{1, 64}, {1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // weights input2 + {{{6}, {6}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{6}, {6}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_key + {{{1, 32}, {1, 32}}, ge::DT_INT32, ge::FORMAT_ND} // block_table input3 + }, + {// 输出Tensor + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND} // sparse_values + }, + {// 属性 + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"layout_key", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + {"sparse_count", Ops::Transformer::AnyValue::CreateFrom(2048)}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"return_values", Ops::Transformer::AnyValue::CreateFrom(false)} + } + ); + + std::vector> expectOutputShape = { // 预期输出 + {1, 8191, 2048}, + {0} + }; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); // 比对成功返回SUCCESS +} + +// TND_TND +TEST_F(LightningIndexerProto, LightningIndexer_infershape_2) +{ + int64_t actual_seq_qlist[] = {73, 111, 209, 331, 403, 420}; + int64_t actual_seq_kvlist[] = {224, 448, 672, 896, 1120, 1344}; + gert::InfershapeContextPara infershapeContextPara( + "LightningIndexer", + // 输入Tensor + { + {{{420, 64, 128}, {420, 64, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // query input0 + {{{1344, 1, 128}, {1344, 1, 128}}, ge::DT_BF16, ge::FORMAT_ND}, // key input1 + {{{420, 64}, {420, 64}}, ge::DT_FLOAT, ge::FORMAT_ND}, // weights input2 + {{{6}, {6}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_qlist}, // actual_seq_lengths_query + {{{6}, {6}}, ge::DT_INT32, ge::FORMAT_ND, true, actual_seq_kvlist}, // actual_seq_lengths_key + {{{1}, {1}}, ge::DT_INT32, ge::FORMAT_ND} // block_table input3 + }, + {// 输出Tensor + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, // sparse_indices + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND} // sparse_values + }, + {// 属性 + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"layout_key", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"sparse_count", Ops::Transformer::AnyValue::CreateFrom(5120)}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"return_values", Ops::Transformer::AnyValue::CreateFrom(true)} + } + ); + + std::vector> expectOutputShape = { // 预期输出 + {420, 1, 5120}, + {420, 1, 5120} + }; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); // 比对成功返回SUCCESS +} + +// infer dataType +TEST_F(LightningIndexerProto, LightningIndexer_inferdtype) +{ + auto spaceRegistry = gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry(); + ASSERT_NE(spaceRegistry, nullptr); + auto data_type_func = spaceRegistry->GetOpImpl("LightningIndexer")->infer_datatype; + if (data_type_func != nullptr) { + ge::DataType input_ref0 = ge::DT_FLOAT16; + ge::DataType input_ref1 = ge::DT_FLOAT; + ge::DataType input_ref2 = ge::DT_INT32; + ge::DataType output_ref0 = ge::DT_INT32; + ge::DataType output_ref1 = ge::DT_FLOAT16; + auto context_holder = + gert::InferDataTypeContextFaker() + .NodeIoNum(6, 2) + .NodeOutputTd(0, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(1, ge::FORMAT_ND, ge::FORMAT_ND) + .InputDataTypes({&input_ref0, &input_ref0, &input_ref1, &input_ref2, &input_ref2, &input_ref2}) + .NodeAttrs({ + {"layout_query", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"layout_key", Ops::Transformer::AnyValue::CreateFrom("TND")}, + {"sparse_count", Ops::Transformer::AnyValue::CreateFrom(2048)}, + {"sparse_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"pre_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"next_tokens", Ops::Transformer::AnyValue::CreateFrom(INT64_MAX)}, + {"return_values", Ops::Transformer::AnyValue::CreateFrom(true)} + }) + .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_ref0); + EXPECT_EQ(context->GetOutputDataType(1), output_ref1); + + } +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..0af0aaa85d3cb5dd57a9488bb6cdb4fec8f258be --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/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.mla_prolog.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/mla_prolog/README.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4ef4c4f190d20c648ebdfc84c9761ffecab25d4d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/README.md @@ -0,0 +1,370 @@ +# MlaProlog + +## 产品支持情况 + +|产品 | 是否支持 | +|:----------------------------|:-----------:| +|Ascend 950PR/Ascend 950DT| × | +|Atlas A3 训练系列产品/Atlas A3 推理系列产品| √ | +|Atlas A2 训练系列产品/Atlas A2 推理系列产品| √ | + +## 功能说明 + +- **算子功能**:推理场景,Multi-Head Latent Attention前处理的计算。主要计算过程分为四路,首先对输入$x$乘以$W^{DQ}$进行下采样和RmsNorm后分为两路,第一路乘以$W^{UQ}$和$W^{UK}$经过两次上采样后得到$q^N$;第二路乘以$W^{QR}$后经过旋转位置编码(ROPE)得到$q^R$;第三路是输入$x$乘以$W^{DKV}$进行下采样和RmsNorm后传入Cache中得到$k^C$;第四路是输入$x$乘以$W^{KR}$后经过旋转位置编码后传入另一个Cache中得到$k^R$。 +- **计算公式**: + + RmsNorm公式 + + $$ + \text{RmsNorm}(x) = \gamma \cdot \frac{x_i}{\text{RMS}(x)} + $$ + + $$ + \text{RMS}(x) = \sqrt{\frac{1}{N} \sum_{i=1}^{N} x_i^2 + \epsilon} + $$ + + Query计算公式,包括下采样,RmsNorm和两次上采样 + + $$ + c^Q = RmsNorm(x \cdot W^{DQ}) + $$ + + $$ + q^C = c^Q \cdot W^{UQ} + $$ + + $$ + q^N = q^C \cdot W^{UK} + $$ + + 对Query的进行ROPE旋转位置编码 + + $$ + q^R = ROPE(c^Q \cdot W^{QR}) + $$ + + Key计算公式,包括下采样和RmsNorm,将计算结果存入cache + + $$ + c^{KV} = RmsNorm(x \cdot W^{DKV}) + $$ + + $$ + k^C = Cache(c^{KV}) + $$ + + 对Key进行ROPE旋转位置编码,并将结果存入cache + + $$ + k^R = Cache(ROPE(x \cdot W^{KR})) + $$ + +## 参数说明 + +| 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 数据格式 | +|----------------------------|-----------|----------------------------------------------------------------------|----------------|------------| +| token_x | 输入 | 公式中计算Query和Key的输入tensor | INT8, BF16 | ND | +| weight_dq | 输入 | 公式中计算Query的下采样权重矩阵$W^{DQ}$ | INT8, BF16 | FRACTAL_NZ | +| weight_uq_qr | 输入 | 公式中计算Query的上采样权重矩阵$W^{UQ}$和位置编码权重矩阵$W^{QR}$。| INT8, BF16 | FRACTAL_NZ | +| weight_uk | 输入 | 公式中计算Key的上采样权重$W^{UK}$ | BF16 | ND | +| weight_dkv_kr | 输入 | 公式中计算Key的下采样权重矩阵$W^{DKV}$和位置编码权重矩阵$W^{KR}$ | INT8, BF16| FRACTAL_NZ | +| rmsnorm_gamma_cq | 输入 | 计算$c^Q$的RmsNorm公式中$\gamma$参数 | FLOAT16, BF16 | ND | +| rmsnorm_gamma_ckv | 输入 | 计算$c^{KV}$的RmsNorm公式中$\gamma$参数 | FLOAT16, BF16 | ND | +| rope_sin | 输入 | 旋转位置编码的正弦参数矩阵 | FLOAT16, BF16 | ND | +| rope_cos | 输入 | 旋转位置编码的余弦参数矩阵 | FLOAT16, BF16 | ND | +| cache_index | 输入 | 存储kvCache和krCache的索引 | INT64 | ND | +| kv_cache | 输入/ 输出| cache索引的aclTensor,计算结果原地更新(对应$k^C$)| FLOAT16, BF16, INT8 | ND | +| kr_cache | 输入/ 输出| key位置编码的cache,计算结果原地更新(对应$k^R$) | FLOAT16, BF16, INT8 | ND | +| dequant_scale_x | 输入 | 预留参数,当前版本暂未使用,必须传入空指针 | FLOAT | ND | +| dequant_scale_w_dq | 输入 | 预留参数,当前版本暂未使用,必须传入空指针 | FLOAT | ND | +| dequant_scale_w_uq_qr | 输入 | MatmulQcQr矩阵乘后反量化的per-channel参数| FLOAT | ND | +| dequant_scale_w_dkv_kr | 输入 | 预留参数,当前版本暂未使用,必须传入空指针 | FLOAT | ND | +| quant_scale_ckv | 输入 | KVCache输出量化参数 | FLOAT | ND | +| quant_scale_ckr | 输入 | KRCache输出量化参数 | FLOAT | ND | +| smooth_scales_cq | 输入 | RmsNormCq输出动态量化参数 | FLOAT | ND | +| rmsnorm_epsilon_cq | 输入 | 计算$c^Q$的RmsNorm公式中$\epsilon$参数 | DOUBLE | - | +| rmsnorm_epsilon_ckv | 输入 | 计算$c^{KV}$的RmsNorm公式中$\epsilon$参数 | DOUBLE | - | +| cache_mode | 输入 | kvCache模式 | CHAR* | - | +| query | 输出 | 公式中Query的输出tensor(对应$q^N$) | FLOAT16, BF16, INT8 | ND | +| query_rope | 输出 | 公式中Query位置编码的输出tensor(对应$q^R$) | FLOAT16, BF16, INT8 | ND | + +## 约束说明 + +- B、S、T、Skv值允许一个或多个取0,即Shape与B、S、T、Skv值相关的入参允许传入空Tensor,其余入参不支持传入空Tensor。 + - 如果B、S、T取值为0,则query、query_rope输出空Tensor,kv_cache、kr_cache不做更新。 + - 如果Skv取值为0,则query、query_rope正常计算,kv_cache、kr_cache不做更新,即输出空Tensor。 +- weight_dq,weight_uq_qr,weight_dkv_kr在不转置的情况下各个维度的表示:(k,n)。 +- aclnnMlaProlog接口支持场景: + + + + + + + + + + + + + + + + + + +
场景含义
非量化 + 入参:所有入参皆为非量化数据
+ 出参:所有出参皆为非量化数据 +
部分量化kv_cache非量化 + 入参:weight_uq_qr传入pertoken量化数据,其余入参皆为非量化数据
+ 出参:所有出参返回非量化数据 +
kv_cache量化 + 入参:weight_uq_qr传入pertoken量化数据,kv_cache、kr_cache传入perchannel量化数据,其余入参皆为非量化数据
+ 出参:kv_cache、kr_cache返回perchannel量化数据,其余出参返回非量化数据 +
+ +- 在不同量化场景下,参数的dtype和shape组合需要满足如下条件: +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名非量化场景部分量化场景
kv_cache非量化kv_cache量化
dtypeshapedtypeshapedtypeshape
token_xBFLOAT16· (B,S,He)
· (T, He)
BFLOAT16· (B,S,He)
· (T, He)
BFLOAT16· (B,S,He)
· (T, He)
weight_dqBFLOAT16 (He, Hcq)BFLOAT16 (He, Hcq)BFLOAT16 (He, Hcq)
weight_uq_qrBFLOAT16 (Hcq, N*(D+Dr))INT8 (Hcq, N*(D+Dr))INT8 (Hcq, N*(D+Dr))
weight_ukBFLOAT16 (N, D, Hckv)BFLOAT16 (N, D, Hckv)BFLOAT16 (N, D, Hckv)
weight_dkv_krBFLOAT16 (He, Hckv+Dr)BFLOAT16 (He, Hckv+Dr)BFLOAT16 (He, Hckv+Dr)
rmsnorm_gamma_cq BFLOAT16 (Hcq)BFLOAT16 (Hcq)BFLOAT16 (Hcq)
rmsnorm_gamma_ckv BFLOAT16 (Hckv)BFLOAT16 (Hckv)BFLOAT16 (Hckv)
rope_sin BFLOAT16 · (B,S,Dr)
· (T, Dr )
BFLOAT16 · (B,S,Dr)
· (T, Dr )
BFLOAT16 · (B,S,Dr)
· (T, Dr )
rope_cos BFLOAT16 · (B,S,Dr)
· (T, Dr )
BFLOAT16 · (B,S,Dr)
· (T, Dr )
BFLOAT16 · (B,S,Dr)
· (T, Dr )
cache_index INT64 · (B,S)
· (T)
INT64 · (B,S)
· (T)
INT64 · (B,S)
· (T)
kv_cache BFLOAT16 (BlockNum, BlockSize, Nkv, Hckv)BFLOAT16 (BlockNum, BlockSize, Nkv, Hckv)INT8 (BlockNum, BlockSize, Nkv, Hckv)
kr_cache BFLOAT16 (BlockNum, BlockSize, Nkv, Dr)BFLOAT16 (BlockNum, BlockSize, Nkv, Dr)INT8 (BlockNum, BlockSize, Nkv, Dr)
dequant_scale_x 无需赋值 / 无需赋值 / 无需赋值 /
dequant_scale_w_dq 无需赋值 / 无需赋值 / 无需赋值 /
dequant_scale_w_uq_qr 无需赋值 / FLOAT (1, N*(D+Dr)) FLOAT (1, N*(D+Dr))
dequant_scale_w_dkv_kr 无需赋值 / 无需赋值 / 无需赋值 /
quant_scale_ckv 无需赋值 / 无需赋值 / FLOAT (1, Hckv)
quant_scale_ckr 无需赋值 / 无需赋值 / FLOAT (1, Dr)
smooth_scales_cq 无需赋值 / FLOAT (1, Hcq) FLOAT (1, Hcq)
query BFLOAT16 · (B, S, N, Hckv)
· (T, N, Hckv)
BFLOAT16 · (B, S, N, Hckv)
· (T, N, Hckv)
BFLOAT16 · (B, S, N, Hckv)
· (T, N, Hckv)
query_rope BFLOAT16 · (B, S, N, Dr)
· (T, N, Dr)
BFLOAT16 · (B, S, N, Dr)
· (T, N, Dr)
BFLOAT16 · (B, S, N, Dr)
· (T, N, Dr)
+
+ +## 调用说明 + + + + + + + + + + + + + + + + +
调用方式样例代码说明
aclnn接口 + MlaProlog非量化(BSH)接口测试用例代码 + + + 通过 + aclnnMlaProlog + + 接口方式调用算子 +
+ MlaProlog半量化KV量化(BSH)接口测试用例代码 + +
+ + diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/docs/.gitkeep b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/docs/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git "a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/docs/MlaProlog\347\256\227\345\255\220\350\256\276\350\256\241\344\273\213\347\273\215.md" "b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/docs/MlaProlog\347\256\227\345\255\220\350\256\276\350\256\241\344\273\213\347\273\215.md" new file mode 100644 index 0000000000000000000000000000000000000000..eb98dcbf2fee162ca692cd96b78e612d2154ed7a --- /dev/null +++ "b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/docs/MlaProlog\347\256\227\345\255\220\350\256\276\350\256\241\344\273\213\347\273\215.md" @@ -0,0 +1,420 @@ + +# MlaProlog算子设计介绍 + +近年来,随着人工智能技术的快速发展,大模型在自然语言处理、计算机视觉、多模态交互等领域取得了显著突破。然而,模型的复杂度和规模呈指数级增长,对底层计算框架和硬件算力提出了更高的要求。 +传统的矩阵运算(如GEMM)和注意力机制实现方式在应对超大规模参数模型时,逐渐暴露出计算效率低、内存占用高、并行扩展性不足等问题,制约了模型训练和推理的实时性能及资源利用率。 + +在此背景下,DeepSeek团队提出Mla算子需求,需要对算法和硬件进行协同优化,通过算子融合,减少算子调用和头开销时间,在保证模型精度的前提下,降低推理延迟、并减少硬件资源消耗,MlaProlog算子正是Mla算子前处理融合部分。 + +## 实现原理 + +按照Multi-Head Latent Attention定义的计算流程实现,整体计算流程如下: + +1. 输入序列x经过下采样$W^{DQ}$矩阵进行降秩变换,并进行归一化处理得到$c^Q$ + +2. 将$W^{UQ}$和$W^{QR}$矩阵进行拼接,实现对$c^Q$的升秩和映射计算,对运算结果再进行split拆分,分别做Qn的归一化处理和Rope位置编码,最终得到Query和Query Rope + +3. 将$W^{DKV}$和$W^{KR}$矩阵进行拼接,对输入序列x实现降秩和映射计算,对运算结果再进行split拆分,分别做Rope位置编码和$C^{KV}$的归一化处理,最终得到KR Cache和KV Cache + +具体的计算公式,参见[完整计算公式](#完整计算公式)章节 + +## 数据切分设计 + +由于硬件buffer大小是有限的,而计算的数据量又是巨大的,无法一次计算完,那么就需要进行tiling切分,shape不同会导致算子的切分轴不同,而算子的切分轴,会影响模板的功能及性能。需要考虑如下几个点: + +a. 将核心的数量用满,防止部分核闲置。 + +b. 每一个核心被分配的计算量相对均匀,避免出现某些核计算的数据量过大,其余核空闲的情况。 + +c. AIC和AIV之间处理的数据量要符合其对应的算力,避免AIC或AIV出现长时间的空闲。 + +MlaProlog算子有多个Matmul运算: + +1、MatmulCq:将BS合轴,作为M轴,HeadSizeCq为N轴,HeadSizeX为K轴,核间对HeadSizeCq按照cube核数进行切分,每个核分配一定的子块 + +2、MatmulCkvKr:将BS合轴,作为M轴,HeadSizeCkvKr为N轴,HeadSizeX为K轴,核间对HeadSizeCkvKr进行切分,分为64块 + +3、MatmulQcQr:将BS合轴,作为M轴,HeadSizeQcQr为N轴,HeadSizeCq为K轴,核间对HeadSizeQcQr按照cube核数进行切分,每个核分配一定的子块 + +4、MatmulQn:将BS合轴,作为M轴,HeadSizeCkv为N轴,dimHeadSizeQc为K轴 + +## 流水设计 + +MlaProlog融合算子包含了Vector计算和Cube计算,Vector侧和Cube侧的计算存在依赖关系,因此需要进行CV流水设计, +否则C侧和V侧很有可能是串行流水的效果,不能达到并行计算的目的,无法使得融合算子性能达到最优。 + +同步控制要点如下: + +1、MatmulCq计算的时候,对Hcq进行了分核,单核没有计算一个完整的token,所以在RmsNormCq计算前, +需要做AIC与AIV之间的同步控制(SYNC_MMCQ_NOMRCQ) + +2、MatmulCkvKr计算的时候,也是对Hcq进行了分核,单核没有计算一个完整的token,所以在RmsNormCkv计算前,也 +需要做AIC与AIV之间的同步控制(SYNC_MMCKVKR_NOMRCKV) + +3、由于RmsNormCq按照行切分到不同核上,因此在做MatmulQcQr计算的时候,也需要AIV与AIC的同步控制(SYNC_NOMRCQ_MMQCQR) + +4、由于和RopeQr的分核策略不同,因此RopeQr计算前,也需要AIC和AIV之间的同步控制(SYNC_MMQCQR_ROPEQR) + +5、由于MatmulQcQr和MatmulQn的分核策略不同,MatmulQn依赖于MatmulQcQr的输出,因此需要做cube的全核同步(SYNC_ALL_CUBE) + +6、Vector核运算前,需要做vector的全核同步(SYNC_ALL_VECTOR),确保数据流水搬运 + +## TilingKey划分 + +TilingKey为uint64类型,每个模板参数对应TilingKey中的一到数个二进制位,具体实现如下: + +|二进制位|变量名|说明|参数列表| +|-------|------|----|-------| +|0-3|CACHE_MODE|KVCache的存储格式|0-BNSD(预留),1-PA_BSND,2-PA_NZ| +|4-5|SCENARIO|输入场景|0-FP16(预留),1-非量化场景,2-量化场景| +|6-9|QUANT_MODE|量化场景|0-MMQcQr量化,1-MMQcQr量化+KVCache量化| +|10|ENABLE_DEQUANT_OPTIONAL|反量化开启,不能与ENABLE_DEQUANT_OPTIONAL一同使用|0-关闭,1-开启| +|11|ENABLE_GROUP_COMPUTE_OPTIONAL|量化的算力分组优化,不能与ENABLE_DEQUANT_OPTIONAL一同使用|0-关闭,1-开启| +|12-13|EMPTY_TENSOR_MODE|空tensor场景,用于输入tensor维度为0的情况|0-无空tensor,1-KVCache为空和KRCache为空, 2-Query为空| + +## 主流程 + +```c +// 单核计算伪码 +void Process() { + loops = compute_step_this_core(); //计算当前core的循环次数 + // + for (i = 0; i < loops; i++) { + updateCurrentStepSize(i, stepSize, allTokenSize); //刷新当前轮的计算的M轴大小 + + if ASCEND_IS_AIC { + + MatmulCq(tokenXOffset, weightDqOffset, cqResOffset); + CrossCoreSetFlag<0x2, PIPE_FIX>(SYNC_MMCQ_NORMSCQ_FLG); //cube与vector同步 + + MatmulCkvKr(tokenXOffset, weightDkvKrOffset, ckvKrResOffset); + CrossCoreSetFlag<0x2, PIPE_FIX>(SYNC_MMCKVKR_NORMROPE_FLG); //cube与vector同步 + + CrossCoreWaitFlag(SYNC_MMCQ_NORMSCQ_FLG); // MatmulQcQr依赖RmsNormCq的输出,需要插入CV核间同步 + + MatmulQcQr(weightUqQrOffset, qcQrResOffset); + CrossCoreSetFlag<0x2, PIPE_FIX>(SYNC_MMQCQR_ROPEQR_FLG); //cube与vector同步 + + + // 由于MatmulQn和MatmulQcQr的分核策略不一样,MatmulQn又依赖MatmulQcQr的输出 + // 需要等所有cube核上的MatmulQcQr执行完后才能启动MatmulQn + CrossCoreSetFlag<0x0, PIPE_FIX>(SYNC_ALL_CUBE_FLG); + CrossCoreWaitFlag(SYNC_ALL_CUBE_FLG); + + MatmulQn(qcOffset, weightUkOffset, qnResOffset, mmQnLoopTime); // MatmulQn的结果直接输出到queryOut, qnOffset需要按Batch轴偏移 + + } + + if ASCEND_IS_AIV { + + GetSinCos(tokenIndex); + + CrossCoreWaitFlag(SYNC_MMCQ_NORMSCQ_FLG); // wait MatmulCq + + CrossCoreSetFlag<0x0, PIPE_MTE3>(SYNC_ALL_VECTOR_FLG); + CrossCoreWaitFlag(SYNC_ALL_VECTOR_FLG); + + RmsNormCq(rmsNormCqOffset); + + // 由于RmsNormCq和MatmulQcQr的分核策略不一样,需要等所有vector上的RmsNormCq执行完成后才能启动MatmulQcQr + // 需要所有vector核上的RmsNormCq执行完成后,才发起MatmulQcQr的执行 + CrossCoreSetFlag<0x0, PIPE_MTE3>(SYNC_ALL_VECTOR_FLG); + CrossCoreWaitFlag(SYNC_ALL_VECTOR_FLG); + + CrossCoreSetFlag<0x2, PIPE_MTE3>(SYNC_MMCQ_NORMSCQ_FLG); // 保障MatmulQcQr等RmsNormCq + + + CrossCoreWaitFlag(SYNC_MMCKVKR_NORMROPE_FLG); // wait MatmulCkvKr + + CrossCoreSetFlag<0x0, PIPE_MTE3>(SYNC_ALL_VECTOR_FLG); + CrossCoreWaitFlag(SYNC_ALL_VECTOR_FLG); + RmsNormRopeScatterCkvKr(tokenIndex, rmsNormCkvOffset, ropeKrOffset); + + CrossCoreWaitFlag(SYNC_MMQCQR_ROPEQR_FLG); // wait MatmulQcQr + + CrossCoreSetFlag<0x0, PIPE_MTE3>(SYNC_ALL_VECTOR_FLG); + CrossCoreWaitFlag(SYNC_ALL_VECTOR_FLG); + RopeQr(ropeQrOffset, ropeQrResOffset); + } + } +} +``` + +## 完整计算公式 + +结合前序章节的流程图,整个MlaProlog的完整计算公式如下: + +$$ +q^N = RmsNorm(x \cdot W^{DQ}) \cdot W^{UQ} \cdot W^{UK} \tag{a} +$$ + +$$ +q^R = ROPE(RmsNorm(x \cdot W^{DQ}) \cdot W^{QR}) \tag{b} +$$ + +$$ +k^R = ROPE(x \cdot W^{KR}) \tag{c} +$$ + +$$ +c^{KV} = RmsNorm(x \cdot W^{DKV}) \tag{d} +$$ + +完整计算流程可以分解为以下的基本计算单元。 + +### MatmulCq + +对输入$x$乘以Query下采样矩阵$W^{DQ}$进行下采样操作得到压缩后的Query矩阵$c^Q$。 +$$ +c^Q = x \cdot W^{DQ} \tag{1} +$$ + +本章节(以及后续章节)涉及的矩阵乘法模块使用AscendC Kernel API中Matmul高阶API实现。相关API使用可以参考官网[算子实现->矩阵编程(高阶API)](https://www.hiascend.com/document/detail/zh/CANNCommunityEdition/80RC3alpha003/devguide/opdevg/ascendcopdevg/atlas_ascendc_10_0041.html)开发指南。 + +### RMSNormCq + +对压缩后的$Q$矩阵按行进行RMSNorm(均方根归一化)操作。RMSNorm操作需要传入两个超参$\gamma$和$\epsilon$,对应到接口文档中的$rmsnormGammaCq$和$rmsnormEpsilonCq$。 +$$ +c_{norm}^Q = RMSNorm(c^Q) \tag{2} +$$ +RMSNorm的计算公式如下: +$$ +RMSNorm(x) = \gamma \cdot \frac{x_i}{RMS(x)} \tag{3} +$$ +$$ +RMS(x) = \sqrt{\frac{1}{N} \sum_{i=1}^{N} x_i^2 + \epsilon} \tag{4} +$$ + +### MatmulCkvKr + +对输入$x$乘以Key/Value下采样矩阵(Key/Value共享相同的下采样矩阵)得到压缩后的Key/Value矩阵$c^{KV}$。 +$$ +c^{KV} = x \cdot W^{DKV} \tag{5} +$$ +对输入$x$乘以$W^{KR}$矩阵得到用于位置编码计算的$K^R$矩阵。 +$$ +k^R = x \cdot W^{KR} \tag{6} +$$ +利用矩阵乘法的性质,$W^{DKV}$和$W^{KR}$矩阵可以横向拼接成一个矩阵$[W^{DKV}|W^{KR}]$来计算,该拼接矩阵对应接口文档的$weightDkvKr$参数。 +$$ +c^{KV}k^R = x \cdot [W^{DKV}|W^{KR}] = [x \cdot W^{DKV}|x \cdot W^{KR}] \tag{7} +$$ + +### RMSNormCkv + +对压缩后的$KV$矩阵按行进行RMSNorm(均方根归一化)操作。RMSNorm操作需要传入两个超参$\gamma$和$\epsilon$,对应到接口文档中的$rmsnormGammaCkv$和$rmsnormEpsilonCkv$。 +$$ +c_{norm}^{KV} = RMSNorm(c^{KV}) \tag{8} +$$ +RMSNorm的计算参考公式(3)-(4)。 + +### PostQuant/Dequant + +- 基本概念 + - 量化:泛指用低位宽数据(通常是INT8)替代高位宽数据(通常是浮点数)完成存储、传输、计算等任务。有时特指把浮点数变成整数的计算过程。 + - 反量化:把低位宽数据恢复成高位宽数据。 +- 量化基础公式是: + $$ + x\_float≈round(x\_float/scale)∗scale + $$ + 其中PostQuant对应的是$round(x\_float/scale)$,将数据里的每个值都进行scale缩放,然后计算四舍五入。乘scale参数对应着反量化操作。 + +当前包含两种量化方式: + + - 动态量化:需要根据输入计算scale,并使用smooth_scale对输入进行平滑,对应公式为 + $$ + scale=max(abs(x\_float∗smooth\_scale))/127 + $$ + smooth_scale 用于平滑输入数据,便于后续量化。 + + - 静态量化:当前仅支持Perchannel量化,该量化是指按列量化,对输入tensor的每一列用一个scale进行量化。 + +### MatmulQcQr + +对归一化的$C^q$矩阵乘上Query上采样矩阵$W^{UQ}$得到$q^C$矩阵。 +$$ +q^C = c_{norm}^Q \cdot W^{UQ} \tag{9} +$$ +对归一化的$C^q$矩阵乘以$W^{QR}$矩阵得到用于位置编码计算的$q^R$矩阵。 +$$ +q^R = c_{norm}^Q \cdot W^{QR} \tag{10} +$$ +同样利用矩阵乘法的性质,$W^{UQ}$和$W^{QR}$矩阵可以横向拼接成一个矩阵$[W^{UQ}|W^{QR}]$来计算,该拼接矩阵对应接口文档的$weightDkvKr$参数。 +$$ +q^Cq^R = c_{norm}^Q \cdot [W^{UQ}|W^{QR}] = [c_{norm}^Q \cdot W^{UQ}|c_{norm}^Q \cdot W^{QR}] \tag{11} +$$ + +### RotaryPosEmb + +旋转位置编码(Rotary Position Embedding, RoPE)是论文[Roformer](https://arxiv.org/abs/2104.09864)提出的一种位置编码算法,其原始计算公式如下: +$$ +f_{\{q,k\}}(x_m, m) = R_{\Theta,m}^{d}W_{\{q,k\}}x_m \tag{12} +$$ + +$$ +R_{\Theta,m}^{d} = +\left( +\begin{matrix} +\cos m\theta_1 & -\sin m\theta_1 & 0 & 0 & \cdots & 0 & 0 \\ +\sin m\theta_1 & \cos m\theta_1 & 0 & 0 & \cdots & 0 & 0 \\ +0 & 0 & \cos m\theta_2 & -\sin m\theta_2 & \cdots & 0 & 0 \\ +0 & 0 & \sin m\theta_2 & \cos m\theta_2 & \cdots & 0 & 0 \\ +\vdots & \vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\ +0 & 0 & 0 & 0 & \cdots & \cos m\theta_{d/2} & -\sin m\theta_{d/2} \\ +0 & 0 & 0 & 0 & \cdots & \sin m\theta_{d/2} & \cos m\theta_{d/2} \\ +\end{matrix} +\right) +\tag{13} +$$ +$$ +\Theta = \{ \theta_i = 10000^{-2(i-1)/d}, i \in [1,2,...,d/2] \} +$$ + +其中,$f_{\{q,k\}}(x_m, m)$代表第$m$个token对应的词向量$x_m$集成了位置信息$m$之后的Query/Key向量,Query和Key向量计算公式一致。$d$为词向量的维度。 + +公式(12)展开变形后可以得到公式(14)的形式,其中$\otimes$为逐位对应相乘的叉乘。 + +$$ +ROPE(x) = R_{\Theta,m}^{d} x = +\left( +\begin{matrix} +x_0 \\ +x_1 \\ +x_2 \\ +x_3 \\ +\vdots \\ +x_{d-2} \\ +x_{d-1} +\end{matrix} +\right) +\otimes +\left( +\begin{matrix} +\cos m\theta_0 \\ +\cos m\theta_0 \\ +\cos m\theta_1 \\ +\cos m\theta_1 \\ +\vdots \\ +\cos m\theta_{d/2-1} \\ +\cos m\theta_{d/2-1} +\end{matrix} +\right) ++ +\left( +\begin{matrix} +-x_1 \\ +x_0 \\ +-x_3 \\ +x_2 \\ +\vdots \\ +-x_{d-1} \\ +x_{d-2} +\end{matrix} +\right) +\otimes +\left( +\begin{matrix} +\sin m\theta_0 \\ +\sin m\theta_0 \\ +\sin m\theta_1 \\ +\sin m\theta_1 \\ +\vdots \\ +\sin m\theta_{d/2-1} \\ +\sin m\theta_{d/2-1} \\ +\end{matrix} +\right) +\tag{14} +$$ + +为了节省$cos$/$sin$的存储空间并简化内部的实现逻辑,考虑$q^R*k^R$矩阵乘最终要进行Reduce操作:同时调整行和列中元素的位置,不影响最后的累加结果。最终内部$ROPE$实现的计算调整成公式(15)的形式,对输入$x$按奇偶位置拆分成两部分,对应的$cos$和$sin$部分的输入是连续的。 + +$$ +ROPE(x) = R_{\Theta,m}^{d} x = +\left( +\begin{matrix} +x_0 \\ +x_2 \\ +\vdots \\ +x_{d-2} \\ +x_{1} \\ +x_{3} \\ +\vdots \\ +x_{d-1} +\end{matrix} +\right) +\otimes +\left( +\begin{matrix} +\cos m\theta_0 \\ +\cos m\theta_1 \\ +\vdots \\ +\cos m\theta_{d/2-1} \\ +\cos m\theta_0 \\ +\cos m\theta_1 \\ +\vdots \\ +\cos m\theta_{d/2-1} \\ +\end{matrix} +\right) ++ +\left( +\begin{matrix} +-x_1 \\ +-x_3 \\ +\vdots \\ +-x_{d-1} \\ +x_0 \\ +x_2 \\ +\vdots \\ +x_{d-2} +\end{matrix} +\right) +\otimes +\left( +\begin{matrix} +\sin m\theta_0 \\ +\sin m\theta_1 \\ +\vdots \\ +\sin m\theta_{d/2-1} \\ +\sin m\theta_0 \\ +\sin m\theta_1 \\ +\vdots \\ +\sin m\theta_{d/2-1} \\ +\end{matrix} +\right) +\tag{15} +$$ + +在整个MlaProlog算子中,需要对$q^R$矩阵和$k^R$矩阵执行$ROPE$计算得到最终的$queryRope$和$keyRope$信息,$keyRope$信息最终要更新到$KRCache$中。 + +$$ +q^R = ROPE(q^R) +$$ + +$$ +k^R = ROPE(k^R) +$$ + +### MatmulQn + +对$q^C$矩阵乘上Key的上采样矩阵$W^{UK}$得到最终的Query矩阵$q^N$。 +$$ +q^N = q^C \cdot W^{UK} \tag{16} +$$ + +### KVCache + +在计算得到输入$x$对应的Key/Value结果后,将Key/Value的结果更新到KVCache的对应位置。当前引入cacheIndex来标识计算结果在KVCache中的存储位置。cacheIndex是一个2维的Tensor,shape为[B, S],标识Query中每个Token的目标更新位置。当前KVCache主要支持非PA(Page Attention)场景、PA场景(ND格式存储和NZ格式存储)。 + +PA场景 + +- KVCache 使用 ND 格式存储时,cacheIndex 指定每个 Token 的目标更新行。 + - 假设Query中Token/序列长度为S1,cacheIndex中第二维的某个具体数值代表了本轮计算得到的KVCache要更新到KVCache的第几行;例如,索引值 11 表示要更新到第 11 行的位置。 + +- KVCache 使用 NZ 格式存储时,按块更新缓存。数据分形格式的介绍可以参考官网指南-[数据排布格式](https://www.hiascend.com/document/detail/zh/CANNCommunityEdition/80RC3alpha003/devguide/opdevg/ascendcopdevg/atlas_ascendc_10_0104.html)。 + - 当前按NZ格式存储KVCache时,是将整个Block存储成NZ格式;小块内是以行为主(Row Major)的排布,形状如Z字型;块与块之间是以列为主的排布,形状如N字形。将完整的H(Hidden States)按32B长度的小块进行分块后,在ND格式下连续存储的小块,在NZ格式下需要跳$32B * BlockSize$存储,即需要设置stride为$32B * BlockSize$。 + +### KRCache + +在计算得到输入$x$对应的KeyRope结果后,将KeyRope结果更新到KRCache的对应位置。当前引入cacheIndex来标识计算结果在KRCache中的存储位置。 + +KRCache的更新逻辑同KVCache。 diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/docs/aclnnMlaProlog.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/docs/aclnnMlaProlog.md new file mode 100644 index 0000000000000000000000000000000000000000..f3911ffb45b8ba069ecce9c052e6ed61708b5c48 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/docs/aclnnMlaProlog.md @@ -0,0 +1,1266 @@ +# aclnnMlaProlog + +**须知:该接口后续版本会废弃,请使用最新接口aclnnMlaPrologV3WeightNz。** + +## 产品支持情况 + + +- Ascend 950PR/Ascend 950DT:不支持 + + +- Atlas A3 训练系列产品/Atlas A3 推理系列产品:支持 + + +- Atlas A2 训练系列产品/Atlas A2 推理系列产品:支持 + + +## 功能说明 + +- **接口功能**:推理场景,Multi-Head Latent Attention前处理的计算。主要计算过程分为四路,首先对输入$x$乘以$W^{DQ}$进行下采样和RmsNorm后分为两路,第一路乘以$W^{UQ}$和$W^{UK}$经过两次上采样后得到$q^N$;第二路乘以$W^{QR}$后经过旋转位置编码(ROPE)得到$q^R$;第三路是输入$x$乘以$W^{DKV}$进行下采样和RmsNorm后传入Cache中得到$k^C$;第四路是输入$x$乘以$W^{KR}$后经过旋转位置编码后传入另一个Cache中得到$k^R$。 +- **计算公式**: + + RmsNorm公式 + + $$ + \text{RmsNorm}(x) = \gamma \cdot \frac{x_i}{\text{RMS}(x)} + $$ + + $$ + \text{RMS}(x) = \sqrt{\frac{1}{N} \sum_{i=1}^{N} x_i^2 + \epsilon} + $$ + + Query的计算公式,包括下采样、RmsNorm和两次上采样 + + $$ + c^Q = RmsNorm(x \cdot W^{DQ}) + $$ + + $$ + q^C = c^Q \cdot W^{UQ} + $$ + + $$ + q^N = q^C \cdot W^{UK} + $$ + + 对Query进行ROPE旋转位置编码 + + $$ + q^R = ROPE(c^Q \cdot W^{QR}) + $$ + + Key的计算公式,包括下采样和RmsNorm,将计算结果存入cache + + $$ + c^{KV} = RmsNorm(x \cdot W^{DKV}) + $$ + + $$ + k^C = Cache(c^{KV}) + $$ + + 对Key进行ROPE旋转位置编码,并将结果存入cache + + $$ + k^R = Cache(ROPE(x \cdot W^{KR})) + $$ + +## 函数原型 + +该算子采用两段式接口,必须先调用“aclnnMlaPrologGetWorkspaceSize”接口获取入参并根据流程计算所需workspace大小,再调用“aclnnMlaProlog”接口执行计算。 + +```cpp +aclnnStatus aclnnMlaPrologGetWorkspaceSize( + const aclTensor *tokenX, + const aclTensor *weightDq, + const aclTensor *weightUqQr, + const aclTensor *weightUk, + const aclTensor *weightDkvKr, + const aclTensor *rmsnormGammaCq, + const aclTensor *rmsnormGammaCkv, + const aclTensor *ropeSin, + const aclTensor *ropeCos, + const aclTensor *cacheIndex, + aclTensor *kvCacheRef, + aclTensor *krCacheRef, + const aclTensor *dequantScaleXOptional, + const aclTensor *dequantScaleWDqOptional, + const aclTensor *dequantScaleWUqQrOptional, + const aclTensor *dequantScaleWDkvKrOptional, + const aclTensor *quantScaleCkvOptional, + const aclTensor *quantScaleCkrOptional, + const aclTensor *smoothScalesCqOptional, + double rmsnormEpsilonCq, + double rmsnormEpsilonCkv, + char *cacheModeOptional, + const aclTensor *queryOut, + const aclTensor *queryRopeOut, + uint64_t *workspaceSize, + aclOpExecutor **executor) +``` + +``` cpp +aclnnStatus aclnnMlaProlog( + void *workspace, + uint64_t workspaceSize, + aclOpExecutor *executor, + aclrtStream stream) +``` + +## aclnnMlaPrologGetWorkspaceSize + +- **参数说明** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述使用说明数据类型数据格式维度(shape)非连续Tensor
tokenX输入公式中用于计算Query和Key的输入tensor。 +
    +
  • 支持B=0,S=0,T=0的空Tensor
  • +
+
BFLOAT16ND +
    +
  • BS合轴:(T,He)
  • +
  • BS非合轴:(B,S,He)
  • +
+
×
weightDq输入公式中用于计算Query的下采样权重矩阵 WDQ +
    +
  • 不支持空Tensor
  • +
+
BFLOAT16FRACTAL_NZ(He,Hcq)×
weightUqQr输入公式中用于计算Query的上采样权重矩阵 WUQ 和位置编码权重矩阵 WQR。 +
    +
  • 不支持空Tensor
  • +
  • dtype为INT8(量化场景): +
      +
    • 需为per-tensor量化输入
    • +
    • 非量化输出时必传dequantScaleWUqQrOptional
    • +
    • 量化输出时必传dequantScaleWUqQrOptional、quantScaleCkvOptional、quantScaleCkrOptional
    • +
    • smoothScalesCqOptional可选传
    • +
    +
  • +
  • dtype为BFLOAT16(非量化场景):dequantScaleWUqQrOptional、quantScaleCkvOptional、quantScaleCkrOptional、smoothScalesCqOptional必须传空指针
  • +
+
BFLOAT16、INT8FRACTAL_NZ(Hcq,N*(D+Dr))×
weightUk输入公式中用于计算Key的上采样权重 WUK。 + 不支持空Tensor + BFLOAT16ND(N,D,Hckv)×
weightDkvKr输入公式中用于计算Key的下采样权重矩阵 WDKV 和位置编码权重矩阵 WKR。 + 不支持空Tensor + BFLOAT16FRACTAL_NZ(He,Hckv+Dr)×
rmsnormGammaCq输入计算 cQ 的RmsNorm公式中的 γ 参数。 + 不支持空Tensor + BFLOAT16ND(Hcq)×
rmsnormGammaCkv输入计算 cKV 的RmsNorm公式中的 γ 参数。 + 不支持空Tensor + BFLOAT16ND(Hckv)×
ropeSin输入用于计算旋转位置编码的正弦参数矩阵。 + 支持B=0,S=0,T=0的空Tensor + BFLOAT16ND +
    +
  • BS合轴:(T,Dr)
  • +
  • BS非合轴:(B,S,Dr)
  • +
+
×
ropeCos输入用于计算旋转位置编码的余弦参数矩阵。 + 支持B=0,S=0,T=0的空Tensor + BFLOAT16ND +
    +
  • BS合轴:(T,Dr)
  • +
  • BS非合轴:(B,S,Dr)
  • +
+
×
cacheIndex输入用于存储kvCache和krCache的索引。 +
    +
  • 支持B=0,S=0,T=0的空Tensor
  • +
  • 取值范围需在[0,BlockNum*BlockSize)内
  • +
+
INT64ND +
    +
  • BS合轴:(T)
  • +
  • BS非合轴:(B,S)
  • +
+
×
kvCacheRef输入用于cache索引的aclTensor,计算结果原地更新(对应公式中的 kC)。 +
    +
  • 支持B=0,Skv=0的空Tensor
  • +
  • Nkv与N关联,N是超参,故Nkv不支持等于0
  • +
+
BFLOAT16、INT8ND(BlockNum,BlockSize,Nkv,Hckv)×
krCacheRef输入用于key位置编码的cache,计算结果原地更新(对应公式中的 kR)。 +
    +
  • 支持B=0,Skv=0的空Tensor
  • +
  • Nkv与N关联,N是超参,故Nkv不支持等于0
  • +
+
BFLOAT16、INT8ND(BlockNum,BlockSize,Nkv,Dr)×
dequantScaleXOptional输入tokenX的反量化参数。 + 数据格式支持ND + FLOATND +
    +
  • BS合轴:(T)
  • +
  • BS非合轴:(B*S,1)
  • +
+
×
dequantScaleWDqOptional输入weightDq的反量化参数。 + 数据格式支持ND + FLOATND(1,Hcq)×
dequantScaleWUqQrOptional输入用于MatmulQcQr矩阵乘后反量化操作的per-channel参数。 + 支持非空Tensor(仅INT8 dtype场景需传) + FLOATND(1,N*(D+Dr))×
dequantScaleWDkvKrOptional输入weightDkvKr的反量化参数。 + 数据格式支持ND + FLOATND(1, Hckv+Dr)×
quantScaleCkvOptional输入用于对kvCache输出数据做量化操作的参数。 + 支持非空Tensor(仅INT8 dtype场景需传) + FLOATND(1,Hckv)×
quantScaleCkrOptional输入用于对krCache输出数据做量化操作的参数。 + 支持非空Tensor(仅INT8 dtype场景需传) + FLOATND(1,Dr)×
smoothScalesCqOptional输入用于对RmsNormCq输出做动态量化操作的参数。 + 支持非空Tensor(仅INT8 dtype场景需传) + FLOATND(1,Hcq)×
rmsnormEpsilonCq输入计算 cQ 的RmsNorm公式中的 ε 参数。 +
    +
  • 用户未特意指定时,建议传入1e-05
  • +
  • 仅支持double类型
  • +
+
DOUBLE---
rmsnormEpsilonCkv输入计算 cKV 的RmsNorm公式中的 ε 参数。 +
    +
  • 用户未特意指定时,建议传入1e-05
  • +
  • 仅支持double类型
  • +
+
DOUBLE---
cacheModeOptional输入表示kvCache的模式。 +
    +
  • 用户未特意指定时,建议传入"PA_BSND"
  • +
  • 仅支持char*类型
  • +
  • 可选值为"PA_BSND"、"PA_NZ"
  • +
+
CHAR*---
queryOut输出公式中Query的输出tensor(对应 qN)。-BFLOAT16、INT8ND +
    +
  • BS合轴:(T,N,Hckv)
  • +
  • BS非合轴:(B,S,N,Hckv)
  • +
+
×
queryRopeOut输出公式中Query位置编码的输出tensor(对应 qR)。-BFLOAT16ND +
    +
  • BS合轴:(T,N,Dr)
  • +
  • BS非合轴:(B,S,N,Dr)
  • +
+
×
workspaceSize输出返回需在Device侧申请的workspace大小。 +
    +
  • 仅用于输出结果,无需输入配置
  • +
  • 数据类型为uint64_t*
  • +
+
----
executor输出返回op执行器,包含算子计算流程。 +
    +
  • 仅用于输出结果,无需输入配置
  • +
  • 数据类型为aclOpExecutor**
  • +
+
----
+ +- **返回值** + + aclnnStatus:返回算子的执行状态码。 + + 第一段接口完成入参校验,出现以下场景时报错: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
返回值错误码描述
ACLNN_ERR_PARAM_NULLPTR161001必须传入的参数(如接口核心依赖的输入/输出参数)中存在空指针。
ACLNN_ERR_PARAM_INVALID161002输入参数的shape(维度/尺寸)、dtype(数据类型)不在接口支持的范围内。
ACLNN_ERR_RUNTIME_ERROR361001API内存调用NPU Runtime接口时发生异常(如Runtime服务未启动、内存申请失败等)。
ACLNN_ERR_INNER_TILING_ERROR561002tiling发生异常,入参的dtype类型或者shape错误。
+ +## aclnnMlaProlog + +- **参数说明** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名参数类型含义
workspacevoid*在Device侧申请的workspace内存地址。
workspaceSizeuint64_t在Device侧申请的workspace大小,由第一段接口aclnnMlaPrologGetWorkspaceSize获取。
executoraclOpExecutor*op执行器,包含了算子计算流程。
streamaclrtStream指定执行任务的Stream。
+ +- **返回值** + + aclnnStatus:返回算子的执行状态码。 + +## 约束说明 + +- 确定性计算: + - aclnnMlaProlog默认确定性实现。 + +
+ shape格式字段含义说明 +   + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
字段名英文全称/含义取值规则与说明
BBatch(输入样本批量大小)取值范围:0~65536
SSeq-Length(输入样本序列长度) + 取值范围:不限制 +
HeHidden-Size(隐藏层大小) + 取值固定为:1024、2048、3072、4096、5120、6144、7168、7680、8192 +
Hcqq低秩矩阵维度取值固定为:1536
NHead-Num(多头数)取值范围:1、2、4、8、16、32、64、128
Hckvkv低秩矩阵维度取值固定为:512
Dqk不含位置编码维度取值固定为:128
Drqk位置编码维度取值固定为:64
Nkvkv的head数取值固定为:1
BlockNumPagedAttention场景下的块数取值为计算B*Skv/BlockSize的结果后向上取整 ⌈B*Skv/BlockSize⌉(Skv表示kv的序列长度,允许取0)
BlockSizePagedAttention场景下的块大小取值范围:16~1024,且为16的倍数
TBS合轴后的大小 +
    +
  • 取值范围:0~1048576
  • +
  • 注:若采用BS合轴,此时tokenX、ropeSin、ropeCos均为2维,cacheIndex为1维,queryOut、queryRopeOut为3维
  • +
+
+
+ +
+ 特殊约束 + + - weight_dq,weight_uq_qr,weight_dkv_kr在不转置的情况下各个维度的表示:(k, n)。 + +
+ +
+ aclnnMlaProlog接口支持场景 + + + + + + + + + + + + + + + + + + + +
场景含义
非量化 + 入参:所有入参皆为非量化数据
+ 出参:所有出参皆为非量化数据 +
部分量化kv_cache非量化 + 入参:weightUqQr传入pertoken量化数据,其余入参皆为非量化数据
+ 出参:所有出参返回非量化数据 +
kv_cache量化 + 入参:weightUqQr传入pertoken量化数据,kvCacheRef、krCacheRef传入perchannel量化数据,其余入参皆为非量化数据
+ 出参:kvCacheRef、krCacheRef返回perchannel量化数据,其余出参返回非量化数据 +
+
+ + 不同量化场景参数的dtype与shape约束 + +- 在不同量化场景下,参数的dtype和shape组合需要满足如下条件: +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名非量化场景部分量化场景
kv_cache非量化kv_cache量化
dtypeshapedtypeshapedtypeshape
tokenXBFLOAT16· (B,S,He)
· (T, He)
BFLOAT16· (B,S,He)
· (T, He)
BFLOAT16· (B,S,He)
· (T, He)
weightDqBFLOAT16 (He, Hcq)BFLOAT16 (He, Hcq)BFLOAT16 (He, Hcq)
weightUqQrBFLOAT16 (Hcq, N*(D+Dr))INT8 (Hcq, N*(D+Dr))INT8 (Hcq, N*(D+Dr))
weightUkBFLOAT16 (N, D, Hckv)BFLOAT16 (N, D, Hckv)BFLOAT16 (N, D, Hckv)
weightDkvKrBFLOAT16 (He, Hckv+Dr)BFLOAT16 (He, Hckv+Dr)BFLOAT16 (He, Hckv+Dr)
rmsnormGammaCq BFLOAT16 (Hcq)BFLOAT16 (Hcq)BFLOAT16 (Hcq)
rmsnormGammaCkv BFLOAT16 (Hckv)BFLOAT16 (Hckv)BFLOAT16 (Hckv)
ropeSin BFLOAT16 · (B,S,Dr)
· (T, Dr )
BFLOAT16 · (B,S,Dr)
· (T, Dr )
BFLOAT16 · (B,S,Dr)
· (T, Dr )
ropeCos BFLOAT16 · (B,S,Dr)
· (T, Dr )
BFLOAT16 · (B,S,Dr)
· (T, Dr )
BFLOAT16 · (B,S,Dr)
· (T, Dr )
cacheIndex INT64 · (B,S)
· (T)
INT64 · (B,S)
· (T)
INT64 · (B,S)
· (T)
kvCacheRef BFLOAT16 (BlockNum, BlockSize, Nkv, Hckv)BFLOAT16 (BlockNum, BlockSize, Nkv, Hckv)INT8 (BlockNum, BlockSize, Nkv, Hckv)
krCacheRef BFLOAT16 (BlockNum, BlockSize, Nkv, Dr)BFLOAT16 (BlockNum, BlockSize, Nkv, Dr)INT8 (BlockNum, BlockSize, Nkv, Dr)
dequantScaleXOptional 无需赋值-无需赋值-无需赋值-
dequantScaleWDqOptional 无需赋值-无需赋值-无需赋值-
dequantScaleWUqQrOptional 无需赋值-FLOAT (1, N*(D+Dr)) FLOAT (1, N*(D+Dr))
dequantScaleWDkvKrOptional 无需赋值 - 无需赋值 - 无需赋值 -
quantScaleCkvOptional 无需赋值-无需赋值-FLOAT (1, Hckv)
quantScaleCkrOptional 无需赋值-无需赋值-FLOAT (1, Dr)
smoothScalesCqOptional 无需赋值-FLOAT (1, Hcq) FLOAT (1, Hcq)
queryOut BFLOAT16 · (B, S, N, Hckv)
· (T, N, Hckv)
BFLOAT16 · (B, S, N, Hckv)
· (T, N, Hckv)
BFLOAT16 · (B, S, N, Hckv)
· (T, N, Hckv)
queryRopeOut BFLOAT16 · (B, S, N, Dr)
· (T, N, Dr)
BFLOAT16 · (B, S, N, Dr)
· (T, N, Dr)
BFLOAT16 · (B, S, N, Dr)
· (T, N, Dr)
dequantScaleQNopeOutOptional 无需赋值-无需赋值-无需赋值-
+
+ + + +## 调用示例 + +以下示例代码展示接口调用流程,可供编译和运行时参考。 + + ```Cpp + #include + #include + #include "acl/acl.h" + #include "aclnnop/aclnn_mla_prolog.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 shape_size = 1; + for (auto i : shape) { + shape_size *= i; + } + return shape_size; + } + + 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 CreateAclTensorND(const std::vector& shape, void** deviceAddr, void** hostAddr, + 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); + // 调用aclrtMalloc申请host侧内存 + ret = aclrtMalloc(hostAddr, size, ACL_MEM_MALLOC_HUGE_FIRST); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc 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); + // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 + ret = aclrtMemcpy(*deviceAddr, size, *hostAddr, GetShapeSize(shape)*aclDataTypeSize(dataType), ACL_MEMCPY_HOST_TO_DEVICE); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); + return 0; + } + + template + int CreateAclTensorNZ(const std::vector& shape, void** deviceAddr, void** hostAddr, + 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); + // 调用aclrtMalloc申请host侧内存 + ret = aclrtMalloc(hostAddr, size, ACL_MEM_MALLOC_HUGE_FIRST); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret); + // 调用aclCreateTensor接口创建aclTensor + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_FRACTAL_NZ, + shape.data(), shape.size(), *deviceAddr); + // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 + ret = aclrtMemcpy(*deviceAddr, size, *hostAddr, GetShapeSize(shape)*aclDataTypeSize(dataType), ACL_MEMCPY_HOST_TO_DEVICE); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); + return 0; + } + + int TransToNZShape(std::vector &shapeND) { + int64_t inputParam1 = shapeND[0]; + int64_t inputParam2 = shapeND[1]; + int64_t h0 = 16; + int64_t newParam1 = inputParam2 / h0; + int64_t newParam2 = inputParam1 / h0; + shapeND[0] = newParam1; + shapeND[1] = newParam2; + shapeND.emplace_back(h0); + shapeND.emplace_back(h0); + 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的接口定义构造 + std::vector tokenXShape = {8, 1, 7168}; // B,S,He + std::vector weightDqShape = {7168, 1536}; // He,Hcq + std::vector weightUqQrShape = {1536, 6144}; // Hcq,N*(D+Dr) + std::vector weightUkShape = {32, 128, 512}; // N,D,Hckv + std::vector weightDkvKrShape = {7168, 576}; // He,Hckv+Dr + std::vector rmsnormGammaCqShape = {1536}; // Hcq + std::vector rmsnormGammaCkvShape = {512}; // Hckv + std::vector ropeSinShape = {8, 1, 64}; // B,S,Dr + std::vector ropeCosShape = {8, 1, 64}; // B,S,Dr + std::vector cacheIndexShape = {8, 1}; // B,S + std::vector kvCacheShape = {16, 128, 1, 512}; // BlockNum,BlockSize,Nkv,Hckv + std::vector krCacheShape = {16, 128, 1, 64}; // BlockNum,BlockSize,Nkv,Dr + std::vector queryShape = {8, 1, 32, 512}; // B,S,N,Hckv + std::vector queryRopeShape = {8, 1, 32, 64}; // B,S,N,Dr + double rmsnormEpsilonCq = 1e-5; + double rmsnormEpsilonCkv = 1e-5; + char cacheMode[] = "PA_BSND"; + + void* tokenXDeviceAddr = nullptr; + void* weightDqDeviceAddr = nullptr; + void* weightUqQrDeviceAddr = nullptr; + void* weightUkDeviceAddr = nullptr; + void* weightDkvKrDeviceAddr = nullptr; + void* rmsnormGammaCqDeviceAddr = nullptr; + void* rmsnormGammaCkvDeviceAddr = nullptr; + void* ropeSinDeviceAddr = nullptr; + void* ropeCosDeviceAddr = nullptr; + void* cacheIndexDeviceAddr = nullptr; + void* kvCacheDeviceAddr = nullptr; + void* krCacheDeviceAddr = nullptr; + void* queryDeviceAddr = nullptr; + void* queryRopeDeviceAddr = nullptr; + + void* tokenXHostAddr = nullptr; + void* weightDqHostAddr = nullptr; + void* weightUqQrHostAddr = nullptr; + void* weightUkHostAddr = nullptr; + void* weightDkvKrHostAddr = nullptr; + void* rmsnormGammaCqHostAddr = nullptr; + void* rmsnormGammaCkvHostAddr = nullptr; + void* ropeSinHostAddr = nullptr; + void* ropeCosHostAddr = nullptr; + void* cacheIndexHostAddr = nullptr; + void* kvCacheHostAddr = nullptr; + void* krCacheHostAddr = nullptr; + void* queryHostAddr = nullptr; + void* queryRopeHostAddr = nullptr; + + aclTensor* tokenX = nullptr; + aclTensor* weightDq = nullptr; + aclTensor* weightUqQr = nullptr; + aclTensor* weightUk = nullptr; + aclTensor* weightDkvKr = nullptr; + aclTensor* rmsnormGammaCq = nullptr; + aclTensor* rmsnormGammaCkv = nullptr; + aclTensor* ropeSin = nullptr; + aclTensor* ropeCos = nullptr; + aclTensor* cacheIndex = nullptr; + aclTensor* kvCache = nullptr; + aclTensor* krCache = nullptr; + aclTensor* query = nullptr; + aclTensor* queryRope = nullptr; + + // 转换三个NZ格式变量的shape + ret = TransToNZShape(weightDqShape); + CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret); + ret = TransToNZShape(weightUqQrShape); + CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret); + ret = TransToNZShape(weightDkvKrShape); + CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret); + + // 创建tokenX aclTensor + ret = CreateAclTensorND(tokenXShape, &tokenXDeviceAddr, &tokenXHostAddr, aclDataType::ACL_BF16, &tokenX); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightDq aclTensor + ret = CreateAclTensorNZ(weightDqShape, &weightDqDeviceAddr, &weightDqHostAddr, aclDataType::ACL_BF16, &weightDq); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightUqQr aclTensor + ret = CreateAclTensorNZ(weightUqQrShape, &weightUqQrDeviceAddr, &weightUqQrHostAddr, aclDataType::ACL_BF16, &weightUqQr); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightUk aclTensor + ret = CreateAclTensorND(weightUkShape, &weightUkDeviceAddr, &weightUkHostAddr, aclDataType::ACL_BF16, &weightUk); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightDkvKr aclTensor + ret = CreateAclTensorNZ(weightDkvKrShape, &weightDkvKrDeviceAddr, &weightDkvKrHostAddr, aclDataType::ACL_BF16, &weightDkvKr); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建ropeSin aclTensor + ret = CreateAclTensorND(ropeSinShape, &ropeSinDeviceAddr, &ropeSinHostAddr, aclDataType::ACL_BF16, &ropeSin); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建ropeCos aclTensor + ret = CreateAclTensorND(ropeCosShape, &ropeCosDeviceAddr, &ropeCosHostAddr, aclDataType::ACL_BF16, &ropeCos); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建rmsnormGammaCq aclTensor + ret = CreateAclTensorND(rmsnormGammaCqShape, &rmsnormGammaCqDeviceAddr, &rmsnormGammaCqHostAddr, aclDataType::ACL_BF16, &rmsnormGammaCq); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建rmsnormGammaCkv aclTensor + ret = CreateAclTensorND(rmsnormGammaCkvShape, &rmsnormGammaCkvDeviceAddr, &rmsnormGammaCkvHostAddr, aclDataType::ACL_BF16, &rmsnormGammaCkv); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建cacheIndex aclTensor + ret = CreateAclTensorND(cacheIndexShape, &cacheIndexDeviceAddr, &cacheIndexHostAddr, aclDataType::ACL_INT64, &cacheIndex); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建kvCache aclTensor + ret = CreateAclTensorND(kvCacheShape, &kvCacheDeviceAddr, &kvCacheHostAddr, aclDataType::ACL_BF16, &kvCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建krCache aclTensor + ret = CreateAclTensorND(krCacheShape, &krCacheDeviceAddr, &krCacheHostAddr, aclDataType::ACL_BF16, &krCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建query aclTensor + ret = CreateAclTensorND(queryShape, &queryDeviceAddr, &queryHostAddr, aclDataType::ACL_BF16, &query); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建queryRope aclTensor + ret = CreateAclTensorND(queryRopeShape, &queryRopeDeviceAddr, &queryRopeHostAddr, aclDataType::ACL_BF16, &queryRope); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3. 调用CANN算子库API,需要修改为具体的API + uint64_t workspaceSize = 0; + aclOpExecutor* executor = nullptr; + // 调用aclnnMlaProlog第一段接口 + ret = aclnnMlaPrologGetWorkspaceSize(tokenX, weightDq, weightUqQr, weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv, ropeSin, ropeCos, cacheIndex, kvCache, krCache, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, rmsnormEpsilonCq, rmsnormEpsilonCkv, cacheMode, query, queryRope, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologGetWorkspaceSize 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;); + } + // 调用aclnnMlaProlog第二段接口 + ret = aclnnMlaProlog(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaProlog 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(queryShape); + std::vector resultData(size, 0); + ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), queryDeviceAddr, size * sizeof(float), + 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); + + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(tokenX); + aclDestroyTensor(weightDq); + aclDestroyTensor(weightUqQr); + aclDestroyTensor(weightUk); + aclDestroyTensor(weightDkvKr); + aclDestroyTensor(rmsnormGammaCq); + aclDestroyTensor(rmsnormGammaCkv); + aclDestroyTensor(ropeSin); + aclDestroyTensor(ropeCos); + aclDestroyTensor(cacheIndex); + aclDestroyTensor(kvCache); + aclDestroyTensor(krCache); + aclDestroyTensor(query); + aclDestroyTensor(queryRope); + + // 7. 释放device资源 + aclrtFree(tokenXDeviceAddr); + aclrtFree(weightDqDeviceAddr); + aclrtFree(weightUqQrDeviceAddr); + aclrtFree(weightUkDeviceAddr); + aclrtFree(weightDkvKrDeviceAddr); + aclrtFree(rmsnormGammaCqDeviceAddr); + aclrtFree(rmsnormGammaCkvDeviceAddr); + aclrtFree(ropeSinDeviceAddr); + aclrtFree(ropeCosDeviceAddr); + aclrtFree(cacheIndexDeviceAddr); + aclrtFree(kvCacheDeviceAddr); + aclrtFree(krCacheDeviceAddr); + aclrtFree(queryDeviceAddr); + aclrtFree(queryRopeDeviceAddr); + + // 8. 释放host资源 + aclrtFree(tokenXHostAddr); + aclrtFree(weightDqHostAddr); + aclrtFree(weightUqQrHostAddr); + aclrtFree(weightUkHostAddr); + aclrtFree(weightDkvKrHostAddr); + aclrtFree(rmsnormGammaCqHostAddr); + aclrtFree(rmsnormGammaCkvHostAddr); + aclrtFree(ropeSinHostAddr); + aclrtFree(ropeCosHostAddr); + aclrtFree(cacheIndexHostAddr); + aclrtFree(kvCacheHostAddr); + aclrtFree(krCacheHostAddr); + aclrtFree(queryHostAddr); + aclrtFree(queryRopeHostAddr); + + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; + } + ``` diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/examples/test_aclnn_mla_prolog.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/examples/test_aclnn_mla_prolog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..543f82cd87ff2f6b914679c5489fcb66143a7ab2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/examples/test_aclnn_mla_prolog.cpp @@ -0,0 +1,321 @@ +/** + * 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_mla_prolog_nq_bsh.cpp + * \brief + */ + +#include +#include +#include +#include "acl/acl.h" +#include "aclnnop/aclnn_mla_prolog.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 shape_size = 1; + for (auto i : shape) { + shape_size *= i; + } + return shape_size; +} + +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 CreateAclTensorND(const std::vector& shape, void** deviceAddr, void** hostAddr, + 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); + // 调用aclrtMallocHost申请host侧内存 + ret = aclrtMallocHost(hostAddr, size); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMallocHost failed. ERROR: %d\n", ret); return ret); + memset(*hostAddr, 0, size); + // 调用aclCreateTensor接口创建aclTensor + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND, + shape.data(), shape.size(), *deviceAddr); + // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 + ret = aclrtMemcpy(*deviceAddr, size, *hostAddr, size, ACL_MEMCPY_HOST_TO_DEVICE); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); + return 0; +} + +template +int CreateAclTensorNZ(const std::vector& shape, void** deviceAddr, void** hostAddr, + 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); + // 调用aclrtMallocHost申请host侧内存 + ret = aclrtMallocHost(hostAddr, size); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMallocHost failed. ERROR: %d\n", ret); return ret); + memset(*hostAddr, 0, size); + // 调用aclCreateTensor接口创建aclTensor + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_FRACTAL_NZ, + shape.data(), shape.size(), *deviceAddr); + // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 + ret = aclrtMemcpy(*deviceAddr, size, *hostAddr, size, ACL_MEMCPY_HOST_TO_DEVICE); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); + return 0; +} + +int TransToNZShape(std::vector &shapeND, size_t typeSize) { + if (typeSize == static_cast(0)) { + return 0; + } + int64_t h = shapeND[0]; + int64_t w = shapeND[1]; + int64_t h0 = static_cast(16); + int64_t w0 = static_cast(32) / static_cast(typeSize); + int64_t h1 = h / h0; + int64_t w1 = w / w0; + shapeND[0] = w1; + shapeND[1] = h1; + shapeND.emplace_back(h0); + shapeND.emplace_back(w0); + 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的接口定义构造 + std::vector tokenXShape = {8, 1, 7168}; // B,S,He + std::vector weightDqShape = {7168, 1536}; // He,Hcq + std::vector weightUqQrShape = {1536, 6144}; // Hcq,N*(D+Dr) + std::vector weightUkShape = {32, 128, 512}; // N,D,Hckv + std::vector weightDkvKrShape = {7168, 576}; // He,Hckv+Dr + std::vector rmsnormGammaCqShape = {1536}; // Hcq + std::vector rmsnormGammaCkvShape = {512}; // Hckv + std::vector ropeSinShape = {8, 1, 64}; // B,S,Dr + std::vector ropeCosShape = {8, 1, 64}; // B,S,Dr + std::vector cacheIndexShape = {8, 1}; // B,S + std::vector kvCacheShape = {16, 128, 1, 512}; // BolckNum,BlockSize,Nkv,Hckv + std::vector krCacheShape = {16, 128, 1, 64}; // BolckNum,BlockSize,Nkv,Dr + std::vector queryShape = {8, 1, 32, 512}; // B,S,N,Hckv + std::vector queryRopeShape = {8, 1, 32, 64}; // B,S,N,Dr + double rmsnormEpsilonCq = 1e-5; + double rmsnormEpsilonCkv = 1e-5; + char cacheMode[] = "PA_BSND"; + + void* tokenXDeviceAddr = nullptr; + void* weightDqDeviceAddr = nullptr; + void* weightUqQrDeviceAddr = nullptr; + void* weightUkDeviceAddr = nullptr; + void* weightDkvKrDeviceAddr = nullptr; + void* rmsnormGammaCqDeviceAddr = nullptr; + void* rmsnormGammaCkvDeviceAddr = nullptr; + void* ropeSinDeviceAddr = nullptr; + void* ropeCosDeviceAddr = nullptr; + void* cacheIndexDeviceAddr = nullptr; + void* kvCacheDeviceAddr = nullptr; + void* krCacheDeviceAddr = nullptr; + void* queryDeviceAddr = nullptr; + void* queryRopeDeviceAddr = nullptr; + + void* tokenXHostAddr = nullptr; + void* weightDqHostAddr = nullptr; + void* weightUqQrHostAddr = nullptr; + void* weightUkHostAddr = nullptr; + void* weightDkvKrHostAddr = nullptr; + void* rmsnormGammaCqHostAddr = nullptr; + void* rmsnormGammaCkvHostAddr = nullptr; + void* ropeSinHostAddr = nullptr; + void* ropeCosHostAddr = nullptr; + void* cacheIndexHostAddr = nullptr; + void* kvCacheHostAddr = nullptr; + void* krCacheHostAddr = nullptr; + void* queryHostAddr = nullptr; + void* queryRopeHostAddr = nullptr; + + aclTensor* tokenX = nullptr; + aclTensor* weightDq = nullptr; + aclTensor* weightUqQr = nullptr; + aclTensor* weightUk = nullptr; + aclTensor* weightDkvKr = nullptr; + aclTensor* rmsnormGammaCq = nullptr; + aclTensor* rmsnormGammaCkv = nullptr; + aclTensor* ropeSin = nullptr; + aclTensor* ropeCos = nullptr; + aclTensor* cacheIndex = nullptr; + aclTensor* kvCache = nullptr; + aclTensor* krCache = nullptr; + aclTensor* query = nullptr; + aclTensor* queryRope = nullptr; + + // 转换三个NZ格式变量的shape + constexpr size_t EXAMPLE_INT8_SIZE = sizeof(int8_t); + constexpr size_t EXAMPLE_BFLOAT16_SIZE = sizeof(int16_t); + ret = TransToNZShape(weightDqShape, EXAMPLE_BFLOAT16_SIZE); + CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret); + ret = TransToNZShape(weightUqQrShape, EXAMPLE_BFLOAT16_SIZE); + CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret); + ret = TransToNZShape(weightDkvKrShape, EXAMPLE_BFLOAT16_SIZE); + CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret); + + // 创建tokenX aclTensor + ret = CreateAclTensorND(tokenXShape, &tokenXDeviceAddr, &tokenXHostAddr, aclDataType::ACL_BF16, &tokenX); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightDq aclTensor + ret = CreateAclTensorNZ(weightDqShape, &weightDqDeviceAddr, &weightDqHostAddr, aclDataType::ACL_BF16, &weightDq); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightUqQr aclTensor + ret = CreateAclTensorNZ(weightUqQrShape, &weightUqQrDeviceAddr, &weightUqQrHostAddr, aclDataType::ACL_BF16, &weightUqQr); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightUk aclTensor + ret = CreateAclTensorND(weightUkShape, &weightUkDeviceAddr, &weightUkHostAddr, aclDataType::ACL_BF16, &weightUk); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightDkvKr aclTensor + ret = CreateAclTensorNZ(weightDkvKrShape, &weightDkvKrDeviceAddr, &weightDkvKrHostAddr, aclDataType::ACL_BF16, &weightDkvKr); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建ropeSin aclTensor + ret = CreateAclTensorND(ropeSinShape, &ropeSinDeviceAddr, &ropeSinHostAddr, aclDataType::ACL_BF16, &ropeSin); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建ropeCos aclTensor + ret = CreateAclTensorND(ropeCosShape, &ropeCosDeviceAddr, &ropeCosHostAddr, aclDataType::ACL_BF16, &ropeCos); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建rmsnormGammaCq aclTensor + ret = CreateAclTensorND(rmsnormGammaCqShape, &rmsnormGammaCqDeviceAddr, &rmsnormGammaCqHostAddr, aclDataType::ACL_BF16, &rmsnormGammaCq); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建rmsnormGammaCkv aclTensor + ret = CreateAclTensorND(rmsnormGammaCkvShape, &rmsnormGammaCkvDeviceAddr, &rmsnormGammaCkvHostAddr, aclDataType::ACL_BF16, &rmsnormGammaCkv); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建cacheIndex aclTensor + ret = CreateAclTensorND(cacheIndexShape, &cacheIndexDeviceAddr, &cacheIndexHostAddr, aclDataType::ACL_INT64, &cacheIndex); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建kvCache aclTensor + ret = CreateAclTensorND(kvCacheShape, &kvCacheDeviceAddr, &kvCacheHostAddr, aclDataType::ACL_BF16, &kvCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建krCache aclTensor + ret = CreateAclTensorND(krCacheShape, &krCacheDeviceAddr, &krCacheHostAddr, aclDataType::ACL_BF16, &krCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建query aclTensor + ret = CreateAclTensorND(queryShape, &queryDeviceAddr, &queryHostAddr, aclDataType::ACL_BF16, &query); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建queryRope aclTensor + ret = CreateAclTensorND(queryRopeShape, &queryRopeDeviceAddr, &queryRopeHostAddr, aclDataType::ACL_BF16, &queryRope); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3. 调用CANN算子库API,需要修改为具体的API + uint64_t workspaceSize = 0; + aclOpExecutor* executor = nullptr; + // 调用aclnnMlaProlog第一段接口 + ret = aclnnMlaPrologGetWorkspaceSize(tokenX, weightDq, weightUqQr, weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv, ropeSin, ropeCos, cacheIndex, kvCache, krCache, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, rmsnormEpsilonCq, rmsnormEpsilonCkv, cacheMode, query, queryRope, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologGetWorkspaceSize failed. ERROR: %d\n", ret); return ret); + // 根据第一段接口计算出的workspaceSize申请device内存 + void* workspaceAddr = nullptr; + if (workspaceSize > static_cast(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;); + } + // 调用aclnnMlaProlog第二段接口 + ret = aclnnMlaProlog(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaProlog 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(queryShape); + auto copySize = size * aclDataTypeSize(aclDataType::ACL_BF16); + std::vector resultData(size, 0); + ret = aclrtMemcpy(resultData.data(), copySize, queryDeviceAddr, copySize, + 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: %u\n", i, resultData[i]); + } + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(tokenX); + aclDestroyTensor(weightDq); + aclDestroyTensor(weightUqQr); + aclDestroyTensor(weightUk); + aclDestroyTensor(weightDkvKr); + aclDestroyTensor(rmsnormGammaCq); + aclDestroyTensor(rmsnormGammaCkv); + aclDestroyTensor(ropeSin); + aclDestroyTensor(ropeCos); + aclDestroyTensor(cacheIndex); + aclDestroyTensor(kvCache); + aclDestroyTensor(krCache); + aclDestroyTensor(query); + aclDestroyTensor(queryRope); + + // 7. 释放device侧资源 + aclrtFree(tokenXDeviceAddr); + aclrtFree(weightDqDeviceAddr); + aclrtFree(weightUqQrDeviceAddr); + aclrtFree(weightUkDeviceAddr); + aclrtFree(weightDkvKrDeviceAddr); + aclrtFree(rmsnormGammaCqDeviceAddr); + aclrtFree(rmsnormGammaCkvDeviceAddr); + aclrtFree(ropeSinDeviceAddr); + aclrtFree(ropeCosDeviceAddr); + aclrtFree(cacheIndexDeviceAddr); + aclrtFree(kvCacheDeviceAddr); + aclrtFree(krCacheDeviceAddr); + aclrtFree(queryDeviceAddr); + aclrtFree(queryRopeDeviceAddr); + + // 8. 释放host侧资源 + aclrtFreeHost(tokenXHostAddr); + aclrtFreeHost(weightDqHostAddr); + aclrtFreeHost(weightUqQrHostAddr); + aclrtFreeHost(weightUkHostAddr); + aclrtFreeHost(weightDkvKrHostAddr); + aclrtFreeHost(rmsnormGammaCqHostAddr); + aclrtFreeHost(rmsnormGammaCkvHostAddr); + aclrtFreeHost(ropeSinHostAddr); + aclrtFreeHost(ropeCosHostAddr); + aclrtFreeHost(cacheIndexHostAddr); + aclrtFreeHost(kvCacheHostAddr); + aclrtFreeHost(krCacheHostAddr); + aclrtFreeHost(queryHostAddr); + aclrtFreeHost(queryRopeHostAddr); + + if (workspaceSize > static_cast(0)) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/examples/test_aclnn_mla_prolog_nq_bsh.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/examples/test_aclnn_mla_prolog_nq_bsh.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f7f5bcfddec31a1ee208663cdca656d4a65f2ae --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/examples/test_aclnn_mla_prolog_nq_bsh.cpp @@ -0,0 +1,321 @@ +/** + * 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_mla_prolog_nq_bsh.cpp + * \brief + */ + +#include +#include +#include +#include "acl/acl.h" +#include "aclnnop/aclnn_mla_prolog.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 shape_size = 1; + for (auto i : shape) { + shape_size *= i; + } + return shape_size; +} + +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 CreateAclTensorND(const std::vector& shape, void** deviceAddr, void** hostAddr, + 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); + // 调用aclrtMallocHost申请host侧内存 + ret = aclrtMallocHost(hostAddr, size); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMallocHost failed. ERROR: %d\n", ret); return ret); + memset(*hostAddr, 0, size); + // 调用aclCreateTensor接口创建aclTensor + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND, + shape.data(), shape.size(), *deviceAddr); + // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 + ret = aclrtMemcpy(*deviceAddr, size, *hostAddr, size, ACL_MEMCPY_HOST_TO_DEVICE); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); + return 0; +} + +template +int CreateAclTensorNZ(const std::vector& shape, void** deviceAddr, void** hostAddr, + 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); + // 调用aclrtMallocHost申请host侧内存 + ret = aclrtMallocHost(hostAddr, size); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMallocHost failed. ERROR: %d\n", ret); return ret); + memset(*hostAddr, 0, size); + // 调用aclCreateTensor接口创建aclTensor + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_FRACTAL_NZ, + shape.data(), shape.size(), *deviceAddr); + // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 + ret = aclrtMemcpy(*deviceAddr, size, *hostAddr, size, ACL_MEMCPY_HOST_TO_DEVICE); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); + return 0; +} + +int TransToNZShape(std::vector &shapeND, size_t typeSize) { + if (typeSize == static_cast(0)) { + return 0; + } + int64_t h = shapeND[0]; + int64_t w = shapeND[1]; + int64_t h0 = static_cast(16); + int64_t w0 = static_cast(32) / static_cast(typeSize); + int64_t h1 = h / h0; + int64_t w1 = w / w0; + shapeND[0] = w1; + shapeND[1] = h1; + shapeND.emplace_back(h0); + shapeND.emplace_back(w0); + 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的接口定义构造 + std::vector tokenXShape = {8, 1, 7168}; // B,S,He + std::vector weightDqShape = {7168, 1536}; // He,Hcq + std::vector weightUqQrShape = {1536, 6144}; // Hcq,N*(D+Dr) + std::vector weightUkShape = {32, 128, 512}; // N,D,Hckv + std::vector weightDkvKrShape = {7168, 576}; // He,Hckv+Dr + std::vector rmsnormGammaCqShape = {1536}; // Hcq + std::vector rmsnormGammaCkvShape = {512}; // Hckv + std::vector ropeSinShape = {8, 1, 64}; // B,S,Dr + std::vector ropeCosShape = {8, 1, 64}; // B,S,Dr + std::vector cacheIndexShape = {8, 1}; // B,S + std::vector kvCacheShape = {16, 128, 1, 512}; // BolckNum,BlockSize,Nkv,Hckv + std::vector krCacheShape = {16, 128, 1, 64}; // BolckNum,BlockSize,Nkv,Dr + std::vector queryShape = {8, 1, 32, 512}; // B,S,N,Hckv + std::vector queryRopeShape = {8, 1, 32, 64}; // B,S,N,Dr + double rmsnormEpsilonCq = 1e-5; + double rmsnormEpsilonCkv = 1e-5; + char cacheMode[] = "PA_BSND"; + + void* tokenXDeviceAddr = nullptr; + void* weightDqDeviceAddr = nullptr; + void* weightUqQrDeviceAddr = nullptr; + void* weightUkDeviceAddr = nullptr; + void* weightDkvKrDeviceAddr = nullptr; + void* rmsnormGammaCqDeviceAddr = nullptr; + void* rmsnormGammaCkvDeviceAddr = nullptr; + void* ropeSinDeviceAddr = nullptr; + void* ropeCosDeviceAddr = nullptr; + void* cacheIndexDeviceAddr = nullptr; + void* kvCacheDeviceAddr = nullptr; + void* krCacheDeviceAddr = nullptr; + void* queryDeviceAddr = nullptr; + void* queryRopeDeviceAddr = nullptr; + + void* tokenXHostAddr = nullptr; + void* weightDqHostAddr = nullptr; + void* weightUqQrHostAddr = nullptr; + void* weightUkHostAddr = nullptr; + void* weightDkvKrHostAddr = nullptr; + void* rmsnormGammaCqHostAddr = nullptr; + void* rmsnormGammaCkvHostAddr = nullptr; + void* ropeSinHostAddr = nullptr; + void* ropeCosHostAddr = nullptr; + void* cacheIndexHostAddr = nullptr; + void* kvCacheHostAddr = nullptr; + void* krCacheHostAddr = nullptr; + void* queryHostAddr = nullptr; + void* queryRopeHostAddr = nullptr; + + aclTensor* tokenX = nullptr; + aclTensor* weightDq = nullptr; + aclTensor* weightUqQr = nullptr; + aclTensor* weightUk = nullptr; + aclTensor* weightDkvKr = nullptr; + aclTensor* rmsnormGammaCq = nullptr; + aclTensor* rmsnormGammaCkv = nullptr; + aclTensor* ropeSin = nullptr; + aclTensor* ropeCos = nullptr; + aclTensor* cacheIndex = nullptr; + aclTensor* kvCache = nullptr; + aclTensor* krCache = nullptr; + aclTensor* query = nullptr; + aclTensor* queryRope = nullptr; + + // 转换三个NZ格式变量的shape + constexpr size_t EXAMPLE_INT8_SIZE = sizeof(int8_t); + constexpr size_t EXAMPLE_BFLOAT16_SIZE = sizeof(int16_t); + ret = TransToNZShape(weightDqShape, EXAMPLE_BFLOAT16_SIZE); + CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret); + ret = TransToNZShape(weightUqQrShape, EXAMPLE_BFLOAT16_SIZE); + CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret); + ret = TransToNZShape(weightDkvKrShape, EXAMPLE_BFLOAT16_SIZE); + CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret); + + // 创建tokenX aclTensor + ret = CreateAclTensorND(tokenXShape, &tokenXDeviceAddr, &tokenXHostAddr, aclDataType::ACL_BF16, &tokenX); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightDq aclTensor + ret = CreateAclTensorNZ(weightDqShape, &weightDqDeviceAddr, &weightDqHostAddr, aclDataType::ACL_BF16, &weightDq); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightUqQr aclTensor + ret = CreateAclTensorNZ(weightUqQrShape, &weightUqQrDeviceAddr, &weightUqQrHostAddr, aclDataType::ACL_BF16, &weightUqQr); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightUk aclTensor + ret = CreateAclTensorND(weightUkShape, &weightUkDeviceAddr, &weightUkHostAddr, aclDataType::ACL_BF16, &weightUk); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightDkvKr aclTensor + ret = CreateAclTensorNZ(weightDkvKrShape, &weightDkvKrDeviceAddr, &weightDkvKrHostAddr, aclDataType::ACL_BF16, &weightDkvKr); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建ropeSin aclTensor + ret = CreateAclTensorND(ropeSinShape, &ropeSinDeviceAddr, &ropeSinHostAddr, aclDataType::ACL_BF16, &ropeSin); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建ropeCos aclTensor + ret = CreateAclTensorND(ropeCosShape, &ropeCosDeviceAddr, &ropeCosHostAddr, aclDataType::ACL_BF16, &ropeCos); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建rmsnormGammaCq aclTensor + ret = CreateAclTensorND(rmsnormGammaCqShape, &rmsnormGammaCqDeviceAddr, &rmsnormGammaCqHostAddr, aclDataType::ACL_BF16, &rmsnormGammaCq); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建rmsnormGammaCkv aclTensor + ret = CreateAclTensorND(rmsnormGammaCkvShape, &rmsnormGammaCkvDeviceAddr, &rmsnormGammaCkvHostAddr, aclDataType::ACL_BF16, &rmsnormGammaCkv); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建cacheIndex aclTensor + ret = CreateAclTensorND(cacheIndexShape, &cacheIndexDeviceAddr, &cacheIndexHostAddr, aclDataType::ACL_INT64, &cacheIndex); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建kvCache aclTensor + ret = CreateAclTensorND(kvCacheShape, &kvCacheDeviceAddr, &kvCacheHostAddr, aclDataType::ACL_BF16, &kvCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建krCache aclTensor + ret = CreateAclTensorND(krCacheShape, &krCacheDeviceAddr, &krCacheHostAddr, aclDataType::ACL_BF16, &krCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建query aclTensor + ret = CreateAclTensorND(queryShape, &queryDeviceAddr, &queryHostAddr, aclDataType::ACL_BF16, &query); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建queryRope aclTensor + ret = CreateAclTensorND(queryRopeShape, &queryRopeDeviceAddr, &queryRopeHostAddr, aclDataType::ACL_BF16, &queryRope); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3. 调用CANN算子库API,需要修改为具体的API + uint64_t workspaceSize = 0; + aclOpExecutor* executor = nullptr; + // 调用aclnnMlaProlog第一段接口 + ret = aclnnMlaPrologGetWorkspaceSize(tokenX, weightDq, weightUqQr, weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv, ropeSin, ropeCos, cacheIndex, kvCache, krCache, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, rmsnormEpsilonCq, rmsnormEpsilonCkv, cacheMode, query, queryRope, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologGetWorkspaceSize failed. ERROR: %d\n", ret); return ret); + // 根据第一段接口计算出的workspaceSize申请device内存 + void* workspaceAddr = nullptr; + if (workspaceSize > static_cast(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;); + } + // 调用aclnnMlaProlog第二段接口 + ret = aclnnMlaProlog(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaProlog 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(queryShape); + auto copySize = size * aclDataTypeSize(aclDataType::ACL_BF16); + std::vector resultData(size, 0); + ret = aclrtMemcpy(resultData.data(), copySize, queryDeviceAddr, copySize, + 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: %u\n", i, resultData[i]); + } + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(tokenX); + aclDestroyTensor(weightDq); + aclDestroyTensor(weightUqQr); + aclDestroyTensor(weightUk); + aclDestroyTensor(weightDkvKr); + aclDestroyTensor(rmsnormGammaCq); + aclDestroyTensor(rmsnormGammaCkv); + aclDestroyTensor(ropeSin); + aclDestroyTensor(ropeCos); + aclDestroyTensor(cacheIndex); + aclDestroyTensor(kvCache); + aclDestroyTensor(krCache); + aclDestroyTensor(query); + aclDestroyTensor(queryRope); + + // 7. 释放device 资源 + aclrtFree(tokenXDeviceAddr); + aclrtFree(weightDqDeviceAddr); + aclrtFree(weightUqQrDeviceAddr); + aclrtFree(weightUkDeviceAddr); + aclrtFree(weightDkvKrDeviceAddr); + aclrtFree(rmsnormGammaCqDeviceAddr); + aclrtFree(rmsnormGammaCkvDeviceAddr); + aclrtFree(ropeSinDeviceAddr); + aclrtFree(ropeCosDeviceAddr); + aclrtFree(cacheIndexDeviceAddr); + aclrtFree(kvCacheDeviceAddr); + aclrtFree(krCacheDeviceAddr); + aclrtFree(queryDeviceAddr); + aclrtFree(queryRopeDeviceAddr); + + // 8. 释放host 资源 + aclrtFreeHost(tokenXHostAddr); + aclrtFreeHost(weightDqHostAddr); + aclrtFreeHost(weightUqQrHostAddr); + aclrtFreeHost(weightUkHostAddr); + aclrtFreeHost(weightDkvKrHostAddr); + aclrtFreeHost(rmsnormGammaCqHostAddr); + aclrtFreeHost(rmsnormGammaCkvHostAddr); + aclrtFreeHost(ropeSinHostAddr); + aclrtFreeHost(ropeCosHostAddr); + aclrtFreeHost(cacheIndexHostAddr); + aclrtFreeHost(kvCacheHostAddr); + aclrtFreeHost(krCacheHostAddr); + aclrtFreeHost(queryHostAddr); + aclrtFreeHost(queryRopeHostAddr); + + if (workspaceSize > static_cast(0)) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/examples/test_aclnn_mla_prolog_pq.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/examples/test_aclnn_mla_prolog_pq.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1fbb5920e8142f3b5486222f4cc4ecff966848c9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/examples/test_aclnn_mla_prolog_pq.cpp @@ -0,0 +1,362 @@ +/** + * 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_mla_prolog_pq.cpp + * \brief Example: 部分量化场景 (partial quant with INT8 quantized output) + */ + +#include +#include +#include +#include "acl/acl.h" +#include "aclnnop/aclnn_mla_prolog.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 shape_size = 1; + for (auto i : shape) { + shape_size *= i; + } + return shape_size; +} + +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 CreateAclTensorND(const std::vector& shape, void** deviceAddr, void** hostAddr, + 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); + // 调用aclrtMallocHost申请host侧内存 + ret = aclrtMallocHost(hostAddr, size); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMallocHost failed. ERROR: %d\n", ret); return ret); + memset(*hostAddr, 0, size); + // 调用aclCreateTensor接口创建aclTensor + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND, + shape.data(), shape.size(), *deviceAddr); + // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 + ret = aclrtMemcpy(*deviceAddr, size, *hostAddr, size, ACL_MEMCPY_HOST_TO_DEVICE); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); + return 0; +} + +template +int CreateAclTensorNZ(const std::vector& shape, void** deviceAddr, void** hostAddr, + 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); + // 调用aclrtMallocHost申请host侧内存 + ret = aclrtMallocHost(hostAddr, size); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMallocHost failed. ERROR: %d\n", ret); return ret); + memset(*hostAddr, 0, size); + // 调用aclCreateTensor接口创建aclTensor + *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_FRACTAL_NZ, + shape.data(), shape.size(), *deviceAddr); + // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 + ret = aclrtMemcpy(*deviceAddr, size, *hostAddr, size, ACL_MEMCPY_HOST_TO_DEVICE); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret); + return 0; +} + +int TransToNZShape(std::vector &shapeND, size_t typeSize) { + if (typeSize == static_cast(0)) { + return 0; + } + int64_t h = shapeND[0]; + int64_t w = shapeND[1]; + int64_t h0 = static_cast(16); + int64_t w0 = static_cast(32) / static_cast(typeSize); + int64_t h1 = h / h0; + int64_t w1 = w / w0; + shapeND[0] = w1; + shapeND[1] = h1; + shapeND.emplace_back(h0); + shapeND.emplace_back(w0); + 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的接口定义构造 + std::vector tokenXShape = {8, 1, 7168}; // B,S,He + std::vector weightDqShape = {7168, 1536}; // He,Hcq + std::vector weightUqQrShape = {1536, 6144}; // Hcq,N*(D+Dr) + std::vector weightUkShape = {32, 128, 512}; // N,D,Hckv + std::vector weightDkvKrShape = {7168, 576}; // He,Hckv+Dr + std::vector rmsnormGammaCqShape = {1536}; // Hcq + std::vector rmsnormGammaCkvShape = {512}; // Hckv + std::vector ropeSinShape = {8, 1, 64}; // B,S,Dr + std::vector ropeCosShape = {8, 1, 64}; // B,S,Dr + std::vector cacheIndexShape = {8, 1}; // B,S + std::vector kvCacheShape = {16, 128, 1, 512}; // BolckNum,BlockSize,Nkv,Hckv + std::vector krCacheShape = {16, 128, 1, 64}; // BolckNum,BlockSize,Nkv,Dr + std::vector queryShape = {8, 1, 32, 512}; // B,S,N,Hckv + std::vector queryRopeShape = {8, 1, 32, 64}; // B,S,N,Dr + std::vector dequantScaleWUqQrShape = {1, 6144}; // 1, N*(D+Dr) + std::vector quantScaleCkvShape = {1, 512}; // 1, Hckv + std::vector quantScaleCkrShape = {1, 64}; // 1, Dr + std::vector smoothScalesCqShape = {1, 1536}; // 1, Hcq + double rmsnormEpsilonCq = 1e-5; + double rmsnormEpsilonCkv = 1e-5; + char cacheMode[] = "PA_BSND"; + + void* tokenXDeviceAddr = nullptr; + void* weightDqDeviceAddr = nullptr; + void* weightUqQrDeviceAddr = nullptr; + void* weightUkDeviceAddr = nullptr; + void* weightDkvKrDeviceAddr = nullptr; + void* rmsnormGammaCqDeviceAddr = nullptr; + void* rmsnormGammaCkvDeviceAddr = nullptr; + void* ropeSinDeviceAddr = nullptr; + void* ropeCosDeviceAddr = nullptr; + void* cacheIndexDeviceAddr = nullptr; + void* kvCacheDeviceAddr = nullptr; + void* krCacheDeviceAddr = nullptr; + void* queryDeviceAddr = nullptr; + void* queryRopeDeviceAddr = nullptr; + void* dequantScaleWUqQrDeviceAddr = nullptr; + void* quantScaleCkvDeviceAddr = nullptr; + void* quantScaleCkrDeviceAddr = nullptr; + void* smoothScalesCqDeviceAddr = nullptr; + + void* tokenXHostAddr = nullptr; + void* weightDqHostAddr = nullptr; + void* weightUqQrHostAddr = nullptr; + void* weightUkHostAddr = nullptr; + void* weightDkvKrHostAddr = nullptr; + void* rmsnormGammaCqHostAddr = nullptr; + void* rmsnormGammaCkvHostAddr = nullptr; + void* ropeSinHostAddr = nullptr; + void* ropeCosHostAddr = nullptr; + void* cacheIndexHostAddr = nullptr; + void* kvCacheHostAddr = nullptr; + void* krCacheHostAddr = nullptr; + void* queryHostAddr = nullptr; + void* queryRopeHostAddr = nullptr; + void* dequantScaleWUqQrHostAddr = nullptr; + void* quantScaleCkvHostAddr = nullptr; + void* quantScaleCkrHostAddr = nullptr; + void* smoothScalesCqHostAddr = nullptr; + + aclTensor* tokenX = nullptr; + aclTensor* weightDq = nullptr; + aclTensor* weightUqQr = nullptr; + aclTensor* weightUk = nullptr; + aclTensor* weightDkvKr = nullptr; + aclTensor* rmsnormGammaCq = nullptr; + aclTensor* rmsnormGammaCkv = nullptr; + aclTensor* ropeSin = nullptr; + aclTensor* ropeCos = nullptr; + aclTensor* cacheIndex = nullptr; + aclTensor* kvCache = nullptr; + aclTensor* krCache = nullptr; + aclTensor* query = nullptr; + aclTensor* queryRope = nullptr; + aclTensor* dequantScaleWUqQr = nullptr; + aclTensor* quantScaleCkv = nullptr; + aclTensor* quantScaleCkr = nullptr; + aclTensor* smoothScalesCq = nullptr; + + // 转换三个NZ格式变量的shape + constexpr size_t EXAMPLE_INT8_SIZE = sizeof(int8_t); + constexpr size_t EXAMPLE_BFLOAT16_SIZE = sizeof(int16_t); + ret = TransToNZShape(weightDqShape, EXAMPLE_BFLOAT16_SIZE); + CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret); + ret = TransToNZShape(weightUqQrShape, EXAMPLE_INT8_SIZE); + CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret); + ret = TransToNZShape(weightDkvKrShape, EXAMPLE_BFLOAT16_SIZE); + CHECK_RET(ret == 0, LOG_PRINT("trans NZ shape failed.\n"); return ret); + + // 创建tokenX aclTensor + ret = CreateAclTensorND(tokenXShape, &tokenXDeviceAddr, &tokenXHostAddr, aclDataType::ACL_BF16, &tokenX); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightDq aclTensor + ret = CreateAclTensorNZ(weightDqShape, &weightDqDeviceAddr, &weightDqHostAddr, aclDataType::ACL_BF16, &weightDq); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightUqQr aclTensor + ret = CreateAclTensorNZ(weightUqQrShape, &weightUqQrDeviceAddr, &weightUqQrHostAddr, aclDataType::ACL_INT8, &weightUqQr); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightUk aclTensor + ret = CreateAclTensorND(weightUkShape, &weightUkDeviceAddr, &weightUkHostAddr, aclDataType::ACL_BF16, &weightUk); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建weightDkvKr aclTensor + ret = CreateAclTensorNZ(weightDkvKrShape, &weightDkvKrDeviceAddr, &weightDkvKrHostAddr, aclDataType::ACL_BF16, &weightDkvKr); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建ropeSin aclTensor + ret = CreateAclTensorND(ropeSinShape, &ropeSinDeviceAddr, &ropeSinHostAddr, aclDataType::ACL_BF16, &ropeSin); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建ropeCos aclTensor + ret = CreateAclTensorND(ropeCosShape, &ropeCosDeviceAddr, &ropeCosHostAddr, aclDataType::ACL_BF16, &ropeCos); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建rmsnormGammaCq aclTensor + ret = CreateAclTensorND(rmsnormGammaCqShape, &rmsnormGammaCqDeviceAddr, &rmsnormGammaCqHostAddr, aclDataType::ACL_BF16, &rmsnormGammaCq); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建rmsnormGammaCkv aclTensor + ret = CreateAclTensorND(rmsnormGammaCkvShape, &rmsnormGammaCkvDeviceAddr, &rmsnormGammaCkvHostAddr, aclDataType::ACL_BF16, &rmsnormGammaCkv); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建cacheIndex aclTensor + ret = CreateAclTensorND(cacheIndexShape, &cacheIndexDeviceAddr, &cacheIndexHostAddr, aclDataType::ACL_INT64, &cacheIndex); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建kvCache aclTensor + ret = CreateAclTensorND(kvCacheShape, &kvCacheDeviceAddr, &kvCacheHostAddr, aclDataType::ACL_INT8, &kvCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建krCache aclTensor + ret = CreateAclTensorND(krCacheShape, &krCacheDeviceAddr, &krCacheHostAddr, aclDataType::ACL_INT8, &krCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建query aclTensor + ret = CreateAclTensorND(queryShape, &queryDeviceAddr, &queryHostAddr, aclDataType::ACL_BF16, &query); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建queryRope aclTensor + ret = CreateAclTensorND(queryRopeShape, &queryRopeDeviceAddr, &queryRopeHostAddr, aclDataType::ACL_BF16, &queryRope); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建dequantScaleWUqQr aclTensor + ret = CreateAclTensorND(dequantScaleWUqQrShape, &dequantScaleWUqQrDeviceAddr, &dequantScaleWUqQrHostAddr, aclDataType::ACL_FLOAT, &dequantScaleWUqQr); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建quantScaleCkv aclTensor + ret = CreateAclTensorND(quantScaleCkvShape, &quantScaleCkvDeviceAddr, &quantScaleCkvHostAddr, aclDataType::ACL_FLOAT, &quantScaleCkv); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建quantScaleCkr aclTensor + ret = CreateAclTensorND(quantScaleCkrShape, &quantScaleCkrDeviceAddr, &quantScaleCkrHostAddr, aclDataType::ACL_FLOAT, &quantScaleCkr); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建smoothScalesCq aclTensor + ret = CreateAclTensorND(smoothScalesCqShape, &smoothScalesCqDeviceAddr, &smoothScalesCqHostAddr, aclDataType::ACL_FLOAT, &smoothScalesCq); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3. 调用CANN算子库API,需要修改为具体的API + uint64_t workspaceSize = 0; + aclOpExecutor* executor = nullptr; + // 调用aclnnMlaProlog第一段接口 + ret = aclnnMlaPrologGetWorkspaceSize(tokenX, weightDq, weightUqQr, weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv, ropeSin, ropeCos, cacheIndex, kvCache, krCache, + nullptr, nullptr, dequantScaleWUqQr, nullptr, quantScaleCkv, quantScaleCkr, smoothScalesCq, + rmsnormEpsilonCq, rmsnormEpsilonCkv, cacheMode, query, queryRope, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaPrologGetWorkspaceSize failed. ERROR: %d\n", ret); return ret); + // 根据第一段接口计算出的workspaceSize申请device内存 + void* workspaceAddr = nullptr; + if (workspaceSize > static_cast(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;); + } + // 调用aclnnMlaProlog第二段接口 + ret = aclnnMlaProlog(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMlaProlog 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(queryShape); + auto copySize = size * aclDataTypeSize(aclDataType::ACL_BF16); + std::vector resultData(size, 0); + ret = aclrtMemcpy(resultData.data(), copySize, queryDeviceAddr, copySize, 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: %u\n", i, resultData[i]); + } + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(tokenX); + aclDestroyTensor(weightDq); + aclDestroyTensor(weightUqQr); + aclDestroyTensor(weightUk); + aclDestroyTensor(weightDkvKr); + aclDestroyTensor(rmsnormGammaCq); + aclDestroyTensor(rmsnormGammaCkv); + aclDestroyTensor(ropeSin); + aclDestroyTensor(ropeCos); + aclDestroyTensor(cacheIndex); + aclDestroyTensor(kvCache); + aclDestroyTensor(krCache); + aclDestroyTensor(query); + aclDestroyTensor(queryRope); + aclDestroyTensor(dequantScaleWUqQr); + aclDestroyTensor(quantScaleCkv); + aclDestroyTensor(quantScaleCkr); + aclDestroyTensor(smoothScalesCq); + + // 7. 释放device侧资源 + aclrtFree(tokenXDeviceAddr); + aclrtFree(weightDqDeviceAddr); + aclrtFree(weightUqQrDeviceAddr); + aclrtFree(weightUkDeviceAddr); + aclrtFree(weightDkvKrDeviceAddr); + aclrtFree(rmsnormGammaCqDeviceAddr); + aclrtFree(rmsnormGammaCkvDeviceAddr); + aclrtFree(ropeSinDeviceAddr); + aclrtFree(ropeCosDeviceAddr); + aclrtFree(cacheIndexDeviceAddr); + aclrtFree(kvCacheDeviceAddr); + aclrtFree(krCacheDeviceAddr); + aclrtFree(queryDeviceAddr); + aclrtFree(queryRopeDeviceAddr); + aclrtFree(dequantScaleWUqQrDeviceAddr); + aclrtFree(quantScaleCkvDeviceAddr); + aclrtFree(quantScaleCkrDeviceAddr); + aclrtFree(smoothScalesCqDeviceAddr); + + // 8. 释放host侧资源 + aclrtFreeHost(tokenXHostAddr); + aclrtFreeHost(weightDqHostAddr); + aclrtFreeHost(weightUqQrHostAddr); + aclrtFreeHost(weightUkHostAddr); + aclrtFreeHost(weightDkvKrHostAddr); + aclrtFreeHost(rmsnormGammaCqHostAddr); + aclrtFreeHost(rmsnormGammaCkvHostAddr); + aclrtFreeHost(ropeSinHostAddr); + aclrtFreeHost(ropeCosHostAddr); + aclrtFreeHost(cacheIndexHostAddr); + aclrtFreeHost(kvCacheHostAddr); + aclrtFreeHost(krCacheHostAddr); + aclrtFreeHost(queryHostAddr); + aclrtFreeHost(queryRopeHostAddr); + aclrtFreeHost(dequantScaleWUqQrHostAddr); + aclrtFreeHost(quantScaleCkvHostAddr); + aclrtFreeHost(quantScaleCkrHostAddr); + aclrtFreeHost(smoothScalesCqHostAddr); + + if (workspaceSize > static_cast(0)) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/mla_prolog_collect.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/mla_prolog_collect.py new file mode 100644 index 0000000000000000000000000000000000000000..053bf160ed1f9378f55bfc4174ab94adc00dea0d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/mla_prolog_collect.py @@ -0,0 +1,302 @@ +#!/usr/bin/env python3 +"""Collect golden data for mla_prolog 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/mla_prolog_def.cpp + docs/aclnnMlaProlog.md + README.md +(parameter/constraint tables). MLA "prolog": compute query (q^N), rope-rotated query +(q^R) and write k^C / k^R into two paged caches, given token_x and weight matrices. + + Non-quantized BF16 path (all computation tensors BF16, cache_index INT64): + token_x (B,S,He) | (T,He) BF16 input activations + weight_dq (He,Hcq) BF16 W^DQ (FRACTAL_NZ, passed as logical ND) + weight_uq_qr (Hcq,N*(D+Dr)) BF16 W^UQ + W^QR (fused) + weight_uk (N,D,Hckv) BF16 W^UK + weight_dkv_kr (He,Hckv+Dr) BF16 W^DKV + W^KR (fused) + rmsnorm_gamma_cq (Hcq,) BF16 + rmsnorm_gamma_ckv (Hckv,) BF16 + rope_sin / rope_cos (B,S,Dr) | (T,Dr) BF16 + cache_index (B,S) | (T) INT64 slot indices in [0, BlockNum*BlockSize) + kv_cache (BlockNum,BlockSize,1,Hckv) BF16 in-place: written through (k^C) + kr_cache (BlockNum,BlockSize,1,Dr) BF16 in-place: written through (k^R) + 7 optional dequant/quant/smooth scales -> None (non-quantized) + + attrs: rmsnorm_epsilon_cq (double, default 1e-5), rmsnorm_epsilon_ckv (double, 1e-5), + cache_mode (str; doc-valid values "PA_BSND"/"PA_NZ", recommended "PA_BSND" — used here). + + outputs (OpDef order): + query (B,S,N,Hckv) | (T,N,Hckv) BF16 buffered template 0 (q^N) + query_rope (B,S,N,Dr) | (T,N,Dr) BF16 buffered template 1 (q^R) + kv_cache / kr_cache in-place (inputs written through) + +CONSTRAINTS (from docs): He in {1024..8192 step 1024}, Hcq=1536 fixed, N in {1,2,4,8,16, + 32,64,128}, Hckv=512 fixed, D=128 fixed, Dr=64 fixed, Nkv=1 fixed, BlockSize in + [16,1024] multiple of 16, BlockNum=ceil(T/BlockSize), cache_index in [0,BlockNum*BlockSize). + DynamicFormatFlag(true) -> ND weight tensors are auto-converted to FRACTAL_NZ. + +CALL (binding.py wrapper, op_def order; no op_host/op_api so the aclnn call uses op_host +order, which matches the aclnnMlaProlog signature): 19 inputs then 3 attrs, then the +trailing out_tmpls buffer list (2 buffers, OpDef output order: query, query_rope). + token_x, weight_dq, weight_uq_qr, weight_uk, weight_dkv_kr, rmsnorm_gamma_cq, + rmsnorm_gamma_ckv, rope_sin, rope_cos, cache_index, kv_cache, kr_cache, + dequant_scale_x, dequant_scale_w_dq, dequant_scale_w_uq_qr, dequant_scale_w_dkv_kr, + quant_scale_ckv, quant_scale_ckr, smooth_scales_cq, + rmsnorm_epsilon_cq, rmsnorm_epsilon_ckv, cache_mode +Returns tuple (query, query_rope, kv_cache, kr_cache). kv_cache/kr_cache are the same +in-place input tensors, written through by the kernel. + +# case_0: BF16 BS B1 S1 N4 BlockSize16 (tiny, single token) +# case_1: BF16 T-fused T2 N2 BlockSize16 (2D token_x + 1D cache_index rank variant) +# case_2: BF16 BS B1 S4 N8 BlockSize32 +# case_3: BF16 BS B2 S1 N4 BlockSize64 +# case_4: BF16 BS B1 S8 N16 BlockSize32 +# case_5: BF16 BS B2 S4 N8 BlockSize32 +# case_6: BF16 BS B2 S2 N2 BlockSize16 (min heads) +# case_7: BF16 BS B4 S4 T16 N4 BlockSize16 (full block, 16 slots) +# case_8: BF16 BS B2 S16 T32 N16 BlockSize16 (multi-block: BlockNum=2) +# case_9: BF16 BS B3 S3 T9 N8 BlockSize64 +""" +import inspect +import json +import os +import sys + +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +# Allow creating FRACTAL_NZ (internal format) tensors via npu_format_cast — otherwise the +# weight tensors declared FORMAT_FRACTAL_NZ stay ND and aclnnMlaProlog rejects them. +torch_npu.npu.config.allow_internal_format = True + +OP_NAME = "mla_prolog" +OP_CAMEL = "MlaProlog" +DEVICE = "npu:0" +SEED = 202601 +HE = 1024 # hidden size (smallest allowed) +HCQ = 1536 # q low-rank dim (fixed) +HCKV = 512 # kv low-rank dim (fixed) +D = 128 # qk dim without rope (fixed) +DR = 64 # rope dim (fixed) +NKV = 1 # kv heads (fixed) + +# Positional order of the generated wrapper (binding.py), op_def order: inputs then attrs, +# excluding the trailing out_tmpls buffer list. +PARAM_NAMES = [ + "token_x", "weight_dq", "weight_uq_qr", "weight_uk", "weight_dkv_kr", + "rmsnorm_gamma_cq", "rmsnorm_gamma_ckv", "rope_sin", "rope_cos", "cache_index", + "kv_cache", "kr_cache", + "dequant_scale_x", "dequant_scale_w_dq", "dequant_scale_w_uq_qr", + "dequant_scale_w_dkv_kr", "quant_scale_ckv", "quant_scale_ckr", "smooth_scales_cq", + "rmsnorm_epsilon_cq", "rmsnorm_epsilon_ckv", "cache_mode", +] +OUTPUT_KEYS = ["query", "query_rope", "kv_cache", "kr_cache"] + + +def _cache_index(B, S, T, BlockNum, BlockSize): + """Distinct slot indices in [0, BlockNum*BlockSize) for the (B,S) | (T) tokens.""" + idx = torch.arange(T, dtype=torch.int64, device=DEVICE) + if B and S: + return idx.view(B, S) + return idx # T layout: 1-D + + +def make_inputs(case): + g = torch.Generator(device=DEVICE) + g.manual_seed(SEED + case["id"]) + dt = torch.bfloat16 + B, S, N = case["B"], case["S"], case["N"] + fused = case.get("fused", False) + T = B * S if not fused else case["T"] + BlockSize = case["bsz"] + BlockNum = max(1, -(-T // BlockSize)) # ceil(T/BlockSize), >=1 so cache non-empty + + # token_x / rope: (B,S,...) or (T,...) + if fused: + token_x = (torch.randn((T, HE), generator=g, device=DEVICE) * 0.1).to(dt) + rope_sin = (torch.randn((T, DR), generator=g, device=DEVICE) * 0.1).to(dt) + rope_cos = (torch.randn((T, DR), generator=g, device=DEVICE) * 0.1).to(dt) + cache_index = _cache_index(0, 0, T, BlockNum, BlockSize) + else: + token_x = (torch.randn((B, S, HE), generator=g, device=DEVICE) * 0.1).to(dt) + rope_sin = (torch.randn((B, S, DR), generator=g, device=DEVICE) * 0.1).to(dt) + rope_cos = (torch.randn((B, S, DR), generator=g, device=DEVICE) * 0.1).to(dt) + cache_index = _cache_index(B, S, T, BlockNum, BlockSize) + + # weights: dq / uq_qr / dkv_kr are declared FORMAT_FRACTAL_NZ in the OpDef, so they + # must be cast to NZ storage (format 29 = FRACTAL_NZ) while keeping the logical ND + # shape (matches official mla_prolog_v2 pytest). weight_uk stays ND. + weight_dq = (torch.randn((HE, HCQ), generator=g, device=DEVICE) * 0.05).to(dt) + weight_dq = torch_npu.npu_format_cast(weight_dq.contiguous(), 29) + weight_uq_qr = (torch.randn((HCQ, N * (D + DR)), generator=g, device=DEVICE) * 0.05).to(dt) + weight_uq_qr = torch_npu.npu_format_cast(weight_uq_qr.contiguous(), 29) + weight_uk = (torch.randn((N, D, HCKV), generator=g, device=DEVICE) * 0.05).to(dt) + weight_dkv_kr = (torch.randn((HE, HCKV + DR), generator=g, device=DEVICE) * 0.05).to(dt) + weight_dkv_kr = torch_npu.npu_format_cast(weight_dkv_kr.contiguous(), 29) + + # rmsnorm gamma = ones (identity scaling) + rmsnorm_gamma_cq = torch.ones((HCQ,), dtype=dt, device=DEVICE) + rmsnorm_gamma_ckv = torch.ones((HCKV,), dtype=dt, device=DEVICE) + + # paged caches (in-place), zero-init for determinism of unwritten slots + kv_cache = torch.zeros((BlockNum, BlockSize, NKV, HCKV), dtype=dt, device=DEVICE) + kr_cache = torch.zeros((BlockNum, BlockSize, NKV, DR), dtype=dt, device=DEVICE) + + return { + "token_x": token_x, + "weight_dq": weight_dq, + "weight_uq_qr": weight_uq_qr, + "weight_uk": weight_uk, + "weight_dkv_kr": weight_dkv_kr, + "rmsnorm_gamma_cq": rmsnorm_gamma_cq, + "rmsnorm_gamma_ckv": rmsnorm_gamma_ckv, + "rope_sin": rope_sin, + "rope_cos": rope_cos, + "cache_index": cache_index, + "kv_cache": kv_cache, + "kr_cache": kr_cache, + "dequant_scale_x": None, # non-quantized: must be null + "dequant_scale_w_dq": None, + "dequant_scale_w_uq_qr": None, + "dequant_scale_w_dkv_kr": None, + "quant_scale_ckv": None, + "quant_scale_ckr": None, + "smooth_scales_cq": None, + "rmsnorm_epsilon_cq": 1e-5, + "rmsnorm_epsilon_ckv": 1e-5, + "cache_mode": "PA_BSND", + } + + +def make_output_bufs(case): + """Two buffered template outputs (OpDef output order): query, query_rope.""" + dt = torch.bfloat16 + B, S, N = case["B"], case["S"], case["N"] + if case.get("fused", False): + T = case["T"] + query = torch.zeros((T, N, HCKV), dtype=dt, device=DEVICE) + query_rope = torch.zeros((T, N, DR), dtype=dt, device=DEVICE) + else: + query = torch.zeros((B, S, N, HCKV), dtype=dt, device=DEVICE) + query_rope = torch.zeros((B, S, N, DR), dtype=dt, device=DEVICE) + return [query, query_rope] + + +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 inputs BEFORE the call — kv_cache / kr_cache are in-place outputs and the + # kernel writes through them, so the saved golden_input must be the pre-call tensors. + saved_in = {k: (v.cpu() if isinstance(v, torch.Tensor) else v) for k, v in inputs.items()} + + outputs = ops.npu_mla_prolog(*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 + + 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_mla_prolog).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": 1, "S": 1, "N": 4, "bsz": 16, "fused": False}, + {"id": 1, "B": 1, "S": 1, "T": 2, "N": 2, "bsz": 16, "fused": True}, + {"id": 2, "B": 1, "S": 4, "N": 8, "bsz": 32, "fused": False}, + {"id": 3, "B": 2, "S": 1, "N": 4, "bsz": 64, "fused": False}, + {"id": 4, "B": 1, "S": 8, "N": 16, "bsz": 32, "fused": False}, + {"id": 5, "B": 2, "S": 4, "N": 8, "bsz": 32, "fused": False}, + {"id": 6, "B": 2, "S": 2, "N": 2, "bsz": 16, "fused": False}, + {"id": 7, "B": 4, "S": 4, "N": 4, "bsz": 16, "fused": False}, + {"id": 8, "B": 2, "S": 16, "N": 16, "bsz": 16, "fused": False}, + {"id": 9, "B": 3, "S": 3, "N": 8, "bsz": 64, "fused": 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_mla_prolog.__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"], + "shape": [case["B"], case["S"], case["N"], HCKV], + "attrs": {k: v for k, v in case.items() if k not in ("id", "B", "S")}, + }) + 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/mla_prolog/mla_prolog_test.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/mla_prolog_test.py new file mode 100644 index 0000000000000000000000000000000000000000..a2540f8b0d5869a894c7a3f6629ca652ee0116b3 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/mla_prolog_test.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Regression test: NPU mla_prolog 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 prolog operator (non-quantized BF16 path). All four outputs +(query, query_rope, kv_cache, kr_cache) are replayed from the same NPU kernel, so an exact +match is expected. kv_cache / kr_cache are in-place outputs: the test passes the saved +pre-call cache tensors in and compares the written-through result. query / query_rope are +buffered template outputs (2-list out_tmpls). +""" +import json +import os +import sys + +import numpy as np +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +# Re-create FRACTAL_NZ (internal format) tensors via npu_format_cast for the NZ-declared +# weights; allow_internal_format must be on or the cast falls back to ND. +torch_npu.npu.config.allow_internal_format = True + +OP_NAME = "mla_prolog" +OP_CAMEL = "MlaProlog" +DEVICE = "npu:0" + +# Positional order of the generated wrapper (binding.py), op_def order, excluding the +# trailing out_tmpls buffer list. +PARAM_NAMES = [ + "token_x", "weight_dq", "weight_uq_qr", "weight_uk", "weight_dkv_kr", + "rmsnorm_gamma_cq", "rmsnorm_gamma_ckv", "rope_sin", "rope_cos", "cache_index", + "kv_cache", "kr_cache", + "dequant_scale_x", "dequant_scale_w_dq", "dequant_scale_w_uq_qr", + "dequant_scale_w_dkv_kr", "quant_scale_ckv", "quant_scale_ckr", "smooth_scales_cq", + "rmsnorm_epsilon_cq", "rmsnorm_epsilon_ckv", "cache_mode", +] +OUTPUT_KEYS = ["query", "query_rope", "kv_cache", "kr_cache"] + +# These OpDef inputs are declared FORMAT_FRACTAL_NZ. torch.save / .cpu() do not persist the +# NPU format, so after loading from golden_input they come back as ND — re-apply the NZ cast +# (format 29) before the call, matching how they were passed at collection time. +NZ_WEIGHTS = {"weight_dq", "weight_uq_qr", "weight_dkv_kr"} + +# All outputs are direct BF16 kernel results stored in BF16 — no float32 intermediates here. +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) + + 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): + t = val.to(DEVICE) + if pname in NZ_WEIGHTS: + t = torch_npu.npu_format_cast(t.contiguous(), 29) + call_kwargs[pname] = t + else: + call_kwargs[pname] = val + + # Zero-init the two template output buffers (OpDef output order: query, query_rope) — + # deterministic unwritten slots, matching collect. kv_cache / kr_cache are passed in as + # in-place inputs and written through by the kernel. + out_bufs = [ + torch.zeros_like(golden["query"]).to(DEVICE), + torch.zeros_like(golden["query_rope"]).to(DEVICE), + ] + + positional = [call_kwargs[p] for p in PARAM_NAMES] + [out_bufs] + outputs = ops.npu_mla_prolog(*positional) + torch.npu.synchronize() + + outputs = [outputs] if isinstance(outputs, torch.Tensor) else list(outputs) + input_dtype = input_data["token_x"].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/mla_prolog/op_api/aclnn_mla_prolog.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_api/aclnn_mla_prolog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..30dd025da7dc2a3eacef5f78834227ebaf740a60 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_api/aclnn_mla_prolog.cpp @@ -0,0 +1,95 @@ +/** + * 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 "graph/types.h" +#include "aclnn_mla_prolog.h" +#include "opdev/platform.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 aclnnInnerMlaPrologGetWorkspaceSize( + const aclTensor *tokenX, const aclTensor *weightDq, const aclTensor *weightUqQr, const aclTensor *weightUk, + const aclTensor *weightDkvKr, const aclTensor *rmsnormGammaCq, const aclTensor *rmsnormGammaCkv, + const aclTensor *ropeSin, const aclTensor *ropeCos, const aclTensor *cacheIndex, aclTensor *kvCacheRef, + aclTensor *krCacheRef, const aclTensor *dequantScaleXOptional, const aclTensor *dequantScaleWDqOptional, + const aclTensor *dequantScaleWUqQrOptional, const aclTensor *dequantScaleWDkvKrOptional, + const aclTensor *quantScaleCkvOptional, const aclTensor *quantScaleCkrOptional, + const aclTensor *smoothScalesCqOptional, double rmsnormEpsilonCq, double rmsnormEpsilonCkv, char *cacheModeOptional, + const aclTensor *queryOut, const aclTensor *queryRopeOut, uint64_t *workspaceSize, aclOpExecutor **executor); + +extern aclnnStatus aclnnInnerMlaProlog(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + aclrtStream stream); + +aclnnStatus aclnnMlaPrologGetWorkspaceSize( + const aclTensor *tokenX, const aclTensor *weightDq, const aclTensor *weightUqQr, const aclTensor *weightUk, + const aclTensor *weightDkvKr, const aclTensor *rmsnormGammaCq, const aclTensor *rmsnormGammaCkv, + const aclTensor *ropeSin, const aclTensor *ropeCos, const aclTensor *cacheIndex, aclTensor *kvCacheRef, + aclTensor *krCacheRef, const aclTensor *dequantScaleXOptional, const aclTensor *dequantScaleWDqOptional, + const aclTensor *dequantScaleWUqQrOptional, const aclTensor *dequantScaleWDkvKrOptional, + const aclTensor *quantScaleCkvOptional, const aclTensor *quantScaleCkrOptional, + const aclTensor *smoothScalesCqOptional, double rmsnormEpsilonCq, double rmsnormEpsilonCkv, char *cacheModeOptional, + const aclTensor *queryOut, const aclTensor *queryRopeOut, uint64_t *workspaceSize, aclOpExecutor **executor) +{ + if (op::GetCurrentPlatformInfo().GetCurNpuArch() == NpuArch::DAV_3510) { + OP_LOGE(ACLNN_ERR_RUNTIME_ERROR, "Interface aclnnMlaPrologGetWorkspaceSize " + "are no longer supported on Ascend950."); + return ACLNN_ERR_RUNTIME_ERROR; + } + static bool isFirstCall = true; + if (isFirstCall) { + OP_LOGW("aclnnMlaPrologGetWorkspaceSize is scheduled to be deprecated in December 2026, " + "and will be replaced by the aclnnMlaPrologV3GetWorkspaceSize. " + "We apologize for any inconvenience caused and appreciate your timely migration to the new interface."); + isFirstCall = false; + } + return aclnnInnerMlaPrologGetWorkspaceSize( + tokenX, weightDq, weightUqQr, weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv, ropeSin, ropeCos, + cacheIndex, kvCacheRef, krCacheRef, dequantScaleXOptional, dequantScaleWDqOptional, dequantScaleWUqQrOptional, + dequantScaleWDkvKrOptional, quantScaleCkvOptional, quantScaleCkrOptional, smoothScalesCqOptional, + rmsnormEpsilonCq, rmsnormEpsilonCkv, cacheModeOptional, queryOut, queryRopeOut, workspaceSize, executor); +} + +aclnnStatus aclnnMlaProlog(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, aclrtStream stream) +{ + if (op::GetCurrentPlatformInfo().GetCurNpuArch() == NpuArch::DAV_3510) { + OP_LOGE(ACLNN_ERR_RUNTIME_ERROR, "Interface aclnnMlaProlog are no longer supported on Ascend950."); + return ACLNN_ERR_RUNTIME_ERROR; + } + static bool isFirstCall = true; + if (isFirstCall) { + OP_LOGW("aclnnMlaProlog is scheduled to be deprecated in December 2026, " + "and will be replaced by the aclnnMlaPrologV3WeightNz. " + "We apologize for any inconvenience caused and appreciate your timely migration to the new interface."); + isFirstCall = false; + } + return aclnnInnerMlaProlog(workspace, workspaceSize, executor, stream); +} + +} // namespace + +#ifdef __cplusplus +} +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_api/aclnn_mla_prolog.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_api/aclnn_mla_prolog.h new file mode 100644 index 0000000000000000000000000000000000000000..6f9f83cb253ed41120ee626ad540b9d07cd7913d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_api/aclnn_mla_prolog.h @@ -0,0 +1,60 @@ +/** + * 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 ACLNN_MLA_PROLOG +#define ACLNN_MLA_PROLOG +#warning "aclnn_mla_prolog.h is scheduled to be deprecated in December 2026, " \ + "and will be replaced by the aclnn_mla_prolog_v3_weight_nz.h. " \ + "We apologize for any inconvenience caused " \ + "and appreciate your timely migration to the new interface. " +#include "aclnn/acl_meta.h" +#include "aclnn/aclnn_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief The first interface of aclnnMlaProlog calculates the workspace size based on the specific calculation process. + * @domain aclnn_ops_infer + */ +__attribute__((deprecated("aclnnMlaPrologGetWorkspaceSize is scheduled to be deprecated " + "in December 2026, and will be replaced by the " + "aclnnMlaPrologV3WeightNzGetWorkspaceSize. " + "We apologize for any inconvenience caused " + "and appreciate your timely migration to the new interface. "))) +__attribute__((visibility("default"))) aclnnStatus +aclnnMlaPrologGetWorkspaceSize(const aclTensor *tokenX, const aclTensor *weightDq, const aclTensor *weightUqQr, + const aclTensor *weightUk, const aclTensor *weightDkvKr, const aclTensor *rmsnormGammaCq, + const aclTensor *rmsnormGammaCkv, const aclTensor *ropeSin, const aclTensor *ropeCos, + const aclTensor *cacheIndex, aclTensor *kvCacheRef, aclTensor *krCacheRef, + const aclTensor *dequantScaleXOptional, const aclTensor *dequantScaleWDqOptional, + const aclTensor *dequantScaleWUqQrOptional, const aclTensor *dequantScaleWDkvKrOptional, + const aclTensor *quantScaleCkvOptional, const aclTensor *quantScaleCkrOptional, + const aclTensor *smoothScalesCqOptional, double rmsnormEpsilonCq, + double rmsnormEpsilonCkv, char *cacheModeOptional, const aclTensor *queryOut, + const aclTensor *queryRopeOut, uint64_t *workspaceSize, aclOpExecutor **executor); + +/** + * @brief The second interface of aclnnMlaProlog is used to perform calculations. + */ +__attribute__((deprecated("aclnnMlaProlog is scheduled to be deprecated in December 2026, " + "and will be replaced by the aclnnMlaPrologV3WeightNz. " + "We apologize for any inconvenience caused " + "and appreciate your timely migration to the new interface. "))) +__attribute__((visibility("default"))) aclnnStatus +aclnnMlaProlog(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, aclrtStream stream); + + +#ifdef __cplusplus +} +#endif + +#endif // ACLNN_MLA_PROLOG diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_graph/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_graph/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..23300ec165082a60e0ed64c9ad5ccbe85410c1e1 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/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. +# ----------------------------------------------------------------------------------------------------------- +if (BUILD_OPEN_PROJECT AND NOT BUILD_OPS_RTY_KERNEL) + add_graph_plugin_sources() +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_graph/fallback_mla_prolog.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_graph/fallback_mla_prolog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93fa52e3fbbdb211e59417d96ebd36fbae2bd2fe --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_graph/fallback_mla_prolog.cpp @@ -0,0 +1,138 @@ +/** + * 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 "fallback_mla_prolog.h" + +#ifdef __cplusplus +extern "C" { +#endif +namespace fallback { + +using namespace ge; +using namespace gert; + +graphStatus GetMlaPrologInputTensor(const OpExecuteContext *ctx, MlaPrologFallBackParam ¶m) +{ + param.tokenX = ctx->GetRequiredInputTensor(TOKEN_X_INDEX); + OP_CHECK_IF(param.tokenX == nullptr, OP_LOGE("aclnnfallback", "tokenX is null"), return GRAPH_FAILED); + + param.weightDq = ctx->GetRequiredInputTensor(WEIGHT_DQ_INDEX); + OP_CHECK_IF(param.weightDq == nullptr, OP_LOGE("aclnnfallback", "weightDq is null"), return GRAPH_FAILED); + + param.weightUqQr = ctx->GetRequiredInputTensor(WEIGHT_UQ_QR_INDEX); + OP_CHECK_IF(param.weightUqQr == nullptr, OP_LOGE("aclnnfallback", "weightUqQr is null"), return GRAPH_FAILED); + + param.weightUk = ctx->GetRequiredInputTensor(WEIGHT_UK_INDEX); + OP_CHECK_IF(param.weightUk == nullptr, OP_LOGE("aclnnfallback", "weightUk is null"), return GRAPH_FAILED); + + param.weightDkvKr = ctx->GetRequiredInputTensor(WEIGHT_DKV_KR_INDEX); + OP_CHECK_IF(param.weightDkvKr == nullptr, OP_LOGE("aclnnfallback", "weightDkvKr is null"), return GRAPH_FAILED); + + param.rmsnormGammaCq = ctx->GetRequiredInputTensor(RMSNORM_GAMMA_CQ_INDEX); + OP_CHECK_IF(param.rmsnormGammaCq == nullptr, OP_LOGE("aclnnfallback", "rmsnormGammaCq is null"), + return GRAPH_FAILED); + + param.rmsnormGammaCkv = ctx->GetRequiredInputTensor(RMSNORM_GAMMA_CKV_INDEX); + OP_CHECK_IF(param.rmsnormGammaCkv == nullptr, OP_LOGE("aclnnfallback", "rmsnormGammaCkv is null"), + return GRAPH_FAILED); + + param.ropeSin = ctx->GetRequiredInputTensor(ROPE_SIN_INDEX); + OP_CHECK_IF(param.ropeSin == nullptr, OP_LOGE("aclnnfallback", "ropeSin is null"), return GRAPH_FAILED); + + param.ropeCos = ctx->GetRequiredInputTensor(ROPE_COS_INDEX); + OP_CHECK_IF(param.ropeCos == nullptr, OP_LOGE("aclnnfallback", "ropeCos is null"), return GRAPH_FAILED); + + param.cacheIndex = ctx->GetRequiredInputTensor(CACHE_INDEX_INDEX); + OP_CHECK_IF(param.cacheIndex == nullptr, OP_LOGE("aclnnfallback", "cacheIndex is null"), return GRAPH_FAILED); + + param.kvCache = ctx->GetRequiredInputTensor(KV_CACHE_INDEX); + OP_CHECK_IF(param.kvCache == nullptr, OP_LOGE("aclnnfallback", "kvCache is null"), return GRAPH_FAILED); + + param.krCache = ctx->GetRequiredInputTensor(KR_CACHE_INDEX); + OP_CHECK_IF(param.krCache == nullptr, OP_LOGE("aclnnfallback", "krCache is null"), return GRAPH_FAILED); + + param.dequantScaleX = ctx->GetOptionalInputTensor(DEQUANT_SCALE_X_INDEX); + param.dequantScaleWDq = ctx->GetOptionalInputTensor(DEQUANT_SCALE_W_DQ_INDEX); + param.dequantScaleWUqQr = ctx->GetOptionalInputTensor(DEQUANT_SCALE_W_UQ_QR_INDEX); + param.dequantScaleWDkvKr = ctx->GetOptionalInputTensor(DEQUANT_SCALE_W_DKV_KR_INDEX); + param.quantScaleCkv = ctx->GetOptionalInputTensor(QUANT_SCALE_CKV_INDEX); + param.quantScaleCkr = ctx->GetOptionalInputTensor(QUANT_SCALE_CKR_INDEX); + param.smoothScalesCq = ctx->GetOptionalInputTensor(SMOOTH_SCALES_CQ_INDEX); + + return GRAPH_SUCCESS; +} + +graphStatus GetMlaPrologOutputTensor(const OpExecuteContext *ctx, MlaPrologFallBackParam ¶m) +{ + param.query = ctx->GetOutputTensor(QUERY_INDEX); + OP_CHECK_IF(param.query == nullptr, OP_LOGE("aclnnfallback", "query is null"), return GRAPH_FAILED); + + param.queryRope = ctx->GetOutputTensor(QUERY_ROPE_INDEX); + OP_CHECK_IF(param.queryRope == nullptr, OP_LOGE("aclnnfallback", "queryRope is null"), return GRAPH_FAILED); + + param.kvCacheOut = ctx->GetOutputTensor(KV_CACHE_OUT_INDEX); + OP_CHECK_IF(param.kvCacheOut == nullptr, OP_LOGE("aclnnfallback", "kvCacheOut is null"), return GRAPH_FAILED); + + param.krCacheOut = ctx->GetOutputTensor(KR_CACHE_OUT_INDEX); + OP_CHECK_IF(param.krCacheOut == nullptr, OP_LOGE("aclnnfallback", "krCacheOut is null"), return GRAPH_FAILED); + + return GRAPH_SUCCESS; +} + +graphStatus GetMlaPrologAttr(const OpExecuteContext *ctx, MlaPrologFallBackParam ¶m) +{ + auto attrs = ctx->GetAttrs(); + const double *getRmsnormEpsilonCq = attrs->GetAttrPointer(ATTR_RMSNORM_EPSILON_CQ_INDEX); + const double *getRmsnormEpsilonCkv = attrs->GetAttrPointer(ATTR_RMSNORM_EPSILON_CKV_INDEX); + const char *getCacheMode = attrs->GetAttrPointer(ATTR_CACHE_MODE_INDEX); + + param.rmsnormEpsilonCq = *getRmsnormEpsilonCq; + param.rmsnormEpsilonCkv = *getRmsnormEpsilonCkv; + param.cacheMode = getCacheMode; + + OP_LOGD("aclnnFallback", "MlaProlog fallback begin, RmsnormEpsilonCq = %f, RmsnormEpsilonCkv = %f", + param.rmsnormEpsilonCq, param.rmsnormEpsilonCkv); + + return GRAPH_SUCCESS; +} + +graphStatus MlaHostExecuteFunc(OpExecuteContext *host_api_ctx) +{ + OP_CHECK_IF(host_api_ctx == nullptr, OP_LOGE("aclnnfallback", "host_api_ctx is null"), return GRAPH_FAILED); + + MlaPrologFallBackParam param{}; + auto apiRet = GetMlaPrologInputTensor(host_api_ctx, param); + OP_CHECK_IF(apiRet != GRAPH_SUCCESS, OP_LOGE("aclnnfallback", "Context get input tesnor failed"), + return GRAPH_FAILED); + + apiRet = GetMlaPrologOutputTensor(host_api_ctx, param); + OP_CHECK_IF(apiRet != GRAPH_SUCCESS, OP_LOGE("aclnnfallback", "Context get output tesnor failed"), + return GRAPH_FAILED); + + apiRet = GetMlaPrologAttr(host_api_ctx, param); + OP_CHECK_IF(apiRet != GRAPH_SUCCESS, OP_LOGE("aclnnfallback", "Context get attr failed"), return GRAPH_FAILED); + + apiRet = EXEC_OPAPI_CMD( + aclnnMlaProlog, param.tokenX, param.weightDq, param.weightUqQr, param.weightUk, param.weightDkvKr, + param.rmsnormGammaCq, param.rmsnormGammaCkv, param.ropeSin, param.ropeCos, param.cacheIndex, param.kvCache, + param.krCache, param.dequantScaleX, param.dequantScaleWDq, param.dequantScaleWUqQr, param.dequantScaleWDkvKr, + param.quantScaleCkv, param.quantScaleCkr, param.smoothScalesCq, param.rmsnormEpsilonCq, param.rmsnormEpsilonCkv, + param.cacheMode, param.query, param.queryRope, param.kvCacheOut, param.krCacheOut); + OP_CHECK_IF(apiRet != GRAPH_SUCCESS, OP_LOGE("aclnnfallback", "ret failed:%u", apiRet), return GRAPH_FAILED); + + return GRAPH_SUCCESS; +} + +IMPL_OP(MlaProlog).OpExecuteFunc(MlaHostExecuteFunc); +} // namespace fallback + +#ifdef __cplusplus +} +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_graph/fallback_mla_prolog.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_graph/fallback_mla_prolog.h new file mode 100644 index 0000000000000000000000000000000000000000..93c06e9f9887a8a55c6b3040e2fd6c9cd4d8e819 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_graph/fallback_mla_prolog.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. + */ + +#ifndef FALLBACK_MLA_PROLOG_H +#define FALLBACK_MLA_PROLOG_H + +#include +#include "log/log.h" +#include "fallback/fallback_comm.h" +#include "fallback/fallback.h" + +#ifdef __cplusplus +extern "C" { +#endif +namespace fallback { + +// INPUT +constexpr size_t TOKEN_X_INDEX = 0; +constexpr size_t WEIGHT_DQ_INDEX = 1; +constexpr size_t WEIGHT_UQ_QR_INDEX = 2; +constexpr size_t WEIGHT_UK_INDEX = 3; +constexpr size_t WEIGHT_DKV_KR_INDEX = 4; +constexpr size_t RMSNORM_GAMMA_CQ_INDEX = 5; +constexpr size_t RMSNORM_GAMMA_CKV_INDEX = 6; +constexpr size_t ROPE_SIN_INDEX = 7; +constexpr size_t ROPE_COS_INDEX = 8; +constexpr size_t CACHE_INDEX_INDEX = 9; +constexpr size_t KV_CACHE_INDEX = 10; +constexpr size_t KR_CACHE_INDEX = 11; +constexpr size_t DEQUANT_SCALE_X_INDEX = 12; +constexpr size_t DEQUANT_SCALE_W_DQ_INDEX = 13; +constexpr size_t DEQUANT_SCALE_W_UQ_QR_INDEX = 14; +constexpr size_t DEQUANT_SCALE_W_DKV_KR_INDEX = 15; +constexpr size_t QUANT_SCALE_CKV_INDEX = 16; +constexpr size_t QUANT_SCALE_CKR_INDEX = 17; +constexpr size_t SMOOTH_SCALES_CQ_INDEX = 18; +// ATTR +constexpr size_t ATTR_RMSNORM_EPSILON_CQ_INDEX = 0; +constexpr size_t ATTR_RMSNORM_EPSILON_CKV_INDEX = 1; +constexpr size_t ATTR_CACHE_MODE_INDEX = 2; +// OUTPUT +constexpr size_t QUERY_INDEX = 0; +constexpr size_t QUERY_ROPE_INDEX = 1; +constexpr size_t KV_CACHE_OUT_INDEX = 2; +constexpr size_t KR_CACHE_OUT_INDEX = 3; + +struct MlaPrologFallBackParam { + const gert::Tensor *tokenX = nullptr; + const gert::Tensor *weightDq = nullptr; + const gert::Tensor *weightUqQr = nullptr; + const gert::Tensor *weightUk = nullptr; + const gert::Tensor *weightDkvKr = nullptr; + const gert::Tensor *rmsnormGammaCq = nullptr; + const gert::Tensor *rmsnormGammaCkv = nullptr; + const gert::Tensor *ropeSin = nullptr; + const gert::Tensor *ropeCos = nullptr; + const gert::Tensor *cacheIndex = nullptr; + const gert::Tensor *kvCache = nullptr; + const gert::Tensor *krCache = nullptr; + const gert::Tensor *query = nullptr; + const gert::Tensor *queryRope = nullptr; + const gert::Tensor *kvCacheOut = nullptr; + const gert::Tensor *krCacheOut = nullptr; + const gert::Tensor *dequantScaleX = nullptr; + const gert::Tensor *dequantScaleWDq = nullptr; + const gert::Tensor *dequantScaleWUqQr = nullptr; + const gert::Tensor *dequantScaleWDkvKr = nullptr; + const gert::Tensor *quantScaleCkv = nullptr; + const gert::Tensor *quantScaleCkr = nullptr; + const gert::Tensor *smoothScalesCq = nullptr; + double rmsnormEpsilonCq = 1e-05f; + double rmsnormEpsilonCkv = 1e-05f; + const char *cacheMode = nullptr; +}; + +graphStatus GetMlaPrologInputTensor(const OpExecuteContext *ctx, MlaPrologFallBackParam ¶m); +graphStatus GetMlaPrologOutputTensor(const OpExecuteContext *ctx, MlaPrologFallBackParam ¶m); +graphStatus GetMlaPrologAttr(const OpExecuteContext *ctx, MlaPrologFallBackParam ¶m); +graphStatus MlaHostExecuteFunc(OpExecuteContext *host_api_ctx); +} // namespace fallback + +#ifdef __cplusplus +} +#endif + +#endif // FALLBACK_MLA_PROLOG_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..4203401a201958b0134c04c0a81f70d99379adf1 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/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. +# ----------------------------------------------------------------------------------------------------------- +add_op_to_compiled_list() +if (BUILD_OPEN_PROJECT) + target_sources(op_host_aclnnInner PRIVATE + mla_prolog_def.cpp + ) + + add_ops_compile_options( + OP_NAME MlaProlog + OPTIONS --cce-auto-sync=off + -Wno-deprecated-declarations + -Werror + -mllvm -cce-aicore-hoist-movemask=false + ) +endif() + +if (NOT BUILD_OPS_RTY_KERNEL) + add_modules_sources( + OP_API_INDEPENDENT ON + OP_API_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../op_api + OPTYPE mla_prolog ACLNNTYPE aclnn_inner) +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_def.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_def.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1a517ddb4efc5720d60950afe7898289d3cb906 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_def.cpp @@ -0,0 +1,271 @@ +/** + * 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 mla_prolog_def.cpp + * \brief + */ + +#include "register/op_def_registry.h" + +namespace ops { +class MlaProlog : public OpDef { +public: + MlaProlog(const char *name) : OpDef(name) + { + this->Input("token_x") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_INT8, ge::DT_INT8}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("weight_dq") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_INT8, ge::DT_INT8}) + .FormatList({ge::FORMAT_FRACTAL_NZ}) + .AutoContiguous(); + this->Input("weight_uq_qr") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_INT8, ge::DT_INT8, ge::DT_INT8, ge::DT_INT8}) + .FormatList({ge::FORMAT_FRACTAL_NZ}) + .AutoContiguous(); + this->Input("weight_uk") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("weight_dkv_kr") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_INT8, ge::DT_INT8}) + .FormatList({ge::FORMAT_FRACTAL_NZ}) + .AutoContiguous(); + this->Input("rmsnorm_gamma_cq") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("rmsnorm_gamma_ckv") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("rope_sin") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("rope_cos") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("cache_index") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_INT64}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("kv_cache") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_INT8, ge::DT_BF16, ge::DT_INT8, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("kr_cache") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_INT8, ge::DT_BF16, ge::DT_INT8, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("dequant_scale_x") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("dequant_scale_w_dq") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("dequant_scale_w_uq_qr") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("dequant_scale_w_dkv_kr") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("quant_scale_ckv") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("quant_scale_ckr") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("smooth_scales_cq") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + this->Output("query") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}); + this->Output("query_rope") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}); + this->Output("kv_cache") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_INT8, ge::DT_BF16, ge::DT_INT8, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}); + this->Output("kr_cache") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_INT8, ge::DT_BF16, ge::DT_INT8, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}); + this->Attr("rmsnorm_epsilon_cq").AttrType(OPTIONAL).Float(1e-05f); + this->Attr("rmsnorm_epsilon_ckv").AttrType(OPTIONAL).Float(1e-05f); + this->Attr("cache_mode").AttrType(OPTIONAL).String("BNSD"); + OpAICoreConfig aicore_config; + aicore_config.DynamicCompileStaticFlag(true) + .DynamicFormatFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .NeedCheckSupportFlag(false) + .PrecisionReduceFlag(true) + .ExtendCfgInfo("aclnnSupport.value", "support_aclnn"); // set value of aclnn support + this->AICore().AddConfig("ascend910b", aicore_config); + this->AICore().AddConfig("ascend910_93", aicore_config); + + OpAICoreConfig aicore_config_95; + aicore_config_95.Input("token_x") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_INT8, ge::DT_INT8, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("weight_dq") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_INT8, ge::DT_INT8, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN}) + .FormatList({ge::FORMAT_FRACTAL_NZ}) + .AutoContiguous(); + aicore_config_95.Input("weight_uq_qr") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_INT8, ge::DT_INT8, ge::DT_INT8, ge::DT_INT8, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN}) + .FormatList({ge::FORMAT_FRACTAL_NZ}) + .AutoContiguous(); + aicore_config_95.Input("weight_uk") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("weight_dkv_kr") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_INT8, ge::DT_INT8, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN}) + .FormatList({ge::FORMAT_FRACTAL_NZ}) + .AutoContiguous(); + aicore_config_95.Input("rmsnorm_gamma_cq") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("rmsnorm_gamma_ckv") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("rope_sin") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("rope_cos") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("cache_index") + .ParamType(REQUIRED) + .DataTypeList({ge::DT_INT64}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("kv_cache") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_INT8, ge::DT_BF16, ge::DT_INT8, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("kr_cache") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_INT8, ge::DT_BF16, ge::DT_INT8, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("dequant_scale_x") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("dequant_scale_w_dq") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("dequant_scale_w_uq_qr") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("dequant_scale_w_dkv_kr") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("quant_scale_ckv") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("quant_scale_ckr") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Input("smooth_scales_cq") + .ParamType(OPTIONAL) + .DataTypeList({ge::DT_FLOAT}) + .FormatList({ge::FORMAT_ND}) + .AutoContiguous(); + aicore_config_95.Output("query") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}); + aicore_config_95.Output("query_rope") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}); + aicore_config_95.Output("kv_cache") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_INT8, ge::DT_BF16, ge::DT_INT8, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}); + aicore_config_95.Output("kr_cache") + .ParamType(REQUIRED) + .DataType({ge::DT_BF16, ge::DT_INT8, ge::DT_BF16, ge::DT_INT8, ge::DT_BF16, ge::DT_FLOAT8_E4M3FN, ge::DT_BF16}) + .FormatList({ge::FORMAT_ND}); + aicore_config_95.DynamicCompileStaticFlag(true) + .DynamicFormatFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .NeedCheckSupportFlag(false) + .PrecisionReduceFlag(true) + .ExtendCfgInfo("aclnnSupport.value", "support_aclnn"); + this->AICore().AddConfig("ascend950", aicore_config_95); + } +}; +OP_ADD(MlaProlog, optiling::MlaPrologCompileInfo); +} // namespace ops diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d375cba662959f650586f582482fbeea044f0b33 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_infershape.cpp @@ -0,0 +1,138 @@ +/** + * 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 mla_prolog_proto.cpp + * \brief + */ + +#include "mla_prolog_infershape.h" + +using namespace ge; + +namespace ops { + +ge::graphStatus GetMlaPrologShapeDim(const gert::InferShapeContext *context, MlaPrologProtoShapeParam &shapeParam) +{ + auto tokenXShape = context->GetRequiredInputShape(TOKEN_X_INDEX); // (B, S, He) | (T, He) + OP_CHECK_NULL_WITH_CONTEXT(context, tokenXShape); + auto weightUkShape = context->GetRequiredInputShape(WEIGHT_UK_INDEX); // (N, D, Hckv) + OP_CHECK_NULL_WITH_CONTEXT(context, weightUkShape); + auto ropeSinShape = context->GetRequiredInputShape(ROPE_SIN_INDEX); // (B, S, Dr) | (T, Dr) + OP_CHECK_NULL_WITH_CONTEXT(context, ropeSinShape); + if (std::strcmp(context->GetNodeType(), "MlaPrologV3") == 0) { + auto kvCacheShape = context->GetRequiredInputShape(KV_CACHE_INDEX_V3); // (B, Nkv, Skv, Hckv) + OP_CHECK_NULL_WITH_CONTEXT(context, kvCacheShape); + auto krCacheShape = context->GetRequiredInputShape(KR_CACHE_INDEX_V3); // (B, Nkv, Skv, Dr) + OP_CHECK_NULL_WITH_CONTEXT(context, krCacheShape); + } else { + auto kvCacheShape = context->GetRequiredInputShape(KV_CACHE_INDEX); // (B, Nkv, Skv, Hckv) + OP_CHECK_NULL_WITH_CONTEXT(context, kvCacheShape); + auto krCacheShape = context->GetRequiredInputShape(KR_CACHE_INDEX); // (B, Nkv, Skv, Dr) + OP_CHECK_NULL_WITH_CONTEXT(context, krCacheShape); + } + + OP_CHECK_IF(((tokenXShape->GetDimNum() != DIM_NUM_3) && (tokenXShape->GetDimNum() != DIM_NUM_2)), + OP_LOGE(context->GetNodeName(), "tokenXShape is not 2 or 3, but %zu", tokenXShape->GetDimNum()), return ge::GRAPH_FAILED); + + if (tokenXShape->GetDimNum() == DIM_NUM_3) { // BS + shapeParam.isBsMerge = false; + shapeParam.B = tokenXShape->GetDim(DIM_INDEX_0); + shapeParam.S = tokenXShape->GetDim(DIM_INDEX_1); + shapeParam.Dr = ropeSinShape->GetDim(DIM_INDEX_2); + shapeParam.T = shapeParam.B * shapeParam.S; + } else { // T + shapeParam.isBsMerge = true; + shapeParam.T = tokenXShape->GetDim(DIM_INDEX_0); + shapeParam.Dr = ropeSinShape->GetDim(DIM_INDEX_1); + } + + shapeParam.N = weightUkShape->GetDim(DIM_INDEX_0); + shapeParam.Hckv = weightUkShape->GetDim(DIM_INDEX_2); + return GRAPH_SUCCESS; +} + +ge::graphStatus SetMlaPrologShapeDim(const MlaPrologProtoShapeParam &shapeParam, gert::InferShapeContext *context) +{ + auto queryShape = context->GetOutputShape(QUERY_INDEX); // query: (B, S, N, Hckv) | (T, N, Hckv) + OP_CHECK_NULL_WITH_CONTEXT(context, queryShape); + auto queryRopeShape = context->GetOutputShape(QUERY_ROPE_INDEX); // queryRope: (B, S, N, Dr) | (T, N, Dr) + OP_CHECK_NULL_WITH_CONTEXT(context, queryRopeShape); + auto kvCacheOutShape = context->GetOutputShape(KV_CACHE_OUT_INDEX); // kvCacheOut: (B, Nkv, Skv, Hckv) + OP_CHECK_NULL_WITH_CONTEXT(context, kvCacheOutShape); + auto krCacheOutShape = context->GetOutputShape(KR_CACHE_OUT_INDEX); // krCacheOut: (B, Nkv, Skv, Dr) + OP_CHECK_NULL_WITH_CONTEXT(context, krCacheOutShape); + + // Set output shape + if (!shapeParam.isBsMerge) { + queryShape->SetDimNum(DIM_NUM_4); // (B, S, N, Hckv) + queryShape->SetDim(DIM_INDEX_0, shapeParam.B); + queryShape->SetDim(DIM_INDEX_1, shapeParam.S); + queryShape->SetDim(DIM_INDEX_2, shapeParam.N); + queryShape->SetDim(DIM_INDEX_3, shapeParam.Hckv); + + queryRopeShape->SetDimNum(DIM_NUM_4); // (B, S, N, Dr) + queryRopeShape->SetDim(DIM_INDEX_0, shapeParam.B); + queryRopeShape->SetDim(DIM_INDEX_1, shapeParam.S); + queryRopeShape->SetDim(DIM_INDEX_2, shapeParam.N); + queryRopeShape->SetDim(DIM_INDEX_3, shapeParam.Dr); + } else { + queryShape->SetDimNum(DIM_NUM_3); // (T, N, Hckv) + queryShape->SetDim(DIM_INDEX_0, shapeParam.T); + queryShape->SetDim(DIM_INDEX_1, shapeParam.N); + queryShape->SetDim(DIM_INDEX_2, shapeParam.Hckv); + + queryRopeShape->SetDimNum(DIM_NUM_3); // (T, N, Dr) + queryRopeShape->SetDim(DIM_INDEX_0, shapeParam.T); + queryRopeShape->SetDim(DIM_INDEX_1, shapeParam.N); + queryRopeShape->SetDim(DIM_INDEX_2, shapeParam.Dr); + } + + if (std::strcmp(context->GetNodeType(), "MlaPrologV3") == 0) { + *kvCacheOutShape = *context->GetRequiredInputShape(KV_CACHE_INDEX_V3); + *krCacheOutShape = *context->GetRequiredInputShape(KR_CACHE_INDEX_V3); + } else { + *kvCacheOutShape = *context->GetRequiredInputShape(KV_CACHE_INDEX); + *krCacheOutShape = *context->GetRequiredInputShape(KR_CACHE_INDEX); + } + return GRAPH_SUCCESS; +} + +ge::graphStatus InferShapeMlaProlog(gert::InferShapeContext *context) { + OP_LOGI(context->GetNodeName(), "Enter MlaProlog infershape impl."); + + MlaPrologProtoShapeParam shapeParam {}; + auto apiRet = GetMlaPrologShapeDim(context, shapeParam); + OP_CHECK_IF((apiRet != GRAPH_SUCCESS), OP_LOGE(context->GetNodeName(), "Context get input shape failed"), return ge::GRAPH_FAILED); + + apiRet = SetMlaPrologShapeDim(shapeParam, context); + OP_CHECK_IF((apiRet != GRAPH_SUCCESS), OP_LOGE(context->GetNodeName(), "Context set output shape failed"), return ge::GRAPH_FAILED); + + OP_LOGI(context->GetNodeName(), "MlaProlog infershape end."); + return GRAPH_SUCCESS; +} + +ge::graphStatus InferDataTypeMlaProlog(gert::InferDataTypeContext *context) { + OP_LOGI(context->GetNodeName(), "Enter MlaProlog inferdatatype impl."); + + context->SetOutputDataType(QUERY_INDEX, context->GetRequiredInputDataType(WEIGHT_UK_INDEX)); + context->SetOutputDataType(QUERY_ROPE_INDEX, context->GetRequiredInputDataType(WEIGHT_UK_INDEX)); + if (std::strcmp(context->GetNodeType(), "MlaPrologV3") == 0) { + context->SetOutputDataType(KV_CACHE_OUT_INDEX, context->GetRequiredInputDataType(KV_CACHE_INDEX_V3)); + context->SetOutputDataType(KR_CACHE_OUT_INDEX, context->GetRequiredInputDataType(KR_CACHE_INDEX_V3)); + } else { + context->SetOutputDataType(KV_CACHE_OUT_INDEX, context->GetRequiredInputDataType(KV_CACHE_INDEX)); + context->SetOutputDataType(KR_CACHE_OUT_INDEX, context->GetRequiredInputDataType(KR_CACHE_INDEX)); + } + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(MlaProlog).InferShape(InferShapeMlaProlog).InferDataType(InferDataTypeMlaProlog); +} // namespace ops \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_infershape.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_infershape.h new file mode 100644 index 0000000000000000000000000000000000000000..dcf22547cf5f1fbe9e00e7693c1f409db7942fd5 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_infershape.h @@ -0,0 +1,70 @@ +/** + * 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 mla_prolog_infershape.h + * \brief + */ + +#ifndef MLA_PROLOG_INFERSHAPE_H +#define MLA_PROLOG_INFERSHAPE_H + +#include +#include +#include "log/log.h" + +using namespace ge; + +namespace ops { +// INPUT +constexpr uint32_t TOKEN_X_INDEX = 0; +constexpr uint32_t WEIGHT_UK_INDEX = 3; +constexpr uint32_t ROPE_SIN_INDEX = 7; +constexpr uint32_t KV_CACHE_INDEX = 10; +constexpr uint32_t KR_CACHE_INDEX = 11; +constexpr uint32_t KV_CACHE_INDEX_V3 = 9; +constexpr uint32_t KR_CACHE_INDEX_V3 = 10; +// OUTPUT +constexpr uint32_t QUERY_INDEX = 0; +constexpr uint32_t QUERY_ROPE_INDEX = 1; +constexpr uint32_t KV_CACHE_OUT_INDEX = 2; +constexpr uint32_t KR_CACHE_OUT_INDEX = 3; +// TMP +constexpr uint32_t DIM_NUM_0 = 0; +constexpr uint32_t DIM_NUM_1 = 1; +constexpr uint32_t DIM_NUM_2 = 2; +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 FP8_E4M3_BLOCK_SIZE = 32; // Mxfp8全量化场景下 block_size = 32 + +struct MlaPrologProtoShapeParam { + bool isBsMerge { false }; + int64_t B { 0 }; + int64_t T { 0 }; + int64_t S { 0 }; + int64_t N { 0 }; + int64_t Hckv { 0 }; + int64_t He { 0 }; + int64_t Dr { 0 }; + int64_t Hcq { 0 }; +}; + +ge::graphStatus GetMlaPrologShapeDim(const gert::InferShapeContext *context, MlaPrologProtoShapeParam &shapeParam); +ge::graphStatus SetMlaPrologShapeDim(const MlaPrologProtoShapeParam &shapeParam, gert::InferShapeContext *context); +ge::graphStatus InferShapeMlaProlog(gert::InferShapeContext *context); +ge::graphStatus InferDataTypeMlaProlog(gert::InferDataTypeContext *context); +} // namespace ops + +#endif // MLA_PROLOG_INFERSHAPE_H \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e556b0b3f2b4f87529ebc3020db8a4b6fdbe2a5e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling.cpp @@ -0,0 +1,842 @@ +/** + * 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 mla_prolog_tiling.cpp + * \brief + */ + +#include +#include +#include +#include +#include "log/log.h" +#include "err/ops_err.h" +#include "register/op_def_registry.h" +#include "mla_prolog_tiling_check.h" +#include "mla_prolog_tiling.h" +using namespace ge; +namespace optiling { + +const std::unordered_map DTYPE_TO_SIZE{ + {ge::DT_BF16, 2}, {ge::DT_FLOAT16, 2}, {ge::DT_INT8, 1}, {ge::DT_FLOAT8_E4M3FN, 1}, + {ge::DT_FLOAT8_E8M0, 1}, {ge::DT_HIFLOAT8, 1}, {ge::DT_INT32, 4}, {ge::DT_FLOAT, 4}}; + +const std::unordered_map GE_TO_MM_DTYPE{ + {ge::DT_FLOAT16, matmul_tiling::DataType::DT_FLOAT16}, + {ge::DT_BF16, matmul_tiling::DataType::DT_BF16}, + {ge::DT_INT8, matmul_tiling::DataType::DT_INT8}, + {ge::DT_INT4, matmul_tiling::DataType::DT_INT4}, + {ge::DT_FLOAT, matmul_tiling::DataType::DT_FLOAT}, + {ge::DT_FLOAT8_E4M3FN, matmul_tiling::DataType::DT_FLOAT8_E4M3FN}, + {ge::DT_FLOAT8_E8M0, matmul_tiling::DataType::DT_FLOAT8_E8M0}, + {ge::DT_HIFLOAT8, matmul_tiling::DataType::DT_HIFLOAT8}}; + +template +inline auto CeilDiv(T a, T b) -> T +{ + if (b == 0) { + return b; + } + return (a + b - 1) / b; +} + +template +inline auto Align(T num, T rnd) -> T +{ + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd))); +} + +NpuArch MlaPrologTiling::GetCurNpuArch() const +{ + auto ascendcPlatform = platform_ascendc::PlatformAscendC(context_->platformInfo); + NpuArch npuArch = ascendcPlatform.GetCurNpuArch(); + return npuArch; +} + +ge::graphStatus MlaPrologTiling::GetNpuInfo() +{ + OP_CHECK_IF(context_->platformInfo == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(context_->opName, "GetPlatformInfo is nullptr."), return ge::GRAPH_FAILED); + + auto ascendcPlatform = platform_ascendc::PlatformAscendC(context_->platformInfo); + libapiSize_ = ascendcPlatform.GetLibApiWorkSpaceSize(); + + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize_); + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L1, l1Size_); + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_C, l0cSize_); + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_B, l0bSize_); + + aivNum_ = ascendcPlatform.GetCoreNumAiv(); + aicNum_ = ascendcPlatform.GetCoreNumAic(); + + OP_CHECK_IF(aicNum_ == 0 || aivNum_ == 0, + OPS_REPORT_VECTOR_INNER_ERR(context_->opName, "num of core obtained is 0."), return GRAPH_FAILED); + + OP_CHECK_IF((aicNum_ != aivNum_) && (aicNum_ * 2 != aivNum_), + OPS_REPORT_VECTOR_INNER_ERR(context_->opName, "aicNum(%u):aivNum(%u) only support 1:1 or 1:2", aicNum_, + aivNum_), + return GRAPH_FAILED); + + return ge::GRAPH_SUCCESS; +} + +QUANT_MODE MlaPrologTiling::GetQuantizationModeV3() const +{ + if (*(context_->weightQuantMode) == static_cast(WEIGHT_QUANT_MODE::NO_QUANT)) { + if (*(context_->kvQuantMode) == static_cast(KV_QUANT_MODE::NO_QUANT)) { + return QUANT_MODE::NO_QUANT; + } else { + OP_LOGE(context_->opName, "When weightQuantMode == 0, kvQuantMode must be within {0}, actually is %ld.", + *(context_->kvQuantMode)); + } + } else if (*(context_->weightQuantMode) == static_cast(WEIGHT_QUANT_MODE::PARTIAL_QUANT)) { + if (*(context_->kvQuantMode) == static_cast(KV_QUANT_MODE::NO_QUANT)) { + return QUANT_MODE::PARTIAL_QUANT_KV_NO_QUANT; + } else if (*(context_->kvQuantMode) == static_cast(KV_QUANT_MODE::PER_CHANNEL)) { + return QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_CHANNEL; + } else if (*(context_->kvQuantMode) == static_cast(KV_QUANT_MODE::PER_TILE)) { + return QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_TILE; + } else { + OP_LOGE(context_->opName, + "When weightQuantMode == 1, kvQuantMode must be within {0, 2, 3}, actually is %ld.", + *(context_->kvQuantMode)); + } + } else if (*(context_->weightQuantMode) == static_cast(WEIGHT_QUANT_MODE::FULL_QUANT)) { + if (*(context_->kvQuantMode) == static_cast(KV_QUANT_MODE::NO_QUANT)) { + return QUANT_MODE::FULL_QUANT_KV_NO_QUANT; + } else if (*(context_->kvQuantMode) == static_cast(KV_QUANT_MODE::PER_TENSOR)) { + return QUANT_MODE::FULL_QUANT_KV_QUANT_PER_TENSOR; + } else if (*(context_->kvQuantMode) == static_cast(KV_QUANT_MODE::PER_TILE)) { + return QUANT_MODE::FULL_QUANT_KV_QUANT_PER_TILE; + } else { + OP_LOGE(context_->opName, + "When weightQuantMode == 2, kvQuantMode must be within {0, 1, 3}, actually is %ld.", + *(context_->kvQuantMode)); + } + } else { + OP_LOGE(context_->opName, "WeightQuantMode must be within {0, 1, 2}, actually is %ld.", + *(context_->weightQuantMode)); + } + return QUANT_MODE::ERROR_MODE; +} + +QUANT_MODE MlaPrologTiling::GetQuantizationModeV3Dav() const +{ + const int weightQuantMode = *(context_->weightQuantMode); + const int kvQuantMode = *(context_->kvQuantMode); + + // 卫语句1:weightQuantMode 越界(外层哈希找不到) + auto wqIt = QUANT_MODE_HASH_TABLE.find(weightQuantMode); + if (wqIt == QUANT_MODE_HASH_TABLE.end()) { + OP_LOGE_FOR_INVALID_VALUE(context_->opName, "weightQuantMode", std::to_string(weightQuantMode), + "{0, 1, 2, 3, 4, 5}"); + return QUANT_MODE::ERROR_MODE; + } + + // 卫语句2:kvQuantMode 越界或组合非法(内层哈希找不到) + auto kvIt = wqIt->second.find(kvQuantMode); + if (kvIt == wqIt->second.end()) { + auto reasonIt = VALID_KV_REASON_TABLE.find(weightQuantMode); + const char *reason = (reasonIt != VALID_KV_REASON_TABLE.end()) ? reasonIt->second : "invalid kvQuantMode"; + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_->opName, "kvQuantMode", std::to_string(kvQuantMode), reason); + return QUANT_MODE::ERROR_MODE; + } + + // hash 命中,返回对应场景 + return kvIt->second; +} + +QUANT_MODE MlaPrologTiling::GetQuantizationMode() const +{ + if (std::strncmp(context_->opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + if (GetCurNpuArch() == NpuArch::DAV_3510) { + return GetQuantizationModeV3Dav(); + } else { + return GetQuantizationModeV3(); + } + } else { + if (context_->tokenX.desc->GetDataType() == ge::DT_INT8) { + if (context_->kvCache.desc->GetDataType() == ge::DT_INT8) { + return QUANT_MODE::FULL_QUANT_KV_QUANT_PER_TENSOR; + } else { + return QUANT_MODE::FULL_QUANT_KV_NO_QUANT; + } + } + if (context_->tokenX.desc->GetDataType() == ge::DT_BF16 && + context_->weightUqQr.desc->GetDataType() == ge::DT_INT8) { + if (context_->kvCache.desc->GetDataType() == ge::DT_INT8) { + return QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_CHANNEL; + } else { + return QUANT_MODE::PARTIAL_QUANT_KV_NO_QUANT; + } + } + return QUANT_MODE::NO_QUANT; + } + return QUANT_MODE::ERROR_MODE; +} + +ge::graphStatus MlaPrologTiling::SetShapeInfo() +{ + if (context_->tokenX.shape->GetStorageShape().GetDimNum() == MLA_PROLOG_DIM_NUM_3) { + baseShapeInfo_.bSize = context_->tokenX.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_0); + baseShapeInfo_.s1Size = context_->tokenX.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_1); + baseShapeInfo_.heSize = context_->tokenX.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_2); + baseShapeInfo_.tSize = baseShapeInfo_.bSize * baseShapeInfo_.s1Size; + } else { + baseShapeInfo_.tSize = context_->tokenX.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_0); + baseShapeInfo_.heSize = context_->tokenX.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_1); + } + if (context_->weightDq.shape->GetStorageShape().GetDimNum() == MLA_PROLOG_DIM_NUM_2) { + baseShapeInfo_.hcqSize = context_->weightDq.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_1); + } else { + uint32_t weightDqAxisSize_ = 32U / ge::GetSizeByDataType(context_->weightDq.desc->GetDataType()); + // weightDq: [He, Hcq] -> [Hcq/16, He/16, 16, 16] || [Hcq/32, He/16, 16, 32] + baseShapeInfo_.hcqSize = + weightDqAxisSize_ * context_->weightDq.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_0); + } + baseShapeInfo_.nSize = context_->weightUk.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_0); + baseShapeInfo_.drSize = + context_->ropeCos.shape->GetStorageShape().GetDim(context_->ropeCos.shape->GetStorageShape().GetDimNum() - 1); + baseShapeInfo_.dSize = context_->weightUk.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_1); + baseShapeInfo_.headSizeQc = baseShapeInfo_.dSize * baseShapeInfo_.nSize; + baseShapeInfo_.headSizeQr = baseShapeInfo_.drSize * baseShapeInfo_.nSize; + baseShapeInfo_.headSizeUqQr = baseShapeInfo_.headSizeQc + baseShapeInfo_.headSizeQr; + if (context_->kvCache.shape->GetStorageShape().GetDimNum() == MLA_PROLOG_DIM_NUM_3) { + baseShapeInfo_.blockNum = context_->kvCache.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_0); + baseShapeInfo_.nkvSize = context_->kvCache.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_1); + baseShapeInfo_.dtileSize = context_->kvCache.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_2); + } else { + baseShapeInfo_.blockNum = context_->kvCache.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_0); + baseShapeInfo_.blockSize = context_->kvCache.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_1); + baseShapeInfo_.nkvSize = context_->kvCache.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_2); + baseShapeInfo_.dtileSize = context_->kvCache.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_3); + } + if (context_->weightDkvKr.shape->GetStorageShape().GetDimNum() == MLA_PROLOG_DIM_NUM_4) { + baseShapeInfo_.hckvSize = context_->weightDkvKr.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_0) * + context_->weightDkvKr.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_3) - + baseShapeInfo_.drSize; + } else { + baseShapeInfo_.hckvSize = + context_->weightDkvKr.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_1) - baseShapeInfo_.drSize; + } + baseShapeInfo_.s2Size = baseShapeInfo_.nkvSize; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTiling::SetScenarioInfo() +{ + scenarioInfo_.isV1Flag_ = (std::strncmp(context_->opType, V1_OP_NAME, OP_NAME_LEN) == 0); + scenarioInfo_.batchSeqFusedFlag_ = context_->tokenX.shape->GetStorageShape().GetDimNum() == MLA_PROLOG_DIM_NUM_2; + scenarioInfo_.quantMode_ = GetQuantizationMode(); + if (scenarioInfo_.quantMode_ == QUANT_MODE::ERROR_MODE) { + return ge::GRAPH_FAILED; + } + + // 由 quantMode_ 反向映射 wq/kvq(V1/V2 按 dtype 推断、V3 正向查表,均唯一可反推) + const auto &wqKvq = QUANT_MODE_REVERSE_TABLE.at(scenarioInfo_.quantMode_); + scenarioInfo_.weightQuantMode_ = wqKvq.first; + scenarioInfo_.kvQuantMode_ = wqKvq.second; + + // cacheMode 字符串 → 枚举,hash 查表(CheckCacheMode 已保证 cacheMode 合法,必命中) + scenarioInfo_.cacheMode_ = CACHE_MODE_HASH_TABLE.at(std::string(context_->cacheMode)); + + if ((scenarioInfo_.batchSeqFusedFlag_ && baseShapeInfo_.tSize == 0U) || + (!scenarioInfo_.batchSeqFusedFlag_ && (baseShapeInfo_.bSize * baseShapeInfo_.s1Size == 0U))) { + scenarioInfo_.emptyTensorMode_ = EMPTY_TENSOR_MODE::EMPTY_QUERY; + } else if (baseShapeInfo_.blockNum == 0U) { + scenarioInfo_.emptyTensorMode_ = EMPTY_TENSOR_MODE::EMPTY_CACHE; + } else { + scenarioInfo_.emptyTensorMode_ = EMPTY_TENSOR_MODE::NON_EMPTY; + } + + if (scenarioInfo_.batchSeqFusedFlag_ && + (scenarioInfo_.cacheMode_ == CACHE_MODE::PA_BLK_BSND || scenarioInfo_.cacheMode_ == CACHE_MODE::PA_BLK_NZ)) { + OP_CHECK_IF(context_->actualSeqLen.shape == nullptr, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_->opName, "actualSeqLen", "null", + "When cacheMode in {PA_BLK_BSND, PA_BLK_NZ} and tokenX " + "shape dim num is 2, actualSeqLen should not be null"), + return GRAPH_FAILED); + baseShapeInfo_.bSize = context_->actualSeqLen.shape->GetStorageShape().GetDim(MLA_PROLOG_DIM_INDEX_0); + scenarioInfo_.actualSeqMode_ = ACTUAL_SEQ_MODE::EN_Q_LEN; + } else { + scenarioInfo_.actualSeqMode_ = ACTUAL_SEQ_MODE::DISABLED; + } + uint32_t cvRatio = aivNum_ / aicNum_; + // 当前仅在BS>=8K且数据类型为MXFP8时路由到切M模板,其他情况均路由到切N模板 + scenarioInfo_.splitMFlag_ = 0U; + if (scenarioInfo_.weightQuantMode_ == WEIGHT_QUANT_MODE::MXFP8_FULL_QUANT && + baseShapeInfo_.tSize >= 8192 && cvRatio == 2) { // 8192:BS >= 8K + if ((baseShapeInfo_.heSize == HEAD_SIZE1 || baseShapeInfo_.heSize == HEAD_SIZE2) && + baseShapeInfo_.nSize == 128) { // 128:N为128时路由到切M模板 + scenarioInfo_.splitMFlag_ = 1U; + } + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTiling::SetAttrInfo() +{ + reciprocalCq_ = 1.0f / baseShapeInfo_.hcqSize; + epsilonCq_ = *(context_->rmsNormEspilonCq); + reciprocalCkv_ = 1.0f / baseShapeInfo_.hckvSize; + epsilonCkv_ = *(context_->rmsNormEspilonCkv); + if (std::strncmp(context_->opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + queryNormFlag_ = *(context_->queryNormFlag); + weightQuantMode_ = static_cast(*(context_->weightQuantMode)); + kvQuantMode_ = static_cast(*(context_->kvQuantMode)); + queryQuantMode_ = static_cast(*(context_->queryQuantMode)); + ckvkrRepoMode_ = static_cast(*(context_->ckvkrRepoMode)); + quantSacleRepoMode_ = static_cast(*(context_->quantScaleRepoMode)); + tileSize_ = static_cast(*(context_->tileSize)); + qcQrScale_ = *(context_->qcQrScale); + kcScale_ = *(context_->kcScale); + } + return ge::GRAPH_SUCCESS; +} + +bool MlaPrologTiling::GetMatmulType(ge::DataType getype, matmul_tiling::DataType *mmType) +{ + auto mmdt = GE_TO_MM_DTYPE.find(getype); + if (mmdt != GE_TO_MM_DTYPE.end()) { + *mmType = mmdt->second; + return true; + } + return false; +} + +uint32_t MlaPrologTiling::CalcSingleCoreN(uint32_t n, uint32_t coreNum, uint32_t alignNum) const +{ + return CeilDiv(n, alignNum * coreNum) * alignNum; +} + +// mm1.m = stepBatchSize // 32 +// mm1.n = singlecoreHeadSizeCq // 64 +// mm1.k = headSizeX // 7168 +// mm1.baseM = stepBatchSize // 32 +// mm1.baseN = singlecoreHeadSizeCq // 64 +// mm1.baseK = 256 +ge::graphStatus MlaPrologTiling::FillMatmul1Tiling() +{ + if (scenarioInfo_.splitMFlag_ == 1U) { + singlecoreHeadSizeCq_ = baseShapeInfo_.hcqSize; + mm1BlockNum_ = aicNum_; + } else { + auto dataType = context_->weightDq.desc->GetDataType(); + singlecoreHeadSizeCq_ = + CalcSingleCoreN(baseShapeInfo_.hcqSize, aicNum_, BLOCK_SIZE / DTYPE_TO_SIZE.at(dataType)); + singlecoreHeadSizeCq_ = std::max(singlecoreHeadSizeCq_, 64U); // 64:最大使用24核 + mm1BlockNum_ = CeilDiv(baseShapeInfo_.hcqSize, singlecoreHeadSizeCq_); + } + return ge::GRAPH_SUCCESS; +} + +// singlecoreHeadSizeCkvKr = HeadSizeCkvDr / mm2CoreNum // 576 / 9 == 64 +// mm2.m = stepBatchSize +// mm2.n = singlecoreHeadSizeCkvKr +// mm2.k = headSizeX // size of He +// mm2.baseN = n +// mm2.baseK = 256 +ge::graphStatus MlaPrologTiling::FillMatmul2Tiling() +{ + if (scenarioInfo_.emptyTensorMode_ == EMPTY_TENSOR_MODE::EMPTY_CACHE) { + return ge::GRAPH_SUCCESS; + } + if (scenarioInfo_.splitMFlag_ == 1U) { + singlecoreHeadSizeCkvKr_ = baseShapeInfo_.hckvSize + baseShapeInfo_.drSize; + mm2BlockNum_ = aicNum_; + } else if (aicNum_ >= 9U) { // 9是经验值 + uint32_t baseN = 64U; + mm2BlockNum_ = (baseShapeInfo_.hckvSize + baseShapeInfo_.drSize) / baseN; + singlecoreHeadSizeCkvKr_ = baseN; + } else { + auto dataType = context_->weightDkvKr.desc->GetDataType(); + singlecoreHeadSizeCkvKr_ = CalcSingleCoreN(baseShapeInfo_.hckvSize + baseShapeInfo_.drSize, aicNum_, + BLOCK_SIZE / DTYPE_TO_SIZE.at(dataType)); + mm2BlockNum_ = CeilDiv(baseShapeInfo_.hckvSize + baseShapeInfo_.drSize, singlecoreHeadSizeCkvKr_); + } + return ge::GRAPH_SUCCESS; +} + +// singlecoreHeadSizeQcQr = headNum * (dimHeadSizeQc + dimHeadRope) / mm3CoreNum = 32 * (128 + 64) / 24 +// mm3.m = stepBatchSize +// mm3.n = singlecoreHeadSizeQcQr // 256 +// mm3.k = headSizeCq // size of Hcq 1536 +// mm3.baseN = 64 // +// mm3.baseK = 256 // +ge::graphStatus MlaPrologTiling::FillMatmul3Tiling() +{ + auto dataType = context_->weightUqQr.desc->GetDataType(); + auto oriM = baseShapeInfo_.nSize * (baseShapeInfo_.dSize + baseShapeInfo_.drSize); + if (enableGroupComputeOpt_) { + // 算力分组场景下G=8,dimHeadSizeQc跨8核切,dimHeadSizeQr跨4核切;matmulQc和matmulQr的singleN都取128 + singlecoreHeadSizeQcQr_ = CalcSingleCoreN(baseShapeInfo_.nSize * baseShapeInfo_.dSize, + GROUP_COMPUTE_CUBE_NUM_PER_GROUP, baseShapeInfo_.dSize); + } else if (enableDequantOpt_) { + // dequant流水掩盖场景,dimHeadSizeQc + dimHeadRope不跨核 + singlecoreHeadSizeQcQr_ = CalcSingleCoreN(oriM, aicNum_, baseShapeInfo_.dSize + baseShapeInfo_.drSize); + } else { + // headnum * (dimHeadSizeQc + dimHeadRope) 合轴切 + singlecoreHeadSizeQcQr_ = CalcSingleCoreN(oriM, aicNum_, BLOCK_SIZE / DTYPE_TO_SIZE.at(dataType)); + } + mm3BlockNum_ = CeilDiv(oriM, singlecoreHeadSizeQcQr_); + + if (scenarioInfo_.splitMFlag_ == 1U) { + singlecoreHeadSizeQcQr_ = oriM; + mm3BlockNum_ = aicNum_; + } + + return ge::GRAPH_SUCCESS; +} + +// mm4.m = stepBatchSize +// mm4.n = headSizeCkv // 512 +// mm4.k = dimHeadSizeQc // size of Qc 128 +// mm4.baseN = 128 // +// mm4.baseK = 128 // +// mm4.Kstride = dimHeadSizeQc + dimHeadRope +ge::graphStatus MlaPrologTiling::FillMatmul4Tiling() +{ + if (scenarioInfo_.splitMFlag_ == 1U) { + singlecoreNumHeadSize_ = baseShapeInfo_.nSize; + mm4BlockNum_ = aicNum_; + } else { + singlecoreNumHeadSize_ = CeilDiv(baseShapeInfo_.nSize, aicNum_); + mm4BlockNum_ = CeilDiv(baseShapeInfo_.nSize, singlecoreNumHeadSize_); + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTiling::ProcessBaseInputs() +{ + stepBatchSize_ = std::min(128U, baseShapeInfo_.tSize); + if (scenarioInfo_.splitMFlag_ == 1U && (stepBatchSize_ > 0U) && (aicNum_ > 0U) && (baseShapeInfo_.tSize > 0U)) { + mSubSize_ = (baseShapeInfo_.tSize + aicNum_ - 1U) / aicNum_; + // idx为[0, mSubCoreNum_]的核分到mSubSize_,其余核分到mSubSize_ - 1 + mSubCoreNum_ = baseShapeInfo_.tSize - (mSubSize_ - 1U) * aicNum_; + } + if (baseShapeInfo_.dSize == HIGH_THROUGHPUT__D_SIZE) { + stepNumHeadDequant_ = std::min(64U, baseShapeInfo_.nSize); + } else { + stepNumHeadDequant_ = std::min(16U, baseShapeInfo_.nSize); + } + vectorBlockNum_ = std::min(stepBatchSize_, aivNum_); + + uint32_t cvRatio = aivNum_ / aicNum_; + // 算力分组开关,仅当半量化场景,BS=1,G=8,可用核数大于等于16时进入分支 + // CV1:1时不支持分组计算场景 + if ((scenarioInfo_.quantMode_ == QUANT_MODE::PARTIAL_QUANT_KV_NO_QUANT || + scenarioInfo_.quantMode_ == QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_CHANNEL) && + baseShapeInfo_.tSize == GROUP_COMPUTE_T_SIZE && baseShapeInfo_.nkvSize == GROUP_COMPUTE_N_SIZE && + aivNum_ >= GROUP_COMPUTE_MIN_AIV_NUM && aicNum_ >= GROUP_COMPUTE_MIN_AIC_NUM && cvRatio != 1) { + enableGroupComputeOpt_ = true; + aivNum_ = 32U; + aicNum_ = 16U; + } else if ((context_->weightUqQr.desc->GetDataType() == ge::DT_INT8 && + baseShapeInfo_.nSize >= GROUP_COMPUTE_N_SIZE) || + context_->weightUqQr.desc->GetDataType() == ge::DT_FLOAT8_E4M3FN || + context_->weightUqQr.desc->GetDataType() == ge::DT_HIFLOAT8) { + // 场景1:INT8全量化且N大于等于8;场景2:MXFP8全量化场景 + // 通过切N处理MM3,MM4之后的操作例如Rope,DynamicQuant等会有性能收益 + enableDequantOpt_ = true; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTiling::FillTiling() +{ + baseParams_->tokenSize = baseShapeInfo_.tSize; + baseParams_->seq1Size = baseShapeInfo_.s1Size; + baseParams_->seq2Size = baseShapeInfo_.s2Size; + baseParams_->headSizeX = baseShapeInfo_.heSize; + baseParams_->headSizeCq = baseShapeInfo_.hcqSize; + baseParams_->headSizeCkv = baseShapeInfo_.hckvSize; + baseParams_->dtileSize = baseShapeInfo_.dtileSize; + baseParams_->headSizeQc = baseShapeInfo_.headSizeQc; + baseParams_->headSizeQr = baseShapeInfo_.headSizeQr; + baseParams_->headSizeKr = baseShapeInfo_.drSize; + baseParams_->numHeadSize = baseShapeInfo_.nSize; + baseParams_->numHeadKvSize = baseShapeInfo_.nkvSize; + baseParams_->dimHeadSizeQc = baseShapeInfo_.dSize; + baseParams_->dimHeadRope = baseShapeInfo_.drSize; + baseParams_->blockNum = baseShapeInfo_.blockNum; + baseParams_->blockSize = baseShapeInfo_.blockSize; + baseParams_->reciprocalCq = reciprocalCq_; + baseParams_->epsilonCq = epsilonCq_; + baseParams_->reciprocalCkv = reciprocalCkv_; + baseParams_->epsilonCkv = epsilonCkv_; + if (std::strncmp(context_->opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + baseParams_->queryNormFlag = queryNormFlag_ ? 1U : 0U; + baseParams_->kvQuantMode = static_cast(kvQuantMode_); + baseParams_->ckvkrRepoMode = static_cast(ckvkrRepoMode_); + baseParams_->quantScaleRepoMode = static_cast(quantSacleRepoMode_); + baseParams_->tileSize = tileSize_; + baseParams_->qcQrScale = qcQrScale_; + baseParams_->kcScale = kcScale_; + baseParams_->isQcQrScaleEnable = + static_cast(std::abs(qcQrScale_ - 1.0f) >= std::numeric_limits::epsilon()); + baseParams_->isKcScaleEnable = + static_cast(std::abs(kcScale_ - 1.0f) >= std::numeric_limits::epsilon()); + } else { + baseParams_->queryNormFlag = 0U; + baseParams_->kvQuantMode = 0U; + baseParams_->ckvkrRepoMode = 0U; + baseParams_->quantScaleRepoMode = 0U; + baseParams_->tileSize = 128U; + baseParams_->qcQrScale = 0; + baseParams_->kcScale = 0; + baseParams_->isQcQrScaleEnable = 0U; + baseParams_->isKcScaleEnable = 0U; + } + FillTilingCoreParams(); // 分核相关baseParams + return ge::GRAPH_SUCCESS; +} + +void MlaPrologTiling::FillTilingCoreParams() +{ + baseParams_->batchSize = baseShapeInfo_.bSize; + baseParams_->stepBatchSize = stepBatchSize_; + baseParams_->stepNumHeadDequant = stepNumHeadDequant_; + baseParams_->mSubSize = mSubSize_; + baseParams_->mSubCoreNum = mSubCoreNum_; + baseParams_->mm1BlockNum = mm1BlockNum_; + baseParams_->mm2BlockNum = mm2BlockNum_; + baseParams_->mm3BlockNum = mm3BlockNum_; + baseParams_->mm4BlockNum = mm4BlockNum_; + baseParams_->mm1SingleCoreN = singlecoreHeadSizeCq_; + baseParams_->mm2SingleCoreN = singlecoreHeadSizeCkvKr_; + baseParams_->mm3SingleCoreN = singlecoreHeadSizeQcQr_; + baseParams_->mm4SingleCoreBatch = singlecoreNumHeadSize_; + baseParams_->vectorBlockNum = vectorBlockNum_; +} + +ge::graphStatus MlaPrologTiling::CalcWorkSpace() +{ + workspaceSize_ = libapiSize_; + uint32_t mm1Mult = (scenarioInfo_.splitMFlag_ == 1U) ? mm1BlockNum_ : 1U; + uint32_t mm2Mult = (scenarioInfo_.splitMFlag_ == 1U) ? mm2BlockNum_ : 1U; + uint32_t mm3Mult = (scenarioInfo_.splitMFlag_ == 1U) ? mm3BlockNum_ : 1U; + uint32_t mm4Mult = (scenarioInfo_.splitMFlag_ == 1U) ? mm4BlockNum_ : 1U; + uint32_t dequantScaleMult = (scenarioInfo_.splitMFlag_ == 1U) ? static_cast(aicNum_) : 1U; + // 全量化场景:weightQuantMode 为 FULL/MXFP8/FP8/HIF8(即非 NO_QUANT 且非 PARTIAL) + if (scenarioInfo_.weightQuantMode_ != WEIGHT_QUANT_MODE::NO_QUANT && + scenarioInfo_.weightQuantMode_ != WEIGHT_QUANT_MODE::PARTIAL_QUANT) { + workspaceSize_ += static_cast(stepBatchSize_) * static_cast(baseShapeInfo_.hcqSize) * mm1Mult * + static_cast(NUM_BYTES_INT32); + workspaceSize_ += static_cast(stepBatchSize_) * static_cast(baseShapeInfo_.hcqSize) * mm1Mult * + static_cast(NUM_BYTES_BF16); + workspaceSize_ += static_cast(stepBatchSize_) * + static_cast(baseShapeInfo_.hckvSize + baseShapeInfo_.drSize) * mm2Mult * + static_cast(NUM_BYTES_INT32); + if (scenarioInfo_.kvQuantMode_ == KV_QUANT_MODE::PER_TENSOR) { + // 全量化场景mmQnRes输出到workspace, B, S1, N, Hckv, BF16 + workspaceSize_ += static_cast(stepBatchSize_) * static_cast(baseShapeInfo_.nSize) * + static_cast(baseShapeInfo_.hckvSize) * mm4Mult * + static_cast(NUM_BYTES_BF16); + } + } else { + workspaceSize_ += static_cast(stepBatchSize_) * static_cast(baseShapeInfo_.hcqSize) * mm1Mult * + static_cast(NUM_BYTES_BF16) * static_cast(2); // 2: double + workspaceSize_ += static_cast(stepBatchSize_) * + static_cast(baseShapeInfo_.hckvSize + baseShapeInfo_.drSize) * mm2Mult * + static_cast(NUM_BYTES_BF16); + } + workspaceSize_ += static_cast(stepBatchSize_) * + static_cast(baseShapeInfo_.headSizeQc + baseShapeInfo_.headSizeQr) * mm3Mult * + static_cast(NUM_BYTES_INT32); + workspaceSize_ += static_cast(stepBatchSize_) * static_cast(baseShapeInfo_.nSize) * + static_cast(baseShapeInfo_.dSize) * mm3Mult * static_cast(NUM_BYTES_BF16); + // SplitM非pertoken-pergroup量化场景下 mmQcQrResDequant使用两份workspace + if (scenarioInfo_.splitMFlag_ == 1U && + (scenarioInfo_.quantMode_ == QUANT_MODE::MXFP8_FULL_QUANT_KV_NO_QUANT || + scenarioInfo_.quantMode_ == QUANT_MODE::MXFP8_FULL_QUANT_KV_QUANT_PER_TENSOR)) { + workspaceSize_ += static_cast(stepBatchSize_) * static_cast(baseShapeInfo_.nSize) * + static_cast(baseShapeInfo_.dSize) * mm3Mult * static_cast(NUM_BYTES_BF16); + } + + if (enableGroupComputeOpt_ || enableDequantOpt_) { + workspaceSize_ += static_cast(stepBatchSize_) * dequantScaleMult * static_cast(BLOCK_SIZE); + } + if (context_->workSpaces) { + context_->workSpaces[0] = workspaceSize_; + } + OP_LOGI(context_->opName, "Tiling info: workspaceSize_ = %zu", workspaceSize_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTiling::GenTilingKey() const +{ + uint8_t typeValue = 0; + uint8_t quantType = 0; + if (scenarioInfo_.quantMode_ == QUANT_MODE::NO_QUANT) { + typeValue = 1U; + } else { + typeValue = 2U; + // kvCache量化场景,对应tiling key为1(半量化:0 + kv量化:1)或3(全量化:2 + kv量化:1) + // 全量化场景,对应tiling key为2+0(全量化:2)或2+1(全量化:2+ kv量化:1) + // 非量化和半量化场景,对应tiling key为0 + quantType = static_cast(scenarioInfo_.quantMode_); + } + + uint8_t cvMode = ASCENDC_TPL_MIX_AIC_1_2; // 默认cv 1:2模式 + if (aivNum_ == aicNum_) { + cvMode = ASCENDC_TPL_MIX_AIC_1_1; // cv 1:1模式 + } + + if (cvMode == ASCENDC_TPL_MIX_AIC_1_1 && + (scenarioInfo_.quantMode_ != QUANT_MODE::NO_QUANT || + (scenarioInfo_.cacheMode_ != CACHE_MODE::PA_BSND && scenarioInfo_.cacheMode_ != CACHE_MODE::PA_NZ))) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + context_->opName, "quantMode", + std::to_string(static_cast(scenarioInfo_.quantMode_)) + ", cacheMode is " + + std::to_string(static_cast(scenarioInfo_.cacheMode_)), + "CV1:1 mode only support quantMode in {NO_QUANT} and cacheMode in {PA_BSND,PA_NZ}"); + return ge::GRAPH_FAILED; + } + + if (scenarioInfo_.emptyTensorMode_ == EMPTY_TENSOR_MODE::EMPTY_QUERY) { + context_->tilingKey = GET_TPL_TILING_KEY(0, 0, 0, false, false, + static_cast(scenarioInfo_.emptyTensorMode_), 0, 0, cvMode); + } else { + uint8_t cacheMode = + scenarioInfo_.cacheMode_ == CACHE_MODE::TND ? 0 : static_cast(scenarioInfo_.cacheMode_); + context_->tilingKey = GET_TPL_TILING_KEY( + static_cast(cacheMode), typeValue, quantType, enableDequantOpt_, enableGroupComputeOpt_, + static_cast(scenarioInfo_.emptyTensorMode_), static_cast(scenarioInfo_.actualSeqMode_), + static_cast(scenarioInfo_.splitMFlag_), cvMode); + OP_LOGI( + context_->opName, + "MlaProlog tilingKey args: " + "CACHE_MODE:%u, SCENARIO:%u, QUANT_MODE:%u, ENABLE_DEQUANT_OPTIONAL:%u, ENABLE_GROUP_COMPUTE_OPTIONAL:%u, " + "EMPTY_TENSOR_MODE:%u, ACTUAL_SEQ_LEN_MODE:%u, SPLIT_M_MODE:%u, CV_MODE:%u", + static_cast(cacheMode), typeValue, quantType, enableDequantOpt_, enableGroupComputeOpt_, + static_cast(scenarioInfo_.emptyTensorMode_), static_cast(scenarioInfo_.actualSeqMode_), + static_cast(scenarioInfo_.splitMFlag_), cvMode); + } + OP_LOGI(context_->opName, "MlaProlog tilingKey:%lu", context_->tilingKey); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTiling::RunBigKernelTiling(MlaPrologContext &context, MlaPrologTilingData *tilingData) +{ + this->context_ = &context; + this->baseParams_ = &tilingData->baseParams; + MlaPrologTilingCheck tilingCheck_{*context_, baseShapeInfo_, scenarioInfo_}; + + using StatusFunction = std::function; + std::vector requiredTilingFuncs{ + std::bind(&MlaPrologTiling::GetNpuInfo, this), + std::bind(&MlaPrologTilingCheck::CheckAttrs, &tilingCheck_), + std::bind(&MlaPrologTilingCheck::CheckSingleRequiredParam, &tilingCheck_), + std::bind(&MlaPrologTilingCheck::CheckCacheMode, &tilingCheck_), + std::bind(&MlaPrologTiling::SetShapeInfo, this), + std::bind(&MlaPrologTiling::SetScenarioInfo, this), + std::bind(&MlaPrologTilingCheck::CheckScenarParam, &tilingCheck_), + std::bind(&MlaPrologTilingCheck::CheckQuantMode, &tilingCheck_), + std::bind(&MlaPrologTilingCheck::CheckDims, &tilingCheck_), + std::bind(&MlaPrologTilingCheck::CheckSpecialScenarioParamShape, &tilingCheck_), + std::bind(&MlaPrologTilingCheck::CheckParamByScenario, &tilingCheck_), + std::bind(&MlaPrologTiling::SetAttrInfo, this), + std::bind(&MlaPrologTiling::ProcessBaseInputs, this), + }; + for (const auto &func : requiredTilingFuncs) { + if (func() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + + if (scenarioInfo_.emptyTensorMode_ == EMPTY_TENSOR_MODE::EMPTY_QUERY) { + FillTiling(); + if (context_->workSpaces) { + context_->workSpaces[0] = libapiSize_; + } + GenTilingKey(); + context_->blockDim = 1U; + return ge::GRAPH_SUCCESS; + } + + std::vector optionalTilingFuncs{ + std::bind(&MlaPrologTiling::FillMatmul1Tiling, this), std::bind(&MlaPrologTiling::FillMatmul2Tiling, this), + std::bind(&MlaPrologTiling::FillMatmul3Tiling, this), std::bind(&MlaPrologTiling::FillMatmul4Tiling, this), + std::bind(&MlaPrologTiling::FillTiling, this), std::bind(&MlaPrologTiling::CalcWorkSpace, this), + std::bind(&MlaPrologTiling::GenTilingKey, this)}; + for (const auto &func : optionalTilingFuncs) { + if (func() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + } + + context_->blockDim = aicNum_; + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTiling::ConvertContext(gert::TilingContext &context, MlaPrologContext &mlaPrologContext) +{ + OP_CHECK_IF(context.GetNodeName() == nullptr, OP_LOGE_WITH_INVALID_INPUT(V1_OP_NAME, "OpName"), + return ge::GRAPH_FAILED); + + mlaPrologContext.opName = context.GetNodeName(); + mlaPrologContext.opType = context.GetNodeType(); + mlaPrologContext.platformInfo = context.GetPlatformInfo(); + + ConvertRequiredParams(context, mlaPrologContext); + ConvertOptionalParams(context, mlaPrologContext); + + auto attrs = context.GetAttrs(); + OP_CHECK_IF(attrs == nullptr, OP_LOGE_WITH_INVALID_INPUT(context.GetNodeName(), "attrs"), return ge::GRAPH_FAILED); + mlaPrologContext.rmsNormEspilonCq = attrs->GetAttrPointer(RMS_NORM_EPSILON_CQ_ATTR_INDEX); + mlaPrologContext.rmsNormEspilonCkv = attrs->GetAttrPointer(RMS_NORM_EPSILON_CKV_ATTR_INDEX); + mlaPrologContext.cacheMode = attrs->GetStr(CACHE_MODE_ATTR_INDEX); + if (std::strncmp(mlaPrologContext.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + mlaPrologContext.queryNormFlag = attrs->GetAttrPointer(QUERY_NORM_FLAG_ATTR_INDEX); + mlaPrologContext.weightQuantMode = attrs->GetAttrPointer(WEIGHT_QUANT_MODE_ATTR_INDEX); + mlaPrologContext.kvQuantMode = attrs->GetAttrPointer(KV_CACHE_QUANT_MODE_ATTR_INDEX); + mlaPrologContext.queryQuantMode = attrs->GetAttrPointer(QUERY_QUANT_MODE_ATTR_INDEX); + mlaPrologContext.ckvkrRepoMode = attrs->GetAttrPointer(CKVKR_REPO_MODE_ATTR_INDEX); + mlaPrologContext.quantScaleRepoMode = attrs->GetAttrPointer(QUANT_SCALE_REPO_MODE_ATTR_INDEX); + mlaPrologContext.tileSize = attrs->GetAttrPointer(TILE_SIZE_ATTR_INDEX); + mlaPrologContext.qcQrScale = attrs->GetAttrPointer(QC_QR_SCALE_ATTR_INDEX); + mlaPrologContext.kcScale = attrs->GetAttrPointer(KC_SCALE_ATTR_INDEX); + } else { + mlaPrologContext.queryNormFlag = nullptr; + mlaPrologContext.weightQuantMode = nullptr; + mlaPrologContext.kvQuantMode = nullptr; + mlaPrologContext.queryQuantMode = nullptr; + mlaPrologContext.ckvkrRepoMode = nullptr; + mlaPrologContext.quantScaleRepoMode = nullptr; + mlaPrologContext.tileSize = nullptr; + mlaPrologContext.qcQrScale = nullptr; + mlaPrologContext.kcScale = nullptr; + } + + OP_CHECK_IF(context.GetWorkspaceSizes(1) == nullptr, + OPS_REPORT_VECTOR_INNER_ERR(context.GetNodeName(), "workSpaceSize got from ge is nullptr"), + return ge::GRAPH_FAILED); + mlaPrologContext.workSpaces = context.GetWorkspaceSizes(1); + return ge::GRAPH_SUCCESS; +} + +void MlaPrologTiling::ConvertRequiredParams(gert::TilingContext &context, MlaPrologContext &mlaPrologContext) +{ + mlaPrologContext.tokenX.desc = context.GetRequiredInputDesc(TOKEN_X_INPUT_INDEX); + mlaPrologContext.tokenX.shape = context.GetRequiredInputShape(TOKEN_X_INPUT_INDEX); + mlaPrologContext.weightDq.desc = context.GetRequiredInputDesc(WEIGHT_DQ_INPUT_INDEX); + mlaPrologContext.weightDq.shape = context.GetRequiredInputShape(WEIGHT_DQ_INPUT_INDEX); + mlaPrologContext.weightUqQr.desc = context.GetRequiredInputDesc(WEIGHT_UQ_QR_INPUT_INDEX); + mlaPrologContext.weightUqQr.shape = context.GetRequiredInputShape(WEIGHT_UQ_QR_INPUT_INDEX); + mlaPrologContext.weightUk.desc = context.GetRequiredInputDesc(WEIGHT_UK_INPUT_INDEX); + mlaPrologContext.weightUk.shape = context.GetRequiredInputShape(WEIGHT_UK_INPUT_INDEX); + mlaPrologContext.weightDkvKr.desc = context.GetRequiredInputDesc(WEIGHT_DKV_KR_INPUT_INDEX); + mlaPrologContext.weightDkvKr.shape = context.GetRequiredInputShape(WEIGHT_DKV_KR_INPUT_INDEX); + mlaPrologContext.rmsnormGammaCq.desc = context.GetRequiredInputDesc(RMSNORM_GAMMA_CQ_INPUT_INDEX); + mlaPrologContext.rmsnormGammaCq.shape = context.GetRequiredInputShape(RMSNORM_GAMMA_CQ_INPUT_INDEX); + mlaPrologContext.rmsnormGammaCkv.desc = context.GetRequiredInputDesc(RMS_NORM_GAMMA_CKV_INPUT_INDEX); + mlaPrologContext.rmsnormGammaCkv.shape = context.GetRequiredInputShape(RMS_NORM_GAMMA_CKV_INPUT_INDEX); + mlaPrologContext.ropeSin.desc = context.GetRequiredInputDesc(ROPE_SIN_INPUT_INDEX); + mlaPrologContext.ropeSin.shape = context.GetRequiredInputShape(ROPE_SIN_INPUT_INDEX); + mlaPrologContext.ropeCos.desc = context.GetRequiredInputDesc(ROPE_COS_INPUT_INDEX); + mlaPrologContext.ropeCos.shape = context.GetRequiredInputShape(ROPE_COS_INPUT_INDEX); + + if (std::strncmp(mlaPrologContext.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + mlaPrologContext.kvCache.desc = context.GetRequiredInputDesc(KV_CACHE_INPUT_INDEX_V3); + mlaPrologContext.kvCache.shape = context.GetRequiredInputShape(KV_CACHE_INPUT_INDEX_V3); + mlaPrologContext.krCache.desc = context.GetRequiredInputDesc(KR_CACHE_INPUT_INDEX_V3); + mlaPrologContext.krCache.shape = context.GetRequiredInputShape(KR_CACHE_INPUT_INDEX_V3); + } else { + mlaPrologContext.cacheIndex.desc = context.GetRequiredInputDesc(CACHE_INDEX_INPUT_INDEX); + mlaPrologContext.cacheIndex.shape = context.GetRequiredInputShape(CACHE_INDEX_INPUT_INDEX); + mlaPrologContext.kvCache.desc = context.GetRequiredInputDesc(KV_CACHE_INPUT_INDEX); + mlaPrologContext.kvCache.shape = context.GetRequiredInputShape(KV_CACHE_INPUT_INDEX); + mlaPrologContext.krCache.desc = context.GetRequiredInputDesc(KR_CACHE_INPUT_INDEX); + mlaPrologContext.krCache.shape = context.GetRequiredInputShape(KR_CACHE_INPUT_INDEX); + } + + mlaPrologContext.query.desc = context.GetOutputDesc(QUERY_OUTPUT_INDEX); + mlaPrologContext.query.shape = context.GetOutputShape(QUERY_OUTPUT_INDEX); + mlaPrologContext.queryRope.desc = context.GetOutputDesc(QUERY_ROPE_OUTPUT_INDEX); + mlaPrologContext.queryRope.shape = context.GetOutputShape(QUERY_ROPE_OUTPUT_INDEX); + mlaPrologContext.kvCacheOut.desc = context.GetOutputDesc(KV_CACHE_OUT_OUTPUT_INDEX); + mlaPrologContext.kvCacheOut.shape = context.GetOutputShape(KV_CACHE_OUT_OUTPUT_INDEX); + mlaPrologContext.krCacheOut.desc = context.GetOutputDesc(KR_CACHE_OUT_OUTPUT_INDEX); + mlaPrologContext.krCacheOut.shape = context.GetOutputShape(KR_CACHE_OUT_OUTPUT_INDEX); +} + +void MlaPrologTiling::ConvertOptionalParams(gert::TilingContext &context, MlaPrologContext &mlaPrologContext) +{ + if (std::strncmp(mlaPrologContext.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + mlaPrologContext.cacheIndex.desc = context.GetRequiredInputDesc(CACHE_INDEX_INPUT_INDEX_V3); + mlaPrologContext.cacheIndex.shape = context.GetRequiredInputShape(CACHE_INDEX_INPUT_INDEX_V3); + } + mlaPrologContext.dequantScaleX.desc = context.GetOptionalInputDesc(DEQUANT_SCALE_X_INDEX); + mlaPrologContext.dequantScaleX.shape = context.GetOptionalInputShape(DEQUANT_SCALE_X_INDEX); + mlaPrologContext.dequantScaleWDq.desc = context.GetOptionalInputDesc(DEQUANT_SCALE_W_DQ_INDEX); + mlaPrologContext.dequantScaleWDq.shape = context.GetOptionalInputShape(DEQUANT_SCALE_W_DQ_INDEX); + mlaPrologContext.dequantScaleWUqQr.desc = context.GetOptionalInputDesc(DEQUANT_SCALE_W_UQ_QR_INDEX); + mlaPrologContext.dequantScaleWUqQr.shape = context.GetOptionalInputShape(DEQUANT_SCALE_W_UQ_QR_INDEX); + mlaPrologContext.dequantScaleWDkvKr.desc = context.GetOptionalInputDesc(DEQUANT_SCALE_W_DKV_KR_INDEX); + mlaPrologContext.dequantScaleWDkvKr.shape = context.GetOptionalInputShape(DEQUANT_SCALE_W_DKV_KR_INDEX); + mlaPrologContext.quantScaleCkv.desc = context.GetOptionalInputDesc(QUANT_SCALE_CKV_INDEX); + mlaPrologContext.quantScaleCkv.shape = context.GetOptionalInputShape(QUANT_SCALE_CKV_INDEX); + mlaPrologContext.quantScaleCkr.desc = context.GetOptionalInputDesc(QUANT_SCALE_CKR_INDEX); + mlaPrologContext.quantScaleCkr.shape = context.GetOptionalInputShape(QUANT_SCALE_CKR_INDEX); + mlaPrologContext.smoothScalesCq.desc = context.GetOptionalInputDesc(SMOOTH_SCALES_CQ_INDEX); + mlaPrologContext.smoothScalesCq.shape = context.GetOptionalInputShape(SMOOTH_SCALES_CQ_INDEX); + mlaPrologContext.actualSeqLen.desc = context.GetOptionalInputDesc(ACTUAL_SEQ_LEN_INDEX); + mlaPrologContext.actualSeqLen.shape = context.GetOptionalInputShape(ACTUAL_SEQ_LEN_INDEX); + mlaPrologContext.kNopeClipAlpha.desc = context.GetOptionalInputDesc(K_NOPE_CLIP_ALPHA_INDEX); + mlaPrologContext.kNopeClipAlpha.shape = context.GetOptionalInputShape(K_NOPE_CLIP_ALPHA_INDEX); + + // only v1 does not support dequantScaleQNope + if (std::strncmp(mlaPrologContext.opType, V1_OP_NAME, OP_NAME_LEN) == 0) { + mlaPrologContext.dequantScaleQNope.desc = nullptr; + mlaPrologContext.dequantScaleQNope.shape = nullptr; + } else { + mlaPrologContext.dequantScaleQNope.desc = context.GetOutputDesc(DEQUANT_SCALE_Q_NOPE_OUTPUT_INDEX); + mlaPrologContext.dequantScaleQNope.shape = context.GetOutputShape(DEQUANT_SCALE_Q_NOPE_OUTPUT_INDEX); + } + + if (std::strncmp(mlaPrologContext.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + mlaPrologContext.queryNorm.desc = context.GetOutputDesc(QUERY_NORM_OUTPUT_INDEX); + mlaPrologContext.queryNorm.shape = context.GetOutputShape(QUERY_NORM_OUTPUT_INDEX); + mlaPrologContext.dequantScaleQNorm.desc = context.GetOutputDesc(DEQUANT_SCALE_Q_NORM_OUTPUT_INDEX); + mlaPrologContext.dequantScaleQNorm.shape = context.GetOutputShape(DEQUANT_SCALE_Q_NORM_OUTPUT_INDEX); + } else { + mlaPrologContext.queryNorm.desc = nullptr; + mlaPrologContext.queryNorm.shape = nullptr; + mlaPrologContext.dequantScaleQNorm.desc = nullptr; + mlaPrologContext.dequantScaleQNorm.shape = nullptr; + } +} + +MLA_EXTERN_C ge::graphStatus TilingMlaProlog(gert::TilingContext *context) +{ + OP_CHECK_IF(context == nullptr, OPS_REPORT_VECTOR_INNER_ERR(V1_OP_NAME, "Context is nullptr."), + return ge::GRAPH_FAILED); + + MlaPrologContext mlaPrologContext{}; + OP_CHECK_IF(MlaPrologTiling::ConvertContext(*context, mlaPrologContext) != ge::GRAPH_SUCCESS, + OP_LOGE_WITHOUT_REPORT(context->GetNodeName(), + "Error occurred while converting tilingContext to MlaProlog context."), + return ge::GRAPH_FAILED); + + MlaPrologTiling mlaPrologTiling; + MlaPrologTilingData *tilingData = context->GetTilingData(); + OP_CHECK_IF(tilingData == nullptr, OPS_REPORT_VECTOR_INNER_ERR(context->GetNodeName(), "TilingData is nullptr."), + return ge::GRAPH_FAILED); + if (mlaPrologTiling.RunBigKernelTiling(mlaPrologContext, tilingData) == ge::SUCCESS) { + context->SetTilingKey(mlaPrologContext.tilingKey); + context->SetBlockDim(mlaPrologContext.blockDim); + return ge::GRAPH_SUCCESS; + } + return ge::GRAPH_FAILED; +} +} // namespace optiling diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling.h new file mode 100644 index 0000000000000000000000000000000000000000..ffe16405aacb423253626373f58371eb0faa9b78 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling.h @@ -0,0 +1,470 @@ +/** + * 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 mla_prolog_tiling.h + * \brief + */ + +#ifndef MLA_PROLOG_TILING_H +#define MLA_PROLOG_TILING_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "register/tilingdata_base.h" +#include "tiling/tiling_api.h" +#include "op_host/data_copy_transpose_tiling.h" +#include "exe_graph/runtime/tiling_context.h" +#include "register/op_def_registry.h" +#include "../op_kernel/mla_prolog_template_tiling_key.h" +#include "../op_kernel/mla_prolog_tiling_data.h" +#include "platform/soc_spec.h" + +#ifdef ASCENDC_OP_TEST +#define MLA_EXTERN_C extern "C" +#else +#define MLA_EXTERN_C +#endif + +namespace optiling { + +// INPUT +constexpr uint32_t TOKEN_X_INPUT_INDEX = 0; +constexpr uint32_t WEIGHT_DQ_INPUT_INDEX = 1; +constexpr uint32_t WEIGHT_UQ_QR_INPUT_INDEX = 2; +constexpr uint32_t WEIGHT_UK_INPUT_INDEX = 3; +constexpr uint32_t WEIGHT_DKV_KR_INPUT_INDEX = 4; +constexpr uint32_t RMSNORM_GAMMA_CQ_INPUT_INDEX = 5; +constexpr uint32_t RMS_NORM_GAMMA_CKV_INPUT_INDEX = 6; +constexpr uint32_t ROPE_SIN_INPUT_INDEX = 7; +constexpr uint32_t ROPE_COS_INPUT_INDEX = 8; +constexpr uint32_t CACHE_INDEX_INPUT_INDEX = 9; +constexpr uint32_t KV_CACHE_INPUT_INDEX = 10; +constexpr uint32_t KR_CACHE_INPUT_INDEX = 11; + +constexpr uint32_t KV_CACHE_INPUT_INDEX_V3 = 9; +constexpr uint32_t KR_CACHE_INPUT_INDEX_V3 = 10; +constexpr uint32_t CACHE_INDEX_INPUT_INDEX_V3 = 11; + +// INPUT(OPTION) +constexpr uint32_t DEQUANT_SCALE_X_INDEX = 12; +constexpr uint32_t DEQUANT_SCALE_W_DQ_INDEX = 13; +constexpr uint32_t DEQUANT_SCALE_W_UQ_QR_INDEX = 14; +constexpr uint32_t DEQUANT_SCALE_W_DKV_KR_INDEX = 15; +constexpr uint32_t QUANT_SCALE_CKV_INDEX = 16; +constexpr uint32_t QUANT_SCALE_CKR_INDEX = 17; +constexpr uint32_t SMOOTH_SCALES_CQ_INDEX = 18; +constexpr uint32_t ACTUAL_SEQ_LEN_INDEX = 19; +constexpr uint32_t K_NOPE_CLIP_ALPHA_INDEX = 20; + +// OUTPUT +constexpr uint32_t QUERY_OUTPUT_INDEX = 0; +constexpr uint32_t QUERY_ROPE_OUTPUT_INDEX = 1; +constexpr uint32_t KV_CACHE_OUT_OUTPUT_INDEX = 2; +constexpr uint32_t KR_CACHE_OUT_OUTPUT_INDEX = 3; +constexpr uint32_t DEQUANT_SCALE_Q_NOPE_OUTPUT_INDEX = 4; +constexpr uint32_t QUERY_NORM_OUTPUT_INDEX = 5; +constexpr uint32_t DEQUANT_SCALE_Q_NORM_OUTPUT_INDEX = 6; + +// ATTR +constexpr uint32_t RMS_NORM_EPSILON_CQ_ATTR_INDEX = 0; +constexpr uint32_t RMS_NORM_EPSILON_CKV_ATTR_INDEX = 1; +constexpr uint32_t CACHE_MODE_ATTR_INDEX = 2; +constexpr uint32_t QUERY_NORM_FLAG_ATTR_INDEX = 3; +constexpr uint32_t WEIGHT_QUANT_MODE_ATTR_INDEX = 4; +constexpr uint32_t KV_CACHE_QUANT_MODE_ATTR_INDEX = 5; +constexpr uint32_t QUERY_QUANT_MODE_ATTR_INDEX = 6; +constexpr uint32_t CKVKR_REPO_MODE_ATTR_INDEX = 7; +constexpr uint32_t QUANT_SCALE_REPO_MODE_ATTR_INDEX = 8; +constexpr uint32_t TILE_SIZE_ATTR_INDEX = 9; +constexpr uint32_t QC_QR_SCALE_ATTR_INDEX = 10; +constexpr uint32_t KC_SCALE_ATTR_INDEX = 11; + +constexpr uint32_t MLA_PROLOG_DIM_INDEX_0 = 0; +constexpr uint32_t MLA_PROLOG_DIM_INDEX_1 = 1; +constexpr uint32_t MLA_PROLOG_DIM_INDEX_2 = 2; +constexpr uint32_t MLA_PROLOG_DIM_INDEX_3 = 3; + +constexpr uint32_t MLA_PROLOG_DIM_NUM_0 = 0; +constexpr uint32_t MLA_PROLOG_DIM_NUM_1 = 1; +constexpr uint32_t MLA_PROLOG_DIM_NUM_2 = 2; +constexpr uint32_t MLA_PROLOG_DIM_NUM_3 = 3; +constexpr uint32_t MLA_PROLOG_DIM_NUM_4 = 4; + +constexpr uint32_t HEAD_SIZE1 = 7168; +constexpr uint32_t HEAD_SIZE2 = 7680; + +constexpr char CACHE_MODE_BSND[]{"BSND"}; +constexpr char CACHE_MODE_TND[]{"TND"}; +constexpr char CACHE_MODE_PA_BSND[]{"PA_BSND"}; +constexpr char CACHE_MODE_PA_NZ[]{"PA_NZ"}; +constexpr char CACHE_MODE_PA_BLK_BSND[]{"PA_BLK_BSND"}; +constexpr char CACHE_MODE_PA_BLK_NZ[]{"PA_BLK_NZ"}; + +constexpr char V1_OP_NAME[]{"MlaProlog"}; +constexpr char V2_OP_NAME[]{"MlaPrologV2"}; +constexpr char V3_OP_NAME[]{"MlaPrologV3"}; + + +constexpr uint32_t CACHE_MODE_LEN = + std::max({sizeof(CACHE_MODE_BSND), sizeof(CACHE_MODE_TND), sizeof(CACHE_MODE_PA_BSND), sizeof(CACHE_MODE_PA_NZ), + sizeof(CACHE_MODE_PA_BLK_BSND), sizeof(CACHE_MODE_PA_BLK_NZ)}); + +constexpr uint32_t OP_NAME_LEN = std::max({sizeof(V1_OP_NAME), sizeof(V2_OP_NAME), sizeof(V3_OP_NAME)}); + +struct MlaPrologBaseShapeInfo { + uint32_t bSize = 0; // B + uint32_t s1Size = 0; // S1 + uint32_t tSize = 0; // T + uint32_t s2Size = 0; // S2 + uint32_t heSize = 0; // He + uint32_t hcqSize = 0; // Hcq + uint32_t hckvSize = 0; // Hckv + uint32_t headSizeQc = 0; // N * D + uint32_t headSizeQr = 0; // N * Dr + uint32_t headSizeUqQr = 0; // N * (D + Dr) + uint32_t nSize = 0; // N + uint32_t nkvSize = 0; // Nkv + uint32_t dSize = 0; // D + uint32_t blockNum = 0; + uint32_t blockSize = 0; + uint32_t drSize = 0; // Dr + uint32_t dtileSize = 0; // Dtile +}; + +enum class CACHE_MODE : uint8_t { + BSND = 0, + PA_BSND = 1, + PA_NZ = 2, + PA_BLK_BSND = 3, + PA_BLK_NZ = 4, + TND = 5 +}; + +// cacheMode 字符串 → CACHE_MODE 枚举 hash 查找表 +// CheckCacheMode 已保证执行到此处的 cacheMode 必为 6 个合法串之一 +inline const std::unordered_map CACHE_MODE_HASH_TABLE = { + {CACHE_MODE_BSND, CACHE_MODE::BSND}, + {CACHE_MODE_TND, CACHE_MODE::TND}, + {CACHE_MODE_PA_BSND, CACHE_MODE::PA_BSND}, + {CACHE_MODE_PA_NZ, CACHE_MODE::PA_NZ}, + {CACHE_MODE_PA_BLK_BSND, CACHE_MODE::PA_BLK_BSND}, + {CACHE_MODE_PA_BLK_NZ, CACHE_MODE::PA_BLK_NZ}}; + +enum class EMPTY_TENSOR_MODE : uint8_t { + NON_EMPTY = 0, + EMPTY_CACHE = 1, + EMPTY_QUERY = 2 +}; + +enum class ACTUAL_SEQ_MODE : uint8_t { + DISABLED = 0, + EN_Q_LEN = 1, +}; + +enum class QUANT_MODE : int8_t { + ERROR_MODE = -1, + NO_QUANT = 0, + PARTIAL_QUANT_KV_NO_QUANT = 1, + PARTIAL_QUANT_KV_QUANT_PER_CHANNEL = 2, + FULL_QUANT_KV_NO_QUANT = 3, + FULL_QUANT_KV_QUANT_PER_TENSOR = 4, + PARTIAL_QUANT_KV_QUANT_PER_TILE = 5, + FULL_QUANT_KV_QUANT_PER_TILE = 6, + MXFP8_FULL_QUANT_KV_NO_QUANT = 7, + MXFP8_FULL_QUANT_KV_QUANT_PER_TENSOR = 8, + MXFP8_FULL_QUANT_KV_QUANT_PER_TILE = 9, + FP8_FULL_QUANT_KV_NO_QUANT = 10, + FP8_FULL_QUANT_KV_QUANT_PER_TENSOR = 11, + HIF8_FULL_QUANT_KV_NO_QUANT = 12, + HIF8_FULL_QUANT_KV_QUANT_PER_TENSOR = 13, + FP8_FULL_QUANT_KV_QUANT_PER_TILE = 14, + HIF8_FULL_QUANT_KV_QUANT_PER_TILE = 15 +}; + +enum class WEIGHT_QUANT_MODE : uint8_t { + NO_QUANT = 0, + PARTIAL_QUANT = 1, + FULL_QUANT = 2, + MXFP8_FULL_QUANT = 3, + FP8_FULL_QUANT = 4, + HIF8_FULL_QUANT = 5 +}; + +enum class KV_QUANT_MODE : uint8_t { + NO_QUANT = 0, + PER_TENSOR = 1, + PER_CHANNEL = 2, + PER_TILE = 3 +}; + +// weightQuantMode(0-5) × kvQuantMode(0-3) → QUANT_MODE 双重哈希查找表 +// 外层 Key 是 weightQuantMode,内层 Key 是 kvQuantMode,Value 是 QUANT_MODE +// 只存放合法组合,查不到即非法(含越界与组合非法) +inline const std::unordered_map> QUANT_MODE_HASH_TABLE = { + // wq=0 NO_QUANT: 合法 kv 仅 {0} + {0, {{0, QUANT_MODE::NO_QUANT}}}, + // wq=1 PARTIAL: 合法 kv 为 {0, 2, 3} + {1, + {{0, QUANT_MODE::PARTIAL_QUANT_KV_NO_QUANT}, + {2, QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_CHANNEL}, + {3, QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_TILE}}}, + // wq=2 FULL: 合法 kv 为 {0, 1, 3} + {2, + {{0, QUANT_MODE::FULL_QUANT_KV_NO_QUANT}, + {1, QUANT_MODE::FULL_QUANT_KV_QUANT_PER_TENSOR}, + {3, QUANT_MODE::FULL_QUANT_KV_QUANT_PER_TILE}}}, + // wq=3 MXFP8: 合法 kv 为 {0, 1, 3} + {3, + {{0, QUANT_MODE::MXFP8_FULL_QUANT_KV_NO_QUANT}, + {1, QUANT_MODE::MXFP8_FULL_QUANT_KV_QUANT_PER_TENSOR}, + {3, QUANT_MODE::MXFP8_FULL_QUANT_KV_QUANT_PER_TILE}}}, + // wq=4 FP8: 合法 kv 为 {0, 1, 3} + {4, + {{0, QUANT_MODE::FP8_FULL_QUANT_KV_NO_QUANT}, + {1, QUANT_MODE::FP8_FULL_QUANT_KV_QUANT_PER_TENSOR}, + {3, QUANT_MODE::FP8_FULL_QUANT_KV_QUANT_PER_TILE}}}, + // wq=5 HIF8: 合法 kv 为 {0, 1, 3} + {5, + {{0, QUANT_MODE::HIF8_FULL_QUANT_KV_NO_QUANT}, + {1, QUANT_MODE::HIF8_FULL_QUANT_KV_QUANT_PER_TENSOR}, + {3, QUANT_MODE::HIF8_FULL_QUANT_KV_QUANT_PER_TILE}}}}; + +// 各 weightQuantMode 下合法 kvQuantMode 集合说明(用于错误日志 reason 文本,与原实现逐字一致) +inline const std::unordered_map VALID_KV_REASON_TABLE = { + {0, "When weightQuantMode==0, must be {0}"}, {1, "When weightQuantMode==1, must be {0, 2, 3}"}, + {2, "When weightQuantMode==2, must be {0, 1, 3}"}, {3, "When weightQuantMode==3, must be {0, 1, 3}"}, + {4, "When weightQuantMode==4, must be {0, 1, 3}"}, {5, "When weightQuantMode==5, must be {0, 1, 3}"}}; + +// QUANT_MODE → (weightQuantMode, kvQuantMode) 反向映射表 +// 用于从 quantMode_ 反推 wq/kvq,V1/V2(按 dtype 推断 quantMode_)与 V3(正向查表得 quantMode_)通用 +// 每个 QUANT_MODE 唯一对应一组 (wq, kvq),与正向表 QUANT_MODE_HASH_TABLE 互逆 +inline const std::unordered_map> QUANT_MODE_REVERSE_TABLE = { + {QUANT_MODE::NO_QUANT, {WEIGHT_QUANT_MODE::NO_QUANT, KV_QUANT_MODE::NO_QUANT}}, + {QUANT_MODE::PARTIAL_QUANT_KV_NO_QUANT, {WEIGHT_QUANT_MODE::PARTIAL_QUANT, KV_QUANT_MODE::NO_QUANT}}, + {QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_CHANNEL, {WEIGHT_QUANT_MODE::PARTIAL_QUANT, KV_QUANT_MODE::PER_CHANNEL}}, + {QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_TILE, {WEIGHT_QUANT_MODE::PARTIAL_QUANT, KV_QUANT_MODE::PER_TILE}}, + {QUANT_MODE::FULL_QUANT_KV_NO_QUANT, {WEIGHT_QUANT_MODE::FULL_QUANT, KV_QUANT_MODE::NO_QUANT}}, + {QUANT_MODE::FULL_QUANT_KV_QUANT_PER_TENSOR, {WEIGHT_QUANT_MODE::FULL_QUANT, KV_QUANT_MODE::PER_TENSOR}}, + {QUANT_MODE::FULL_QUANT_KV_QUANT_PER_TILE, {WEIGHT_QUANT_MODE::FULL_QUANT, KV_QUANT_MODE::PER_TILE}}, + {QUANT_MODE::MXFP8_FULL_QUANT_KV_NO_QUANT, {WEIGHT_QUANT_MODE::MXFP8_FULL_QUANT, KV_QUANT_MODE::NO_QUANT}}, + {QUANT_MODE::MXFP8_FULL_QUANT_KV_QUANT_PER_TENSOR, + {WEIGHT_QUANT_MODE::MXFP8_FULL_QUANT, KV_QUANT_MODE::PER_TENSOR}}, + {QUANT_MODE::MXFP8_FULL_QUANT_KV_QUANT_PER_TILE, {WEIGHT_QUANT_MODE::MXFP8_FULL_QUANT, KV_QUANT_MODE::PER_TILE}}, + {QUANT_MODE::FP8_FULL_QUANT_KV_NO_QUANT, {WEIGHT_QUANT_MODE::FP8_FULL_QUANT, KV_QUANT_MODE::NO_QUANT}}, + {QUANT_MODE::FP8_FULL_QUANT_KV_QUANT_PER_TENSOR, {WEIGHT_QUANT_MODE::FP8_FULL_QUANT, KV_QUANT_MODE::PER_TENSOR}}, + {QUANT_MODE::FP8_FULL_QUANT_KV_QUANT_PER_TILE, {WEIGHT_QUANT_MODE::FP8_FULL_QUANT, KV_QUANT_MODE::PER_TILE}}, + {QUANT_MODE::HIF8_FULL_QUANT_KV_NO_QUANT, {WEIGHT_QUANT_MODE::HIF8_FULL_QUANT, KV_QUANT_MODE::NO_QUANT}}, + {QUANT_MODE::HIF8_FULL_QUANT_KV_QUANT_PER_TENSOR, {WEIGHT_QUANT_MODE::HIF8_FULL_QUANT, KV_QUANT_MODE::PER_TENSOR}}, + {QUANT_MODE::HIF8_FULL_QUANT_KV_QUANT_PER_TILE, {WEIGHT_QUANT_MODE::HIF8_FULL_QUANT, KV_QUANT_MODE::PER_TILE}}}; + +enum class QUERY_QUANT_MODE : uint8_t { + NO_QUANT = 0, + PER_TOKEN_HEAD = 1 +}; + +enum class CKVKR_REPO_MODE : uint8_t { + DIVIDE = 0, + COMBINE = 1 +}; + +enum class QUANT_SCALE_REPO_MODE : uint8_t { + DIVIDE = 0, + COMBINE = 1 +}; + +struct MlaPrologScenarioInfo { + bool isV1Flag_; + bool batchSeqFusedFlag_; + uint8_t splitMFlag_; + QUANT_MODE quantMode_; + CACHE_MODE cacheMode_; + EMPTY_TENSOR_MODE emptyTensorMode_; + ACTUAL_SEQ_MODE actualSeqMode_; + WEIGHT_QUANT_MODE weightQuantMode_; + KV_QUANT_MODE kvQuantMode_; +}; + +struct MlaPrologCompileInfo { + int64_t core_num; +}; + +struct BaseParaInfo { + const gert::CompileTimeTensorDesc *desc; + const gert::StorageShape *shape; +}; + +struct RequiredParaInfo : BaseParaInfo {}; + +struct OptionalParaInfo : BaseParaInfo {}; + +constexpr uint32_t BLOCK_SIZE = 32; +constexpr uint32_t NUM_BYTES_BF16 = 2; +constexpr uint32_t NUM_BYTES_INT8 = 1; +constexpr uint32_t NUM_BYTES_INT32 = 4; +constexpr uint32_t NUM_BYTES_FP32 = 4; + +constexpr uint32_t GROUP_COMPUTE_CUBE_NUM_PER_GROUP = 8U; +constexpr uint32_t HIGH_THROUGHPUT__D_SIZE = 128U; +constexpr uint32_t GROUP_COMPUTE_T_SIZE = 1U; +constexpr uint32_t GROUP_COMPUTE_NKV_SIZE = 8U; +constexpr uint32_t GROUP_COMPUTE_MIN_AIC_NUM = 16U; +constexpr uint32_t GROUP_COMPUTE_MIN_AIV_NUM = 32U; +constexpr uint32_t GROUP_COMPUTE_N_SIZE = 8U; + +struct MlaPrologContext { + const char *opName; + const char *opType; + fe::PlatFormInfos *platformInfo; + RequiredParaInfo tokenX; + RequiredParaInfo weightDq; + RequiredParaInfo weightUqQr; + RequiredParaInfo weightUk; + RequiredParaInfo weightDkvKr; + RequiredParaInfo rmsnormGammaCq; + RequiredParaInfo rmsnormGammaCkv; + RequiredParaInfo ropeSin; + RequiredParaInfo ropeCos; + RequiredParaInfo kvCache; + RequiredParaInfo krCache; + OptionalParaInfo cacheIndex; + OptionalParaInfo dequantScaleX; + OptionalParaInfo dequantScaleWDq; + OptionalParaInfo dequantScaleWUqQr; + OptionalParaInfo dequantScaleWDkvKr; + OptionalParaInfo quantScaleCkv; + OptionalParaInfo quantScaleCkr; + OptionalParaInfo smoothScalesCq; + OptionalParaInfo actualSeqLen; + OptionalParaInfo kNopeClipAlpha; + RequiredParaInfo query; + RequiredParaInfo queryRope; + RequiredParaInfo kvCacheOut; + RequiredParaInfo krCacheOut; + OptionalParaInfo dequantScaleQNope; + OptionalParaInfo queryNorm; + OptionalParaInfo dequantScaleQNorm; + + const float *rmsNormEspilonCq; + const float *rmsNormEspilonCkv; + const char *cacheMode; + const bool *queryNormFlag; + + const int64_t *weightQuantMode; + const int64_t *kvQuantMode; + const int64_t *queryQuantMode; + const int64_t *ckvkrRepoMode; + const int64_t *quantScaleRepoMode; + const int64_t *tileSize; + + const float *qcQrScale; + const float *kcScale; + + size_t *workSpaces; + uint64_t tilingKey; + uint32_t blockDim; +}; + +class MlaPrologTiling { +public: + MlaPrologTiling() = default; + ~MlaPrologTiling() = default; + + ge::graphStatus RunBigKernelTiling(MlaPrologContext &context, MlaPrologTilingData *tilingData); + static ge::graphStatus ConvertContext(gert::TilingContext &context, MlaPrologContext &mlaPrologContext); + +private: + static void ConvertRequiredParams(gert::TilingContext &context, MlaPrologContext &mlaPrologContext); + static void ConvertOptionalParams(gert::TilingContext &context, MlaPrologContext &mlaPrologContext); + ge::graphStatus GetNpuInfo(); + ge::graphStatus SetScenarioInfo(); + ge::graphStatus SetAttrInfo(); + QUANT_MODE GetQuantizationMode() const; + QUANT_MODE GetQuantizationModeV3() const; + QUANT_MODE GetQuantizationModeV3Dav() const; + ge::graphStatus SetShapeInfo(); + ge::graphStatus ProcessBaseInputs(); + ge::graphStatus FillTiling(); + void FillTilingCoreParams(); + ge::graphStatus FillMatmul1Tiling(); + ge::graphStatus FillMatmul2Tiling(); + ge::graphStatus FillMatmul3Tiling(); + ge::graphStatus FillMatmul4Tiling(); + uint32_t CalcSingleCoreN(uint32_t n, uint32_t coreNum, uint32_t alignNum = 16) const; + bool GetMatmulType(ge::DataType getype, matmul_tiling::DataType *mmType); + ge::graphStatus CalcWorkSpace(); + ge::graphStatus GenTilingKey() const; + + NpuArch GetCurNpuArch() const; + + MlaPrologBaseShapeInfo baseShapeInfo_; + MlaPrologScenarioInfo scenarioInfo_; + + uint32_t stepBatchSize_ = 0; + uint32_t stepNumHeadDequant_ = 0; + uint32_t mSubSize_ = 0; + uint32_t mSubCoreNum_ = 0; + + uint32_t mm1BlockNum_ = 0; + uint32_t mm2BlockNum_ = 0; + uint32_t mm3BlockNum_ = 0; + uint32_t mm4BlockNum_ = 0; + uint32_t vectorBlockNum_ = 0; + + uint32_t singlecoreHeadSizeCq_ = 0; + uint32_t singlecoreHeadSizeQcQr_ = 0; + uint32_t singlecoreHeadSizeCkvKr_ = 0; + uint32_t singlecoreNumHeadSize_ = 0; + + float reciprocalCq_ = 0.00001f; + float epsilonCq_ = 1.0f; + float reciprocalCkv_ = 0.00001f; + float epsilonCkv_ = 1.0f; + bool queryNormFlag_ = false; + + WEIGHT_QUANT_MODE weightQuantMode_ = WEIGHT_QUANT_MODE::NO_QUANT; + KV_QUANT_MODE kvQuantMode_ = KV_QUANT_MODE::NO_QUANT; + QUERY_QUANT_MODE queryQuantMode_ = QUERY_QUANT_MODE::NO_QUANT; + CKVKR_REPO_MODE ckvkrRepoMode_ = CKVKR_REPO_MODE::DIVIDE; + QUANT_SCALE_REPO_MODE quantSacleRepoMode_ = QUANT_SCALE_REPO_MODE::DIVIDE; + uint32_t tileSize_ = 128; + float qcQrScale_ = 1.0f; + float kcScale_ = 1.0f; + + ge::DataType mmDateType_ = ge::DT_BF16; + bool enableDequantOpt_ = false; + bool enableGroupComputeOpt_ = false; // 低延时场景算例分组标记 + + size_t ubSize_ = 0; + size_t l1Size_ = 0; + size_t l0cSize_ = 0; + size_t l0bSize_ = 0; + uint32_t coreNum_ = 0; + uint32_t aicNum_ = 0; + uint32_t aivNum_ = 0; + size_t libapiSize_ = 0; + size_t workspaceSize_ = 0; + + MlaPrologContext *context_ = nullptr; + MlaPrologBaseParams *baseParams_ = nullptr; +}; + +ge::graphStatus TilingPrepareForMlaProlog(gert::TilingParseContext *context); +MLA_EXTERN_C ge::graphStatus TilingMlaProlog(gert::TilingContext *context); +} // namespace optiling + +#endif // MLA_PROLOG_TILING_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling_check.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling_check.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f0b8d0dc51a8278de254d8681ddfbb9b98eb4ae9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling_check.cpp @@ -0,0 +1,1277 @@ +/** + * 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 mla_prolog_tiling_check.cpp + * \brief + */ + +#include "mla_prolog_tiling_check.h" +#include +#include "log/log.h" + +using namespace ge; + +namespace optiling { + +const std::unordered_map DTYPE_TO_SIZE{ + {ge::DT_BF16, 2}, {ge::DT_FLOAT16, 2}, {ge::DT_INT8, 1}, {ge::DT_FLOAT8_E4M3FN, 1}, + {ge::DT_FLOAT8_E8M0, 1}, {ge::DT_HIFLOAT8, 1}, {ge::DT_INT32, 4}, {ge::DT_FLOAT, 4}}; + +template +std::string ElemToString(const E &elem) +{ + return std::to_string(elem); +} + +std::string FormatToString(const ge::Format format) +{ + return std::string(ge::GetFormatName(format)); +} + +template +std::string ConvertContainerToString(const C &container, Func func = ElemToString) +{ + if (container.empty() || func == nullptr) { + return "[]"; + } + std::stringstream ss; + ss << "["; + bool isFirst = true; + for (const auto &elem : container) { + if (!isFirst) { + ss << ", "; + } + ss << func(elem); + isFirst = false; + } + ss << "]"; + return ss.str(); +} + +template +std::string ConvertShapeToString(const C &container, Func func = ElemToString) +{ + if (container.empty() || func == nullptr) { + return "[]"; + } + std::stringstream ss; + bool isFirst = true; + for (const auto &elem : container) { + if (!isFirst) { + ss << ", "; + } + ss << func(elem); + isFirst = false; + } + return ss.str(); +} + +template +std::string ConvertContainerToStringV3(const C &container, Func func = ElemToString) +{ + if (container.empty() || func == nullptr) { + return "[]"; + } + std::stringstream ss; + const size_t total = container.size(); + size_t idx = 0; + for (const auto &elem : container) { + if (idx > 0) { + if (idx == total - 1) { + ss << " or "; + } else { + ss << ", "; + } + } + ss << func(elem); + ++idx; + } + return ss.str(); +} + +std::string GetShapeStr(const gert::Shape &aShape) +{ + std::string shapeStr = "["; + for (size_t i = 0; i < aShape.GetDimNum(); ++i) { + shapeStr += std::to_string(aShape.GetDim(i)) + (i + 1 < aShape.GetDimNum() ? ", " : ""); + } + return shapeStr + "]"; +} + +template +inline auto CeilDiv(T a, T b) -> T +{ + if (b == 0) { + return b; + } + return (a + b - 1) / b; +} + +NpuArch MlaPrologTilingCheck::GetCurNpuArch() const +{ + auto ascendcPlatform = platform_ascendc::PlatformAscendC(context_.platformInfo); + NpuArch npuArch = ascendcPlatform.GetCurNpuArch(); + return npuArch; +} + +// =================================全量参数校验================================= +bool MlaPrologTilingCheck::CheckAttrsRange() const +{ + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + if (GetCurNpuArch() == NpuArch::DAV_3510) { + const std::unordered_set supportedWeightQuantMode{0U, 1U, 2U, 3U, 4U, 5U}; + OP_CHECK_IF(supportedWeightQuantMode.find(*context_.weightQuantMode) == supportedWeightQuantMode.end(), + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "WeightQuantMode", + std::to_string(*context_.weightQuantMode), "0, 1, 2, 3, 4 or 5"), + return false); + } else { + const std::unordered_set supportedWeightQuantMode{0U, 1U, 2U}; + OP_CHECK_IF(supportedWeightQuantMode.find(*context_.weightQuantMode) == supportedWeightQuantMode.end(), + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "WeightQuantMode", + std::to_string(*context_.weightQuantMode), "0, 1 or 2"), + return false); + } + + const std::unordered_set supportedKvQuantMode{0U, 1U, 2U, 3U}; + OP_CHECK_IF(supportedKvQuantMode.find(*context_.kvQuantMode) == supportedKvQuantMode.end(), + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "KvQuantMode", std::to_string(*context_.kvQuantMode), + "0, 1, 2 or 3"), + return false); + + const std::unordered_set supportedQueryQuantMode{0U, 1U}; + OP_CHECK_IF(supportedQueryQuantMode.find(*context_.queryQuantMode) == supportedQueryQuantMode.end(), + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "QueryQuantMode", + std::to_string(*context_.queryQuantMode), "0 or 1"), + return false); + + const std::unordered_set supportedCkvkrRepoMode{0U, 1U}; + OP_CHECK_IF(supportedCkvkrRepoMode.find(*context_.ckvkrRepoMode) == supportedCkvkrRepoMode.end(), + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "CkvkrRepoMode", std::to_string(*context_.ckvkrRepoMode), + "0 or 1"), + return false); + + const std::unordered_set supportedQuantScaleRepoMode{0U, 1U}; + OP_CHECK_IF(supportedQuantScaleRepoMode.find(*context_.quantScaleRepoMode) == supportedQuantScaleRepoMode.end(), + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "QuantScaleRepoMode", + std::to_string(*context_.quantScaleRepoMode), "0 or 1"), + return false); + + const std::unordered_set supportedTileSize{128U}; + OP_CHECK_IF(supportedTileSize.find(*context_.tileSize) == supportedTileSize.end(), + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "TileSize", std::to_string(*context_.tileSize), "128"), + return false); + } + return true; +} + +bool MlaPrologTilingCheck::CheckAttrsNotNull() const +{ + OP_CHECK_IF(context_.rmsNormEspilonCq == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_.opName, "rmsNormEspilonCq"), + return false); + + OP_CHECK_IF(context_.rmsNormEspilonCkv == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_.opName, "rmsNormEspilonCkv"), + return false); + + OP_CHECK_IF(context_.cacheMode == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_.opName, "cacheMode"), return false); + + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + OP_CHECK_IF(context_.queryNormFlag == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_.opName, "queryNormFlag"), + return false); + + OP_CHECK_IF(context_.weightQuantMode == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_.opName, "weightQuantMode"), + return false); + + OP_CHECK_IF(context_.kvQuantMode == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_.opName, "kvQuantMode"), + return false); + + OP_CHECK_IF(context_.queryQuantMode == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_.opName, "queryQuantMode"), + return false); + + OP_CHECK_IF(context_.ckvkrRepoMode == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_.opName, "ckvkrRepoMode"), + return false); + + OP_CHECK_IF(context_.quantScaleRepoMode == nullptr, + OP_LOGE_WITH_INVALID_INPUT(context_.opName, "quantScaleRepoMode"), return false); + + OP_CHECK_IF(context_.tileSize == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_.opName, "tileSize"), + return false); + + OP_CHECK_IF(context_.qcQrScale == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_.opName, "qcQrScale"), + return false); + + OP_CHECK_IF(context_.kcScale == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_.opName, "kcScale"), return false); + } + return true; +} + +ge::graphStatus MlaPrologTilingCheck::CheckAttrs() const +{ + if (!CheckAttrsNotNull() || !CheckAttrsRange()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTilingCheck::CheckDims() const +{ + OP_CHECK_IF( + baseShapeInfo_.bSize > MAX_B_SIZE, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_.opName, "B", std::to_string(baseShapeInfo_.bSize), + "B size should not be greater than " + std::to_string(MAX_B_SIZE)), + return ge::GRAPH_FAILED); + const std::set supportedHeSize{1024U, 2048U, 3072U, 4096U, 5120U, 6144U, 7168U, 7680U, 8192U}; + OP_CHECK_IF(supportedHeSize.find(baseShapeInfo_.heSize) == supportedHeSize.end(), + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "He", std::to_string(baseShapeInfo_.heSize), + ConvertContainerToStringV3(supportedHeSize)), + return ge::GRAPH_FAILED); + const std::set supportedNSize{1U, 2U, 4U, 8U, 16U, 32U, 64U, 128U}; + OP_CHECK_IF((supportedNSize.find(baseShapeInfo_.nSize) == supportedNSize.end()), + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "N", std::to_string(baseShapeInfo_.nSize), + ConvertContainerToStringV3(supportedNSize)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(baseShapeInfo_.hckvSize != HCKV_SIZE, + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "Hckv", std::to_string(baseShapeInfo_.hckvSize), + std::to_string(HCKV_SIZE)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(baseShapeInfo_.drSize != DR_SIZE, + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "Dr", std::to_string(baseShapeInfo_.drSize), + std::to_string(DR_SIZE)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(baseShapeInfo_.nkvSize != NKV_SIZE, + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "Nkv", std::to_string(baseShapeInfo_.nkvSize), + std::to_string(NKV_SIZE)), + return ge::GRAPH_FAILED); + if (scenarioInfo_.cacheMode_ != CACHE_MODE::BSND && scenarioInfo_.cacheMode_ != CACHE_MODE::TND) { + OP_CHECK_IF(baseShapeInfo_.blockSize < MIN_BLOCK_SIZE || baseShapeInfo_.blockSize > MAX_BLOCK_SIZE || + baseShapeInfo_.blockSize % ALIGN_BLOCK_SIZE != 0, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + context_.opName, "blockSize", std::to_string(baseShapeInfo_.blockSize), + "BlockSize must be within [" + std::to_string(MIN_BLOCK_SIZE) + ", " + + std::to_string(MAX_BLOCK_SIZE) + "] and a multiple of " + std::to_string(ALIGN_BLOCK_SIZE)), + return ge::GRAPH_FAILED); + } + if (CheckHcqSize() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + if (CheckDSize() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + if (CheckDtileSize() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTilingCheck::CheckQuantMode() const +{ + if (GetCurNpuArch() == NpuArch::DAV_3510) { + const std::set supportedQuantModes{ + static_cast(QUANT_MODE::NO_QUANT), + static_cast(QUANT_MODE::PARTIAL_QUANT_KV_NO_QUANT), + static_cast(QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_CHANNEL), + static_cast(QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_TILE), + static_cast(QUANT_MODE::FULL_QUANT_KV_NO_QUANT), + static_cast(QUANT_MODE::FULL_QUANT_KV_QUANT_PER_TENSOR), + static_cast(QUANT_MODE::FULL_QUANT_KV_QUANT_PER_TILE), + static_cast(QUANT_MODE::MXFP8_FULL_QUANT_KV_NO_QUANT), + static_cast(QUANT_MODE::MXFP8_FULL_QUANT_KV_QUANT_PER_TENSOR), + static_cast(QUANT_MODE::MXFP8_FULL_QUANT_KV_QUANT_PER_TILE), + static_cast(QUANT_MODE::FP8_FULL_QUANT_KV_NO_QUANT), + static_cast(QUANT_MODE::FP8_FULL_QUANT_KV_QUANT_PER_TENSOR), + static_cast(QUANT_MODE::HIF8_FULL_QUANT_KV_NO_QUANT), + static_cast(QUANT_MODE::HIF8_FULL_QUANT_KV_QUANT_PER_TENSOR), + static_cast(QUANT_MODE::FP8_FULL_QUANT_KV_QUANT_PER_TILE), + static_cast(QUANT_MODE::HIF8_FULL_QUANT_KV_QUANT_PER_TILE)}; + OP_CHECK_IF(supportedQuantModes.find(static_cast(scenarioInfo_.quantMode_)) == + supportedQuantModes.end(), + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + context_.opName, "quantMode", std::to_string(static_cast(scenarioInfo_.quantMode_)), + "On DAV3510, quantMode allows only " + ConvertContainerToStringV3(supportedQuantModes)), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTilingCheck::CheckHcqSize() const +{ + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + const std::set supportedHcqSize{1536U, 2048U}; + OP_CHECK_IF(supportedHcqSize.find(baseShapeInfo_.hcqSize) == supportedHcqSize.end(), + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "Hcq", std::to_string(baseShapeInfo_.hcqSize), + ConvertContainerToStringV3(supportedHcqSize)), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(baseShapeInfo_.hcqSize != HCQ_SIZE, + OP_LOGE(context_.opName, "Hcq allows only %u, got %u.", HCQ_SIZE, baseShapeInfo_.hcqSize), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTilingCheck::CheckDSize() const +{ + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + const std::set supportedDSize{128U, 192U}; + OP_CHECK_IF(supportedDSize.find(baseShapeInfo_.dSize) == supportedDSize.end(), + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "D", std::to_string(baseShapeInfo_.dSize), + ConvertContainerToStringV3(supportedDSize)), + return ge::GRAPH_FAILED); + } else { + OP_CHECK_IF(baseShapeInfo_.dSize != D_SIZE, + OP_LOGE(context_.opName, "D allows only %u, got %u.", D_SIZE, baseShapeInfo_.dSize), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTilingCheck::CheckDtileSize() const +{ + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + uint32_t supportedDtileSize = baseShapeInfo_.hckvSize; + if (*(context_.ckvkrRepoMode) == static_cast(CKVKR_REPO_MODE::COMBINE)) { + supportedDtileSize += + baseShapeInfo_.drSize * (DTYPE_TO_SIZE.at(ge::DT_BF16) / DTYPE_TO_SIZE.at(ge::DT_INT8)); + } + if (*(context_.quantScaleRepoMode) == static_cast(QUANT_SCALE_REPO_MODE::COMBINE)) { + supportedDtileSize += baseShapeInfo_.hckvSize / static_cast(*(context_.tileSize)) * + (DTYPE_TO_SIZE.at(ge::DT_FLOAT) / DTYPE_TO_SIZE.at(ge::DT_INT8)); + } + if (baseShapeInfo_.dtileSize != supportedDtileSize) { + if (*(context_.kvQuantMode) == static_cast(KV_QUANT_MODE::PER_TILE)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + context_.opName, "dtileSize", std::to_string(baseShapeInfo_.dtileSize), + "when kvQuantMode is pertoken-pergroup, dtileSize allows only " + + std::to_string(supportedDtileSize)); + } else { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + context_.opName, "dtileSize", std::to_string(baseShapeInfo_.dtileSize), + "when kvQuantMode is in {NO_QUANT, PER_TENSOR, PER_CHANNEL}, dtileSize allows only " + + std::to_string(supportedDtileSize)); + } + return ge::GRAPH_FAILED; + } + } + return ge::GRAPH_SUCCESS; +} + +void MlaPrologTilingCheck::GenExpectedParamInfo() +{ + FillCommonParamInfo(); + FillScenarioParamInfo(); +} + +void MlaPrologTilingCheck::FillCommonParamInfo() +{ + FillRequiredParamShapeWithDims(); + FillOptionalOutputParamShapeWithDims(); + + if (context_.weightDq.shape->GetStorageShape().GetDimNum() == MLA_PROLOG_DIM_NUM_4) { + expectedParamInfo_[WEIGHT_DQ_NAME].dimNum = MLA_PROLOG_DIM_NUM_4; + int64_t weightAxisSize = 32L / ge::GetSizeByDataType(context_.weightDq.desc->GetDataType()); + expectedParamInfo_[WEIGHT_DQ_NAME].shape = + std::vector{static_cast(baseShapeInfo_.hcqSize) / weightAxisSize, + static_cast(baseShapeInfo_.heSize) / NZ_H0_SIZE, NZ_H0_SIZE, weightAxisSize}; + } + if (context_.weightUqQr.shape->GetStorageShape().GetDimNum() == MLA_PROLOG_DIM_NUM_4) { + expectedParamInfo_[WEIGHT_UQ_QR_NAME].dimNum = MLA_PROLOG_DIM_NUM_4; + int64_t weightAxisSize = 32L / ge::GetSizeByDataType(context_.weightUqQr.desc->GetDataType()); + expectedParamInfo_[WEIGHT_UQ_QR_NAME].shape = + std::vector{static_cast(baseShapeInfo_.headSizeUqQr) / weightAxisSize, + static_cast(baseShapeInfo_.hcqSize) / NZ_H0_SIZE, NZ_H0_SIZE, weightAxisSize}; + } + if (context_.weightDkvKr.shape->GetStorageShape().GetDimNum() == MLA_PROLOG_DIM_NUM_4) { + expectedParamInfo_[WEIGHT_DKV_KR_NAME].dimNum = MLA_PROLOG_DIM_NUM_4; + int64_t weightAxisSize = 32L / ge::GetSizeByDataType(context_.weightDkvKr.desc->GetDataType()); + expectedParamInfo_[WEIGHT_DKV_KR_NAME].shape = + std::vector{static_cast(baseShapeInfo_.hckvSize + baseShapeInfo_.drSize) / weightAxisSize, + static_cast(baseShapeInfo_.heSize) / NZ_H0_SIZE, NZ_H0_SIZE, weightAxisSize}; + } + + expectedParamInfo_[WEIGHT_DQ_NAME].format = ge::FORMAT_FRACTAL_NZ; + expectedParamInfo_[WEIGHT_UQ_QR_NAME].format = ge::FORMAT_FRACTAL_NZ; + expectedParamInfo_[WEIGHT_DKV_KR_NAME].format = ge::FORMAT_FRACTAL_NZ; + + if (scenarioInfo_.cacheMode_ == CACHE_MODE::PA_BLK_BSND || scenarioInfo_.cacheMode_ == CACHE_MODE::PA_BLK_NZ) { + if (scenarioInfo_.batchSeqFusedFlag_) { + expectedParamInfo_.emplace(ACTUAL_SEQ_LEN_NAME, std::vector{baseShapeInfo_.bSize}); + expectedParamInfo_[ACTUAL_SEQ_LEN_NAME].dtype = ge::DT_INT32; + expectedParamInfo_[ACTUAL_SEQ_LEN_NAME].format = ge::FORMAT_ND; + expectedParamInfo_[CACHE_INDEX_NAME].shape = actualParamInfo_[CACHE_INDEX_NAME].shape; + } else { + expectedParamInfo_[CACHE_INDEX_NAME].shape = + std::vector{baseShapeInfo_.bSize, CeilDiv(baseShapeInfo_.s1Size, baseShapeInfo_.blockSize)}; + } + } +} + +void MlaPrologTilingCheck::FillRequiredParamShapeWithDims() +{ + FillTokenAndQueryShapes(); + FillWeightAndNormShapes(); + FillCacheShapes(); + expectedParamInfo_.emplace(KV_CACHE_OUT_NAME, expectedParamInfo_[KV_CACHE_NAME]); + expectedParamInfo_.emplace(KR_CACHE_OUT_NAME, expectedParamInfo_[KR_CACHE_NAME]); +} + +void MlaPrologTilingCheck::FillTokenAndQueryShapes() +{ + if (scenarioInfo_.batchSeqFusedFlag_) { + expectedParamInfo_.emplace(TOKEN_X_NAME, std::vector{baseShapeInfo_.tSize, baseShapeInfo_.heSize}); + expectedParamInfo_.emplace(ROPE_SIN_NAME, std::vector{baseShapeInfo_.tSize, baseShapeInfo_.drSize}); + expectedParamInfo_.emplace(ROPE_COS_NAME, std::vector{baseShapeInfo_.tSize, baseShapeInfo_.drSize}); + if ((scenarioInfo_.cacheMode_ != CACHE_MODE::BSND) && (scenarioInfo_.cacheMode_ != CACHE_MODE::TND)) { + expectedParamInfo_.emplace(CACHE_INDEX_NAME, std::vector{baseShapeInfo_.tSize}); + expectedParamInfo_[CACHE_INDEX_NAME].dtype = ge::DT_INT64; + } + expectedParamInfo_.emplace( + QUERY_NAME, std::vector{baseShapeInfo_.tSize, baseShapeInfo_.nSize, baseShapeInfo_.hckvSize}); + expectedParamInfo_.emplace( + QUERY_ROPE_NAME, std::vector{baseShapeInfo_.tSize, baseShapeInfo_.nSize, baseShapeInfo_.drSize}); + } else { + expectedParamInfo_.emplace( + TOKEN_X_NAME, std::vector{baseShapeInfo_.bSize, baseShapeInfo_.s1Size, baseShapeInfo_.heSize}); + expectedParamInfo_.emplace( + ROPE_SIN_NAME, std::vector{baseShapeInfo_.bSize, baseShapeInfo_.s1Size, baseShapeInfo_.drSize}); + expectedParamInfo_.emplace( + ROPE_COS_NAME, std::vector{baseShapeInfo_.bSize, baseShapeInfo_.s1Size, baseShapeInfo_.drSize}); + if ((scenarioInfo_.cacheMode_ != CACHE_MODE::BSND) && (scenarioInfo_.cacheMode_ != CACHE_MODE::TND)) { + expectedParamInfo_.emplace(CACHE_INDEX_NAME, + std::vector{baseShapeInfo_.bSize, baseShapeInfo_.s1Size}); + expectedParamInfo_[CACHE_INDEX_NAME].dtype = ge::DT_INT64; + } + expectedParamInfo_.emplace(QUERY_NAME, std::vector{baseShapeInfo_.bSize, baseShapeInfo_.s1Size, + baseShapeInfo_.nSize, baseShapeInfo_.hckvSize}); + expectedParamInfo_.emplace(QUERY_ROPE_NAME, std::vector{baseShapeInfo_.bSize, baseShapeInfo_.s1Size, + baseShapeInfo_.nSize, baseShapeInfo_.drSize}); + } +} + +void MlaPrologTilingCheck::FillWeightAndNormShapes() +{ + expectedParamInfo_.emplace(WEIGHT_DQ_NAME, std::vector{baseShapeInfo_.heSize, baseShapeInfo_.hcqSize}); + expectedParamInfo_.emplace(WEIGHT_UQ_QR_NAME, + std::vector{baseShapeInfo_.hcqSize, baseShapeInfo_.headSizeUqQr}); + expectedParamInfo_.emplace( + WEIGHT_UK_NAME, std::vector{baseShapeInfo_.nSize, baseShapeInfo_.dSize, baseShapeInfo_.hckvSize}); + expectedParamInfo_.emplace( + WEIGHT_DKV_KR_NAME, + std::vector{baseShapeInfo_.heSize, baseShapeInfo_.hckvSize + baseShapeInfo_.drSize}); + expectedParamInfo_.emplace(RMSNORM_GAMMA_CQ_NAME, std::vector{baseShapeInfo_.hcqSize}); + expectedParamInfo_.emplace(RMSNORM_GAMMA_CKV_NAME, std::vector{baseShapeInfo_.hckvSize}); +} + +void MlaPrologTilingCheck::FillCacheShapes() +{ + if (scenarioInfo_.cacheMode_ == CACHE_MODE::TND) { + expectedParamInfo_.emplace(KV_CACHE_NAME, std::vector{baseShapeInfo_.tSize, baseShapeInfo_.nkvSize, + baseShapeInfo_.dtileSize}); + expectedParamInfo_.emplace( + KR_CACHE_NAME, std::vector{baseShapeInfo_.tSize, baseShapeInfo_.nkvSize, baseShapeInfo_.drSize}); + } else if (scenarioInfo_.cacheMode_ == CACHE_MODE::BSND) { + expectedParamInfo_.emplace(KV_CACHE_NAME, + std::vector{baseShapeInfo_.bSize, baseShapeInfo_.s1Size, + baseShapeInfo_.nkvSize, baseShapeInfo_.dtileSize}); + expectedParamInfo_.emplace(KR_CACHE_NAME, std::vector{baseShapeInfo_.bSize, baseShapeInfo_.s1Size, + baseShapeInfo_.nkvSize, baseShapeInfo_.drSize}); + } else { + expectedParamInfo_.emplace(KV_CACHE_NAME, + std::vector{baseShapeInfo_.blockNum, baseShapeInfo_.blockSize, + baseShapeInfo_.nkvSize, baseShapeInfo_.dtileSize}); + expectedParamInfo_.emplace(KR_CACHE_NAME, + std::vector{baseShapeInfo_.blockNum, baseShapeInfo_.blockSize, + baseShapeInfo_.nkvSize, baseShapeInfo_.drSize}); + } +} + +void MlaPrologTilingCheck::FillOptionalOutputParamShapeWithDims() +{ + if (std::strncmp(context_.opType, V2_OP_NAME, OP_NAME_LEN) == 0) { + FillOptionalOutputParamShapeWithDimsV2(); + } + + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + FillOptionalOutputParamShapeWithDimsV3(); + } +} + +void MlaPrologTilingCheck::FillOptionalOutputParamShapeWithDimsV2() +{ + if (scenarioInfo_.quantMode_ == QUANT_MODE::FULL_QUANT_KV_QUANT_PER_TENSOR) { + expectedParamInfo_.emplace(DEQUANT_SCALE_Q_NOPE_NAME, + std::vector{baseShapeInfo_.tSize, baseShapeInfo_.nSize, 1}); + expectedParamInfo_[DEQUANT_SCALE_Q_NOPE_NAME].dtype = ge::DT_FLOAT; + } else { + // 仅校验dequantScaleQNope有传入 + expectedParamInfo_.emplace(DEQUANT_SCALE_Q_NOPE_NAME, context_.dequantScaleQNope); + } +} + +void MlaPrologTilingCheck::FillOptionalOutputParamShapeWithDimsV3() +{ + if (scenarioInfo_.kvQuantMode_ == KV_QUANT_MODE::PER_TENSOR) { + expectedParamInfo_.emplace(DEQUANT_SCALE_Q_NOPE_NAME, + std::vector{baseShapeInfo_.tSize, baseShapeInfo_.nSize, 1}); + } else { + expectedParamInfo_.emplace(DEQUANT_SCALE_Q_NOPE_NAME, std::vector{0}); + } + expectedParamInfo_[DEQUANT_SCALE_Q_NOPE_NAME].dtype = ge::DT_FLOAT; + + if (*(context_.queryNormFlag)) { + if (scenarioInfo_.batchSeqFusedFlag_) { + expectedParamInfo_.emplace(QUERY_NORM_NAME, + std::vector{baseShapeInfo_.tSize, baseShapeInfo_.hcqSize}); + } else { + expectedParamInfo_.emplace( + QUERY_NORM_NAME, + std::vector{baseShapeInfo_.bSize, baseShapeInfo_.s1Size, baseShapeInfo_.hcqSize}); + } + FillQueryNormScaleShape(); + } else { + expectedParamInfo_.emplace(QUERY_NORM_NAME, std::vector{0}); + expectedParamInfo_.emplace(DEQUANT_SCALE_Q_NORM_NAME, std::vector{0}); + } + FillQueryNormDtypes(); +} + +void MlaPrologTilingCheck::FillQueryNormScaleShape() +{ + if (scenarioInfo_.weightQuantMode_ == WEIGHT_QUANT_MODE::NO_QUANT) { + expectedParamInfo_.emplace(DEQUANT_SCALE_Q_NORM_NAME, std::vector{0}); + } else if (scenarioInfo_.weightQuantMode_ == WEIGHT_QUANT_MODE::MXFP8_FULL_QUANT) { + expectedParamInfo_.emplace( + DEQUANT_SCALE_Q_NORM_NAME, + std::vector{baseShapeInfo_.tSize, baseShapeInfo_.hcqSize / MXFP8_BLOCK_SIZE}); + } else { + expectedParamInfo_.emplace(DEQUANT_SCALE_Q_NORM_NAME, std::vector{baseShapeInfo_.tSize, 1}); + } +} + +void MlaPrologTilingCheck::FillQueryNormDtypes() +{ + if (scenarioInfo_.weightQuantMode_ == WEIGHT_QUANT_MODE::NO_QUANT) { + expectedParamInfo_[QUERY_NORM_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[DEQUANT_SCALE_Q_NORM_NAME].dtype = ge::DT_FLOAT; + } else if (scenarioInfo_.weightQuantMode_ == WEIGHT_QUANT_MODE::MXFP8_FULL_QUANT) { + expectedParamInfo_[QUERY_NORM_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[DEQUANT_SCALE_Q_NORM_NAME].dtype = ge::DT_FLOAT8_E8M0; + } else if (scenarioInfo_.weightQuantMode_ == WEIGHT_QUANT_MODE::FP8_FULL_QUANT) { + expectedParamInfo_[QUERY_NORM_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[DEQUANT_SCALE_Q_NORM_NAME].dtype = ge::DT_FLOAT; + } else if (scenarioInfo_.weightQuantMode_ == WEIGHT_QUANT_MODE::HIF8_FULL_QUANT) { + expectedParamInfo_[QUERY_NORM_NAME].dtype = ge::DT_HIFLOAT8; + expectedParamInfo_[DEQUANT_SCALE_Q_NORM_NAME].dtype = ge::DT_FLOAT; + } else { + expectedParamInfo_[QUERY_NORM_NAME].dtype = ge::DT_INT8; + expectedParamInfo_[DEQUANT_SCALE_Q_NORM_NAME].dtype = ge::DT_FLOAT; + } +} + +void MlaPrologTilingCheck::FillScenarioParamInfo() +{ + using FillFunc = void (MlaPrologTilingCheck::*)(); + static const std::unordered_map dispatchTable = { + {QUANT_MODE::NO_QUANT, &MlaPrologTilingCheck::FillNonQuantParamInfo}, + {QUANT_MODE::PARTIAL_QUANT_KV_NO_QUANT, &MlaPrologTilingCheck::FillPartialQuantParamInfo}, + {QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_CHANNEL, &MlaPrologTilingCheck::FillPartialKVQuantParamInfo}, + {QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_TILE, &MlaPrologTilingCheck::FillPartialKVPertileQuantParamInfo}, + {QUANT_MODE::FULL_QUANT_KV_NO_QUANT, &MlaPrologTilingCheck::FillFullQuantParamInfo}, + {QUANT_MODE::FULL_QUANT_KV_QUANT_PER_TENSOR, &MlaPrologTilingCheck::FillFullKVQuantParamInfo}, + {QUANT_MODE::FULL_QUANT_KV_QUANT_PER_TILE, &MlaPrologTilingCheck::FillFullKVPertileQuantParamInfo}, + {QUANT_MODE::MXFP8_FULL_QUANT_KV_NO_QUANT, &MlaPrologTilingCheck::FillMxfp8FullQuantParamInfo}, + {QUANT_MODE::MXFP8_FULL_QUANT_KV_QUANT_PER_TENSOR, &MlaPrologTilingCheck::FillMxfp8FullKVQuantParamInfo}, + {QUANT_MODE::MXFP8_FULL_QUANT_KV_QUANT_PER_TILE, &MlaPrologTilingCheck::FillMxfp8FullKVPertileParamInfo}, + {QUANT_MODE::FP8_FULL_QUANT_KV_NO_QUANT, &MlaPrologTilingCheck::FillFP8FullQuantParamInfo}, + {QUANT_MODE::FP8_FULL_QUANT_KV_QUANT_PER_TENSOR, &MlaPrologTilingCheck::FillFP8FullKVQuantParamInfo}, + {QUANT_MODE::HIF8_FULL_QUANT_KV_NO_QUANT, &MlaPrologTilingCheck::FillHIF8FullQuantParamInfo}, + {QUANT_MODE::HIF8_FULL_QUANT_KV_QUANT_PER_TENSOR, &MlaPrologTilingCheck::FillHIF8FullKVQuantParamInfo}, + {QUANT_MODE::FP8_FULL_QUANT_KV_QUANT_PER_TILE, &MlaPrologTilingCheck::FillFP8FullKVPertileQuantParamInfo}, + {QUANT_MODE::HIF8_FULL_QUANT_KV_QUANT_PER_TILE, &MlaPrologTilingCheck::FillHIF8FullKVPertileQuantParamInfo} + }; + auto it = dispatchTable.find(scenarioInfo_.quantMode_); + if (it != dispatchTable.end()) { + (this->*(it->second))(); + } +} + +void MlaPrologTilingCheck::FillNonQuantParamInfo() +{ + expectedParamInfo_[TOKEN_X_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[WEIGHT_DQ_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[WEIGHT_UQ_QR_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[WEIGHT_UK_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[WEIGHT_DKV_KR_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[RMSNORM_GAMMA_CQ_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[RMSNORM_GAMMA_CKV_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[ROPE_SIN_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[ROPE_COS_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[KV_CACHE_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[KR_CACHE_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[QUERY_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[QUERY_ROPE_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[KV_CACHE_OUT_NAME].dtype = ge::DT_BF16; + expectedParamInfo_[KR_CACHE_OUT_NAME].dtype = ge::DT_BF16; +} + +void MlaPrologTilingCheck::FillPartialQuantParamInfo() +{ + FillNonQuantParamInfo(); + + expectedParamInfo_.emplace(DEQUANT_SCALE_W_UQ_QR_NAME, std::vector{1, baseShapeInfo_.headSizeUqQr}); + expectedParamInfo_.emplace(SMOOTH_SCALES_CQ_NAME, std::vector{1, baseShapeInfo_.hcqSize}); + + expectedParamInfo_[WEIGHT_UQ_QR_NAME].dtype = ge::DT_INT8; + + expectedParamInfo_[DEQUANT_SCALE_W_UQ_QR_NAME].dtype = ge::DT_FLOAT; + expectedParamInfo_[SMOOTH_SCALES_CQ_NAME].dtype = ge::DT_FLOAT; + + expectedParamInfo_[SMOOTH_SCALES_CQ_NAME].isValid = (context_.smoothScalesCq.desc != nullptr); +} + +void MlaPrologTilingCheck::FillPartialKVQuantParamInfo() +{ + FillPartialQuantParamInfo(); + + expectedParamInfo_.emplace(QUANT_SCALE_CKV_NAME, std::vector{1, baseShapeInfo_.hckvSize}); + expectedParamInfo_.emplace(QUANT_SCALE_CKR_NAME, std::vector{1, baseShapeInfo_.drSize}); + + expectedParamInfo_[KV_CACHE_NAME].dtype = ge::DT_INT8; + expectedParamInfo_[KR_CACHE_NAME].dtype = ge::DT_INT8; + expectedParamInfo_[KV_CACHE_OUT_NAME].dtype = ge::DT_INT8; + expectedParamInfo_[KR_CACHE_OUT_NAME].dtype = ge::DT_INT8; + + expectedParamInfo_[QUANT_SCALE_CKV_NAME].dtype = ge::DT_FLOAT; + expectedParamInfo_[QUANT_SCALE_CKR_NAME].dtype = ge::DT_FLOAT; +} + +void MlaPrologTilingCheck::FillPartialKVPertileQuantParamInfo() +{ + FillPartialQuantParamInfo(); + + expectedParamInfo_.emplace(K_NOPE_CLIP_ALPHA_NAME, std::vector{1}); + expectedParamInfo_[KV_CACHE_NAME].dtype = ge::DT_INT8; + expectedParamInfo_[KV_CACHE_OUT_NAME].dtype = ge::DT_INT8; + expectedParamInfo_[K_NOPE_CLIP_ALPHA_NAME].dtype = ge::DT_FLOAT; +} + +void MlaPrologTilingCheck::FillFullQuantParamInfo() +{ + FillPartialQuantParamInfo(); + + expectedParamInfo_.emplace(DEQUANT_SCALE_X_NAME, std::vector{baseShapeInfo_.tSize, 1}); + expectedParamInfo_.emplace(DEQUANT_SCALE_W_DQ_NAME, std::vector{1, baseShapeInfo_.hcqSize}); + expectedParamInfo_.emplace(DEQUANT_SCALE_W_DKV_KR_NAME, + std::vector{1, baseShapeInfo_.hckvSize + baseShapeInfo_.drSize}); + + expectedParamInfo_[TOKEN_X_NAME].dtype = ge::DT_INT8; + expectedParamInfo_[WEIGHT_DQ_NAME].dtype = ge::DT_INT8; + expectedParamInfo_[WEIGHT_DKV_KR_NAME].dtype = ge::DT_INT8; + + if (GetCurNpuArch() == NpuArch::DAV_3510 && std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + if (*(context_.weightQuantMode) == static_cast(WEIGHT_QUANT_MODE::FP8_FULL_QUANT)) { + expectedParamInfo_[TOKEN_X_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[WEIGHT_DQ_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[WEIGHT_UQ_QR_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[WEIGHT_DKV_KR_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + } else if (*(context_.weightQuantMode) == static_cast(WEIGHT_QUANT_MODE::HIF8_FULL_QUANT)) { + expectedParamInfo_[TOKEN_X_NAME].dtype = ge::DT_HIFLOAT8; + expectedParamInfo_[WEIGHT_DQ_NAME].dtype = ge::DT_HIFLOAT8; + expectedParamInfo_[WEIGHT_UQ_QR_NAME].dtype = ge::DT_HIFLOAT8; + expectedParamInfo_[WEIGHT_DKV_KR_NAME].dtype = ge::DT_HIFLOAT8; + } + } + + expectedParamInfo_[DEQUANT_SCALE_X_NAME].dtype = ge::DT_FLOAT; + expectedParamInfo_[DEQUANT_SCALE_W_DQ_NAME].dtype = ge::DT_FLOAT; + expectedParamInfo_[DEQUANT_SCALE_W_DKV_KR_NAME].dtype = ge::DT_FLOAT; +} + +void MlaPrologTilingCheck::FillFullKVQuantParamInfo() +{ + FillFullQuantParamInfo(); + + expectedParamInfo_[QUERY_NAME].dtype = ge::DT_INT8; + expectedParamInfo_[KV_CACHE_NAME].dtype = ge::DT_INT8; + expectedParamInfo_[KV_CACHE_OUT_NAME].dtype = ge::DT_INT8; + if (GetCurNpuArch() == NpuArch::DAV_3510 && std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + if (*(context_.weightQuantMode) == static_cast(WEIGHT_QUANT_MODE::FP8_FULL_QUANT)) { + expectedParamInfo_[QUERY_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[KV_CACHE_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[KV_CACHE_OUT_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + } else if (*(context_.weightQuantMode) == static_cast(WEIGHT_QUANT_MODE::HIF8_FULL_QUANT)) { + expectedParamInfo_[QUERY_NAME].dtype = ge::DT_HIFLOAT8; + expectedParamInfo_[KV_CACHE_NAME].dtype = ge::DT_HIFLOAT8; + expectedParamInfo_[KV_CACHE_OUT_NAME].dtype = ge::DT_HIFLOAT8; + } + } + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + expectedParamInfo_.emplace(QUANT_SCALE_CKV_NAME, std::vector{1}); + } else { + expectedParamInfo_.emplace(QUANT_SCALE_CKV_NAME, std::vector{1, baseShapeInfo_.hckvSize}); + } + + expectedParamInfo_[QUANT_SCALE_CKV_NAME].dtype = ge::DT_FLOAT; +} + +void MlaPrologTilingCheck::FillFullKVPertileQuantParamInfo() +{ + FillFullQuantParamInfo(); + + expectedParamInfo_.emplace(K_NOPE_CLIP_ALPHA_NAME, std::vector{1}); + expectedParamInfo_[KV_CACHE_NAME].dtype = ge::DT_INT8; + expectedParamInfo_[KV_CACHE_OUT_NAME].dtype = ge::DT_INT8; + if (GetCurNpuArch() == NpuArch::DAV_3510 && std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0) { + if (*(context_.weightQuantMode) == static_cast(WEIGHT_QUANT_MODE::FP8_FULL_QUANT)) { + expectedParamInfo_[KV_CACHE_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[KV_CACHE_OUT_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + } else if (*(context_.weightQuantMode) == static_cast(WEIGHT_QUANT_MODE::HIF8_FULL_QUANT)) { + expectedParamInfo_[KV_CACHE_NAME].dtype = ge::DT_HIFLOAT8; + expectedParamInfo_[KV_CACHE_OUT_NAME].dtype = ge::DT_HIFLOAT8; + } + } + expectedParamInfo_[K_NOPE_CLIP_ALPHA_NAME].dtype = ge::DT_FLOAT; +} + +void MlaPrologTilingCheck::FillMxfp8FullQuantParamInfo() +{ + FillPartialQuantParamInfo(); + // dequantScaleX: (M, K / 32) [BS, He / 32] || [T, He / 32] + expectedParamInfo_.emplace(DEQUANT_SCALE_X_NAME, + std::vector{baseShapeInfo_.tSize, baseShapeInfo_.heSize / MXFP8_BLOCK_SIZE}); + // dequantScaleWDq: (N, K / 32) [Hcq, He / 32] + expectedParamInfo_.emplace(DEQUANT_SCALE_W_DQ_NAME, + std::vector{baseShapeInfo_.hcqSize, baseShapeInfo_.heSize / MXFP8_BLOCK_SIZE}); + // dequantScaleWDq: (N, K / 32) [Numhead * (D + Dr), Hcq / 32] + expectedParamInfo_.erase(DEQUANT_SCALE_W_UQ_QR_NAME); + expectedParamInfo_.emplace( + DEQUANT_SCALE_W_UQ_QR_NAME, + std::vector{baseShapeInfo_.headSizeUqQr, baseShapeInfo_.hcqSize / MXFP8_BLOCK_SIZE}); + // dequantScaleWDkvKr: (N, K / 32) [Hckv + Dr, He / 32] + expectedParamInfo_.emplace(DEQUANT_SCALE_W_DKV_KR_NAME, + std::vector{baseShapeInfo_.hckvSize + baseShapeInfo_.drSize, + baseShapeInfo_.heSize / MXFP8_BLOCK_SIZE}); + + expectedParamInfo_[TOKEN_X_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[WEIGHT_DQ_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[WEIGHT_UQ_QR_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[WEIGHT_DKV_KR_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[DEQUANT_SCALE_X_NAME].dtype = ge::DT_FLOAT8_E8M0; + expectedParamInfo_[DEQUANT_SCALE_W_DQ_NAME].dtype = ge::DT_FLOAT8_E8M0; + expectedParamInfo_[DEQUANT_SCALE_W_UQ_QR_NAME].dtype = ge::DT_FLOAT8_E8M0; + expectedParamInfo_[DEQUANT_SCALE_W_DKV_KR_NAME].dtype = ge::DT_FLOAT8_E8M0; + + expectedParamInfo_[QUANT_SCALE_CKR_NAME].isValid = false; + expectedParamInfo_[SMOOTH_SCALES_CQ_NAME].isValid = false; + expectedParamInfo_[K_NOPE_CLIP_ALPHA_NAME].isValid = false; +} + +void MlaPrologTilingCheck::FillMxfp8FullKVQuantParamInfo() +{ + FillMxfp8FullQuantParamInfo(); + + expectedParamInfo_.emplace(QUANT_SCALE_CKV_NAME, std::vector{1}); + + expectedParamInfo_[KV_CACHE_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[QUANT_SCALE_CKV_NAME].dtype = ge::DT_FLOAT; + expectedParamInfo_[QUERY_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[KV_CACHE_OUT_NAME].dtype = ge::DT_FLOAT8_E4M3FN; +} + +void MlaPrologTilingCheck::FillMxfp8FullKVPertileParamInfo() +{ + FillMxfp8FullQuantParamInfo(); + + expectedParamInfo_[KV_CACHE_NAME].dtype = ge::DT_FLOAT8_E4M3FN; + expectedParamInfo_[KV_CACHE_OUT_NAME].dtype = ge::DT_FLOAT8_E4M3FN; +} + +void MlaPrologTilingCheck::FillFP8FullQuantParamInfo() +{ + FillFullQuantParamInfo(); +} + +void MlaPrologTilingCheck::FillFP8FullKVQuantParamInfo() +{ + FillFullKVQuantParamInfo(); +} + +void MlaPrologTilingCheck::FillHIF8FullQuantParamInfo() +{ + FillFullQuantParamInfo(); +} + +void MlaPrologTilingCheck::FillHIF8FullKVQuantParamInfo() +{ + FillFullKVQuantParamInfo(); +} + +void MlaPrologTilingCheck::FillFP8FullKVPertileQuantParamInfo() +{ + FillFullKVPertileQuantParamInfo(); + expectedParamInfo_.erase(K_NOPE_CLIP_ALPHA_NAME); + expectedParamInfo_[K_NOPE_CLIP_ALPHA_NAME].isValid = false; +} + +void MlaPrologTilingCheck::FillHIF8FullKVPertileQuantParamInfo() +{ + FillFullKVPertileQuantParamInfo(); + expectedParamInfo_.erase(K_NOPE_CLIP_ALPHA_NAME); + expectedParamInfo_[K_NOPE_CLIP_ALPHA_NAME].isValid = false; +} + +void MlaPrologTilingCheck::GenActualParamInfo() +{ + actualParamInfo_.emplace(TOKEN_X_NAME, context_.tokenX); + actualParamInfo_.emplace(WEIGHT_DQ_NAME, context_.weightDq); + actualParamInfo_.emplace(WEIGHT_UQ_QR_NAME, context_.weightUqQr); + actualParamInfo_.emplace(WEIGHT_UK_NAME, context_.weightUk); + actualParamInfo_.emplace(WEIGHT_DKV_KR_NAME, context_.weightDkvKr); + actualParamInfo_.emplace(RMSNORM_GAMMA_CQ_NAME, context_.rmsnormGammaCq); + actualParamInfo_.emplace(RMSNORM_GAMMA_CKV_NAME, context_.rmsnormGammaCkv); + actualParamInfo_.emplace(ROPE_SIN_NAME, context_.ropeSin); + actualParamInfo_.emplace(ROPE_COS_NAME, context_.ropeCos); + actualParamInfo_.emplace(CACHE_INDEX_NAME, context_.cacheIndex); + actualParamInfo_.emplace(KV_CACHE_NAME, context_.kvCache); + actualParamInfo_.emplace(KR_CACHE_NAME, context_.krCache); + actualParamInfo_.emplace(DEQUANT_SCALE_X_NAME, context_.dequantScaleX); + actualParamInfo_.emplace(DEQUANT_SCALE_W_DQ_NAME, context_.dequantScaleWDq); + actualParamInfo_.emplace(DEQUANT_SCALE_W_UQ_QR_NAME, context_.dequantScaleWUqQr); + actualParamInfo_.emplace(DEQUANT_SCALE_W_DKV_KR_NAME, context_.dequantScaleWDkvKr); + actualParamInfo_.emplace(QUANT_SCALE_CKV_NAME, context_.quantScaleCkv); + actualParamInfo_.emplace(QUANT_SCALE_CKR_NAME, context_.quantScaleCkr); + actualParamInfo_.emplace(SMOOTH_SCALES_CQ_NAME, context_.smoothScalesCq); + actualParamInfo_.emplace(ACTUAL_SEQ_LEN_NAME, context_.actualSeqLen); + actualParamInfo_.emplace(K_NOPE_CLIP_ALPHA_NAME, context_.kNopeClipAlpha); + actualParamInfo_.emplace(QUERY_NAME, context_.query); + actualParamInfo_.emplace(QUERY_ROPE_NAME, context_.queryRope); + actualParamInfo_.emplace(KV_CACHE_OUT_NAME, context_.kvCacheOut); + actualParamInfo_.emplace(KR_CACHE_OUT_NAME, context_.krCacheOut); + actualParamInfo_.emplace(DEQUANT_SCALE_Q_NOPE_NAME, context_.dequantScaleQNope); + actualParamInfo_.emplace(QUERY_NORM_NAME, context_.queryNorm); + actualParamInfo_.emplace(DEQUANT_SCALE_Q_NORM_NAME, context_.dequantScaleQNorm); + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0 && + *(context_.ckvkrRepoMode) == static_cast(CKVKR_REPO_MODE::COMBINE)) { + actualParamInfo_.erase(KR_CACHE_NAME); + actualParamInfo_.erase(KR_CACHE_OUT_NAME); + } +} + +ge::graphStatus MlaPrologTilingCheck::CheckCkvkrRepoMode() +{ + ge::graphStatus isCorrect{ge::GRAPH_SUCCESS}; + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) != 0) { + return isCorrect; + } + if (*(context_.ckvkrRepoMode) == static_cast(CKVKR_REPO_MODE::COMBINE)) { + // 校验所有维度的乘积是否为0 + if (context_.krCache.shape->GetStorageShape().GetShapeSize() != 0) { + isCorrect = ge::GRAPH_FAILED; + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(context_.opName, "krCache", + GetShapeStr(context_.krCache.shape->GetStorageShape()), + "When ckvkrRepoMode is COMBINE, krCache should be empty tensor"); + } + if (context_.krCacheOut.shape->GetStorageShape().GetShapeSize() != 0) { + isCorrect = ge::GRAPH_FAILED; + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(context_.opName, "krCacheOut", + GetShapeStr(context_.krCacheOut.shape->GetStorageShape()), + "When ckvkrRepoMode is COMBINE, krCacheOut should be empty tensor"); + } + } + return isCorrect; +} + +ge::graphStatus MlaPrologTilingCheck::CheckCacheIndexDim() +{ + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) != 0) { + return ge::GRAPH_SUCCESS; + } + if (!scenarioInfo_.batchSeqFusedFlag_) { + return ge::GRAPH_SUCCESS; + } + if (scenarioInfo_.cacheMode_ != CACHE_MODE::PA_BLK_BSND && scenarioInfo_.cacheMode_ != CACHE_MODE::PA_BLK_NZ) { + return ge::GRAPH_SUCCESS; + } + OP_CHECK_IF(context_.cacheIndex.shape == nullptr, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + context_.opName, "cacheIndex", "null", + "When cacheMode is in {PA_BLK_BSND, PA_BLK_NZ}, cacheIndex should not be null"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(context_.cacheIndex.shape->GetStorageShape().GetDimNum() != MLA_PROLOG_DIM_NUM_1, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + context_.opName, "cacheIndex", + std::to_string(context_.cacheIndex.shape->GetStorageShape().GetDimNum()) + "D", + "When cacheMode in {PA_BLK_BSND, PA_BLK_NZ} and tokenX dim is 2, cacheIndex dim should be 1"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTilingCheck::CheckSpecialScenarioParamShape() +{ + if (CheckCkvkrRepoMode() == ge::GRAPH_FAILED) { + return ge::GRAPH_FAILED; + } + if (CheckCacheIndexDim() == ge::GRAPH_FAILED) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MlaPrologTilingCheck::CheckParamByScenario() +{ + GenActualParamInfo(); + GenExpectedParamInfo(); + ge::graphStatus isCorrect{ge::GRAPH_SUCCESS}; + for (const auto &it : actualParamInfo_) { + const auto &expectedParam{expectedParamInfo_[it.first]}; + if (__builtin_expect((expectedParam != it.second), 0)) { + isCorrect = ge::GRAPH_FAILED; + if (expectedParam.isValid != it.second.isValid) { + if (expectedParam.isValid && !it.second.isValid) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_.opName, it.first, "null", + "this parameter is required under current configuration"); + } else { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_.opName, it.first, "not null", + "this parameter is not required under current configuration"); + } + continue; + } + if (expectedParam.dtype != it.second.dtype) { + OP_LOGE_FOR_INVALID_DTYPE_WITH_REASON( + context_.opName, it.first, TypeUtils::DataTypeToSerialString(it.second.dtype), + "this parameter requires dtype " + TypeUtils::DataTypeToSerialString(expectedParam.dtype) + + " under current configuration"); + } + if (expectedParam.format != it.second.format) { + OP_LOGE_FOR_INVALID_FORMAT_WITH_REASON( + context_.opName, it.first, std::string(ge::GetFormatName(it.second.format)), + "this parameter requires format " + std::string(ge::GetFormatName(expectedParam.format)) + + " under current configuration"); + } + if (expectedParam.shape != it.second.shape) { + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON( + context_.opName, it.first, ConvertShapeToString(it.second.shape), + "this parameter requires shape " + ConvertContainerToString(expectedParam.shape) + + " under current configuration"); + } + } + } + return isCorrect; +} + +ge::graphStatus MlaPrologTilingCheck::CheckScenarParam() +{ + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) != 0) { + return ge::GRAPH_SUCCESS; + } + + ge::graphStatus isCorrect{ge::GRAPH_SUCCESS}; + CheckRepoMode(scenarioInfo_.kvQuantMode_ == KV_QUANT_MODE::PER_TILE, isCorrect); + CheckQueryQuantMode(scenarioInfo_.kvQuantMode_ == KV_QUANT_MODE::PER_TENSOR, isCorrect); + return isCorrect; +} + +void MlaPrologTilingCheck::CheckRepoMode(bool isPertile, ge::graphStatus &isCorrect) +{ + auto expectedCkvkr = isPertile ? CKVKR_REPO_MODE::COMBINE : CKVKR_REPO_MODE::DIVIDE; + auto expectedQuantScale = isPertile ? QUANT_SCALE_REPO_MODE::COMBINE : QUANT_SCALE_REPO_MODE::DIVIDE; + std::string desc = isPertile ? "pertoken-pergroup" : "non-pertoken-pergroup"; + std::string name = isPertile ? "COMBINE" : "DIVIDE"; + + if (*(context_.ckvkrRepoMode) != static_cast(expectedCkvkr)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_.opName, "ckvkrRepoMode", + std::to_string(*(context_.ckvkrRepoMode)), + "When " + desc + " quant mode, must be " + name + "(" + + std::to_string(static_cast(expectedCkvkr)) + ")"); + isCorrect = ge::GRAPH_FAILED; + } + if (*(context_.quantScaleRepoMode) != static_cast(expectedQuantScale)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_.opName, "quantScaleRepoMode", + std::to_string(*(context_.quantScaleRepoMode)), + "When " + desc + " quant mode, must be " + name + "(" + + std::to_string(static_cast(expectedQuantScale)) + ")"); + isCorrect = ge::GRAPH_FAILED; + } +} + +void MlaPrologTilingCheck::CheckQueryQuantMode(bool isPertensor, ge::graphStatus &isCorrect) +{ + auto expected = isPertensor ? QUERY_QUANT_MODE::PER_TOKEN_HEAD : QUERY_QUANT_MODE::NO_QUANT; + std::string desc = isPertensor ? "pertensor" : "non-pertensor"; + std::string name = isPertensor ? "PER_TOKEN_HEAD" : "NO_QUANT"; + + if (*(context_.queryQuantMode) != static_cast(expected)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_.opName, "queryQuantMode", + std::to_string(*(context_.queryQuantMode)), + "When " + desc + " quant mode, must be " + name + "(" + + std::to_string(static_cast(expected)) + ")"); + isCorrect = ge::GRAPH_FAILED; + } +} +// =================================全量参数校验================================= + +// ==================================单参数校验================================== +bool MlaPrologTilingCheck::IsSingleParamValid(const BaseParaInfo ¶m, const std::string ¶mName, + const std::set &expectedDtype, + const std::set &expectedFormat, + const std::set &expectedDimNum) const +{ + OP_CHECK_IF((param.shape == nullptr) || (param.desc == nullptr), + OP_LOGE_WITH_INVALID_INPUT(context_.opName, paramName), return false); + + ge::DataType dtype = param.desc->GetDataType(); + OP_CHECK_IF((expectedDtype.find(dtype) == expectedDtype.end()), + OP_LOGE_FOR_INVALID_DTYPE(context_.opName, paramName, TypeUtils::DataTypeToSerialString(dtype), + ConvertContainerToStringV3(expectedDtype, TypeUtils::DataTypeToSerialString)), + return false); + + ge::Format format = static_cast(ge::GetPrimaryFormat(param.desc->GetStorageFormat())); + OP_CHECK_IF((expectedFormat.find(format) == expectedFormat.end()), + OP_LOGE_FOR_INVALID_FORMAT(context_.opName, paramName, std::string(ge::GetFormatName(format)), + ConvertContainerToStringV3(expectedFormat, FormatToString)), + return false); + + size_t dimNum = param.shape->GetStorageShape().GetDimNum(); + OP_CHECK_IF((expectedDimNum.find(dimNum) == expectedDimNum.end()), + OP_LOGE_FOR_INVALID_SHAPEDIM(context_.opName, paramName, std::to_string(dimNum), + ConvertContainerToStringV3(expectedDimNum)), + return false); + return true; +} + +ge::graphStatus MlaPrologTilingCheck::CheckSingleRequiredParam() const +{ + if (!CheckTokenX() || !CheckWDq() || !CheckWUqQr() || !CheckWUk() || !CheckWDkvKr() || !CheckRmsnormGammaCq() || + !CheckRmsnormGammaCkv() || !CheckRopeSin() || !CheckRopeCos() || !CheckCacheIndex() || !CheckKvCache() || + !CheckKrCache() || !CheckActSeqLen()) { + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +bool MlaPrologTilingCheck::CheckTokenX() const +{ + if (GetCurNpuArch() == NpuArch::DAV_3510) { + return IsSingleParamValid(context_.tokenX, TOKEN_X_NAME, + {ge::DT_BF16, ge::DT_INT8, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}, + {ge::FORMAT_ND, ge::FORMAT_NCHW}, {2, 3}); + } else { + return IsSingleParamValid(context_.tokenX, TOKEN_X_NAME, {ge::DT_BF16, ge::DT_INT8}, + {ge::FORMAT_ND, ge::FORMAT_NCHW}, {2, 3}); + } +} + +bool MlaPrologTilingCheck::CheckWDq() const +{ + if (GetCurNpuArch() == NpuArch::DAV_3510) { + return IsSingleParamValid(context_.weightDq, WEIGHT_DQ_NAME, + {ge::DT_BF16, ge::DT_INT8, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}, + {ge::FORMAT_FRACTAL_NZ}, {2, 4}); + } else { + return IsSingleParamValid(context_.weightDq, WEIGHT_DQ_NAME, {ge::DT_BF16, ge::DT_INT8}, + {ge::FORMAT_FRACTAL_NZ}, {2, 4}); + } +} + +bool MlaPrologTilingCheck::CheckWUqQr() const +{ + if (GetCurNpuArch() == NpuArch::DAV_3510) { + return IsSingleParamValid(context_.weightUqQr, WEIGHT_UQ_QR_NAME, + {ge::DT_BF16, ge::DT_INT8, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}, + {ge::FORMAT_FRACTAL_NZ}, {2, 4}); + } else { + return IsSingleParamValid(context_.weightUqQr, WEIGHT_UQ_QR_NAME, {ge::DT_BF16, ge::DT_INT8}, + {ge::FORMAT_FRACTAL_NZ}, {2, 4}); + } +} + +bool MlaPrologTilingCheck::CheckWUk() const +{ + if (GetCurNpuArch() == NpuArch::DAV_3510) { + return IsSingleParamValid(context_.weightUk, WEIGHT_UK_NAME, {ge::DT_BF16}, {ge::FORMAT_ND, ge::FORMAT_NCHW}, + {3}); + } else { + return IsSingleParamValid(context_.weightUk, WEIGHT_UK_NAME, {ge::DT_BF16, ge::DT_INT8}, + {ge::FORMAT_ND, ge::FORMAT_NCHW}, {3}); + } +} + +bool MlaPrologTilingCheck::CheckWDkvKr() const +{ + if (GetCurNpuArch() == NpuArch::DAV_3510) { + return IsSingleParamValid(context_.weightDkvKr, WEIGHT_DKV_KR_NAME, + {ge::DT_BF16, ge::DT_INT8, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}, + {ge::FORMAT_FRACTAL_NZ}, {2, 4}); + } else { + return IsSingleParamValid(context_.weightDkvKr, WEIGHT_DKV_KR_NAME, {ge::DT_BF16, ge::DT_INT8}, + {ge::FORMAT_FRACTAL_NZ}, {2, 4}); + } +} + +bool MlaPrologTilingCheck::CheckRmsnormGammaCq() const +{ + return IsSingleParamValid(context_.rmsnormGammaCq, RMSNORM_GAMMA_CQ_NAME, {ge::DT_BF16}, + {ge::FORMAT_ND, ge::FORMAT_NCHW}, {1}); +} + +bool MlaPrologTilingCheck::CheckRmsnormGammaCkv() const +{ + return IsSingleParamValid(context_.rmsnormGammaCkv, RMSNORM_GAMMA_CKV_NAME, {ge::DT_BF16}, + {ge::FORMAT_ND, ge::FORMAT_NCHW}, {1}); +} + +bool MlaPrologTilingCheck::CheckRopeSin() const +{ + return IsSingleParamValid(context_.ropeSin, ROPE_SIN_NAME, {ge::DT_BF16}, {ge::FORMAT_ND, ge::FORMAT_NCHW}, {2, 3}); +} + +bool MlaPrologTilingCheck::CheckRopeCos() const +{ + return IsSingleParamValid(context_.ropeCos, ROPE_COS_NAME, {ge::DT_BF16}, {ge::FORMAT_ND, ge::FORMAT_NCHW}, {2, 3}); +} + +bool MlaPrologTilingCheck::CheckCacheIndex() const +{ + return std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0 || + IsSingleParamValid(context_.cacheIndex, CACHE_INDEX_NAME, {ge::DT_INT64}, {ge::FORMAT_ND, ge::FORMAT_NCHW}, + {1, 2}); +} + +bool MlaPrologTilingCheck::CheckKvCache() const +{ + if (GetCurNpuArch() == NpuArch::DAV_3510) { + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) != 0) { + return IsSingleParamValid(context_.kvCache, KV_CACHE_NAME, {ge::DT_BF16, ge::DT_INT8}, + {ge::FORMAT_ND, ge::FORMAT_NCHW}, {4}); + } else { + return IsSingleParamValid(context_.kvCache, KV_CACHE_NAME, + {ge::DT_BF16, ge::DT_INT8, ge::DT_FLOAT8_E4M3FN, ge::DT_HIFLOAT8}, + {ge::FORMAT_ND, ge::FORMAT_NCHW}, {3, 4}); + } + } else { + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) != 0) { + return IsSingleParamValid(context_.kvCache, KV_CACHE_NAME, {ge::DT_BF16, ge::DT_INT8}, + {ge::FORMAT_ND, ge::FORMAT_NCHW}, {4}); + } else { + return IsSingleParamValid(context_.kvCache, KV_CACHE_NAME, {ge::DT_BF16, ge::DT_INT8}, + {ge::FORMAT_ND, ge::FORMAT_NCHW}, {3, 4}); + } + } +} + +bool MlaPrologTilingCheck::CheckKrCache() const +{ + if (GetCurNpuArch() == NpuArch::DAV_3510) { + return IsSingleParamValid(context_.krCache, KR_CACHE_NAME, {ge::DT_BF16, ge::DT_INT8}, + {ge::FORMAT_ND, ge::FORMAT_NCHW}, {1, 3, 4}); + } else { + return (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) == 0 && + *(context_.ckvkrRepoMode) == static_cast(CKVKR_REPO_MODE::COMBINE)) || + IsSingleParamValid(context_.krCache, KR_CACHE_NAME, {ge::DT_BF16, ge::DT_INT8}, + {ge::FORMAT_ND, ge::FORMAT_NCHW}, {1, 3, 4}); + } +} + +bool MlaPrologTilingCheck::CheckActSeqLen() const +{ + if (context_.actualSeqLen.desc == nullptr) { + return true; + }; + ge::DataType dtype = context_.actualSeqLen.desc->GetDataType(); + OP_CHECK_IF((ge::DT_INT32 != dtype), + OP_LOGE_FOR_INVALID_DTYPE(context_.opName, "actualSeqLen", TypeUtils::DataTypeToSerialString(dtype), + TypeUtils::DataTypeToSerialString(ge::DT_INT32)), + return false); + return true; +} + +bool MlaPrologTilingCheck::CheckCacheModeParamShape() const +{ + if (std::strncmp(context_.cacheMode, CACHE_MODE_TND, CACHE_MODE_LEN) == 0) { + OP_CHECK_IF(context_.tokenX.shape->GetStorageShape().GetDimNum() != MLA_PROLOG_DIM_NUM_2, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + context_.opName, "tokenX", + std::to_string(context_.tokenX.shape->GetStorageShape().GetDimNum()) + "D", + "When cacheMode is TND, tokenX dim must be 2"), + return false); + OP_CHECK_IF(context_.kvCache.shape->GetStorageShape().GetDimNum() != MLA_PROLOG_DIM_NUM_3, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + context_.opName, "kvCache", + std::to_string(context_.kvCache.shape->GetStorageShape().GetDimNum()) + "D", + "When cacheMode is TND, kvCache dim must be 3"), + return false); + } else if (std::strncmp(context_.cacheMode, CACHE_MODE_BSND, CACHE_MODE_LEN) == 0) { + OP_CHECK_IF(context_.tokenX.shape->GetStorageShape().GetDimNum() != MLA_PROLOG_DIM_NUM_3, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + context_.opName, "tokenX", + std::to_string(context_.tokenX.shape->GetStorageShape().GetDimNum()) + "D", + "When cacheMode is BSND, tokenX dim must be 3"), + return false); + OP_CHECK_IF(context_.kvCache.shape->GetStorageShape().GetDimNum() != MLA_PROLOG_DIM_NUM_4, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + context_.opName, "kvCache", + std::to_string(context_.kvCache.shape->GetStorageShape().GetDimNum()) + "D", + "When cacheMode is BSND, kvCache dim must be 4"), + return false); + } else { + OP_CHECK_IF(context_.kvCache.shape->GetStorageShape().GetDimNum() != MLA_PROLOG_DIM_NUM_4, + OP_LOGE_FOR_INVALID_SHAPEDIM_WITH_REASON( + context_.opName, "kvCache", + std::to_string(context_.kvCache.shape->GetStorageShape().GetDimNum()) + "D", + "When cacheMode in {PA_BSND, PA_NZ, PA_BLK_BSND, PA_BLK_NZ}, kvCache dim must be 4"), + return false); + } + return true; +} + +ge::graphStatus MlaPrologTilingCheck::CheckCacheMode() const +{ + if (std::strncmp(context_.opType, V3_OP_NAME, OP_NAME_LEN) != 0) { + if (std::strncmp(context_.cacheMode, CACHE_MODE_PA_BSND, CACHE_MODE_LEN) != 0 && + std::strncmp(context_.cacheMode, CACHE_MODE_PA_NZ, CACHE_MODE_LEN) != 0) { + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "cacheMode", std::string(context_.cacheMode), + "{PA_BSND, PA_NZ}"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; + } + + if ((std::strncmp(context_.cacheMode, CACHE_MODE_BSND, CACHE_MODE_LEN) != 0) && + (std::strncmp(context_.cacheMode, CACHE_MODE_TND, CACHE_MODE_LEN) != 0) && + (std::strncmp(context_.cacheMode, CACHE_MODE_PA_BSND, CACHE_MODE_LEN) != 0) && + (std::strncmp(context_.cacheMode, CACHE_MODE_PA_NZ, CACHE_MODE_LEN) != 0) && + (std::strncmp(context_.cacheMode, CACHE_MODE_PA_BLK_BSND, CACHE_MODE_LEN) != 0) && + (std::strncmp(context_.cacheMode, CACHE_MODE_PA_BLK_NZ, CACHE_MODE_LEN) != 0)) { + OP_LOGE_FOR_INVALID_VALUE(context_.opName, "cacheMode", std::string(context_.cacheMode), + "{BSND, TND, PA_BSND, PA_NZ, PA_BLK_BSND, PA_BLK_NZ}"); + return ge::GRAPH_FAILED; + } + if (!CheckCacheModeParamShape()) { + return ge::GRAPH_FAILED; + } + + if (*(context_.kvQuantMode) != static_cast(KV_QUANT_MODE::PER_TILE)) { + return ge::GRAPH_SUCCESS; + } + + if ((std::strncmp(context_.cacheMode, CACHE_MODE_PA_NZ, CACHE_MODE_LEN) == 0) || + (std::strncmp(context_.cacheMode, CACHE_MODE_PA_BLK_BSND, CACHE_MODE_LEN) == 0) || + (std::strncmp(context_.cacheMode, CACHE_MODE_PA_BLK_NZ, CACHE_MODE_LEN) == 0)) { + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + context_.opName, "cacheMode", std::string(context_.cacheMode), + "When pertoken-pergroup quant mode, cacheMode cannot be {PA_NZ, PA_BLK_BSND, PA_BLK_NZ}"); + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +// ==================================单参数校验================================== +} // namespace optiling \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling_check.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling_check.h new file mode 100644 index 0000000000000000000000000000000000000000..82b6feedae47fce1ada9d0e38d79588a64d735aa --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling_check.h @@ -0,0 +1,215 @@ +/** + * 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 mla_prolog_tiling_check.h + * \brief + */ + +#ifndef MLA_PROLOG_TILING_CHECK_H +#define MLA_PROLOG_TILING_CHECK_H + +#include "mla_prolog_tiling.h" + +namespace optiling { + +constexpr uint32_t MAX_B_SIZE = 65536U; +constexpr uint32_t MAX_S1_SIZE = 65536U; +constexpr uint32_t MAX_T_SIZE = 1024U * 1024U; +constexpr uint32_t HCQ_SIZE = 1536U; +constexpr uint32_t HCKV_SIZE = 512U; +constexpr uint32_t D_SIZE = 128U; +constexpr uint32_t DR_SIZE = 64U; +constexpr uint32_t NKV_SIZE = 1U; +constexpr uint32_t MIN_BLOCK_SIZE = 16U; +constexpr uint32_t MAX_BLOCK_SIZE = 1024U; +constexpr uint32_t ALIGN_BLOCK_SIZE = 16U; +constexpr uint32_t MXFP8_BLOCK_SIZE = 32U; + +constexpr int64_t NZ_H0_SIZE = 16U; + +constexpr char TOKEN_X_NAME[] {"tokenX"}; +constexpr char WEIGHT_DQ_NAME[] {"weightDq"}; +constexpr char WEIGHT_UQ_QR_NAME[] {"weightUqQr"}; +constexpr char WEIGHT_UK_NAME[] {"weightUk"}; +constexpr char WEIGHT_DKV_KR_NAME[] {"weightDkvKr"}; +constexpr char RMSNORM_GAMMA_CQ_NAME[] {"rmsnormGammaCq"}; +constexpr char RMSNORM_GAMMA_CKV_NAME[] {"rmsnormGammaCkv"}; +constexpr char ROPE_SIN_NAME[] {"ropeSin"}; +constexpr char ROPE_COS_NAME[] {"ropeCos"}; +constexpr char CACHE_INDEX_NAME[] {"cacheIndex"}; +constexpr char KV_CACHE_NAME[] {"kvCache"}; +constexpr char KR_CACHE_NAME[] {"krCache"}; +constexpr char DEQUANT_SCALE_X_NAME[] {"dequantScaleX"}; +constexpr char DEQUANT_SCALE_W_DQ_NAME[] {"dequantScaleWDq"}; +constexpr char DEQUANT_SCALE_W_UQ_QR_NAME[] {"dequantScaleWUqQr"}; +constexpr char DEQUANT_SCALE_W_DKV_KR_NAME[] {"dequantScaleWDkvKr"}; +constexpr char QUANT_SCALE_CKV_NAME[] {"quantScaleCkv"}; +constexpr char QUANT_SCALE_CKR_NAME[] {"quantScaleCkr"}; +constexpr char SMOOTH_SCALES_CQ_NAME[] {"smoothScalesCq"}; +constexpr char ACTUAL_SEQ_LEN_NAME[] {"actualSeqLen"}; +constexpr char K_NOPE_CLIP_ALPHA_NAME[] {"kNopeClipAlpha"}; +constexpr char QUERY_NAME[] {"query"}; +constexpr char QUERY_ROPE_NAME[] {"queryRope"}; +constexpr char KV_CACHE_OUT_NAME[] {"kvCacheOut"}; +constexpr char KR_CACHE_OUT_NAME[] {"krCacheOut"}; +constexpr char DEQUANT_SCALE_Q_NOPE_NAME[] {"dequantScaleQNope"}; +constexpr char QUERY_NORM_NAME[] {"queryNorm"}; +constexpr char DEQUANT_SCALE_Q_NORM_NAME[] {"dequantScaleQNorm"}; + +constexpr uint32_t PARAM_MAP_INIT_RESERVE_NUM = 28; // 预分配所有key的个数,避免使用时动态扩容 + +struct ParamInfo { + ParamInfo() = default; + explicit ParamInfo(const ParamInfo &) = default; + ParamInfo &operator=(const ParamInfo &) = default; + explicit ParamInfo(ParamInfo &&) = default; + ParamInfo &operator=(ParamInfo &&other) = default; + ~ParamInfo() = default; + ParamInfo(const gert::CompileTimeTensorDesc *actualDesc, const gert::StorageShape *actualShape) { + if (actualDesc != nullptr && actualShape != nullptr) { + isValid = true; + dtype = actualDesc->GetDataType(); + format = static_cast(ge::GetPrimaryFormat(actualDesc->GetStorageFormat())); + auto &&actualStorageShape = actualShape->GetStorageShape(); + dimNum = actualStorageShape.GetDimNum(); + this->shape.reserve(dimNum); + for (size_t i = 0; i < dimNum; i++) { + this->shape.emplace_back(actualStorageShape.GetDim(i)); + } + } + } + explicit ParamInfo(const BaseParaInfo &info) : ParamInfo(info.desc, info.shape) {} + explicit ParamInfo(const std::vector &expectedShape) + { + isValid = true; + format = ge::FORMAT_ND; + dimNum = expectedShape.size(); + this->shape.reserve(dimNum); + for (size_t i = 0; i < dimNum; i++) { + this->shape.emplace_back(static_cast(expectedShape[i])); + } + } + + bool operator == (const ParamInfo &other) const { + if (!isValid && !other.isValid) { + return true; + } + static const std::set ndFormats{ge::FORMAT_ND, ge::FORMAT_NCHW}; + if ((ndFormats.find(format) == ndFormats.end() || ndFormats.find(other.format) == ndFormats.end()) && + format != other.format) { + return false; + } + return (isValid == other.isValid && dtype == other.dtype && + dimNum == other.dimNum && shape == other.shape); + } + bool operator != (const ParamInfo &other) const { + return !(*this == other); + } + + bool isValid {}; + ge::DataType dtype {ge::DT_MAX}; + ge::Format format {ge::FORMAT_MAX}; + size_t dimNum {}; + std::vector shape; +}; + +using ParamInfoMap = std::unordered_map; + +class MlaPrologTilingCheck { +public: + MlaPrologTilingCheck(const MlaPrologContext &context, const MlaPrologBaseShapeInfo &baseShapeInfo, + const MlaPrologScenarioInfo &scenarioInfo) + : context_(context), baseShapeInfo_(baseShapeInfo), scenarioInfo_(scenarioInfo) {} + ge::graphStatus CheckSingleRequiredParam() const; + ge::graphStatus CheckCacheMode() const; + ge::graphStatus CheckQuantMode() const; + ge::graphStatus CheckDims() const; + ge::graphStatus CheckParamByScenario(); + ge::graphStatus CheckSpecialScenarioParamShape(); + ge::graphStatus CheckCkvkrRepoMode(); + ge::graphStatus CheckCacheIndexDim(); + ge::graphStatus CheckScenarParam(); + ge::graphStatus CheckAttrs() const; + + NpuArch GetCurNpuArch() const; + +private: + bool CheckAttrsNotNull() const; + bool CheckAttrsRange() const; + bool CheckCacheModeParamShape() const; + ge::graphStatus CheckHcqSize() const; + ge::graphStatus CheckDSize() const; + ge::graphStatus CheckDtileSize() const; + // ==================================单参数校验================================== + bool IsSingleParamValid(const BaseParaInfo ¶m, const std::string ¶mName, + const std::set &expectedDtype, + const std::set &expectedFormat, + const std::set &expectedDimNum) const; + bool CheckTokenX() const; + bool CheckWDq() const; + bool CheckWDkvKr() const; + bool CheckWUqQr() const; + bool CheckWUk() const; + bool CheckRmsnormGammaCkv() const; + bool CheckRmsnormGammaCq() const; + bool CheckRopeCos() const; + bool CheckRopeSin() const; + bool CheckCacheIndex() const; + bool CheckKvCache() const; + bool CheckKrCache() const; + bool CheckActSeqLen() const; + // ==================================单参数校验================================== + + // =================================全量参数校验================================= + void GenExpectedParamInfo(); + void FillCommonParamInfo(); + void FillRequiredParamShapeWithDims(); + void FillOptionalOutputParamShapeWithDims(); + void FillOptionalOutputParamShapeWithDimsV2(); + void FillOptionalOutputParamShapeWithDimsV3(); + void FillScenarioParamInfo(); + void FillQueryNormScaleShape(); + void FillQueryNormDtypes(); + void FillTokenAndQueryShapes(); + void FillWeightAndNormShapes(); + void FillCacheShapes(); + void CheckRepoMode(bool isPertile, ge::graphStatus &isCorrect); + void CheckQueryQuantMode(bool isPertensor, ge::graphStatus &isCorrect); + void FillNonQuantParamInfo(); + void FillPartialQuantParamInfo(); + void FillPartialKVQuantParamInfo(); + void FillPartialKVPertileQuantParamInfo(); + void FillFullQuantParamInfo(); + void FillFullKVQuantParamInfo(); + void FillFullKVPertileQuantParamInfo(); + void FillMxfp8FullQuantParamInfo(); + void FillMxfp8FullKVQuantParamInfo(); + void FillMxfp8FullKVPertileParamInfo(); + void FillFP8FullQuantParamInfo(); + void FillFP8FullKVQuantParamInfo(); + void FillHIF8FullQuantParamInfo(); + void FillHIF8FullKVQuantParamInfo(); + void FillFP8FullKVPertileQuantParamInfo(); + void FillHIF8FullKVPertileQuantParamInfo(); + + void GenActualParamInfo(); + // =================================全量参数校验================================= + + const MlaPrologContext &context_; + const MlaPrologBaseShapeInfo &baseShapeInfo_; + const MlaPrologScenarioInfo &scenarioInfo_; + ParamInfoMap expectedParamInfo_ = ParamInfoMap(PARAM_MAP_INIT_RESERVE_NUM); + ParamInfoMap actualParamInfo_ = ParamInfoMap(PARAM_MAP_INIT_RESERVE_NUM); +}; + +} // namespace optiling + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling_register.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling_register.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1240e84aa05392b4b001e19b7b74e75ea6adeaf0 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_host/mla_prolog_tiling_register.cpp @@ -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. + */ + +/*! + * \file mla_prolog_tiling_register.cpp + * \brief + */ + +#include "mla_prolog_tiling.h" +#include "register/op_def_registry.h" + +using namespace ge; +using namespace AscendC; +namespace optiling { +ge::graphStatus TilingPrepareForMlaProlog(gert::TilingParseContext *context) +{ + (void)context; + return ge::GRAPH_SUCCESS; +} +IMPL_OP_OPTILING(MlaProlog) + .Tiling(TilingMlaProlog) + .TilingParse(TilingPrepareForMlaProlog); +} // namespace optiling diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/kernel_mla_prolog_split_n.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/kernel_mla_prolog_split_n.h new file mode 100644 index 0000000000000000000000000000000000000000..6626db3c07235c0dc5c9d5843b8856e550c3b255 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/kernel_mla_prolog_split_n.h @@ -0,0 +1,2215 @@ +/** + * 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 kernel_mla_prolog_split_n.h + * \brief + */ + +#ifndef KERNEL_MLA_PROLOG_SPLIT_N_H +#define KERNEL_MLA_PROLOG_SPLIT_N_H + +#include "mla_prolog_comm.h" +#include "mla_prolog_vector_comm.h" +#include "service_matmul.h" +#include "service_rms_norm.h" +#include "service_dequant.h" +#include "service_dynamic_quant_qn_mul_qr.h" +#include "service_gather_sin_cos.h" +#include "service_rotary_position_embedding.h" +#include "service_scatter_cache.h" +#include "../mla_prolog_tiling_data.h" +#include "../mla_prolog_template_tiling_key.h" + +namespace MlaProlog { +template +class MlaPrologVecS1CubS2 { +public: + static constexpr bool isPertile = MLAPT::isPertile; + + using mmInputType = typename MLAPT::mmInputType; + using mmQnInputType = typename MLAPT::mmQnInputType; + using mmQcQrInputType = typename MLAPT::mmQcQrInputType; + using mmQnOutputType = typename MLAPT::mmQnOutputType; + using mmQcQrOutputType = typename MLAPT::mmQcQrOutputType; + using mmCkvKrOutputType = typename MLAPT::mmCkvKrOutputType; + using mmCqOutputType = typename MLAPT::mmCqOutputType; + using kvCacheType = typename MLAPT::kvCacheType; + using krCacheType = typename MLAPT::krCacheType; + using queryOutputType = typename std::conditional::type; + using ropeSinCosType = typename MLAPT::ropeSinCosType; + using ropeComputType = typename MLAPT::ropeComputType; + using ropeOutputType = typename MLAPT::ropeOutputType; + using rmsNormGammaType = typename MLAPT::rmsNormGammaType; + using rmsNormComputType = typename MLAPT::rmsNormComputType; + using rmsNormCqOutputType = typename MLAPT::rmsNormCqOutputType; + using rmsNormCkvOutputType = typename MLAPT::rmsNormCkvOutputType; + using dequantScaleQNopeType = typename MLAPT::dequantScaleQNopeType; + using dequantScaleQNormType = typename MLAPT::dequantScaleQNormType; + using dequantScaleType = typename MLAPT::dequantScaleType; + + MMParams mmQnParam_; + MMParams mmQcQrParam_; + MMParams mmCkvKrParam_; + MMParams mmCqParam_; + + __aicore__ inline MlaPrologVecS1CubS2(TPipe *pipe, const optiling::MlaPrologTilingData *__restrict tilingData, + const optiling::MlaPrologBaseParams *__restrict baseParams) + : pipe_(pipe), tilingData_(tilingData), baseParams_(baseParams) + { + } + + __aicore__ inline void Process(); + __aicore__ inline void Init(__gm__ uint8_t *tokenX, __gm__ uint8_t *weightDq, __gm__ uint8_t *weightUqQr, + __gm__ uint8_t *weightUk, __gm__ uint8_t *weightDkvKr, __gm__ uint8_t *rmsnormGammaCq, + __gm__ uint8_t *rmsnormGammaCkv, __gm__ uint8_t *ropeSin, __gm__ uint8_t *ropeCos, + __gm__ uint8_t *cacheIndex, __gm__ uint8_t *kvCache, __gm__ uint8_t *krCache, + __gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *deqScaleQcQrW, __gm__ uint8_t *dequantScaleWDkvkr, + __gm__ uint8_t *quantScaleCkv, __gm__ uint8_t *quantScaleCkr, + __gm__ uint8_t *smoothScaleCq, __gm__ uint8_t *actualSeqLen, + __gm__ uint8_t *kNopeClipAlpha, __gm__ uint8_t *queryOut, __gm__ uint8_t *queryRopeOut, + __gm__ uint8_t *dequantScaleQNopeOut, __gm__ uint8_t *queryNormOut, + __gm__ uint8_t *dequantScaleQNormOut, __gm__ uint8_t *workspace); + +private: + __aicore__ inline void CopyGlobalParams(); + __aicore__ inline void ScaleInit(__gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *deqScaleQcQrW, __gm__ uint8_t *dequantScaleWDkvkr, + __gm__ uint8_t *quantScaleCkv, __gm__ uint8_t *quantScaleCkr, + __gm__ uint8_t *smoothScaleCq, __gm__ uint8_t *kNopeClipAlpha); + __aicore__ inline void WorkspaceInit(__gm__ uint8_t *workspace); + __aicore__ inline void MmParamInit(); + __aicore__ inline void MmQnParamInit(); + __aicore__ inline void MmQcQrParamInit(); + __aicore__ inline void MmCkvKrParamInit(); + __aicore__ inline void MmCqParamInit(); + __aicore__ inline void CubeBufferInit(); + __aicore__ inline void VectorBufferInit(); + __aicore__ inline void UpdateStepBatchParams(int64_t curStepBatchSize); + __aicore__ inline void ComputeAivOffset(AivOffset &aivOffset, int64_t batchOffset); + __aicore__ inline void ComputeAicOffset(AicOffset &aicOffset, int64_t numHeadOffset); + __aicore__ inline void ComputeBlkScatterOffsets(GlobalTensor indexGm, int64_t tokenIndex, int64_t rows, + CkvkrParams &rmsNormAndScatterCkvParams, + CkvkrParams &ropeAndScatterKrParams); + template + __aicore__ inline void AivProcess(AivOffset &aivOffset, int64_t batchOffset, int64_t curStepBatchSize, + int64_t numHeadOffset, int64_t mmQnLoops); + template + __aicore__ inline void AicProcess(AicOffset &aicOffset, int64_t batchOffset, int64_t mmQnLoops); + template + __aicore__ inline void + MatmulSplitN(const GlobalTensor &tensorResGm, const GlobalTensor &tensorAGm, const GlobalTensor &tensorBGm, + const MMParams &mmPara, const UsedBlockParams &mmBlockParams, + const GlobalTensor &tensorAScaleGm = {}, const GlobalTensor &tensorBScaleGm = {}); + __aicore__ inline void MatmulQcQr(AicOffset &aicOffset); + __aicore__ inline void MatmulAndSyncQcQr(AicOffset &aicOffset); + __aicore__ inline void MatmulQnWeightPreload(int64_t weightUkOffset, int64_t mmQnLoops); + __aicore__ inline void PreloadQnAndSync(AicOffset &aicOffset, int64_t mmQnLoops); + template + __aicore__ inline void MatmulQnSyncDynamicQuantAndMulQr(int64_t qcOffset, int64_t weightUkOffset, + int64_t qnResOffset, int64_t mmQnLoops); + __aicore__ inline void CopyInSinCos(int64_t tokenIndex, int64_t curVecToken, int64_t batchOffset, + int64_t curStepBatchSize); + __aicore__ inline void RmsNormCq(int64_t tokenIndex, int64_t rmsNormCqOffset, int64_t rmsNormCqResOffset, + int64_t curVecToken, int64_t curBlockTokenOffset); + __aicore__ inline void RopeAndScatterKr(LocalTensor &dequantScaleXLocal, + LocalTensor &shareTmpUb, + LocalTensor &cosLocalCkvKr, + LocalTensor &sinLocalCkvKr, + CkvkrParams ropeAndScatterKrParams); + __aicore__ inline void RmsNormAndScatterCkv(LocalTensor &dequantScaleXLocal, + LocalTensor &shareTmpUb, + LocalTensor &cosLocalCkvKr, + LocalTensor &sinLocalCkvKr, + CkvkrParams rmsNormAndScatterCkvParams); + __aicore__ inline void RmsNormRopeScatterCkvKr(int64_t tokenIndex, int64_t rmsNormCkvOffset, int64_t ropeKrOffset, + int64_t curVecToken); + __aicore__ inline void RopeQr(int64_t ropeQrOffset, int64_t ropeQrResOffset, int64_t curVecToken, + int64_t curBlockTokenOffset); + __aicore__ inline void DequantQc(int64_t mmQnPreDequantOffset, int64_t mmQnPreDequantResOffset, int64_t curVecToken, + int64_t curBlockTokenOffset); + __aicore__ inline void CastQc(int64_t mmQnPreCastOffset, int64_t mmQnPreCastResOffset, int64_t curVecToken); + // 低时延算力分组场景 + __aicore__ inline void DequantAndRopeSplitNSyncMMQcQr(int64_t mmQnPreDequantOffset, int64_t mmQnPreDequantResOffset, + int64_t ropeQrOffset, int64_t ropeQrResOffset); + __aicore__ inline void DequantQcSplitNGroupCase(int64_t mmQnPreDequantOffset, int64_t mmQnPreDequantResOffset, + int64_t qcQrScaleOffset); + __aicore__ inline void RopeQrSplitNGroupCase(int64_t ropeQrOffset, int64_t ropeQrResOffset); + __aicore__ inline void DequantQcQrSplitN(const DequantQcQrSplitNParams &dequantQcQrSplitN); + __aicore__ inline void CastQcQrSplitN(const CastQcQrSplitNParams &castQcQrSplitN); + __aicore__ inline void RopeQrSplitN(const RopeQrSplitNParams &ropeQrSplitNParams); + __aicore__ inline void DynamicQuantQnAndMulQrSyncMMQn(int64_t batchOffset, int64_t curStepBatchSize, + int64_t numHeadOffset, int64_t mmQnLoops); + + const optiling::MlaPrologBaseParams *__restrict baseParams_; + const optiling::MlaPrologTilingData *__restrict tilingData_; + TPipe *pipe_; + uint32_t cubeBlockIdx_ = 0U; // AIV上使用AIC的blockIdx + uint32_t blockIdx_ = 0U; + int64_t vectorCoreNum_; + int64_t curVectorBlockNum_; + int64_t vectorRow_ = 1; + uint32_t curVecTokenMax_; + uint32_t curStepVecBackToken_; + uint32_t curStepVecFrontListNum_; + uint32_t curStepVecFrontToken_; + uint64_t dequantScaleCqSize_ = 1; + bool enableSmoothScalesCq_; + static constexpr uint32_t cvMode = MLAPT::cvRatio; // 编译态,默认cv1:2 + uint32_t cvRatio_ = 2U; // 默认cv 1:2 + + struct DequantTool { + LocalTensor dequantScaleCqLocal_; + GlobalTensor dequantScaleCqGm_; + TBuf dequantScaleCqBuffer_; // 用于临时存储每一行的Scale,以及汇总最终每一行的Scale参数 + __aicore__ inline DequantTool() + { + } + }; + + // 算子分组开关 + DequantTool dequantTool_; + + // GM + GlobalTensor tokenXGm_; + GlobalTensor weightDqGm_; + GlobalTensor weightDkvKrGm_; + GlobalTensor weightUqQrGm_; + GlobalTensor weightUkGm_; + GlobalTensor rmsnormGammaCqGm_; + GlobalTensor rmsnormGammaCkvGm_; + GlobalTensor ropeSinGm_; + GlobalTensor ropeCosGm_; + GlobalTensor cacheIndexGm_; + GlobalTensor qrOutGm_; + GlobalTensor kvCacheGm_; + GlobalTensor krCacheGm_; + + GlobalTensor dequantScaleXGm_; + GlobalTensor dequantScaleWDqGm_; + GlobalTensor dequantScaleWDkvkrGm_; + GlobalTensor deqScaleQcQrW_; // per-channel反量化参数 + GlobalTensor smoothScaleCqGm_; + GlobalTensor quantScaleCkvGm_; + GlobalTensor quantScaleCkrGm_; + + GlobalTensor actualSeqLenGm_; + GlobalTensor kNopeClipAlphaGm_; + + GlobalTensor mmCqResGm_; + GlobalTensor mmCkvKrResGm_; + GlobalTensor mmQcQrResGm_; + GlobalTensor mmQcQrResDequantGm_; + GlobalTensor mmQnResGm_; + GlobalTensor rmsNormCqResGm_; + GlobalTensor queryOutGm_; + GlobalTensor dequantScaleQNopeGm_; + GlobalTensor dequantScaleQNormGm_; + + // UB + TBuf shareBuffer_; + TBuf sincosBuffer_; + TBuf dequantScaleWDqBuffer_; + TBuf dequantScaleWDkvKrBuffer_; + TBuf rmsnormGammaCqBuffer_; + TBuf rmsnormGammaCkvBuffer_; + TBuf smoothScaleCqBuffer_; + TBuf quantScaleCkvBuffer_; + TBuf quantScaleCkrBuffer_; + TBuf stepActualSeqBuffer_; + + LocalTensor sinLocal_; + LocalTensor cosLocal_; + LocalTensor dequantScaleWDqLocal_; + LocalTensor dequantScaleWDkvKrLocal_; + LocalTensor rmsnormGammaCkvLocal_; + LocalTensor rmsnormGammaCqLocal_; + LocalTensor smoothScaleCqLocal_; + LocalTensor quantScaleCkrLocal_; + LocalTensor quantScaleCkvLocal_; + LocalTensor stepActualSeqLocal_; + + struct ActSeqState { + bool inited = false; // whether state is initialized for the run + int64_t curBatch = 0; // current batch index for the running token index + int64_t curPrefix = 0; // prefix sum of seq lengths up to curBatch (exclusive high bound) + int64_t prevPrefix = 0; // prefix sum of seq lengths up to (curBatch - 1) + int64_t curIndexOffset = 0; // prefix sum of blocks up to curBatch + int64_t prevIndexOffset = 0; // prefix sum of blocks up to (curBatch - 1) + }; + ActSeqState actSeqState_; + int64_t blockSpanPerBatch_ = 0; // blockNum * blockSize + + TBuf bBufL1_; + TBuf aBufL1_; + LocalTensor bL1Tensor_; + LocalTensor aL1Tensor_; + MMBufParams bufParam_; + TBuf bBufL0_; + TBuf aBufL0_; + TBuf cBufL0_; +}; + +template +__aicore__ inline void MlaPrologVecS1CubS2::Init( + __gm__ uint8_t *tokenX, __gm__ uint8_t *weightDq, __gm__ uint8_t *weightUqQr, __gm__ uint8_t *weightUk, + __gm__ uint8_t *weightDkvKr, __gm__ uint8_t *rmsnormGammaCq, __gm__ uint8_t *rmsnormGammaCkv, + __gm__ uint8_t *ropeSin, __gm__ uint8_t *ropeCos, __gm__ uint8_t *cacheIndex, __gm__ uint8_t *kvCache, + __gm__ uint8_t *krCache, __gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *deqScaleQcQrW, __gm__ uint8_t *dequantScaleWDkvkr, __gm__ uint8_t *quantScaleCkv, + __gm__ uint8_t *quantScaleCkr, __gm__ uint8_t *smoothScaleCq, __gm__ uint8_t *actualSeqLen, + __gm__ uint8_t *kNopeClipAlpha, __gm__ uint8_t *queryOut, __gm__ uint8_t *queryRopeOut, + __gm__ uint8_t *dequantScaleQNopeOut, __gm__ uint8_t *queryNormOut, __gm__ uint8_t *dequantScaleQNormOut, + __gm__ uint8_t *workspace) +{ + blockIdx_ = GetBlockIdx(); // cube:0-23 vec:0-47 + if ASCEND_IS_AIC { + cubeBlockIdx_ = blockIdx_; + } else { + cvRatio_ = GetSubBlockNum(); // CV1:2场景返回2,其他场景返回1 + cubeBlockIdx_ = blockIdx_ / cvRatio_; + } + vectorCoreNum_ = static_cast(baseParams_->vectorBlockNum); // aivNum 48 + curVectorBlockNum_ = static_cast(baseParams_->stepBatchSize); + if (cvMode == 1 && cvRatio_ == 2) { // 编译态cv1:1,运行态cv1:2 + if (vectorCoreNum_ < curVectorBlockNum_) { + vectorCoreNum_ = vectorCoreNum_ * 2; // 修正为运行态vector数目 + } + } + enableSmoothScalesCq_ = smoothScaleCq == nullptr ? false : true; + curVecTokenMax_ = (curVectorBlockNum_ + vectorCoreNum_ - 1) / vectorCoreNum_; + // GM + tokenXGm_.SetGlobalBuffer((__gm__ mmInputType *)tokenX); + weightDqGm_.SetGlobalBuffer((__gm__ mmInputType *)weightDq); // NZ + weightDkvKrGm_.SetGlobalBuffer((__gm__ mmInputType *)weightDkvKr); // NZ + weightUqQrGm_.SetGlobalBuffer((__gm__ mmQcQrInputType *)weightUqQr); // NZ + weightUkGm_.SetGlobalBuffer((__gm__ mmQnInputType *)weightUk); + rmsnormGammaCkvGm_.SetGlobalBuffer((__gm__ rmsNormGammaType *)rmsnormGammaCkv); + rmsnormGammaCqGm_.SetGlobalBuffer((__gm__ rmsNormGammaType *)rmsnormGammaCq); + ropeCosGm_.SetGlobalBuffer((__gm__ ropeSinCosType *)ropeCos); + ropeSinGm_.SetGlobalBuffer((__gm__ ropeSinCosType *)ropeSin); + if constexpr (MLAPT::cacheMode != CACHE_MODE::ND) { + cacheIndexGm_.SetGlobalBuffer((__gm__ int64_t *)cacheIndex); + } + krCacheGm_.SetGlobalBuffer((__gm__ krCacheType *)krCache); + kvCacheGm_.SetGlobalBuffer((__gm__ kvCacheType *)kvCache); + qrOutGm_.SetGlobalBuffer((__gm__ ropeOutputType *)queryRopeOut); + if constexpr ((std::is_same::value && std::is_same::value) && + !isPertile) { + dequantScaleQNopeGm_.SetGlobalBuffer((__gm__ dequantScaleQNopeType *)dequantScaleQNopeOut); + queryOutGm_.SetGlobalBuffer((__gm__ queryOutputType *)queryOut); + } else { + mmQnResGm_.SetGlobalBuffer((__gm__ mmQnOutputType *)queryOut); + } + if (baseParams_->queryNormFlag == 1U) { + rmsNormCqResGm_.SetGlobalBuffer((__gm__ mmQcQrInputType *)queryNormOut); + if constexpr (std::is_same::value) { + dequantScaleQNormGm_.SetGlobalBuffer((__gm__ dequantScaleQNormType *)dequantScaleQNormOut); + } + } + if constexpr (MLAPT::actualSeqMode == ACTUAL_SEQ_MODE::EN_Q_LEN) { + actualSeqLenGm_.SetGlobalBuffer((__gm__ int32_t *)actualSeqLen); + } + + MmParamInit(); + ScaleInit(dequantScaleX, dequantScaleWDq, deqScaleQcQrW, dequantScaleWDkvkr, quantScaleCkv, quantScaleCkr, + smoothScaleCq, kNopeClipAlpha); + WorkspaceInit(workspace); + if ASCEND_IS_AIC { + CubeBufferInit(); + } else { + VectorBufferInit(); + } +} + +template +__aicore__ inline void +MlaPrologVecS1CubS2::ScaleInit(__gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *deqScaleQcQrW, __gm__ uint8_t *dequantScaleWDkvkr, + __gm__ uint8_t *quantScaleCkv, __gm__ uint8_t *quantScaleCkr, + __gm__ uint8_t *smoothScaleCq, __gm__ uint8_t *kNopeClipAlpha) +{ + if constexpr (std::is_same::value) { + dequantScaleXGm_.SetGlobalBuffer((__gm__ dequantScaleType *)dequantScaleX); + dequantScaleWDqGm_.SetGlobalBuffer((__gm__ dequantScaleType *)dequantScaleWDq); + dequantScaleWDkvkrGm_.SetGlobalBuffer((__gm__ dequantScaleType *)dequantScaleWDkvkr); + } + if constexpr (std::is_same::value) { + smoothScaleCqGm_.SetGlobalBuffer((__gm__ float *)smoothScaleCq); + deqScaleQcQrW_.SetGlobalBuffer((__gm__ dequantScaleType *)deqScaleQcQrW); + quantScaleCkvGm_.SetGlobalBuffer((__gm__ float *)quantScaleCkv); + quantScaleCkrGm_.SetGlobalBuffer((__gm__ float *)quantScaleCkr); + } + + if constexpr (isPertile) { + kNopeClipAlphaGm_.SetGlobalBuffer((__gm__ float *)kNopeClipAlpha); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MmCqParamInit() +{ + if (cubeBlockIdx_ == baseParams_->mm1BlockNum - 1) { + mmCqParam_.n = baseParams_->headSizeCq - baseParams_->mm1SingleCoreN * cubeBlockIdx_; + } else { + mmCqParam_.n = baseParams_->mm1SingleCoreN; // 1536 / 24 = 64 + } + mmCqParam_.m = baseParams_->stepBatchSize; // 32 + mmCqParam_.k = baseParams_->headSizeX; // 7168 + mmCqParam_.needSetOrgShape = 1; + mmCqParam_.orgKb = mmCqParam_.k; + mmCqParam_.orgKa = mmCqParam_.k; + mmCqParam_.orgN = mmCqParam_.n; + mmCqParam_.orgM = mmCqParam_.m; + mmCqParam_.orgKc = baseParams_->headSizeCq; // 1536 + mmCqParam_.baseK = + (sizeof(mmInputType) != ONE_BYTE_TYPE_SIZE) ? 128 : 256; // 128KB / (128 max baseN * 4 stepK * sizeof(type)) + mmCqParam_.baseN = 128; + mmCqParam_.stepK = 4; + if ((mmCqParam_.k / mmCqParam_.baseK) % mmCqParam_.stepK != 0) { + mmCqParam_.stepK = 3; // support k = 7680, mmInputType int8, no tail + } + mmCqParam_.kL1StepSize = mmCqParam_.baseK * mmCqParam_.stepK; +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MmCkvKrParamInit() +{ + if (cubeBlockIdx_ == baseParams_->mm2BlockNum - 1) { + mmCkvKrParam_.n = + baseParams_->headSizeCkv + baseParams_->headSizeKr - baseParams_->mm2SingleCoreN * cubeBlockIdx_; + } else { + mmCkvKrParam_.n = baseParams_->mm2SingleCoreN; + } + mmCkvKrParam_.m = baseParams_->stepBatchSize; // 32 + mmCkvKrParam_.k = baseParams_->headSizeX; // 7168 + mmCkvKrParam_.needSetOrgShape = 1; + mmCkvKrParam_.orgKb = mmCkvKrParam_.k; + mmCkvKrParam_.orgKa = mmCkvKrParam_.k; + mmCkvKrParam_.orgN = mmCkvKrParam_.n; + mmCkvKrParam_.orgM = mmCkvKrParam_.m; + mmCkvKrParam_.orgKc = (baseParams_->dimHeadRope + baseParams_->headSizeCkv); // 576 + mmCkvKrParam_.baseK = + (sizeof(mmInputType) != ONE_BYTE_TYPE_SIZE) ? 128 : 256; // 128KB / (128 max baseN * 4 stepK * sizeof(type)) + mmCkvKrParam_.baseN = 128; + mmCkvKrParam_.stepK = 4; + if ((mmCkvKrParam_.k / mmCkvKrParam_.baseK) % mmCkvKrParam_.stepK != 0) { + mmCkvKrParam_.stepK = 3; // support k = 7680, mmInputType int8, no tail + } + mmCkvKrParam_.kL1StepSize = mmCkvKrParam_.baseK * mmCkvKrParam_.stepK; +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MmQcQrParamInit() +{ + if constexpr (MLAPT::enableGroupComputeOpt) { + // 算力分组仅考虑G8 Qc Qr(8+4核), n固定128, 这里不处理尾核 + mmQcQrParam_.n = baseParams_->mm3SingleCoreN; + } else { + if (cubeBlockIdx_ == baseParams_->mm3BlockNum - 1) { + mmQcQrParam_.n = + baseParams_->headSizeQr + baseParams_->headSizeQc - baseParams_->mm3SingleCoreN * cubeBlockIdx_; + } else { + mmQcQrParam_.n = baseParams_->mm3SingleCoreN; + } + } + mmQcQrParam_.m = baseParams_->stepBatchSize; // 32 + + mmQcQrParam_.k = baseParams_->headSizeCq; // 1536 + mmQcQrParam_.needSetOrgShape = 1; + mmQcQrParam_.orgKb = mmQcQrParam_.k; + mmQcQrParam_.orgKa = mmQcQrParam_.k; + mmQcQrParam_.orgN = mmQcQrParam_.n; + mmQcQrParam_.orgM = mmQcQrParam_.m; + mmQcQrParam_.orgKc = (baseParams_->headSizeQr + baseParams_->headSizeQc); // (128 * 32 + 64 * 32) + mmQcQrParam_.baseK = (sizeof(mmQcQrInputType) != ONE_BYTE_TYPE_SIZE) ? 64 : 128; + if constexpr (MLAPT::enableGroupComputeOpt) { + mmQcQrParam_.baseN = 128; + } else { + if (mmQcQrParam_.m <= 64) { + mmQcQrParam_.baseN = 256; + } else { + mmQcQrParam_.baseN = 128; + } + } + mmQcQrParam_.stepK = 4; + mmQcQrParam_.kL1StepSize = mmQcQrParam_.baseK * mmQcQrParam_.stepK; +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MmQnParamInit() +{ + mmQnParam_.m = baseParams_->stepBatchSize; // 32 + mmQnParam_.n = baseParams_->headSizeCkv; // 512 + mmQnParam_.k = baseParams_->dimHeadSizeQc; // 128, 这里numHeadSize被分核,matmul设置里不体现 + mmQnParam_.needSetOrgShape = 1; + mmQnParam_.orgN = mmQnParam_.n; + mmQnParam_.orgM = mmQnParam_.m; + if constexpr (std::is_same::value || std::is_same::value) { + mmQnParam_.orgKa = baseParams_->headSizeQc; + } else { + mmQnParam_.orgKa = baseParams_->headSizeQc + baseParams_->headSizeQr; + } + mmQnParam_.orgKc = baseParams_->headSizeCkv * baseParams_->numHeadSize; + mmQnParam_.orgKb = baseParams_->dimHeadSizeQc; + mmQnParam_.baseN = 128; + mmQnParam_.baseK = 128; + mmQnParam_.stepK = 1; + if ((mmQnParam_.k > mmQnParam_.baseK) && (mmQnParam_.k % mmQnParam_.baseK != 0)) { + mmQnParam_.baseK = 64; + mmQnParam_.stepK = 3; // support D = 192 + } + mmQnParam_.kL1StepSize = mmQnParam_.baseK * mmQnParam_.stepK; +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MmParamInit() +{ + MmCqParamInit(); + MmCkvKrParamInit(); + MmQcQrParamInit(); + MmQnParamInit(); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::VectorBufferInit() +{ + // 暂存已分配UB大小,其余为shareBuffer + uint64_t usedBytes = 0; + if constexpr (std::is_same::value) { + uint64_t dequantScaleWDqSize = baseParams_->headSizeCq * sizeof(float); + pipe_->InitBuffer(dequantScaleWDqBuffer_, dequantScaleWDqSize); // [1, 1536] + usedBytes += dequantScaleWDqSize; + dequantScaleWDqLocal_ = dequantScaleWDqBuffer_.Get(); + + uint64_t dequantScaleWDkvKrSize = (baseParams_->dimHeadRope + baseParams_->headSizeCkv) * sizeof(float); + pipe_->InitBuffer(dequantScaleWDkvKrBuffer_, dequantScaleWDkvKrSize); // [1, 512 + 64] + usedBytes += dequantScaleWDkvKrSize; + dequantScaleWDkvKrLocal_ = dequantScaleWDkvKrBuffer_.Get(); + } + uint64_t rmsnormGammaCqSize = baseParams_->headSizeCq * sizeof(rmsNormGammaType); + pipe_->InitBuffer(rmsnormGammaCqBuffer_, rmsnormGammaCqSize); // [1, 1536] bf16 + usedBytes += rmsnormGammaCqSize; + rmsnormGammaCqLocal_ = rmsnormGammaCqBuffer_.Get(); + + uint64_t rmsnormGammaCkvSize = baseParams_->headSizeCkv * sizeof(rmsNormGammaType); + pipe_->InitBuffer(rmsnormGammaCkvBuffer_, rmsnormGammaCkvSize); // [1, 512] bf16 + usedBytes += rmsnormGammaCkvSize; + rmsnormGammaCkvLocal_ = rmsnormGammaCkvBuffer_.Get(); + + if constexpr (std::is_same::value) { + if (enableSmoothScalesCq_) { + uint64_t smoothScaleCqSize = baseParams_->headSizeCq * sizeof(float); + pipe_->InitBuffer(smoothScaleCqBuffer_, smoothScaleCqSize); // [1, 1536] + usedBytes += smoothScaleCqSize; + smoothScaleCqLocal_ = smoothScaleCqBuffer_.Get(); + } + } + + if constexpr (std::is_same::value) { + uint64_t quantScaleCkrSize = baseParams_->dimHeadRope * sizeof(float); + pipe_->InitBuffer(quantScaleCkrBuffer_, baseParams_->dimHeadRope * sizeof(float)); // [1, 64] + usedBytes += quantScaleCkrSize; + quantScaleCkrLocal_ = quantScaleCkrBuffer_.Get(); + } + + if constexpr (std::is_same::value) { + uint64_t quantScaleCkvSize = 0; + if constexpr (std::is_same::value || + std::is_same::value) { + quantScaleCkvSize = ALIGN_BLOCK_SIZE; + pipe_->InitBuffer(quantScaleCkvBuffer_, quantScaleCkvSize); + usedBytes += quantScaleCkvSize; + } else { // per_channel量化场景走else分支 + quantScaleCkvSize = baseParams_->headSizeCkv * sizeof(float); + pipe_->InitBuffer(quantScaleCkvBuffer_, quantScaleCkvSize); // [1, 512] + usedBytes += quantScaleCkvSize; + } + quantScaleCkvLocal_ = quantScaleCkvBuffer_.Get(); + } + + // 预留brcb的空间 + uint64_t deQuantScaleCqSize = (baseParams_->stepBatchSize + 7) * ALIGN_BLOCK_SIZE; + pipe_->InitBuffer(dequantTool_.dequantScaleCqBuffer_, deQuantScaleCqSize); + usedBytes += deQuantScaleCqSize; + dequantTool_.dequantScaleCqLocal_ = dequantTool_.dequantScaleCqBuffer_.template Get(); + + uint64_t sincosSize = 0; + if constexpr (MLAPT::enableDequantOpt) { + // 在ropeQr进行切N处理后,会复用shareBuffer的内存,不需要额外申请 + // 开启开关后会按照head切分rope qr,此时需要加载一半batchsize数量的sin和cos值 + // 需要2倍的空间分别存储sin和cos + sincosSize = sizeof(ropeComputType) * 2 * baseParams_->dimHeadRope * + ((baseParams_->stepBatchSize + cvRatio_ - 1) / cvRatio_); + pipe_->InitBuffer(sincosBuffer_, sincosSize); + } else { + // 需要2倍的空间分别存储sin和cos + sincosSize = sizeof(ropeComputType) * 2 * baseParams_->dimHeadRope * curVecTokenMax_; + pipe_->InitBuffer(sincosBuffer_, sincosSize); // [2, 64] float + } + usedBytes += sincosSize; + + if constexpr (!MLAPT::enableDequantOpt) { + cosLocal_ = sincosBuffer_.Get(); + sinLocal_ = cosLocal_[baseParams_->dimHeadRope * curVecTokenMax_]; + } else { + cosLocal_ = sincosBuffer_.Get(); + sinLocal_ = cosLocal_[baseParams_->dimHeadRope * ((baseParams_->stepBatchSize + cvRatio_ - 1) / cvRatio_)]; + } + + if constexpr (MLAPT::actualSeqMode == ACTUAL_SEQ_MODE::EN_Q_LEN) { + uint64_t stepActualSeqSize = sizeof(int64_t) * baseParams_->stepBatchSize; + pipe_->InitBuffer(stepActualSeqBuffer_, stepActualSeqSize); // [1, stepBatchSize] + usedBytes += stepActualSeqSize; + stepActualSeqLocal_ = stepActualSeqBuffer_.Get(); + } + + // 由于shareBuffer属于各个vector操作临时申请内存的区域内存使用不固定,建议shareBuffer始终放在最后 + // 防止写入shareBuffer越界导致前面固定申请的UB内存被踩。 + pipe_->InitBuffer(shareBuffer_, MAX_UB_SIZE - usedBytes); + CrossCoreSetFlag(FINISH_VEC_CKVKR); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::CubeBufferInit() +{ + // cube相关Buffer初始化 + pipe_->InitBuffer(aBufL1_, L1_A_SIZE * 2); + pipe_->InitBuffer(bBufL1_, L1_B_SIZE * 2); + + aL1Tensor_ = aBufL1_.Get(); + bL1Tensor_ = bBufL1_.Get(); + AscendC::SetFlag(A_EVENT0); + AscendC::SetFlag(A_EVENT1); + AscendC::SetFlag(B_EVENT0); + AscendC::SetFlag(B_EVENT1); + bufParam_.aL1BufAddr = aBufL1_.GetBufferAddr(aL1Tensor_.GetBufferHandle()); + bufParam_.bL1BufAddr = bBufL1_.GetBufferAddr(bL1Tensor_.GetBufferHandle()); + + pipe_->InitBuffer(cBufL0_, L0C_PP_SIZE * 2); // 128K + pipe_->InitBuffer(bBufL0_, L0B_PP_SIZE * 2); // 64K + pipe_->InitBuffer(aBufL0_, L0A_PP_SIZE * 2); // 64K + + AscendC::SetFlag(L0A_EVENT0); + AscendC::SetFlag(L0A_EVENT1); + AscendC::SetFlag(L0B_EVENT0); + AscendC::SetFlag(L0B_EVENT1); + + AscendC::SetFlag(L0C_EVENT0); + AscendC::SetFlag(L0C_EVENT1); + + AscendC::SetFlag(SCALE_EVENT); + + bufParam_.cL0BufAddr = cBufL0_.GetBufferAddr(cBufL0_.Get().GetBufferHandle()); + bufParam_.bL0BufAddr = bBufL0_.GetBufferAddr(bBufL0_.Get().GetBufferHandle()); + bufParam_.aL0BufAddr = aBufL0_.GetBufferAddr(aBufL0_.Get().GetBufferHandle()); +} + +/* + * workspace管理 + * 1. 常驻:dequantTool_.dequantScaleCqGm_ stepBs * 32 Byte + * 2. 中间结果: + * tokenXGm_──────>mmCkvKrResGm_ + * | [stepBS, HCkv + Dr] + * | (bf16 | int32) + * └─────────>mmCqResGm_──────>rmsNormCqResGm_──────>mmQcQrResGm_──────>mmQcQrResDequantGm_──────>mmQnResGm_ + * [stepBS, HCq] [stepBS, HCq] [stepBS, N1, D + Dr] [stepBS, N1, D] [stepBS, N1, + * HCkv] (bf16 | int32) (bf16 | int8) (bf16 | int32) (bf16) (bf16) + */ +template +__aicore__ inline void MlaPrologVecS1CubS2::WorkspaceInit(__gm__ uint8_t *workspace) +{ + int64_t workspaceOffset = 0; + dequantScaleCqSize_ = Align(dequantScaleCqSize_, BYTE_BLOCK); + if constexpr (MLAPT::enableGroupComputeOpt || MLAPT::enableDequantOpt) { + dequantTool_.dequantScaleCqGm_.SetGlobalBuffer((__gm__ dequantScaleType *)(workspace + workspaceOffset)); + workspaceOffset += baseParams_->stepBatchSize * dequantScaleCqSize_; + } + + mmCkvKrResGm_.SetGlobalBuffer((__gm__ mmCkvKrOutputType *)(workspace + workspaceOffset)); + workspaceOffset += static_cast(sizeof(mmCkvKrOutputType)) * + static_cast(baseParams_->headSizeCkv + baseParams_->dimHeadRope) * + static_cast(baseParams_->stepBatchSize); + + mmCqResGm_.SetGlobalBuffer((__gm__ mmCqOutputType *)(workspace + workspaceOffset)); + + if (baseParams_->queryNormFlag == 0U) { + // 全量化场景下`mmCqResGm_`与`rmsNormCqResGm_`的dtype不同,无法共用workspace,此处需要偏移`mmCqResGm_`占用的大小; + if constexpr (!std::is_same::value) { + workspaceOffset += static_cast(sizeof(mmCqOutputType)) * + static_cast(baseParams_->headSizeCq) * + static_cast(baseParams_->stepBatchSize); + } + // 不返回queryNorm时,rmsNormCq结果放在workspace + rmsNormCqResGm_.SetGlobalBuffer((__gm__ rmsNormCqOutputType *)(workspace + workspaceOffset)); + workspaceOffset += static_cast(baseParams_->headSizeCq) * + static_cast(baseParams_->stepBatchSize) * sizeof(rmsNormCqOutputType); + } else { + // 返回queryNorm时,rmsNormCq结果直接输出gm,此处需要偏移`mmCqResGm_`占用的大小 + workspaceOffset += static_cast(baseParams_->headSizeCq) * + static_cast(baseParams_->stepBatchSize) * + static_cast(sizeof(mmCqOutputType)); + } + + mmQcQrResGm_.SetGlobalBuffer((__gm__ mmQcQrOutputType *)(workspace + workspaceOffset)); + if constexpr (std::is_same::value) { + workspaceOffset += static_cast(baseParams_->stepBatchSize) * + static_cast(baseParams_->headSizeQc + baseParams_->headSizeQr) * + static_cast(sizeof(mmQcQrOutputType)); + } + + mmQcQrResDequantGm_.SetGlobalBuffer((__gm__ mmQnInputType *)(workspace + workspaceOffset)); + if constexpr ((std::is_same::value && std::is_same::value) && + !isPertile) { + workspaceOffset += sizeof(mmQnInputType) * static_cast(baseParams_->dimHeadSizeQc) * + static_cast(baseParams_->numHeadSize) * + static_cast(baseParams_->stepBatchSize); + mmQnResGm_.SetGlobalBuffer((__gm__ mmQnOutputType *)(workspace + workspaceOffset)); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::UpdateStepBatchParams(int64_t curStepBatchSize) +{ + mmQnParam_.m = curStepBatchSize; + mmQcQrParam_.m = curStepBatchSize; + mmCkvKrParam_.m = curStepBatchSize; + mmCqParam_.m = curStepBatchSize; + curVectorBlockNum_ = curStepBatchSize; +} + +/* + * MlaProlog算子计算&CV流水同步流程 + * ┌───────────────── token_x ─────────────────┐ + * | ▼ + * | MatmulCkvKr + * ▼ | wait mm CkvKr(0x1) + * MatmulCq ▼ + * | wait mm Cq(0x1) ┌─────────────────┐ + * ▼ ▼ ▼ + * RmsNorm(Cq) RmsNorm(Ckv) Rope(Kr) + * | wait rmsNorm cq(0x1) | | + * ▼ ▼ ▼ + * ┌───────MatmulQcQr───────┐ Scatter(Ckv) Scatter(Kr) + * | wait mm Qc(0x1) | | | + * ▼ | ▼ ▼ + * DequantQc | kv_cache_out kr_cache_out + * | wait dequant qc(0x1) | wait mm Qr(0x2) + * ▼ ▼ + * MatmulQn Rope(Qr) + * | wait mm Qn(0x1) | + * DynamicQuantQn──┐ | + * | ▼ | + * ▼ dequant_scale_out ▼ + * query_out query_rope_out + * 注:仅为表明基本计算与CV同步流程,仅包含了影响CV同步的量化分支,其余量化分支应参考设计文档。 + */ +template +__aicore__ inline void MlaPrologVecS1CubS2::Process() +{ + constexpr bool needQnDynamicQuant = + (std::is_same::value && std::is_same::value) && !isPertile; + int64_t numHeadOffset = cubeBlockIdx_ * baseParams_->mm4SingleCoreBatch; + int64_t mmQnLoops; + if (cubeBlockIdx_ == baseParams_->mm4BlockNum - 1) { + mmQnLoops = static_cast(baseParams_->numHeadSize) - numHeadOffset; + } else { + mmQnLoops = static_cast(baseParams_->mm4SingleCoreBatch); + } + + // AIV的offset参数 + AivOffset aivOffset; + ComputeAivOffset(aivOffset, 0); + + // AIC的offset参数 + AicOffset aicOffset; + ComputeAicOffset(aicOffset, numHeadOffset); + + int64_t bsSize = static_cast(baseParams_->tokenSize); + // 需要考虑BS合轴的尾块情况 + for (int64_t batchOffset = 0; batchOffset < bsSize; + batchOffset += static_cast(baseParams_->stepBatchSize)) { + if constexpr (MLAPT::actualSeqMode == ACTUAL_SEQ_MODE::EN_Q_LEN) { + if (!actSeqState_.inited) { + actSeqState_.curBatch = 0; + actSeqState_.curPrefix = (baseParams_->batchSize > 0) ? actualSeqLenGm_(0) : 0; + actSeqState_.prevPrefix = 0; + actSeqState_.inited = true; + actSeqState_.curIndexOffset = + CeilDivT(actSeqState_.curPrefix, static_cast(baseParams_->blockSize)); + actSeqState_.prevIndexOffset = 0; + } + } + int64_t curStepBatchSize = bsSize - batchOffset; + if (curStepBatchSize >= static_cast(baseParams_->stepBatchSize)) { + curStepBatchSize = static_cast(baseParams_->stepBatchSize); + } else { + UpdateStepBatchParams(curStepBatchSize); // 320 - 256 + if (batchOffset != 0) { + ComputeAivOffset(aivOffset, batchOffset); + } + } + if ASCEND_IS_AIV { + AivProcess(aivOffset, batchOffset, curStepBatchSize, numHeadOffset, mmQnLoops); + } + if ASCEND_IS_AIC { + AicProcess(aicOffset, batchOffset, mmQnLoops); + } + } + if ASCEND_IS_AIC { + AscendC::WaitFlag(A_EVENT0); + AscendC::WaitFlag(A_EVENT1); + AscendC::WaitFlag(B_EVENT0); + AscendC::WaitFlag(B_EVENT1); + + AscendC::WaitFlag(L0A_EVENT0); + AscendC::WaitFlag(L0A_EVENT1); + AscendC::WaitFlag(L0B_EVENT0); + AscendC::WaitFlag(L0B_EVENT1); + + AscendC::WaitFlag(L0C_EVENT0); + AscendC::WaitFlag(L0C_EVENT1); + + AscendC::WaitFlag(SCALE_EVENT); + CrossCoreWaitFlag(FINISH_VEC_CKVKR); + } +} + +template +template +__aicore__ inline void MlaPrologVecS1CubS2::AicProcess(AicOffset &aicOffset, int64_t batchOffset, + int64_t mmQnLoops) +{ + int64_t dequantScaleXOffset = static_cast(baseParams_->headSizeX) * batchOffset / 32; + int64_t tokenXOffset = static_cast(baseParams_->headSizeX) * batchOffset; + // MatmulCq ──> RmsNorm(Cq) + // [32, 7168] * [7168, 1536] = [32, 1536] + MatmulSplitN( + mmCqResGm_[aicOffset.cqResOffset], tokenXGm_[tokenXOffset], weightDqGm_[aicOffset.weightDqOffset], mmCqParam_, + UsedBlockParams{0, baseParams_->mm1BlockNum}); + CrossCoreSetFlag(FINISH_MM_CQ); + // MatmulCkvKr ──> RmsNorm(Ckv) + // └──> Rope(Kr) + // [32, 7168] * [7168, 512+64] = [32, 576] + CrossCoreWaitFlag(FINISH_VEC_CKVKR); + MatmulSplitN( + mmCkvKrResGm_[aicOffset.ckvKrResOffset], tokenXGm_[tokenXOffset], weightDkvKrGm_[aicOffset.weightDkvKrOffset], + mmCkvKrParam_, UsedBlockParams{0, baseParams_->mm2BlockNum}); + CrossCoreSetFlag(FINISH_MM_CKVKR); + CrossCoreWaitFlag(FINISH_VEC_RMSNORM_CQ); + + MatmulAndSyncQcQr(aicOffset); + + PreloadQnAndSync(aicOffset, mmQnLoops); + MatmulQnSyncDynamicQuantAndMulQr(aicOffset.qcOffset, aicOffset.weightUkOffset, + aicOffset.qnResOffset, mmQnLoops); + if constexpr (!needQnDynamicQuant) { + // MatmulQn的结果直接输出到 queryOut, qnOffset需要按Batch轴偏移 + aicOffset.qnResOffset += static_cast(baseParams_->numHeadSize) * + static_cast(baseParams_->headSizeCkv) * + static_cast(baseParams_->stepBatchSize); + } + if (unlikely(baseParams_->queryNormFlag == 1U)) { + aicOffset.rmsNormCqResOffset += + static_cast(baseParams_->headSizeCq) * static_cast(baseParams_->stepBatchSize); + } +} + +template +template +__aicore__ inline void MlaPrologVecS1CubS2::AivProcess(AivOffset &aivOffset, int64_t batchOffset, + int64_t curStepBatchSize, int64_t numHeadOffset, + int64_t mmQnLoops) +{ + int64_t tokenIndex = aivOffset.curBlockTokenOffset + batchOffset; + if (batchOffset == 0) { + // 只需要搬运一次 + CopyGlobalParams(); + } + int64_t rmsNormCqResOffset; + if (baseParams_->queryNormFlag == 1U) { + rmsNormCqResOffset = tokenIndex * baseParams_->headSizeCq; + } else { + rmsNormCqResOffset = aivOffset.rmsNormCqOffset; + } + CopyInSinCos(tokenIndex, aivOffset.curVecToken, batchOffset, curStepBatchSize); + CrossCoreWaitFlag(FINISH_MM_CQ); + WaitAllCore(FINISH_VEC_ALL); + RmsNormCq(tokenIndex, aivOffset.rmsNormCqOffset, rmsNormCqResOffset, aivOffset.curVecToken, + aivOffset.curBlockTokenOffset); + // 由于RmsNormCq和MatmulQcQr的分核策略不一样,需要等所有vector上的RmsNormCq执行完成后才能启动MatmulQcQr + // 需要所有vector核上的RmsNormCq执行完成后,才发起MatmulQcQr的执行 + WaitAllCore(FINISH_VEC_ALL); + + // 聚合全部scale结果 + if constexpr ((MLAPT::enableDequantOpt || MLAPT::enableGroupComputeOpt) && + (std::is_same::value)) { + DataCopy(dequantTool_.dequantScaleCqLocal_, dequantTool_.dequantScaleCqGm_, + ALIGN_BLOCK_SIZE / sizeof(float) * baseParams_->stepBatchSize); + } + CrossCoreSetFlag(FINISH_VEC_RMSNORM_CQ); + CrossCoreWaitFlag(FINISH_MM_CKVKR); + WaitAllCore(FINISH_VEC_ALL); + RmsNormRopeScatterCkvKr(tokenIndex, aivOffset.rmsNormCkvOffset, aivOffset.ropeKrOffset, aivOffset.curVecToken); + CrossCoreSetFlag(FINISH_VEC_CKVKR); + + // 根据不同分支条件处理 + if constexpr (!MLAPT::enableGroupComputeOpt) { + if constexpr (MLAPT::enableDequantOpt) { + DequantAndRopeSplitNSyncMMQcQr(aivOffset.mmQnPreDequantOffset, aivOffset.mmQnPreDequantResOffset, + aivOffset.ropeQrOffset, aivOffset.ropeQrResOffset); + } else if constexpr (std::is_same::value) { + CrossCoreWaitFlag(FINISH_MM_QCQR); + WaitAllCore(FINISH_VEC_ALL); + RopeQr(aivOffset.ropeQrOffset, aivOffset.ropeQrResOffset, aivOffset.curVecToken, + aivOffset.curBlockTokenOffset); + } else { + CrossCoreWaitFlag(FINISH_MM_QCQR); + WaitAllCore(FINISH_VEC_ALL); + DequantQc(aivOffset.mmQnPreDequantOffset, aivOffset.mmQnPreDequantResOffset, aivOffset.curVecToken, + aivOffset.curBlockTokenOffset); + WaitAllCore(FINISH_VEC_ALL); + CrossCoreSetFlag(FINISH_VEC_DEQUANT_QC); + RopeQr(aivOffset.ropeQrOffset, aivOffset.ropeQrResOffset, aivOffset.curVecToken, + aivOffset.curBlockTokenOffset); + } + + if constexpr (!(MLAPT::enableDequantOpt) && needQnDynamicQuant) { + // 非切N场景,需要等待全部rope的结果做完并搬到GM + WaitAllCore(FINISH_VEC_ALL); + } + if constexpr (needQnDynamicQuant) { + DynamicQuantQnAndMulQrSyncMMQn(batchOffset, curStepBatchSize, numHeadOffset, mmQnLoops); + } + aivOffset.ropeQrResOffset += + static_cast(baseParams_->headSizeQr) * static_cast(baseParams_->stepBatchSize); + } else { + CrossCoreWaitFlag(FINISH_MM_QC); + DequantQcSplitNGroupCase(aivOffset.mmQnPreDequantOffset, aivOffset.mmQnPreDequantResOffset, + aivOffset.qcScaleOffsetSplitN); + CrossCoreSetFlag(FINISH_VEC_DEQUANT_QC); + CrossCoreWaitFlag(FINISH_MM_QR); + RopeQrSplitNGroupCase(aivOffset.ropeQrSplitNOffset, aivOffset.ropeQrResSplitNOffset); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::ComputeAicOffset(AicOffset &aicOffset, int64_t numHeadOffset) +{ + aicOffset.cqResOffset = baseParams_->mm1SingleCoreN * blockIdx_; // 64 * idx + aicOffset.dequantScaleWDqOffset = + static_cast(baseParams_->headSizeX) / 32 * aicOffset.cqResOffset; // 7168 * 64 * idx + aicOffset.weightDqOffset = static_cast(baseParams_->headSizeX) * aicOffset.cqResOffset; // 7168 * 64 * idx + + aicOffset.ckvKrResOffset = baseParams_->mm2SingleCoreN * blockIdx_; // (512 + 64) / 9 * idx = 64 * idx + aicOffset.dequantScaleWDkvKrOffset = static_cast(baseParams_->headSizeX) / 32 * + aicOffset.ckvKrResOffset; // 7168 * (512 + 64) / 9 * idx = 7168 * 64 * idx + aicOffset.weightDkvKrOffset = static_cast(baseParams_->headSizeX) * + aicOffset.ckvKrResOffset; // 7168 * (512 + 64) / 9 * idx = 7168 * 64 * idx + + if constexpr (MLAPT::enableGroupComputeOpt) { + aicOffset.weightUqOffset = + blockIdx_ * (baseParams_->dimHeadRope + baseParams_->dimHeadSizeQc) * + static_cast(baseParams_->headSizeCq); // 1536 * (32 * 128 + 32 * 64) / 24 * idx = 1536 * 256 * idx + aicOffset.weightQrOffset = static_cast(baseParams_->headSizeCq) * + (baseParams_->dimHeadRope + baseParams_->dimHeadSizeQc) * 2 * + (blockIdx_ - QC_CORE_NUM) + + baseParams_->dimHeadSizeQc * static_cast(baseParams_->headSizeCq); + aicOffset.qCResOffset = baseParams_->dimHeadSizeQc * blockIdx_; + aicOffset.qRResOffset = + QC_CORE_NUM * baseParams_->dimHeadSizeQc * baseParams_->stepBatchSize + + 2 * baseParams_->dimHeadRope * (blockIdx_ - QC_CORE_NUM); // m=baseParams_->stepBatchSize + } else { + aicOffset.qcQrResOffset = baseParams_->mm3SingleCoreN * blockIdx_; // 192 * idx + aicOffset.weightUqQrOffset = + aicOffset.qcQrResOffset * + static_cast(baseParams_->headSizeCq); // 1536 * (32 * 128 + 32 * 64) / 24 * idx = 1536 * 256 * idx + aicOffset.dequantScaleWuqqrOffset = aicOffset.weightUqQrOffset / 32; + } + + if (cubeBlockIdx_ < baseParams_->mm4BlockNum) { + if constexpr (std::is_same::value || std::is_same::value) { + aicOffset.qcOffset = static_cast(baseParams_->dimHeadSizeQc) * numHeadOffset; // 128 * idx + } else { + aicOffset.qcOffset = static_cast(baseParams_->dimHeadRope + baseParams_->dimHeadSizeQc) * + numHeadOffset; // (128 + 64) * idx + } + aicOffset.weightUkOffset = numHeadOffset * static_cast(baseParams_->headSizeCkv) * + static_cast(baseParams_->dimHeadSizeQc); // (128 * 512) * idx + aicOffset.qnResOffset = static_cast(baseParams_->headSizeCkv) * numHeadOffset; // BS, N, Dq + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::ComputeAivOffset(AivOffset &aivOffset, int64_t batchOffset) +{ + curStepVecFrontListNum_ = curVectorBlockNum_ % static_cast(vectorCoreNum_); + curStepVecBackToken_ = curVectorBlockNum_ / static_cast(vectorCoreNum_); + curStepVecFrontToken_ = curStepVecFrontListNum_ != 0 ? curStepVecBackToken_ + 1 : curStepVecBackToken_; + + aivOffset.curVecToken = blockIdx_ < curStepVecFrontListNum_ ? curStepVecFrontToken_ : curStepVecBackToken_; + aivOffset.curBlockTokenOffset = blockIdx_ < curStepVecFrontListNum_ ? + blockIdx_ * aivOffset.curVecToken : + blockIdx_ * aivOffset.curVecToken + curStepVecFrontListNum_; + aivOffset.rmsNormCqOffset = baseParams_->headSizeCq * aivOffset.curBlockTokenOffset; // 1536 * idx + aivOffset.rmsNormCkvOffset = + (baseParams_->dimHeadRope + baseParams_->headSizeCkv) * aivOffset.curBlockTokenOffset; // (512 + 64) * idx + aivOffset.ropeKrOffset = aivOffset.rmsNormCkvOffset + baseParams_->headSizeCkv; // 512 + (512 + 64) * idx + if constexpr (!MLAPT::enableDequantOpt) { + aivOffset.mmQnPreDequantOffset = + (baseParams_->headSizeQr + baseParams_->headSizeQc) * aivOffset.curBlockTokenOffset; + aivOffset.mmQnPreDequantResOffset = baseParams_->headSizeQc * aivOffset.curBlockTokenOffset; + aivOffset.ropeQrOffset = static_cast(baseParams_->dimHeadSizeQc) + + aivOffset.curBlockTokenOffset * + static_cast(baseParams_->dimHeadRope + baseParams_->dimHeadSizeQc) * + static_cast(baseParams_->numHeadSize); // 128 + 32 * (128 + 64) * idx + aivOffset.ropeQrResOffset = + static_cast(baseParams_->headSizeQr) * + (aivOffset.curBlockTokenOffset + batchOffset); // 32 * 64 * idx; // 按BS合轴切分step + } + + // 以下的Offset均是与batchOffset无关的,仅初始化一次即可。 + if (batchOffset == 0) { + if constexpr (MLAPT::enableDequantOpt) { + aivOffset.mmQnPreDequantOffset = baseParams_->mm3SingleCoreN * cubeBlockIdx_; // qcQrResOffset + aivOffset.mmQnPreDequantResOffset = baseParams_->mm3SingleCoreN / + (baseParams_->dimHeadRope + baseParams_->dimHeadSizeQc) * + baseParams_->dimHeadSizeQc * cubeBlockIdx_; + aivOffset.ropeQrOffset = aivOffset.mmQnPreDequantOffset + baseParams_->dimHeadSizeQc; + aivOffset.ropeQrResOffset = + (baseParams_->mm3SingleCoreN / (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope)) * + baseParams_->dimHeadRope * cubeBlockIdx_; + } + + if constexpr (MLAPT::enableGroupComputeOpt) { + aivOffset.qcScaleOffsetSplitN = + (baseParams_->headSizeQr + baseParams_->headSizeQc) / QC_CORE_NUM * (blockIdx_ / cvRatio_); + aivOffset.mmQnPreDequantResOffset = (baseParams_->headSizeQc) / QC_CORE_NUM * (blockIdx_ / cvRatio_); + aivOffset.mmQnPreDequantOffset = aivOffset.mmQnPreDequantResOffset; + aivOffset.ropeQrResSplitNOffset = (blockIdx_ - QC_CORE_NUM * cvRatio_) * baseParams_->dimHeadRope; + aivOffset.ropeQrSplitNOffset = baseParams_->headSizeQc + aivOffset.ropeQrResSplitNOffset; + } + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::CopyInSinCos(int64_t tokenIndex, int64_t curVecToken, + int64_t batchOffset, int64_t curStepBatchSize) +{ + LocalTensor shareTmpUb = shareBuffer_.Get(); + if constexpr (!MLAPT::enableDequantOpt) { + if (blockIdx_ >= curVectorBlockNum_) { + return; + } + GatherSinCos(cosLocal_, sinLocal_, ropeCosGm_, ropeSinGm_, tokenIndex, + curVecToken, shareTmpUb, vectorRow_, baseParams_->dimHeadRope); + } else { + // 如果是切N场景,mm3的每个C核都会做rope + if (cubeBlockIdx_ >= baseParams_->mm3BlockNum) { + return; + } + // 如果curStepBatchSize是偶数,则两个核平分;如果curStepBatchSize是奇数,则奇数核比偶数核多分一个 + // >> 1 是将curStepBatchSize分到每个vec核上; + uint32_t subBlockIdx_ = blockIdx_ % cvRatio_; + int64_t offset = (curStepBatchSize / cvRatio_) * subBlockIdx_ + batchOffset; + GatherSinCos(cosLocal_, sinLocal_, ropeCosGm_, ropeSinGm_, offset, + (curStepBatchSize + cvRatio_ - 1) / cvRatio_, shareTmpUb, + vectorRow_, baseParams_->dimHeadRope); + } +} + +// Mlaprolog 支持int8进int32出, 参考MatmulQcQr +template +template +__aicore__ inline void +MlaPrologVecS1CubS2::MatmulSplitN(const GlobalTensor &tensorResGm, const GlobalTensor &tensorAGm, + const GlobalTensor &tensorBGm, const MMParams &mmPara, + const UsedBlockParams &mmBlockParams, const GlobalTensor &tensorAScaleGm, + const GlobalTensor &tensorBScaleGm) +{ + if constexpr (needCheckEmptyTensor) { + if constexpr (MLAPT::emptyMode == EMPTY_TENSOR_MODE::EMPTY_CACHE) { + return; + } + } + if (blockIdx_ >= mmBlockParams.blockEndIdx || blockIdx_ < mmBlockParams.blockStartIdx) { + return; + } + // 用于enableGroupComputeOpt场景 + if constexpr (needCheckAFullLoad) { + constexpr uint32_t mSize = + (sizeof(mmQcQrInputType) == sizeof(int8_t)) ? INT8_AFULLLOAD_MAX_MSIZE : BF16_AFULLLOAD_MAX_MSIZE; + bool isAFullLoad = mmQcQrParam_.m <= mSize; + if (isAFullLoad) { + MatmulGroupComputeAFullLoad(tensorResGm, tensorAGm, tensorBGm, mmPara, + bufParam_); + return; + } + } + uint32_t nL1SplitSize = mmPara.baseN; + uint32_t nInput = mmPara.n; + uint32_t subNL1SplitSize = nL1SplitSize; + uint32_t nL1loops = CeilDivT(nInput, nL1SplitSize); + for (int64_t nL1 = 0; nL1 < nL1loops; nL1++) { + if (nL1 == nL1loops - 1) { + subNL1SplitSize = nInput - (nL1loops - 1) * nL1SplitSize; + } + MatmulSplitK(tensorResGm, tensorAGm, tensorBGm, mmPara, bufParam_, nL1 * nL1SplitSize, + subNL1SplitSize); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MatmulAndSyncQcQr(AicOffset &aicOffset) +{ + if constexpr (!MLAPT::enableGroupComputeOpt) { + MatmulQcQr(aicOffset); + } else { + // MatmulQc + // 复用mmCqResGm_ workspace + MatmulSplitN( + mmQcQrResGm_[aicOffset.qCResOffset], rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + weightUqQrGm_[aicOffset.weightUqOffset], mmQcQrParam_, UsedBlockParams{0, QC_CORE_NUM}); + CrossCoreSetFlag(FINISH_MM_QC); + // MatmulQr + MatmulSplitN( + mmQcQrResGm_[aicOffset.qRResOffset], rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + weightUqQrGm_[aicOffset.weightQrOffset], mmQcQrParam_, + UsedBlockParams{QC_CORE_NUM, QC_CORE_NUM + QR_CORE_NUM}); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MatmulQcQr(AicOffset &aicOffset) +{ + if (blockIdx_ >= baseParams_->mm3BlockNum) { + return; + } + // RmsNorm(Cq) ──> MatmulQcQr ──> MatmulQn + // └──> Rope(Qr) + // [32, 1536] * [1536, 32*(128+64)] = [32, 32*192] + constexpr uint32_t mSize = + (sizeof(mmQcQrInputType) != sizeof(int8_t)) ? BF16_AFULLLOAD_MAX_MSIZE : INT8_AFULLLOAD_MAX_MSIZE; + bool isAFullLoad = mmQcQrParam_.m <= mSize; + + uint32_t nL1SplitSize = mmQcQrParam_.baseN; + uint32_t nInput = mmQcQrParam_.n; + uint32_t nL1loops = CeilDivT(nInput, nL1SplitSize); + uint32_t subNL1SplitSize = nL1SplitSize; + if (isAFullLoad) { + LoadL1A(rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], mmQcQrParam_.m, mmQcQrParam_.k, mmQcQrParam_.k, + bufParam_); + AscendC::WaitFlag(A_EVENT0 + (bufParam_.aL1BufIter & 1u)); + } + + for (int64_t nL1 = 0; nL1 < nL1loops; nL1++) { + if (nL1 == nL1loops - 1) { + subNL1SplitSize = nInput - (nL1loops - 1) * nL1SplitSize; + } + if (!isAFullLoad) { + MatmulSplitK( + mmQcQrResGm_[aicOffset.qcQrResOffset], rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + weightUqQrGm_[aicOffset.weightUqQrOffset], mmQcQrParam_, bufParam_, nL1 * nL1SplitSize, + subNL1SplitSize); + } else { + MatmulSplitK( + mmQcQrResGm_[aicOffset.qcQrResOffset], rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + weightUqQrGm_[aicOffset.weightUqQrOffset], mmQcQrParam_, bufParam_, nL1 * nL1SplitSize, + subNL1SplitSize); + } + if constexpr (MLAPT::enableDequantOpt) { + CrossCoreSetFlag<0x2, PIPE_FIX>(FINISH_MM_QCQR_SPLIT_N); + } + } + if (isAFullLoad) { + AscendC::SetFlag(A_EVENT0 + (bufParam_.aL1BufIter & 1u)); + bufParam_.aL1BufIter++; + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::PreloadQnAndSync(AicOffset &aicOffset, int64_t mmQnLoops) +{ + MatmulQnWeightPreload(aicOffset.weightUkOffset, mmQnLoops); + if constexpr (MLAPT::enableDequantOpt) { + // enableDequantOpt分支的CV同步由更细粒度的子函数控制 + return; + } else if constexpr (MLAPT::enableGroupComputeOpt) { + CrossCoreSetFlag(FINISH_MM_QR); + } else { + CrossCoreSetFlag(FINISH_MM_QCQR); + } + + if constexpr (std::is_same::value) { + CrossCoreWaitFlag(FINISH_VEC_DEQUANT_QC); + } else { + WaitAllCore(FINISH_MM_ALL); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MatmulQnWeightPreload(int64_t weightUkOffset, int64_t subLoopTimes) +{ + if constexpr (MLAPT::enableGroupComputeOpt) { + if (blockIdx_ >= QC_CORE_NUM) { + return; + } + } else { + if (blockIdx_ >= baseParams_->mm4BlockNum) { + return; + } + } + if (mmQnParam_.baseK < mmQnParam_.k) { + return; + } + int64_t weightOffset = weightUkOffset; + for (int32_t i = 0; i < subLoopTimes; ++i) { + if (i < 1) { // preload double buffer + LoadL1B(weightUkGm_[weightOffset], mmQnParam_.n, mmQnParam_.n, + mmQnParam_.k, mmQnParam_.k, bufParam_); + AscendC::WaitFlag(B_EVENT0 + (bufParam_.bL1BufIter & 1u)); + weightOffset += + static_cast(baseParams_->headSizeCkv) * static_cast(baseParams_->dimHeadSizeQc); + } + } +} + +template +template +__aicore__ inline void +MlaPrologVecS1CubS2::MatmulQnSyncDynamicQuantAndMulQr(int64_t qcOffset, int64_t weightUkOffset, + int64_t qnResOffset, int64_t subLoopTimes) +{ + uint32_t maxBlockIdx = !MLAPT::enableGroupComputeOpt ? baseParams_->mm4BlockNum : QC_CORE_NUM; + if (blockIdx_ >= maxBlockIdx) { + return; + } + // MatmulQcQr ──> MatmulQn ──> query_out + // [32, 128] * [128, 512] = [32, 512] + // [32, 2, 128] * [2, 128, 512] = [32, 2, 512] + bool needSparseSync = subLoopTimes > MAX_SYNC_FLAG_COUNT; + for (int64_t i = 0; i < subLoopTimes; i++) { + if constexpr (MLAPT::enableDequantOpt) { + if (!needSparseSync || (i % 2 == 0) || (i == subLoopTimes - 1)) { + CrossCoreWaitFlag(FINISH_VEC_DEQUANT_QC_SPLIT_N); + } + } + if (unlikely(mmQnParam_.k > mmQnParam_.baseK)) { + uint32_t nL1SplitSize = mmQnParam_.baseN; + uint32_t nInput = baseParams_->headSizeCkv; + uint32_t subNL1SplitSize = nL1SplitSize; + uint32_t nL1loops = CeilDivT(nInput, nL1SplitSize); + for (int64_t nL1 = 0; nL1 < nL1loops; nL1++) { + if (nL1 == nL1loops - 1) { + subNL1SplitSize = nInput - (nL1loops - 1) * nL1SplitSize; + } + MatmulSplitK( + mmQnResGm_[qnResOffset], mmQcQrResDequantGm_[qcOffset], weightUkGm_[weightUkOffset], mmQnParam_, + bufParam_, nL1 * nL1SplitSize, subNL1SplitSize); + } + } else { + if (i >= 1) { + MatmulFullLoad( + mmQnResGm_[qnResOffset], mmQcQrResDequantGm_[qcOffset], weightUkGm_[weightUkOffset], mmQnParam_, + bufParam_); + } else { + MatmulFullLoad( + mmQnResGm_[qnResOffset], mmQcQrResDequantGm_[qcOffset], weightUkGm_[weightUkOffset], mmQnParam_, + bufParam_); + } + } + if constexpr (std::is_same::value) { + qcOffset += static_cast(baseParams_->dimHeadSizeQc); + } else { + qcOffset += static_cast(baseParams_->dimHeadRope + baseParams_->dimHeadSizeQc); + } + weightUkOffset += + static_cast(baseParams_->headSizeCkv) * static_cast(baseParams_->dimHeadSizeQc); + qnResOffset += static_cast(baseParams_->headSizeCkv); + + if constexpr (needQnDynamicQuant) { + CrossCoreSetFlag(FINISH_MM_QN_SPLIT_N); + } + } +} + + +template +__aicore__ inline void MlaPrologVecS1CubS2::CopyGlobalParams() +{ + // dequantScaleWDq + if constexpr (std::is_same::value) { + DataCopyExtParams dequantCopyParams{1, static_cast(baseParams_->headSizeCq * sizeof(float)), 0, 0, 0}; + DataCopyPadExtParams dequantPadParams{false, 0, 0, 0}; + DataCopyPad(dequantScaleWDqLocal_, dequantScaleWDqGm_, dequantCopyParams, dequantPadParams); + } + + // rmsnormGammaCq + DataCopy(rmsnormGammaCqLocal_, rmsnormGammaCqGm_, baseParams_->headSizeCq); + + // rmsnormGammaCkv + DataCopy(rmsnormGammaCkvLocal_, rmsnormGammaCkvGm_, baseParams_->headSizeCkv); + + // smoothScaleCq + if constexpr (std::is_same::value) { + if (enableSmoothScalesCq_) { + DataCopyExtParams smoothCopyParams{1, static_cast(baseParams_->headSizeCq * sizeof(float)), 0, 0, + 0}; + DataCopyPadExtParams smoothPadParams{false, 0, 0, 0}; + DataCopyPad(smoothScaleCqLocal_, smoothScaleCqGm_, smoothCopyParams, smoothPadParams); + } + } + + // dequantScaleWDkvKr + if constexpr (std::is_same::value) { + DataCopyExtParams dequantCopyParams{ + 1, static_cast((baseParams_->headSizeCkv + baseParams_->dimHeadRope) * sizeof(float)), 0, 0, 0}; + DataCopyPadExtParams dequantPadParams{false, 0, 0, 0}; + DataCopyPad(dequantScaleWDkvKrLocal_, dequantScaleWDkvkrGm_, dequantCopyParams, dequantPadParams); + } + + // quantScaleCkv + if constexpr ((std::is_same::value) && !isPertile) { + if constexpr (std::is_same::value) { + DataCopyExtParams quantCopyParams{1, sizeof(float), 0, 0, 0}; + DataCopyPadExtParams quantPadParams{false, 0, 0, 0}; + DataCopyPad(quantScaleCkvLocal_, quantScaleCkvGm_, quantCopyParams, quantPadParams); + } else { // per_channel量化场景走else分支 + DataCopy(quantScaleCkvLocal_, quantScaleCkvGm_, baseParams_->headSizeCkv); + } + } + + // quantScaleCkr + if constexpr (std::is_same::value) { + DataCopyPadExtParams quantPadParams{false, 0, 0, 0}; + DataCopyExtParams quantCopyParams{1, static_cast(baseParams_->dimHeadRope * sizeof(float)), 0, 0, 0}; + DataCopyPad(quantScaleCkrLocal_, quantScaleCkrGm_, quantCopyParams, quantPadParams); + } +} + + +/** + * @brief RmsNormCq流程,融合了dynamicquant + 内部所需空间约为 curVecToken(128) * 8*4 + 8*4 + (4*vectorRow_*baseParams_->headSizeCq + 8)*4 = 28.0625K + */ +template +__aicore__ inline void MlaPrologVecS1CubS2::RmsNormCq(int64_t tokenIndex, int64_t rmsNormCqOffset, + int64_t rmsNormCqResOffset, int64_t curVecToken, + int64_t curBlockTokenOffset) +{ + if (curVectorBlockNum_ <= blockIdx_) { + return; + } + uint64_t dequantScaleXSize = 1; + uint64_t dequantScaleCqElementNum = dequantScaleCqSize_ / sizeof(dequantScaleType); + int64_t stepTokenIndex = tokenIndex; + uint64_t dequantScaleXElementNum = Align(dequantScaleXSize, BYTE_BLOCK) / sizeof(dequantScaleType); + LocalTensor outputLocal = shareBuffer_.Get(); + LocalTensor dequantScaleQcQr = + outputLocal[baseParams_->headSizeCq].template ReinterpretCast(); + LocalTensor dequantScaleXLocal = + dequantScaleQcQr[curVecToken * dequantScaleCqElementNum].template ReinterpretCast(); + LocalTensor shareTmpUb = dequantScaleXLocal[dequantScaleXElementNum].template ReinterpretCast(); + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVecToken; curVecTokenIdx += 1) { + // MatmulCq ──> RmsNorm(Cq) ──> MatmulQcQr + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); // wait for vector operations to finish + + // dequantScaleXGm_ [BS , 1] 每个每个token对应一个系数,此处扩展为一个DataBlock + if constexpr (std::is_same::value) { + DataCopyPad(dequantScaleXLocal, dequantScaleXGm_[tokenIndex], {1, sizeof(float), 0, 0}, {false, 0, 0, 0}); + } + + RmsNormParam rmsNormParams = { + baseParams_->reciprocalCq, // reciprocal + baseParams_->epsilonCq, // epsilon + (uint32_t)vectorRow_, // row + baseParams_->headSizeCq, // col + baseParams_->qcQrScale, // scale + baseParams_->isQcQrScaleEnable, // isScaleEnable + }; + uint64_t scaleOffset = curVecTokenIdx * dequantScaleCqElementNum; + if constexpr (std::is_same::value) { + RmsNormNormal( + outputLocal, mmCqResGm_[rmsNormCqOffset], rmsnormGammaCqLocal_, dequantScaleWDqLocal_, + dequantScaleXLocal, shareTmpUb, rmsNormParams); + } else { + RmsNormDynamicQuant(outputLocal, dequantScaleQcQr[scaleOffset], + mmCqResGm_[rmsNormCqOffset], rmsnormGammaCqLocal_, + smoothScaleCqLocal_, dequantScaleWDqLocal_, dequantScaleXLocal, + shareTmpUb, rmsNormParams, enableSmoothScalesCq_); + } + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + // RmsNorm(Cq)的结果拷进mmCqResGm_中,用于MatmulQcQr的A矩阵 + DataCopy(rmsNormCqResGm_[rmsNormCqResOffset], outputLocal, baseParams_->headSizeCq); + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + tokenIndex++; + rmsNormCqResOffset += static_cast(baseParams_->headSizeCq); + rmsNormCqOffset += static_cast(baseParams_->headSizeCq); + } + + Brcb(dequantTool_.dequantScaleCqLocal_[curBlockTokenOffset * FP32_BLOCK_ELEMENT_NUM], dequantScaleQcQr, curVecToken, + {1, 1}); + if constexpr (MLAPT::enableDequantOpt || MLAPT::enableGroupComputeOpt) { + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + DataCopy(dequantTool_.dequantScaleCqGm_[curBlockTokenOffset * FP32_BLOCK_ELEMENT_NUM], + dequantTool_.dequantScaleCqLocal_[curBlockTokenOffset * FP32_BLOCK_ELEMENT_NUM], + FP32_BLOCK_ELEMENT_NUM * curVecToken); + } + if (unlikely(baseParams_->queryNormFlag == 1U)) { + if constexpr (std::is_same::value) { + DataCopyPad(dequantScaleQNormGm_[stepTokenIndex], dequantScaleQcQr, + {static_cast(curVecToken), sizeof(dequantScaleQNormType), 0, 0}); + } + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::ComputeBlkScatterOffsets(GlobalTensor indexGm, + int64_t tokenIndex, int64_t rows, + CkvkrParams &rmsNormAndScatterCkvParams, + CkvkrParams &ropeAndScatterKrParams) +{ + bool spill = false; + int64_t rowsThisStep = 0; + int64_t nextPageId = 0; + int64_t batchTokenIndex = 0; + int64_t batchSeqSize = 0; + int64_t batchIndexOffset = 0; + + // Advance batch cursor until the token index falls in [prevPrefix, curPrefix) + // curPrefix is an exclusive upper bound for the current batch + if constexpr (MLAPT::actualSeqMode == ACTUAL_SEQ_MODE::EN_Q_LEN) { + while (actSeqState_.curBatch + 1 < static_cast(baseParams_->batchSize) && + tokenIndex >= actSeqState_.curPrefix) { + actSeqState_.prevPrefix = actSeqState_.curPrefix; + actSeqState_.prevIndexOffset = actSeqState_.curIndexOffset; + actSeqState_.curBatch += 1; + actSeqState_.curPrefix = actualSeqLenGm_(actSeqState_.curBatch); + actSeqState_.curIndexOffset += CeilDivT(actSeqState_.curPrefix - actSeqState_.prevPrefix, + static_cast(baseParams_->blockSize)); + } + batchTokenIndex = tokenIndex - actSeqState_.prevPrefix; + batchSeqSize = actSeqState_.curPrefix - actSeqState_.prevPrefix; + batchIndexOffset = actSeqState_.prevIndexOffset; + } else { + const int64_t batchIndex = tokenIndex / baseParams_->seq1Size; + batchSeqSize = baseParams_->seq1Size; + batchTokenIndex = tokenIndex % baseParams_->seq1Size; + batchIndexOffset = + batchIndex * CeilDivT(batchSeqSize, static_cast(baseParams_->blockSize)); // cacheIndex的offset + } + + int64_t tokenOffsetInPage = batchTokenIndex % baseParams_->blockSize; + + int64_t leftRowsInPage = baseParams_->blockSize - tokenOffsetInPage; + int64_t indexOffset = batchIndexOffset + batchTokenIndex / baseParams_->blockSize; + int64_t paBlkId = indexGm(indexOffset); // 取cacheIdx + + int64_t pageTokenOffset = paBlkId * baseParams_->blockSize; + if (leftRowsInPage < rows) { + rowsThisStep = rows - leftRowsInPage; + spill = true; + nextPageId = indexGm(indexOffset + 1); + } else { + rowsThisStep = rows; + spill = false; + nextPageId = -1; + } + + + MaterializeOffsetsWithHeadSize( + pageTokenOffset, tokenOffsetInPage, rowsThisStep, spill, nextPageId, baseParams_->dimHeadRope, + ropeAndScatterKrParams); + + // --- Materialize for RMSNorm/CKV --- + MaterializeOffsetsWithHeadSize( + pageTokenOffset, tokenOffsetInPage, rowsThisStep, spill, nextPageId, baseParams_->headSizeCkv, + rmsNormAndScatterCkvParams); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::RmsNormAndScatterCkv( + LocalTensor &dequantScaleXLocal, LocalTensor &shareTmpUb, + LocalTensor &cosLocalCkvKr, LocalTensor &sinLocalCkvKr, + CkvkrParams rmsNormAndScatterCkvParams) +{ + // MatmulCkvKr ──> RmsNorm(Ckv) ──> Scatter(Ckv) + uint32_t outputLocalSize = vectorRow_ * baseParams_->headSizeCkv * sizeof(kvCacheType); + LocalTensor outputLocal = shareTmpUb.ReinterpretCast(); + if constexpr (isPertile) { // pertile量化场景,按照concat的最长长度申请内存 + uint32_t tileNum = baseParams_->headSizeCkv / baseParams_->tileSize; + outputLocalSize = vectorRow_ * (baseParams_->headSizeCkv * sizeof(kvCacheType) + tileNum * sizeof(float)); + outputLocalSize = Align(outputLocalSize, static_cast(BYTE_BLOCK)); + } + + RmsNormParam rmsNormParams = { + baseParams_->reciprocalCkv, // reciprocal + baseParams_->epsilonCkv, // epsilon + (uint32_t)vectorRow_, // row + baseParams_->headSizeCkv, // col + baseParams_->kcScale, // scale + baseParams_->isKcScaleEnable, // isScaleEnable + }; + + LocalTensor rmsNormShareTmpUb = shareTmpUb[outputLocalSize].template ReinterpretCast(); + + if constexpr (std::is_same::value) { + // row = vectorRow_ = 1 col = baseParams_->headSizeCkv + LocalTensor inputLocal = rmsNormShareTmpUb.ReinterpretCast(); + LocalTensor sharedBuf = + inputLocal[vectorRow_ * baseParams_->headSizeCkv].template ReinterpretCast(); + RmsNormNormal( + inputLocal, mmCkvKrResGm_[rmsNormAndScatterCkvParams.offset], rmsnormGammaCkvLocal_, + dequantScaleWDkvKrLocal_, dequantScaleXLocal, sharedBuf, rmsNormParams); + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + float kNopeClipAlpha = kNopeClipAlphaGm_.GetValue(0); + + if constexpr (isPertile) { + PerTileQuantParams perTileQuantParams = { + static_cast(baseParams_->tileSize), // baseParams_->tileSize + static_cast(baseParams_->headSizeCkv / baseParams_->tileSize), // tileNum + kNopeClipAlpha, // alpha + static_cast(vectorRow_), // row + baseParams_->headSizeCkv // col + }; + QuantPerTile(outputLocal, inputLocal, sharedBuf, perTileQuantParams); + } else if constexpr (std::is_same::value) { + Rectangle rectangleParams{ + (uint32_t)vectorRow_, // row + (uint32_t)baseParams_->headSizeCkv, // col + (uint32_t)baseParams_->headSizeCkv // columnStride + }; + QuantPerChannel(outputLocal, inputLocal, quantScaleCkvLocal_, sharedBuf, rectangleParams); + } else { + Rectangle rectangleParams{ + (uint32_t)vectorRow_, // row + (uint32_t)baseParams_->headSizeCkv, // col + (uint32_t)baseParams_->headSizeCkv // columnStride + }; + QuantPerTensor(outputLocal, inputLocal, quantScaleCkvLocal_, sharedBuf, rectangleParams); + AscendC::PipeBarrier(); + } + } else { + RmsNormNormal( + outputLocal, mmCkvKrResGm_[rmsNormAndScatterCkvParams.offset], rmsnormGammaCkvLocal_, + dequantScaleWDkvKrLocal_, dequantScaleXLocal, rmsNormShareTmpUb, rmsNormParams); + } + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + // Scatter(Ckv) + // RmsNorm(Ckv) ──> Scatter(Ckv) ──> kv_cache_out + if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_NZ) || (MLAPT::cacheMode == CACHE_MODE::PA_BSND) || + (MLAPT::cacheMode == CACHE_MODE::ND)) { + int64_t paTokenIndex = 0; + if constexpr (MLAPT::cacheMode != CACHE_MODE::ND) { + paTokenIndex = cacheIndexGm_(rmsNormAndScatterCkvParams.tokenIndex); + } else { + paTokenIndex = rmsNormAndScatterCkvParams.tokenIndex; + } + ScatterCache( + kvCacheGm_, outputLocal, + ScatterCacheParams{baseParams_->blockSize, paTokenIndex, vectorRow_, baseParams_->headSizeCkv, + baseParams_->dtileSize}); + // 刷新量化scale + if (baseParams_->quantScaleRepoMode == 1U && isPertile) { + // BSND: + int64_t startColOffset = baseParams_->headSizeCkv; + if (baseParams_->ckvkrRepoMode == 1U) { + startColOffset += baseParams_->headSizeKr * sizeof(krCacheType); + } + int64_t startOffset = 0; + if constexpr ((MLAPT::cacheMode != CACHE_MODE::PA_NZ)) { + startOffset = startColOffset; + } + + LocalTensor quantScaleCkvInt8Tensor = + outputLocal[vectorRow_ * baseParams_->headSizeCkv].template ReinterpretCast(); + uint32_t tileNum = baseParams_->headSizeCkv / baseParams_->tileSize; + ScatterCacheUnAligned( + kvCacheGm_[startOffset], quantScaleCkvInt8Tensor, + ScatterCacheParams{baseParams_->blockSize, paTokenIndex, vectorRow_, + static_cast(sizeof(float) * tileNum), baseParams_->dtileSize}); + } + } else { + ScatterCacheMultiRows( + kvCacheGm_, outputLocal, + ScatterCacheParams{baseParams_->blockSize, rmsNormAndScatterCkvParams.cacheOffset, vectorRow_, + baseParams_->headSizeCkv, baseParams_->headSizeCkv, baseParams_->seq1Size, + rmsNormAndScatterCkvParams.tokenIndex}, + rmsNormAndScatterCkvParams.rowsInCurBatch, rmsNormAndScatterCkvParams.cacheOffset, + rmsNormAndScatterCkvParams.nextBatchOffset); + } + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::RopeAndScatterKr(LocalTensor &dequantScaleXLocal, + LocalTensor &shareTmpUb, + LocalTensor &cosLocalCkvKr, + LocalTensor &sinLocalCkvKr, + CkvkrParams ropeAndScatterKrParams) +{ + // MatmulCkvKr ──> Rope(Ckv) ──> Scatter(Kr) + int64_t stride = static_cast(baseParams_->headSizeCkv + baseParams_->headSizeKr); // 512 + 64 + LocalTensor outputKrLocal = shareTmpUb.ReinterpretCast(); + LocalTensor ropeShareTmpUb = outputKrLocal[baseParams_->dimHeadRope].template ReinterpretCast(); + + LocalTensor sinLocal; + LocalTensor cosLocal; + if constexpr (MLAPT::enableDequantOpt) { + cosLocal = cosLocalCkvKr[baseParams_->dimHeadRope * ropeAndScatterKrParams.curVecTokenIdx]; + sinLocal = sinLocalCkvKr[baseParams_->dimHeadRope * ropeAndScatterKrParams.curVecTokenIdx]; + } else { + cosLocal = cosLocal_[baseParams_->dimHeadRope * ropeAndScatterKrParams.curVecTokenIdx]; + sinLocal = sinLocal_[baseParams_->dimHeadRope * ropeAndScatterKrParams.curVecTokenIdx]; + } + Rectangle ropeParams{ + (uint32_t)vectorRow_, // row + (uint32_t)baseParams_->dimHeadRope, // col + (uint32_t)stride // stride + }; + if constexpr ((std::is_same::value) && std::is_same::value) { + LocalTensor sharedBuf = + ropeShareTmpUb.ReinterpretCast()[baseParams_->dimHeadRope * sizeof(ropeSinCosType)]; + // input为int32_t需在rope中做反量化, intput为float根据模板参数判断是否做反量化 + RotaryPosEmbPerTensor( + outputKrLocal, mmCkvKrResGm_[ropeAndScatterKrParams.offset], cosLocal, sinLocal, sharedBuf, ropeParams, + dequantScaleWDkvKrLocal_[baseParams_->headSizeCkv], dequantScaleXLocal); + } else if constexpr (std::is_same::value) { + LocalTensor sharedBuf = + ropeShareTmpUb.ReinterpretCast()[baseParams_->dimHeadRope * sizeof(ropeSinCosType)]; + LocalTensor inputLocal = ropeShareTmpUb.ReinterpretCast(); + RotaryPosEmbPerTensor::value>( + inputLocal, mmCkvKrResGm_[ropeAndScatterKrParams.offset], cosLocal, sinLocal, sharedBuf, ropeParams); + RopePostQuantPerChannel(outputKrLocal, inputLocal, quantScaleCkrLocal_, sharedBuf, + baseParams_->dimHeadRope * vectorRow_); + } else { + RotaryPosEmbPerTensor( + outputKrLocal, mmCkvKrResGm_[ropeAndScatterKrParams.offset], cosLocal, sinLocal, ropeShareTmpUb, + ropeParams); + } + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + // scatter(Kr) + // Rope(Kr) ──> Scatter(Kr) ──> kr_cache_out + int64_t paTokenIndex; + if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_NZ) || (MLAPT::cacheMode == CACHE_MODE::PA_BSND) || + (MLAPT::cacheMode == CACHE_MODE::ND)) { + if constexpr (MLAPT::cacheMode != CACHE_MODE::ND) { + paTokenIndex = cacheIndexGm_(ropeAndScatterKrParams.tokenIndex); + } else { + paTokenIndex = ropeAndScatterKrParams.tokenIndex; + } + if (baseParams_->ckvkrRepoMode == 1U && isPertile) { + int64_t startOffset; + if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_NZ)) { + constexpr uint8_t col0 = ALIGN_BLOCK_SIZE / sizeof(kvCacheType); + startOffset = baseParams_->blockSize * col0 * CeilDiv(baseParams_->headSizeCkv, col0); // 列方向的偏移 + } else { + startOffset = baseParams_->headSizeCkv; + } + LocalTensor outputKrInt8Tensor = outputKrLocal.template ReinterpretCast(); + ScatterCache( + kvCacheGm_[startOffset], outputKrInt8Tensor, + ScatterCacheParams{baseParams_->blockSize, paTokenIndex, vectorRow_, + static_cast(sizeof(krCacheType) * baseParams_->dimHeadRope), + baseParams_->dtileSize}); + } else { + ScatterCache( + krCacheGm_, outputKrLocal, + ScatterCacheParams{baseParams_->blockSize, paTokenIndex, vectorRow_, baseParams_->dimHeadRope, + baseParams_->dimHeadRope}); + } + } else { + ScatterCacheMultiRows( + krCacheGm_, outputKrLocal, + ScatterCacheParams{baseParams_->blockSize, ropeAndScatterKrParams.cacheOffset, vectorRow_, + baseParams_->dimHeadRope, baseParams_->dimHeadRope, baseParams_->seq1Size, + ropeAndScatterKrParams.tokenIndex}, + ropeAndScatterKrParams.rowsInCurBatch, ropeAndScatterKrParams.cacheOffset, + ropeAndScatterKrParams.nextBatchOffset); + } + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::RmsNormRopeScatterCkvKr(int64_t tokenIndex, int64_t rmsNormCkvOffset, + int64_t ropeKrOffset, int64_t curVecToken) +{ + if (blockIdx_ >= curVectorBlockNum_) { + return; + } + LocalTensor dequantScaleXLocal = shareBuffer_.Get(); + + LocalTensor cosLocalCkvKr = + dequantScaleXLocal[FP32_BLOCK_ELEMENT_NUM].template ReinterpretCast(); + LocalTensor sinLocalCkvKr = cosLocalCkvKr[curVecToken * baseParams_->dimHeadRope]; + LocalTensor shareTmpUb = + sinLocalCkvKr[curVecToken * baseParams_->dimHeadRope].template ReinterpretCast(); + if constexpr (MLAPT::enableDequantOpt) { + GatherSinCos(cosLocalCkvKr, sinLocalCkvKr, ropeCosGm_, ropeSinGm_, tokenIndex, + curVecToken, shareTmpUb, vectorRow_, baseParams_->dimHeadRope); + } + if constexpr (MLAPT::emptyMode == EMPTY_TENSOR_MODE::EMPTY_CACHE) { + return; + } + + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVecToken; curVecTokenIdx++) { + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + + if constexpr (std::is_same::value) { + DataCopyPad(dequantScaleXLocal, dequantScaleXGm_[tokenIndex], {1, sizeof(float), 0, 0}, {false, 0, 0, 0}); + } + + CkvkrParams ropeAndScatterKrParams{tokenIndex, ropeKrOffset, curVecTokenIdx, 0, 0, 0}; + + CkvkrParams rmsNormAndScatterCkvParams{tokenIndex, rmsNormCkvOffset, curVecTokenIdx, 0, 0, 0}; + + if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_BLK_BSND) || (MLAPT::cacheMode == CACHE_MODE::PA_BLK_NZ)) { + // --- Compute headSize-independent variables once --- + ComputeBlkScatterOffsets(cacheIndexGm_, tokenIndex, vectorRow_, rmsNormAndScatterCkvParams, + ropeAndScatterKrParams); + } + + RmsNormAndScatterCkv(dequantScaleXLocal, shareTmpUb, cosLocalCkvKr, sinLocalCkvKr, rmsNormAndScatterCkvParams); + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + + RopeAndScatterKr(dequantScaleXLocal, shareTmpUb, cosLocalCkvKr, sinLocalCkvKr, ropeAndScatterKrParams); + + tokenIndex += 1; + ropeKrOffset += static_cast(baseParams_->headSizeCkv + baseParams_->dimHeadRope); + rmsNormCkvOffset += static_cast(baseParams_->headSizeCkv + baseParams_->dimHeadRope); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::RopeQr(int64_t ropeQrOffset, int64_t ropeQrResOffset, + int64_t curVecToken, int64_t curBlockTokenOffset) +{ + if (blockIdx_ >= curVectorBlockNum_) { + return; + } + uint64_t stride = static_cast(baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope); + + + LocalTensor outputLocal; + LocalTensor channelDeqScaleLocal = shareBuffer_.Get(); + + if constexpr (std::is_same::value) { + uint64_t col = baseParams_->dimHeadRope; + uint64_t row = baseParams_->numHeadSize; + DataCopyExtParams copyParams{static_cast(row), static_cast(sizeof(float) * col), + static_cast(sizeof(float) * (stride - col)), 0, 0}; + DataCopyPadExtParams padParams{false, 0, 0, 0}; + DataCopyPad(channelDeqScaleLocal, deqScaleQcQrW_[baseParams_->dimHeadSizeQc], copyParams, + padParams); // 复用内存 + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + + outputLocal = channelDeqScaleLocal[col * row].template ReinterpretCast(); + } else { + outputLocal = shareBuffer_.Get(); + } + LocalTensor ropeShareTmpUb = outputLocal[baseParams_->headSizeQr].template ReinterpretCast(); + + // row, col, stride + Rectangle ropeParams{(uint32_t)baseParams_->numHeadSize, (uint32_t)baseParams_->dimHeadRope, (uint32_t)stride}; + + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVecToken; curVecTokenIdx++) { + // MatmulQcQr ──> Rope(Qr) ──> query_rope_out + if constexpr (std::is_same::value) { + RotaryPosEmbPerTensor( + outputLocal, mmQcQrResGm_[ropeQrOffset], cosLocal_[baseParams_->dimHeadRope * curVecTokenIdx], + sinLocal_[baseParams_->dimHeadRope * curVecTokenIdx], ropeShareTmpUb, ropeParams, channelDeqScaleLocal, + dequantTool_.dequantScaleCqLocal_[(curBlockTokenOffset + curVecTokenIdx) * FP32_BLOCK_ELEMENT_NUM]); + } else { + RotaryPosEmbPerTensor( + outputLocal, mmQcQrResGm_[ropeQrOffset], cosLocal_[baseParams_->dimHeadRope * curVecTokenIdx], + sinLocal_[baseParams_->dimHeadRope * curVecTokenIdx], ropeShareTmpUb, ropeParams); + } + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + + DataCopy(qrOutGm_[ropeQrResOffset], outputLocal, baseParams_->headSizeQr); + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + + ropeQrOffset += static_cast(baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope) * + static_cast(baseParams_->numHeadSize); + ropeQrResOffset += static_cast(baseParams_->headSizeQr); + } +} + +// 用于enableGroupComputeOpt场景 BS = 1 , G = 8 +template +__aicore__ inline void MlaPrologVecS1CubS2::RopeQrSplitNGroupCase(int64_t ropeQrOffset, int64_t ropeQrResOffset) +{ + if (blockIdx_ < QC_CORE_NUM * cvRatio_ || blockIdx_ >= (QC_CORE_NUM + QR_CORE_NUM) * cvRatio_) { + return; + } + + uint32_t col = baseParams_->dimHeadRope; + uint32_t row = baseParams_->numHeadSize / QC_CORE_NUM; + int64_t stride = col; + int64_t strideScale = static_cast(baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope); + int64_t deqScaleOffset = baseParams_->dimHeadSizeQc + row * + (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope) * + (blockIdx_ - QC_CORE_NUM * cvRatio_); + LocalTensor channelDeqScaleLocal = shareBuffer_.Get(); + DataCopyExtParams copyParams{static_cast(row), static_cast(sizeof(float) * col), + static_cast(sizeof(float) * (strideScale - col)), 0, 0}; + DataCopyPadExtParams padParams{false, 0, 0, 0}; + DataCopyPad(channelDeqScaleLocal, deqScaleQcQrW_[deqScaleOffset], copyParams, padParams); // 复用内存 + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + + LocalTensor outputLocal = + channelDeqScaleLocal[row * col].template ReinterpretCast(); + LocalTensor ropeShareTmpUb = outputLocal[baseParams_->headSizeQr].template ReinterpretCast(); + + Rectangle ropeParams{ + (uint32_t)col, // row + (uint32_t)col, // col + (uint32_t)stride // stride + }; + + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVectorBlockNum_; curVecTokenIdx++) { + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + // sharetmp共用,待V算完再执行MTE2搬运规避风险 + GatherSinCos(cosLocal_, sinLocal_, ropeCosGm_, ropeSinGm_, + curVecTokenIdx * baseParams_->dimHeadRope, 1, ropeShareTmpUb, + vectorRow_, baseParams_->dimHeadRope); + + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + + RotaryPosEmbPerTensor( + outputLocal, mmQcQrResGm_[ropeQrOffset], cosLocal_, sinLocal_, ropeShareTmpUb, ropeParams, + channelDeqScaleLocal, dequantTool_.dequantScaleCqLocal_); + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + DataCopy(qrOutGm_[ropeQrResOffset], outputLocal, col * row); + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + + ropeQrOffset += static_cast(baseParams_->dimHeadRope) * static_cast(baseParams_->numHeadSize); + ropeQrResOffset += static_cast(baseParams_->headSizeQr); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::RopeQrSplitN(const RopeQrSplitNParams &ropeQrSplitNParams) +{ + uint32_t colQr = baseParams_->dimHeadRope; + uint32_t ropeCnt = ropeQrSplitNParams.ropeCnt; + uint32_t deQuantScaleCqOffset = ropeQrSplitNParams.deQuantScaleCqOffset; + DataCopyParams outputRopeParams{ + static_cast(ropeCnt), static_cast(sizeof(ropeOutputType) * colQr / ALIGN_BLOCK_SIZE), 0, + static_cast(sizeof(ropeOutputType) * ropeQrSplitNParams.ropeDstStride / ALIGN_BLOCK_SIZE)}; + + Rectangle ropeParams{ + ropeCnt, // row + colQr, // col + (uint32_t)ropeQrSplitNParams.ropeStride // stride + }; + + GlobalTensor outputGmRope = qrOutGm_[ropeQrSplitNParams.ropeQrResOffset]; + GlobalTensor inputGmRope = mmQcQrResGm_[ropeQrSplitNParams.ropeQrOffset]; + + LocalTensor shareTmpUb = shareBuffer_.Get(); + LocalTensor outputLocalRope = shareTmpUb.ReinterpretCast(); + LocalTensor ropeShareTmpUb = outputLocalRope[colQr * ropeCnt].template ReinterpretCast(); + + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + + if constexpr (std::is_same::value) { + GlobalTensor deqScaleRope = deqScaleQcQrW_[ropeQrSplitNParams.ropeQrOffset]; + RotaryPosEmbPerHead( + outputLocalRope, inputGmRope[ropeQrSplitNParams.inputOffsetRope], + cosLocal_[ropeQrSplitNParams.sinCosOffset], sinLocal_[ropeQrSplitNParams.sinCosOffset], ropeShareTmpUb, + ropeParams, ropeQrSplitNParams.ropeStride, deqScaleRope[ropeQrSplitNParams.deqScaleOffset], + dequantTool_.dequantScaleCqLocal_[deQuantScaleCqOffset]); + } else { + RotaryPosEmbPerHead( + outputLocalRope, inputGmRope[ropeQrSplitNParams.inputOffsetRope], + cosLocal_[ropeQrSplitNParams.sinCosOffset], sinLocal_[ropeQrSplitNParams.sinCosOffset], ropeShareTmpUb, + ropeParams, ropeQrSplitNParams.ropeStride); + } + + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + + DataCopy(outputGmRope[ropeQrSplitNParams.outputOffsetRope], outputLocalRope, outputRopeParams); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::CastQcQrSplitN(const CastQcQrSplitNParams &castQcQrSplitN) +{ + uint32_t colQc = baseParams_->dimHeadSizeQc; + uint32_t row = mmQcQrParam_.m; + uint32_t colQcSingle = colQc / cvRatio_; + uint32_t count = colQcSingle * row; + + DataCopyParams inputCopyParams{ + static_cast(row), static_cast(sizeof(mmQcQrOutputType) * colQcSingle / ALIGN_BLOCK_SIZE), + static_cast(sizeof(mmQcQrOutputType) * castQcQrSplitN.srcStride / ALIGN_BLOCK_SIZE), 0}; + + DataCopyParams outputCopyParams{ + static_cast(row), static_cast(sizeof(mmQnInputType) * colQcSingle / ALIGN_BLOCK_SIZE), 0, + static_cast(sizeof(mmQnInputType) * castQcQrSplitN.dstStride / ALIGN_BLOCK_SIZE)}; + + + GlobalTensor outputGm = mmQcQrResDequantGm_[castQcQrSplitN.mmQnPreCastResOffset]; + GlobalTensor inputGm = mmQcQrResGm_[castQcQrSplitN.mmQnPreCastOffset]; + + LocalTensor shareTmpUb = shareBuffer_.Get(); + LocalTensor inputLocal = shareTmpUb.ReinterpretCast(); + LocalTensor outputLocal = inputLocal.template ReinterpretCast(); + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + AscendC::DataCopy(inputLocal, inputGm[castQcQrSplitN.inputOffset], inputCopyParams); + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + // cast + AscendC::Cast(outputLocal, inputLocal, RoundMode::CAST_RINT, count); + AscendC::SetFlag(EVENT_ID2); + // copy out + AscendC::WaitFlag(EVENT_ID2); + AscendC::DataCopy(outputGm[castQcQrSplitN.outputOffset], outputLocal, outputCopyParams); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::DequantQcQrSplitN(const DequantQcQrSplitNParams &dequantQcQrSplitN) +{ + uint32_t colQc = baseParams_->dimHeadSizeQc; + uint32_t row = mmQcQrParam_.m; + uint32_t colQcSingle = colQc / cvRatio_; + uint32_t count = colQcSingle * row; + + DataCopyParams inputCopyParams{ + static_cast(row), static_cast(sizeof(mmQcQrOutputType) * colQcSingle / ALIGN_BLOCK_SIZE), + static_cast(sizeof(mmQcQrOutputType) * dequantQcQrSplitN.srcStride / ALIGN_BLOCK_SIZE), 0}; + + DataCopyParams outputCopyParams{ + static_cast(row), static_cast(sizeof(mmQnInputType) * colQcSingle / ALIGN_BLOCK_SIZE), 0, + static_cast(sizeof(mmQnInputType) * dequantQcQrSplitN.dstStride / ALIGN_BLOCK_SIZE)}; + + + GlobalTensor inputGm = mmQcQrResGm_[dequantQcQrSplitN.mmQnPreDequantOffset]; + GlobalTensor scale1Gm = deqScaleQcQrW_[dequantQcQrSplitN.mmQnPreDequantOffset]; + GlobalTensor outputGm = mmQcQrResDequantGm_[dequantQcQrSplitN.mmQnPreDequantResOffset]; + + LocalTensor shareTmpUb = shareBuffer_.Get(); + LocalTensor scale2Local = dequantTool_.dequantScaleCqLocal_; + LocalTensor inputLocal = shareTmpUb.ReinterpretCast(); + // 可以和inputLocal共享内存地址,减少UB使用 + LocalTensor computeLocal = shareTmpUb.ReinterpretCast(); + LocalTensor scaleLocal = inputLocal[count + FP32_BLOCK_ELEMENT_NUM].template ReinterpretCast(); + // outputLocal比scaleLocal占用UB少,且不会同时使用,故可以复用UB内存 + LocalTensor outputLocal = scaleLocal.template ReinterpretCast(); + + Rectangle dequantParams{ + row, // row + colQcSingle, // col + colQcSingle // columnStride + }; + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + + AscendC::DataCopy(inputLocal, inputGm[dequantQcQrSplitN.inputOffset], inputCopyParams); + AscendC::DataCopy(scaleLocal, scale1Gm[dequantQcQrSplitN.inputOffset], colQc / cvRatio_); + AscendC::SetFlag(EVENT_ID1); + // cast + AscendC::WaitFlag(EVENT_ID1); + Dequant(computeLocal, inputLocal, scaleLocal, scale2Local, dequantParams); + AscendC::PipeBarrier(); + // cast + AscendC::Cast(outputLocal, computeLocal, RoundMode::CAST_RINT, count); + AscendC::SetFlag(EVENT_ID2); + // copy out + AscendC::WaitFlag(EVENT_ID2); + AscendC::DataCopy(outputGm[dequantQcQrSplitN.outputOffset], outputLocal, outputCopyParams); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::DequantAndRopeSplitNSyncMMQcQr(int64_t mmQnPreDequantOffset, + int64_t mmQnPreDequantResOffset, + int64_t ropeQrOffset, + int64_t ropeQrResOffset) +{ + if (baseParams_->mm3BlockNum <= cubeBlockIdx_) { + return; + } + // mmQcQr一个C核算stepBatchSize * singleN,每两个V核做对应C核输出的Qc部分的dequant + // singleN一定整除(dimHeadSizeQc + dimHeadSizeQc),保证dequant能找到dimHeadSizeQc部分的起始位置 + uint32_t colQr = baseParams_->dimHeadRope; + uint32_t colQc = baseParams_->dimHeadSizeQc; + uint32_t colCube = mmQcQrParam_.baseN; + uint32_t subBlockIdx_ = blockIdx_ % cvRatio_; + uint32_t oriCol = mmQcQrParam_.n; + uint32_t colOffsetCube = 0; + + // DequantSplitN参数 + uint32_t srcStride = baseParams_->headSizeQr + baseParams_->headSizeQc - baseParams_->dimHeadSizeQc / cvRatio_; + uint32_t dstStride = baseParams_->headSizeQc - baseParams_->dimHeadSizeQc / cvRatio_; + uint32_t colQcSingle = colQc / cvRatio_; + uint32_t colOffsetVec = 0; + uint32_t inputOffset = subBlockIdx_ * colQcSingle; + uint32_t outputOffset = inputOffset; + + // RopeQrSplitN参数 + uint32_t ropeDstStride = baseParams_->headSizeQr - colQr; + // CV1:2和1:1,M轴方向切成2块处理 + uint32_t ropeCnt = (mmQcQrParam_.m + subBlockIdx_) / cvRatio_; + uint32_t ropeCntDown = mmQcQrParam_.m / 2; + int64_t ropeStride = static_cast(colQr + colQc) * static_cast(baseParams_->numHeadSize); + uint32_t outputOffsetRope = ropeCntDown * subBlockIdx_ * baseParams_->headSizeQr; + uint32_t inputOffsetRope = ropeCntDown * subBlockIdx_ * ropeStride; + uint32_t colOffsetRope = 0; + uint32_t deqScaleOffset = 0; + uint32_t deQuantScaleCqOffset = ropeCntDown * subBlockIdx_ * FP32_BLOCK_ELEMENT_NUM; + // cube一次处理row*colCube,对应的两个vec一次处理row*colQc,两vec之间切colQc + // 等cube生产足够数据了以后,vec开始消费 + uint32_t dequantLoopCount = 0; + uint32_t totalDequantLoops = CeilDiv(oriCol, (colQr + colQc)); + bool needSparseSync = totalDequantLoops > MAX_SYNC_FLAG_COUNT; + while (colOffsetCube < oriCol) { // 循环CeilDiv(oriCol, colCube)次 + colOffsetCube += colCube; + if (colOffsetCube > oriCol) { // 当oriCol不被colCube整除时,mm最后一个base块需要刷新col end + colOffsetCube = oriCol; + } + CrossCoreWaitFlag(FINISH_MM_QCQR_SPLIT_N); + // DequantSplitN + while (colOffsetVec + colQc <= colOffsetCube) { // 循环singleNumHeadSize次 + if constexpr (std::is_same::value) { + DequantQcQrSplitN(DequantQcQrSplitNParams{mmQnPreDequantOffset, mmQnPreDequantResOffset, inputOffset, + outputOffset, srcStride, dstStride}); + } + if (!needSparseSync || dequantLoopCount % 2 == 0 || dequantLoopCount == totalDequantLoops - 1) { + CrossCoreSetFlag(FINISH_VEC_DEQUANT_QC_SPLIT_N); + } + dequantLoopCount++; + outputOffset += colQc; + inputOffset += (colQr + colQc); + colOffsetVec += (colQr + colQc); + } + // RopeQrSplitN + while ((colOffsetRope + colQc + colQr) <= colOffsetCube) { + // cv1:1时,为了防止UB内存溢出,每次处理一半的数量 + if (cvRatio_ == 1) { + ropeCnt = ropeCntDown; + } + RopeQrSplitN(RopeQrSplitNParams{ropeQrOffset, ropeQrResOffset, inputOffsetRope, deqScaleOffset, + outputOffsetRope, ropeStride, ropeDstStride, deQuantScaleCqOffset, 0, + ropeCnt}); + // cv1:1时,还需处理第二次,第二次在第一次的基础上计算偏移等 + if (cvRatio_ == 1) { + RopeQrSplitN(RopeQrSplitNParams{ + ropeQrOffset, ropeQrResOffset, static_cast(inputOffsetRope + ropeStride * ropeCntDown), + deqScaleOffset, static_cast(outputOffsetRope + baseParams_->headSizeQr * ropeCntDown), + ropeStride, ropeDstStride, ropeCntDown * FP32_BLOCK_ELEMENT_NUM, + ropeCntDown * baseParams_->dimHeadRope, (mmQcQrParam_.m + 1) / 2}); + } + + outputOffsetRope += colQr; + deqScaleOffset += (colQr + colQc); + inputOffsetRope += (colQr + colQc); + colOffsetRope += (colQr + colQc); + } + } +} + +// 用于算力切分dequant切N场景 +template +__aicore__ inline void MlaPrologVecS1CubS2::DequantQcSplitNGroupCase(int64_t mmQnPreDequantOffset, + int64_t mmQnPreDequantResOffset, + int64_t qcQrScaleOffset) +{ + if (blockIdx_ >= cvRatio_ * QC_CORE_NUM) { + return; + } + uint32_t subBlockIdx_ = blockIdx_ % cvRatio_; + uint32_t curCol = (baseParams_->headSizeQc) / (cvRatio_ * QC_CORE_NUM); + uint32_t oriCol = (baseParams_->headSizeQc) / QC_CORE_NUM; + uint32_t dstStride = baseParams_->headSizeQc - curCol; + uint32_t srcStride = baseParams_->headSizeQc - curCol; + LocalTensor shareTmpUb = shareBuffer_.Get(); + Rectangle rectangleParams{ + (uint32_t)mmQcQrParam_.m, // row + (uint32_t)curCol, // col + (uint32_t)baseParams_->headSizeQc // columnStride + }; + DequantSplitNQc(mmQcQrResDequantGm_[mmQnPreDequantResOffset], mmQcQrResGm_[mmQnPreDequantOffset], + deqScaleQcQrW_[qcQrScaleOffset], dequantTool_.dequantScaleCqLocal_, shareTmpUb, rectangleParams, + oriCol, dstStride, subBlockIdx_); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::DequantQc(int64_t mmQnPreDequantOffset, + int64_t mmQnPreDequantResOffset, int64_t curVecToken, + int64_t curBlockTokenOffset) +{ + if (curVectorBlockNum_ <= blockIdx_) { + return; + } + + Rectangle rectangleParams{ + static_cast(baseParams_->stepNumHeadDequant), // row + static_cast(baseParams_->dimHeadSizeQc), // col + static_cast(baseParams_->dimHeadRope + baseParams_->dimHeadSizeQc) // columnStride + }; + + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVecToken; curVecTokenIdx++) { + DequantPerTokenQc( + mmQcQrResDequantGm_[mmQnPreDequantResOffset], mmQcQrResGm_[mmQnPreDequantOffset], deqScaleQcQrW_, + dequantTool_.dequantScaleCqLocal_[(curBlockTokenOffset + curVecTokenIdx) * FP32_BLOCK_ELEMENT_NUM], + shareBuffer_.Get(), rectangleParams, baseParams_->numHeadSize); + mmQnPreDequantOffset += baseParams_->headSizeQr + baseParams_->headSizeQc; + mmQnPreDequantResOffset += baseParams_->headSizeQc; + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::CastQc(int64_t mmQnPreCastOffset, int64_t mmQnPreCastResOffset, + int64_t curVecToken) +{ + if (curVectorBlockNum_ <= blockIdx_) { + return; + } + + Rectangle rectangleCastParams{ + static_cast(baseParams_->stepNumHeadDequant), // row + static_cast(baseParams_->dimHeadSizeQc), // col + static_cast(baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope) // columnStride + }; + + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVecToken; curVecTokenIdx++) { + LocalTensor shareTmpUb = shareBuffer_.Get(); + CastPerTokenQc(mmQcQrResDequantGm_[mmQnPreCastResOffset], mmQcQrResGm_[mmQnPreCastOffset], shareTmpUb, + rectangleCastParams, baseParams_->numHeadSize); + + mmQnPreCastOffset += baseParams_->headSizeQr + baseParams_->headSizeQc; + mmQnPreCastResOffset += baseParams_->headSizeQc; + } +} + +template +__aicore__ inline void +MlaPrologVecS1CubS2::DynamicQuantQnAndMulQrSyncMMQn(int64_t batchOffset, int64_t curStepBatchSize, + int64_t numHeadOffset, int64_t mmQnLoops) +{ + // 如果curStepBatchSize是偶数,则两个核平分;如果curStepBatchSize是奇数,则奇数核比偶数核多分一个 + // >> 1 是将curStepBatchSize分到每个vec核上; + int64_t curStepBatchSizeVec = ((blockIdx_ % cvRatio_) + curStepBatchSize) / cvRatio_; + if (blockIdx_ >= baseParams_->mm4BlockNum * cvRatio_) { + return; + } + // 等待前面的Qr部分完成 + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + + constexpr uint32_t DYNAMIC_QUANT_OUTPUT_READY = EVENT_ID3; + constexpr uint32_t MUL_QR_INPUT_COPY_READY = EVENT_ID3; + constexpr uint32_t DYNAMIC_QUANT_INPUT_READY = EVENT_ID0; + + int64_t blockBatchOffset = (blockIdx_ % cvRatio_) * (curStepBatchSize / cvRatio_); + int64_t totalSizeCkv = + static_cast(baseParams_->headSizeCkv) * static_cast(baseParams_->numHeadSize); + // 由于两个vec核分curStepBatchSize,各处理curStepBatchSize/2,blockIdx_ & 1 表示是否为第二个vec核 + int64_t dynamicQuantQueryOffset = + blockBatchOffset * totalSizeCkv + numHeadOffset * static_cast(baseParams_->headSizeCkv); + int64_t dynamicQuantQueryResOffset = batchOffset * totalSizeCkv + blockBatchOffset * totalSizeCkv + + numHeadOffset * static_cast(baseParams_->headSizeCkv); + int64_t scaleQueryNopeOffset = batchOffset * static_cast(baseParams_->numHeadSize) + + blockBatchOffset * static_cast(baseParams_->numHeadSize) + numHeadOffset; + int64_t queryOutStride = totalSizeCkv; + int64_t qrOutputStride = + static_cast(baseParams_->dimHeadRope) * static_cast(baseParams_->numHeadSize); + int64_t qrPostProcessResOffset = blockBatchOffset * static_cast(baseParams_->headSizeQr) + + numHeadOffset * static_cast(baseParams_->dimHeadRope) + + batchOffset * static_cast(baseParams_->headSizeQr); + + + LocalTensor shareTmpUb = shareBuffer_.Get(); + + float quantScaleCkv = quantScaleCkvGm_.GetValue(0); + + // Dynamic Quant + AscendC::SetFlag(DYNAMIC_QUANT_OUTPUT_READY); + AscendC::SetFlag(DYNAMIC_QUANT_INPUT_READY); + + // Rope Post Process + AscendC::SetFlag(MUL_QR_INPUT_COPY_READY); + // per-head循环 + for (int64_t loopIdx = 0; loopIdx < mmQnLoops; loopIdx++) { + CrossCoreWaitFlag(FINISH_MM_QN_SPLIT_N); + DynamicQuantQnWithMulQr( + dequantScaleQNopeGm_[scaleQueryNopeOffset], queryOutGm_[dynamicQuantQueryResOffset], + qrOutGm_[qrPostProcessResOffset], mmQnResGm_[dynamicQuantQueryOffset], shareTmpUb, curStepBatchSizeVec, + baseParams_->headSizeCkv, baseParams_->numHeadSize, queryOutStride, + // Rope Post Process + qrOutGm_[qrPostProcessResOffset], quantScaleCkv, baseParams_->dimHeadRope, qrOutputStride, cvRatio_); + + scaleQueryNopeOffset += 1; + dynamicQuantQueryOffset += static_cast(baseParams_->headSizeCkv); + qrPostProcessResOffset += static_cast(baseParams_->dimHeadRope); + dynamicQuantQueryResOffset += static_cast(baseParams_->headSizeCkv); + } + // Rope Post Process + AscendC::WaitFlag(MUL_QR_INPUT_COPY_READY); + // Dynamic Quant + AscendC::WaitFlag(DYNAMIC_QUANT_INPUT_READY); + AscendC::WaitFlag(DYNAMIC_QUANT_OUTPUT_READY); +} + +} // namespace MlaProlog + +#endif // MLA_PROLOG_VEC_S1_CUB_S2_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/mla_prolog_comm.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/mla_prolog_comm.h new file mode 100644 index 0000000000000000000000000000000000000000..77b58fa71cde5c045100e058c028d3a7af9d2055 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/mla_prolog_comm.h @@ -0,0 +1,367 @@ +/** + * 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 mla_prolog_comm.h + * \brief + */ + +#ifndef MLA_PROLOG_COMM_H +#define MLA_PROLOG_COMM_H + +#include "kernel_tiling/kernel_tiling.h" +#include "kernel_operator.h" +#include "kernel_operator_list_tensor_intf.h" +#include "lib/matmul_intf.h" +#include "lib/matrix/matmul/tiling.h" + +using namespace AscendC; + +namespace MlaProlog { + +template +__aicore__ inline T CeilDivT(T dividend, T divisor) +{ + if (divisor == 0) { + return static_cast(0); + } + return (dividend + divisor - 1) / divisor; +} + +template +__aicore__ inline T Align(T value, T alignment) +{ + return (((alignment) == 0) ? 0 : (((value) + (alignment)-1) / (alignment) * (alignment))); +} + +enum class CACHE_MODE : std::uint8_t { + ND = static_cast(0), // BSND or TND + PA_BSND = static_cast(1), + PA_NZ = static_cast(2), + PA_BLK_BSND = static_cast(3), + PA_BLK_NZ = static_cast(4), + PA_BS = static_cast(5) +}; + +enum class SCENARIO : std::uint8_t { + RESERVED = static_cast(0), + NO_QUANT = static_cast(1), + QUANT = static_cast(2) +}; + +enum class QUANT_MODE : std::uint8_t { + NO_QUANT = static_cast(0), + PARTIAL_QUANT_KV_NO_QUANT = static_cast(1), + PARTIAL_QUANT_KV_QUANT_PER_CHANNEL = static_cast(2), + FULL_QUANT_KV_NO_QUANT = static_cast(3), + FULL_QUANT_KV_QUANT_PER_TENSOR = static_cast(4), + PARTIAL_QUANT_KV_QUANT_PERTILE = static_cast(5), + FULL_QUANT_KV_QUANT_PERTILE = static_cast(6) +}; + +enum class EMPTY_TENSOR_MODE : std::uint8_t { + NON_EMPTY = static_cast(0), + EMPTY_CACHE = static_cast(1), + EMPTY_QUERY = static_cast(2), +}; + +enum class ACTUAL_SEQ_MODE : std::uint8_t { + DISABLED = static_cast(0), + EN_Q_LEN = static_cast(1), +}; + +enum class SPLIT_M_MODE : std::uint8_t { + DISABLED = static_cast(0), + ENABLED = static_cast(1), +}; + +enum class ROPE_MODE : std::uint8_t { + INTERLEAVE_HALF = static_cast(0), + HALF = static_cast(1), +}; + +constexpr uint64_t BYTE_BLOCK = 32UL; +constexpr uint8_t ALIGN_BLOCK_SIZE = 32; // 32B对齐 +constexpr uint32_t BLOCK_CUBE_SIZE = 16; // L1上m轴16对齐 +constexpr uint32_t REPEAT_STRIDE_UP_BOUND = 256; // repeat stride 不能超过256 +constexpr uint32_t REPEAT_BLOCK_BYTE = 256; +constexpr uint32_t FP16_BLOCK_ELEMENT_NUM = ALIGN_BLOCK_SIZE / sizeof(half); +constexpr uint32_t FP32_BLOCK_ELEMENT_NUM = ALIGN_BLOCK_SIZE / sizeof(float); +constexpr uint32_t FP32_REPEAT_ELEMENT_NUM = REPEAT_BLOCK_BYTE / sizeof(float); +constexpr uint32_t MAX_UB_SIZE = 192 * 1024; // 最大的UB大小 +constexpr uint32_t DIM_HEAD_SIZE_QCQR = 192; // 算力分组方案D + Dr = 192 +constexpr uint32_t QR_CORE_NUM = 4; // 算力分组方案QR占用4核 +constexpr uint32_t QC_CORE_NUM = 8; // 算力分组方案QC占用8核 +constexpr uint32_t BF16_AFULLLOAD_MAX_MSIZE = 32; // 计算mmQcQr时,bf16类型的A矩阵在msize小于等于32可以全载L1 +constexpr uint32_t INT8_AFULLLOAD_MAX_MSIZE = 64; // 计算mmQcQr时,int8类型的A矩阵在msize小于等于64可以全载L1 +constexpr uint32_t ONE_BYTE_TYPE_SIZE = 1; // 数据类型int8_t大小为1字节 +constexpr uint32_t K_STEP_SIZE_32 = 32; // for move left or right +constexpr uint32_t SHIFTS_UNIT = 4; +constexpr uint32_t UNIT_SIZE = 512; +constexpr uint32_t ROUND_UP_UNIT = 15; // for round up +constexpr uint32_t MAX_SYNC_FLAG_COUNT = 15; // 同一个flagId的计数器最多设置15次 + +constexpr int SYNC_MODE_ALL_VEC = 0x0; +constexpr int SYNC_MODE_CUBE_VEC = 0x2; +constexpr int SYNC_MODE_ALL_CUBE = 0x0; + +constexpr int FINISH_MM_QR = 0x8; // 算力分组场景 +constexpr int FINISH_MM_CQ = 0x6; +constexpr int FINISH_MM_CKVKR = 0x6; +constexpr int FINISH_MM_QCQR = 0x6; +constexpr int FINISH_MM_QC = 0x6; // 算力分组场景 +constexpr int FINISH_MM_ALL = 0x7; + +constexpr int FINISH_VEC_DEQUANT_QC = 0x6; +constexpr int FINISH_VEC_RMSNORM_CQ = 0x6; +constexpr int FINISH_VEC_CKVKR = 0x9; +constexpr int FINISH_VEC_ALL = 0x7; + +constexpr int FINISH_MM_QCQR_SPLIT_N = 0X6; +constexpr int FINISH_VEC_DEQUANT_QC_SPLIT_N = 0X7; +constexpr int FINISH_MM_QN_SPLIT_N = 0X8; + +#ifdef ENABLE_DUMP_DATA +#define DO_DUMP_DATA(srcTensor, id, len) AscendC::DumpTensor(srcTensor, id, len) +#else +#define DO_DUMP_DATA(srcTensor, id, len) +#endif + +class NoneType {}; + +// fix <> m +#define L0C_EVENT0 EVENT_ID3 +#define L0C_EVENT1 EVENT_ID4 + +// m <> mte1 +#define L0A_EVENT0 EVENT_ID3 +#define L0A_EVENT1 EVENT_ID4 +#define L0B_EVENT0 EVENT_ID5 +#define L0B_EVENT1 EVENT_ID6 + +// mte2 <> mte1 +#define SCALE_EVENT EVENT_ID3 +#define A_EVENT0 EVENT_ID4 +#define A_EVENT1 EVENT_ID5 +#define B_EVENT0 EVENT_ID6 +#define B_EVENT1 EVENT_ID7 + +constexpr uint32_t L1_B_SIZE = 128 * 1024; // 512 / 4 +constexpr uint32_t L1_A_SIZE = 128 * 1024; // 512 / 4 +constexpr uint32_t L0A_PP_SIZE = 32 * 1024; +constexpr uint32_t L0B_PP_SIZE = 32 * 1024; +constexpr uint32_t L0C_PP_SIZE = 64 * 1024; + + +/* + 非量化 半量化(kv非量化) 半量化(kv量化) int8全量化(kv非量化) int8全量化(kv量化) 半量化(kv per-tile量化) int8全量化(kv per-tile量化) + cacheMode PA_BSND/PA_BLK_BSND PA_BSND/PA_BLK_BSND PA_BSND/PA_BLK_BSND PA_BSND/PA_BLK_BSND PA_BSND/PA_BLK_BSND PA_BSND/BSND/TND PA_BSND/BSND/TND + /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ + /BSND/TND /BSND/TND /BSND/TND /BSND/TND /BSND/TND + enableDequantOpt false true/false true/false true/false true/false true true + enableGroupDequantOpt false true/false true/false false false false false + quantMode 0 1 2 3 4 5 6 + tokenXType(复用mmInputType) bfloat16_t bfloat16_t bfloat16_t int8_t int8_t bfloat16_t int8_t + WdqType(复用mmInputType) bfloat16_t bfloat16_t bfloat16_t int8_t int8_t bfloat16_t int8_t + WuqqrType(复用mmQcQrInputType) bfloat16_t int8_t int8_t int8_t int8_t int8_t int8_t + WukType(复用mmQnInputType) bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + WdkvkrType(复用mmInputType) bfloat16_t bfloat16_t bfloat16_t int8_t int8_t bfloat16_t int8_t + rmsNormGammaType bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + gammaCkvType(复用rmsNormGammaType)bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + ropeSinCosType bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + cosType(复用ropeSinCosType) bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + cacheIndexType int64_t int64_t int64_t int64_t int64_t int64_t int64_t + kvCacheType bfloat16_t bfloat16_t int8_t bfloat16_t int8_t int8_t int8_t + krCacheType bfloat16_t bfloat16_t int8_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + deqScaleXType / / / float float / float + deqScaleWdqType / / / float float / float + deqScaleWuqqrType / float float float float float float + deqScaleWdkvkrType / / / float float / float + quantScaleCkvType / / float / float / / + quantScaleCkrType / / float / / / / + smoothScaleCqType / float float float float float float + queryOutputType bfloat16_t bfloat16_t int8_t bfloat16_t int8_t bfloat16_t bfloat16_t + ropeOutputType bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + dequantScaleQNopeType / / / / float / / + queryNormType(复用mmQcQrInputType)bfloat16_t int8_t int8_t int8_t int8_t int8_t int8_t + dequantScaleQNormType / float float float float float float + mmInputType bfloat16_t bfloat16_t bfloat16_t int8_t int8_t bfloat16_t int8_t + mmCqOutputType bfloat16_t bfloat16_t bfloat16_t int32_t int32_t bfloat16_t int32_t + mmCkvKrInputType(复用mmInputType) bfloat16_t bfloat16_t bfloat16_t int8_t int8_t bfloat16_t int8_t + mmCkvKrOutputType bfloat16_t bfloat16_t bfloat16_t int32_t int32_t bfloat16_t int32_t + mmQcQrInputType bfloat16_t int8_t int8_t int8_t int8_t int8_t int8_t + mmQcQrOutputType bfloat16_t bfloat16_t bfloat16_t int32_t int32_t bfloat16_t int32_t + mmQnInputType bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + mmQnOutputType bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + rmsNormComputType float float float float float float float + rmsNormCqOutputType bfloat16_t int8_t int8_t int8_t int8_t int8_t int8_t + rmsNormCkvOutputType bfloat16_t bfloat16_t int8_t bfloat16_t int8_t int8_t int8_t + ropeComputType float float float float float float float +*/ + +template +struct MLAPType { + using mmQcQrInputType = W_T; + using mmInputType = X_T; // tokenX的类型与weight的类型一致 + using mmQnInputType = bfloat16_t; // matmul计算Qn的输入类型 + using mmCqOutputType = typename std::conditional::value, int32_t, + bfloat16_t>::type; // matmul计算Cq的输出类型 + using mmQcQrOutputType = typename std::conditional::value, int32_t, + bfloat16_t>::type; // matmul计算QcQr的输出类型 + using mmQnOutputType = bfloat16_t; // matmul计算Qn的输出类型 + using mmCkvKrOutputType = typename std::conditional::value, int32_t, + bfloat16_t>::type; // matmul计算CkvKr的输出类型 + using rmsNormGammaType = bfloat16_t; // gamma的输入类型 + using rmsNormComputType = float; + using rmsNormCkvOutputType = C_T; + using rmsNormCqOutputType = W_T; + using ropeSinCosType = bfloat16_t; // sin cos的输入类型 + using ropeComputType = float; + using ropeOutputType = bfloat16_t; + using dequantScaleQNopeType = float; // dequantScaleQNope的类型 + using dequantScaleQNormType = float; // dequantScaleQNorm的类型 + using dequantScaleType = float; + using kvCacheType = C_T; // kvcache的类型 + using krCacheType = + typename std::conditional<((std::is_same::value && std::is_same::value) || + IS_PERTILE), + bfloat16_t, C_T>::type; // krcache的类型 + + static constexpr CACHE_MODE cacheMode = C_M; + static constexpr bool enableGroupComputeOpt = ENABLE_GROUP_COMPUTE_OPT; + static constexpr bool enableDequantOpt = ENABLE_DEQUANT_OPT; + static constexpr uint32_t cvRatio = CV_RATIO; // 默认C:V 1:2 + static constexpr EMPTY_TENSOR_MODE emptyMode = EMPTY_MODE; + static constexpr ACTUAL_SEQ_MODE actualSeqMode = SEQ_MODE; + static constexpr bool isPertile = IS_PERTILE; +}; + +struct CastQcQrSplitNParams { + int64_t mmQnPreCastOffset; + int64_t mmQnPreCastResOffset; + uint32_t inputOffset; + uint32_t outputOffset; + uint32_t srcStride; + uint32_t dstStride; +}; + +struct DequantQcQrSplitNParams { + int64_t mmQnPreDequantOffset; + int64_t mmQnPreDequantResOffset; + uint32_t inputOffset; + uint32_t outputOffset; + uint32_t srcStride; + uint32_t dstStride; +}; + +struct RopeQrSplitNParams { + int64_t ropeQrOffset; + int64_t ropeQrResOffset; + uint32_t inputOffsetRope; + uint32_t deqScaleOffset; + uint32_t outputOffsetRope; + int64_t ropeStride; + uint32_t ropeDstStride; + uint32_t deQuantScaleCqOffset; + uint32_t sinCosOffset; + uint32_t ropeCnt; +}; + +struct CkvkrParams { + int64_t tokenIndex; + int64_t offset; + int64_t curVecTokenIdx; + int64_t rowsInCurBatch; + int64_t cacheOffset; + int64_t nextBatchOffset; +}; + +struct UsedBlockParams { + uint32_t blockStartIdx; + uint32_t blockEndIdx; +}; + +struct AivOffset { + int64_t curVecToken = 0; + int64_t curBlockTokenOffset = 0; + int64_t rmsNormCqOffset = 0; + int64_t rmsNormCqResOffset = 0; + int64_t rmsNormCkvOffset = 0; + int64_t ropeKrOffset = 0; + int64_t mmQnPreDequantOffset = 0; + int64_t mmQnPreDequantResOffset = 0; + int64_t ropeQrOffset = 0; + int64_t ropeQrResOffset = 0; + int64_t ropeQrSplitNOffset = 0; + int64_t ropeQrResSplitNOffset = 0; + int64_t qcScaleOffsetSplitN = 0; +}; + +struct AicOffset { + int64_t weightDqOffset = 0; + int64_t dequantScaleWDqOffset = 0; + int64_t cqResOffset = 0; + int64_t rmsNormCqResOffset = 0; + int64_t dequantScaleWDkvKrOffset = 0; + int64_t weightDkvKrOffset = 0; + int64_t ckvKrResOffset = 0; + int64_t weightUqQrOffset = 0; + int64_t weightUqOffset = 0; + int64_t weightQrOffset = 0; + int64_t qcQrResOffset = 0; + int64_t dequantScaleCqOffset = 0; + int64_t qCResOffset = 0; + int64_t qRResOffset = 0; + int64_t qcOffset = 0; + int64_t weightUkOffset = 0; + int64_t dequantScaleWuqqrOffset = 0; + int64_t qnResOffset = 0; +}; + +struct MMBufParams { + uint32_t aL1BufIter = 0; + uint32_t bL1BufIter = 0; + TBuffAddr aL1BufAddr; + TBuffAddr bL1BufAddr; + uint32_t aL0BufIter = 0; + uint32_t bL0BufIter = 0; + uint32_t cL0BufIter = 0; + TBuffAddr aL0BufAddr; + TBuffAddr bL0BufAddr; + TBuffAddr cL0BufAddr; +}; + +struct MMParams { + uint32_t m; + uint32_t n; + uint32_t k; + uint32_t orgM; + uint32_t orgN; + uint32_t orgKa; + uint32_t orgKb; + uint32_t orgKc; + uint32_t baseM; + uint32_t baseN; + uint32_t baseK; + uint32_t stepK; + uint32_t needSetOrgShape; + uint32_t kL1StepSize; +}; + +template +__aicore__ inline void WaitAllCore(uint16_t flagId) +{ + AscendC::CrossCoreSetFlag(flagId); + AscendC::CrossCoreWaitFlag(flagId); +} +} +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/mla_prolog_vector_comm.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/mla_prolog_vector_comm.h new file mode 100644 index 0000000000000000000000000000000000000000..9f54394c7493ca2c5a471e2daceafd0ff12596b7 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/mla_prolog_vector_comm.h @@ -0,0 +1,486 @@ +/** + * 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 mla_prolog_comm.h + * \brief 存放各种vector的公共组件 + */ + +#ifndef MLA_PROLOG_VECTOR_COMM_H +#define MLA_PROLOG_VECTOR_COMM_H + + +#include "mla_prolog_comm.h" +namespace MlaProlog { + +struct PerTileQuantParams { + uint32_t tileSize; + uint32_t tileNum; + float alpha; + uint32_t row; + uint32_t col; +}; + +struct RmsNormParam { + float reciprocal; + float epsilon; + uint32_t row; + uint32_t col; + float scale; + uint16_t isScaleEnable; +}; + +struct Rectangle { + uint32_t row; + uint32_t col; + uint32_t stride; +}; + +/** + * @brief vec mul by row; dstUb[i, j] = src0Ub[j] * src1Ub[i, j], + * @param dstUb 输出tensor [row, columnStride] + * @param src0Ub 输入tensor [1, columnStride] + * @param src1Ub 输入tensor src1Ub:[row, col] + * @param rectangleParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + */ +__aicore__ inline void VecMulMat(LocalTensor dstUb, LocalTensor src0Ub, LocalTensor src1Ub, + const Rectangle &rectangleParams) +{ + uint32_t mask = FP32_REPEAT_ELEMENT_NUM; + uint32_t columnLoopCount = rectangleParams.col / mask; + uint32_t remainCount = rectangleParams.col % mask; + // 选择迭代较少的方式 + // dstRepStride为0~255, columnCount需要小于2048 + if (columnLoopCount < rectangleParams.row && + rectangleParams.stride < REPEAT_STRIDE_UP_BOUND * FP32_BLOCK_ELEMENT_NUM) { + BinaryRepeatParams repeatParams; + repeatParams.dstBlkStride = 1; + repeatParams.src0BlkStride = 1; + repeatParams.src1BlkStride = 1; + repeatParams.dstRepStride = rectangleParams.stride / FP32_BLOCK_ELEMENT_NUM; + repeatParams.src0RepStride = 0; + repeatParams.src1RepStride = rectangleParams.stride / FP32_BLOCK_ELEMENT_NUM; + uint32_t offset = 0; + for (int i = 0; i < columnLoopCount; i++) { + // 偏移 offset : i * mask + Mul(dstUb[offset], src0Ub[offset], src1Ub[offset], mask, rectangleParams.row, repeatParams); + offset += mask; + } + if (remainCount > 0) { + // 偏移 offset : columnLoopCount * mask + Mul(dstUb[offset], src0Ub[offset], src1Ub[offset], remainCount, rectangleParams.row, repeatParams); + } + } else { + uint32_t offset = 0; + for (int i = 0; i < rectangleParams.row; i++) { + Mul(dstUb[offset], src0Ub, src1Ub[offset], rectangleParams.col); + offset += rectangleParams.stride; + } + } +} + +/** + * @brief RowMuls muls by row, 每行的元素乘以相同的元素,该元素需要扩展到一个数据块; + * dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] * src1Ub[i, 0 : 7] + * @param dstUb 输出tensor [row, columnStride] + * @param src0Ub 输入tensor [row, columnStride] + * @param src1Ub 输入tensor [row, FP32_BLOCK_ELEMENT_NUM] + * @param rectangleParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + */ +template +__aicore__ inline void RowMuls(LocalTensor dstUb, LocalTensor src0Ub, LocalTensor src1Ub, + const Rectangle &rectangleParams) +{ + uint32_t repeatElementNum = FP32_REPEAT_ELEMENT_NUM; + uint32_t blockElementNum = FP32_BLOCK_ELEMENT_NUM; + + if constexpr (std::is_same::value) { + // 此限制由于每个repeat至多连续读取256B数据 + blockElementNum = FP32_BLOCK_ELEMENT_NUM * 2; // 32/4 * 2 = 16 + repeatElementNum = FP32_REPEAT_ELEMENT_NUM * 2; // 256/4 * 2 = 128 + } + + // 每次只能连续读取256B的数据进行计算,故每次只能处理256B/sizeof(dType)= + // 列方向分dLoop次,每次处理8列数据 + uint32_t dRemain = rectangleParams.col % repeatElementNum; + uint32_t dLoop = rectangleParams.col / repeatElementNum; + // REPEAT_STRIDE_UP_BOUND=256,此限制由于src0RepStride数据类型为uint8至多256个datablock间距 + if (rectangleParams.stride < REPEAT_STRIDE_UP_BOUND * blockElementNum) { + // dstBlkStrideIn src0BlkStrideIn src1BlkStrideIn dstRepStrideIn src0RepStrideIn src1RepStrideIn + BinaryRepeatParams repeatParams{1, + 1, + 0, + (uint8_t)(rectangleParams.stride / blockElementNum), + (uint8_t)(rectangleParams.stride / blockElementNum), + 1}; + + // 如果以列为repeat所处理的次数小于行处理次数,则以列方式处理。反之则以行进行repeat处理 + if (dLoop <= rectangleParams.row) { + uint32_t offset = 0; + for (uint32_t i = 0; i < dLoop; i++) { + Mul(dstUb[offset], src0Ub[offset], src1Ub, repeatElementNum, rectangleParams.row, repeatParams); + offset += repeatElementNum; + } + } else { + repeatParams.dstRepStride = 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + repeatParams.src0RepStride = 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + repeatParams.src1RepStride = 0; + for (uint32_t i = 0; i < rectangleParams.row; i++) { + Mul(dstUb[rectangleParams.stride * i], src0Ub[rectangleParams.stride * i], src1Ub[blockElementNum * i], + repeatElementNum, dLoop, repeatParams); + } + } + + // 最后一次完成[row, dRemain] * [row, blockElementNum] 只计算有效部分 + if (dRemain > 0) { + Mul(dstUb[repeatElementNum * dLoop], src0Ub[repeatElementNum * dLoop], src1Ub, dRemain, rectangleParams.row, + repeatParams); + } + } else { + // dstBlkStrideIn src0BlkStrideIn src1BlkStrideIn dstRepStrideIn src0RepStrideIn src1RepStrideIn + // 8 : 每个repeat为256B数据,正好8个datablock + BinaryRepeatParams repeatParams{1, 1, 0, 8, 8, 0}; + + // 每次计算一行,共计算dealRowCount行 + for (uint32_t i = 0; i < rectangleParams.row; i++) { + // 计算一行中的dLoop个repeat,每个repeat计算256/block_size个data_block + Mul(dstUb[rectangleParams.stride * i], src0Ub[rectangleParams.stride * i], src1Ub[blockElementNum * i], + repeatElementNum, dLoop, repeatParams); + // 计算一行中的尾块 + if (dRemain > 0) { + Mul(dstUb[rectangleParams.stride * i + repeatElementNum * dLoop], + src0Ub[rectangleParams.stride * i + repeatElementNum * dLoop], src1Ub[blockElementNum * i], dRemain, + 1, repeatParams); + } + } + } +} + +/** + * @brief RowMax max by row, 按行求最大值 + * @param dstUb 输出tensor [row, 1] + dstUb[i] = max(srcUb[i, :]) + * @param srcUb 输入tensor [row, columnStride] + * @param rectangleParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + */ +__aicore__ inline void RowMax(LocalTensor &dstUb, LocalTensor &srcUb, const Rectangle rectangleParams) +{ + uint32_t dtypeMask = FP32_REPEAT_ELEMENT_NUM; + uint32_t remain = rectangleParams.col % dtypeMask; + uint32_t blockCount = rectangleParams.col / dtypeMask; + + BinaryRepeatParams repeatParamsMax; + repeatParamsMax.dstBlkStride = 1; + repeatParamsMax.src0BlkStride = 1; + repeatParamsMax.src1BlkStride = 1; + repeatParamsMax.dstRepStride = rectangleParams.stride / FP32_BLOCK_ELEMENT_NUM; + repeatParamsMax.src0RepStride = rectangleParams.stride / FP32_BLOCK_ELEMENT_NUM; + repeatParamsMax.src1RepStride = rectangleParams.stride / FP32_BLOCK_ELEMENT_NUM; + if (blockCount > 0 && remain > 0) { + Max(srcUb, srcUb, srcUb[dtypeMask * blockCount], remain, rectangleParams.row, repeatParamsMax); + PipeBarrier(); + } + + for (uint32_t columnLoopCount = blockCount >> 1; columnLoopCount > 0; + columnLoopCount = blockCount >> 1) { // 2: 每次处理2个block + blockCount = (blockCount + 1) >> 1; // 2: 每次处理2个block + for (uint32_t j = 0; j < columnLoopCount; j++) { + Max(srcUb[dtypeMask * j], srcUb[dtypeMask * j], srcUb[dtypeMask * (j + blockCount)], dtypeMask, + rectangleParams.row, repeatParamsMax); + } + PipeBarrier(); + } + + WholeReduceMax(dstUb, srcUb, (rectangleParams.col < dtypeMask) ? rectangleParams.col : dtypeMask, + rectangleParams.row, 1, 1, rectangleParams.stride / FP32_BLOCK_ELEMENT_NUM, + ReduceOrder::ORDER_ONLY_VALUE); +} + +/** + * @brief Dequant 对[row * col]的tensor进行反量化。需要输入一个行向量和列向量,共同构成反量化的矩阵。 + outputLocal [i,j] = inputLocal[i,j] * scaleLocal[j] * scale2Local [i] + * @param outputLocal 输出tensor [row , col] + * @param inputLocal 输入tensor [row , col] + * @param scaleLocal [1,col] 量化系数;行向量 + * @param scale2Local [row,8] 量化系数;列向量,8为float扩充为32Bytes + * @param rectangleParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + */ +template +__aicore__ inline void Dequant(const LocalTensor &outputLocal, const LocalTensor &inputLocal, + const LocalTensor &scaleLocal, const LocalTensor &scale2Local, + const Rectangle &rectangleParams) +{ + uint64_t cnt = rectangleParams.col * rectangleParams.row; + Cast(outputLocal, inputLocal, RoundMode::CAST_RINT, cnt); + AscendC::PipeBarrier(); + RowMuls(outputLocal, outputLocal, scale2Local, rectangleParams); + AscendC::PipeBarrier(); + VecMulMat(outputLocal, scaleLocal, outputLocal, rectangleParams); +} + +/** + * @brief DynamicQuant 对row行进行dynamicquant, float ---> int8, 每一行出一个系数。 + * @param outputLocal 输出tensor [row , col],支持和inputLocal是同一块空间 + * @param scale 输出每行的反量化系数 [row] + * @param inputLocal 输入tensor [row , col] + * @param rowMax [row] 一行的最大值 + * @param rowMaxBrcb [row, 8] 一行的最大值,brcb扩充为8的倍数 + * @param shareTmpUb 临时buffer 内部需要的空间为 [row * col * sizeof(float)] + * @param row 待处理的行数 + * @param col 待处理的列数 + */ +__aicore__ inline void DynamicQuant(const LocalTensor &outputLocal, const LocalTensor &scale, + const LocalTensor &inputLocal, const LocalTensor &aMax, + const LocalTensor &rowMaxBrcb, const LocalTensor &shareTmpUb, + float alpha, uint64_t row, uint64_t col) +{ + int32_t aMaxSizeAlign = Align(static_cast(row), FP32_BLOCK_ELEMENT_NUM); + LocalTensor aMaxAlpha = shareTmpUb.ReinterpretCast(); + LocalTensor dupTensor = aMaxAlpha[aMaxSizeAlign]; + LocalTensor scaleReciprocal = dupTensor[aMaxSizeAlign]; + LocalTensor scaleReciprocalBrcb = scaleReciprocal[aMaxSizeAlign]; + + constexpr float maxInt8 = 127.0f; + Duplicate(dupTensor, 1.00f, row); + Muls(aMaxAlpha, aMax, alpha, row); + PipeBarrier(); + Muls(scale, aMaxAlpha, 1.00f / maxInt8, row); + PipeBarrier(); + Div(scaleReciprocal, dupTensor, scale, row); + PipeBarrier(); + Brcb(scaleReciprocalBrcb, scaleReciprocal, CeilDivT(row, 8UL), {1, 8}); + PipeBarrier(); + RowMuls(outputLocal, inputLocal, scaleReciprocalBrcb, Rectangle{(uint32_t)row, (uint32_t)col, (uint32_t)col}); + PipeBarrier(); +} + +// divs by row, 每行的元素除以相同的元素 +// dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] / src1Ub[i, 0 : 7] +// src0Ub:[dealRowCount, columnCount], src1Ub:[dealRowCount, FP32_BLOCK_ELEMENT_NUM] dstUb:[dealRowCount, +// columnCount] +__aicore__ inline void RowClips(LocalTensor &dstUb, const LocalTensor &src0Ub, + const LocalTensor &maxUb, const LocalTensor &minUb, uint32_t dealRowCount, + uint32_t columnCount, uint32_t actualColumnCount) +{ + uint32_t dtypeMask = FP32_REPEAT_ELEMENT_NUM; + uint32_t dLoop = actualColumnCount / dtypeMask; + uint32_t dRemain = actualColumnCount % dtypeMask; + + BinaryRepeatParams repeatParams; + repeatParams.dstBlkStride = 1; + repeatParams.src0BlkStride = 1; + repeatParams.src1BlkStride = 0; + repeatParams.dstRepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; + repeatParams.src0RepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; + repeatParams.src1RepStride = 1; + uint32_t offset = 0; + + for (uint32_t i = 0; i < dLoop; i++) { + Min(dstUb[offset], src0Ub[offset], maxUb, dtypeMask, dealRowCount, repeatParams); + PipeBarrier(); + Max(dstUb[offset], dstUb[offset], minUb, dtypeMask, dealRowCount, repeatParams); + offset += dtypeMask; + } + + if (dRemain == 0) { + return; + } + + Min(dstUb[dLoop * dtypeMask], src0Ub[dLoop * dtypeMask], maxUb, dRemain, dealRowCount, repeatParams); + PipeBarrier(); + Max(dstUb[dLoop * dtypeMask], dstUb[dLoop * dtypeMask], minUb, dRemain, dealRowCount, repeatParams); +} + +__aicore__ inline void PerTileClipWithAlpha(LocalTensor &dstClipUb, LocalTensor &aMax, + LocalTensor &aMaxBrcb, const LocalTensor &srcUb, + const LocalTensor &shareTmpUb, + const PerTileQuantParams &perTileQuantParams) +{ + constexpr uint32_t brcnNum = 8; // brcn一次性处理8个数据 + uint32_t srcSize = perTileQuantParams.row * perTileQuantParams.col; + uint32_t maxAlphaSize = perTileQuantParams.tileNum * perTileQuantParams.row * FP32_BLOCK_ELEMENT_NUM; + + LocalTensor absSrcUb = shareTmpUb.template ReinterpretCast(); + LocalTensor maxAlpha = absSrcUb[Align(srcSize, FP32_BLOCK_ELEMENT_NUM)]; + LocalTensor minAlpha = maxAlpha[Align(maxAlphaSize, FP32_BLOCK_ELEMENT_NUM)]; + + Abs(absSrcUb, srcUb, srcSize); + PipeBarrier(); + + Rectangle rectangleParams{ + static_cast(perTileQuantParams.tileNum * perTileQuantParams.row), + static_cast(perTileQuantParams.tileSize), + static_cast(perTileQuantParams.tileSize) // columnStride + }; + RowMax(aMax, absSrcUb, rectangleParams); + PipeBarrier(); + Brcb(aMaxBrcb, aMax, (CeilDivT((perTileQuantParams.tileNum * perTileQuantParams.row), brcnNum)), {1, brcnNum}); + PipeBarrier(); + + Muls(maxAlpha, aMaxBrcb, perTileQuantParams.alpha, maxAlphaSize); + Muls(minAlpha, aMaxBrcb, -perTileQuantParams.alpha, maxAlphaSize); + PipeBarrier(); + + RowClips(dstClipUb, srcUb, maxAlpha, minAlpha, perTileQuantParams.tileNum * perTileQuantParams.row, + perTileQuantParams.tileSize, perTileQuantParams.tileSize); + PipeBarrier(); +} + +/** + * @brief CastFP32ToINT8 将float类型cast为int8,路径为float--------->int32--------->half---------->int8 + CAST_RINT CAST_ROUND CAST_TRUNC + * @param outputLocal 输出tensor [cnt] + * @param inputLocal 输入tensor [cnt] + * @param shareTmpUb 临时buffer 内部需要的空间为 [cnt * 4] 4 : sizeof(int32) + * @param cnt tensor长度 + */ +template +__aicore__ inline void CastFP32ToINT8(const LocalTensor outLocal, const LocalTensor &inputLocal, + const LocalTensor &shareTmpUb, uint64_t cnt) +{ + LocalTensor tmpHalf = shareTmpUb.ReinterpretCast(); + LocalTensor int32 = shareTmpUb.ReinterpretCast(); + Cast(int32, inputLocal, RoundMode::CAST_RINT, cnt); + PipeBarrier(); + SetDeqScale(static_cast(1.0)); + PipeBarrier(); + Cast(tmpHalf, int32, RoundMode::CAST_ROUND, cnt); + PipeBarrier(); + Cast(outLocal, tmpHalf, RoundMode::CAST_TRUNC, cnt); +} + + +/** + * @brief QuantPerChannel 同时对row行进行FP32到int8的per-channel量化操作。一行中的每一列用不同的量化参数。 + outLocal[i, j] = inputLocal[i, j] * quantScaleLocal[j] + * @param outLocal 输出tensor [row , col] + * @param inputLocal 输入tensor [row , col] + * @param quantScaleLocal quant系数 [1 , col] + * @param shareTmpUb 临时buffer 内部需要的空间为 [row * col * 4],源自CastFP32ToINT8 + * @param rectangleParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + */ +template +__aicore__ inline void QuantPerChannel(const LocalTensor &outLocal, const LocalTensor &inputLocal, + const LocalTensor &quantScaleLocal, const LocalTensor &shareTmpUb, + const Rectangle &rectangleParams) +{ + VecMulMat(inputLocal, quantScaleLocal, inputLocal, rectangleParams); + AscendC::PipeBarrier(); + CastFP32ToINT8(outLocal, inputLocal, shareTmpUb, rectangleParams.row * rectangleParams.col); +} + +/** + * @brief QuantPerTensor 同时对row行进行FP32到int8的per-tensor量化操作。一行内共用同一个量化系数。 + outLocal[i , j] = inputLocal[i , j] * quantScaleLocal[i] + * @param outLocal 输出tensor [row , col] + * @param inputLocal 输入tensor [row , col] + * @param quantScaleLocal quant系数 [row , 8]; 8 : 32Bytes对齐 + * @param shareTmpUb 临时buffer 内部需要的空间为 [row * col * 4],源自CastFP32ToINT8 + * @param rectangleParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + */ +template +__aicore__ inline void QuantPerTensor(const LocalTensor &outLocal, const LocalTensor &inputLocal, + const LocalTensor &quantScaleLocal, const LocalTensor &shareTmpUb, + const Rectangle &rectangleParams) +{ + RowMuls(inputLocal, inputLocal, quantScaleLocal, rectangleParams); + AscendC::PipeBarrier(); + CastFP32ToINT8(outLocal, inputLocal, shareTmpUb, rectangleParams.row * rectangleParams.col); +} + +__aicore__ inline void QuantPerTile(const LocalTensor &outLocal, const LocalTensor &inputLocal, + const LocalTensor &shareTmpUb, + const PerTileQuantParams &perTileQuantParams) +{ + LocalTensor scale = + outLocal[perTileQuantParams.col * perTileQuantParams.row].template ReinterpretCast(); + + LocalTensor clipOut = inputLocal; + uint32_t aMaxSizeAlign = + Align(static_cast(perTileQuantParams.tileNum * perTileQuantParams.row), FP32_BLOCK_ELEMENT_NUM); + uint32_t aMaxBrcbSize = perTileQuantParams.tileNum * perTileQuantParams.row * FP32_BLOCK_ELEMENT_NUM; + LocalTensor aMax = shareTmpUb.template ReinterpretCast(); + LocalTensor aMaxBrcb = aMax[aMaxSizeAlign]; + LocalTensor sharedBuf = aMaxBrcb[aMaxBrcbSize].template ReinterpretCast(); + + PerTileClipWithAlpha(clipOut, aMax, aMaxBrcb, inputLocal, sharedBuf, perTileQuantParams); + + LocalTensor quantOut = clipOut; + DynamicQuant(quantOut, scale, clipOut, aMax, aMaxBrcb, sharedBuf, perTileQuantParams.alpha, + perTileQuantParams.tileNum * perTileQuantParams.row, perTileQuantParams.tileSize); + PipeBarrier(); + CastFP32ToINT8(outLocal, quantOut, sharedBuf, perTileQuantParams.col * perTileQuantParams.row); +} + +/** + * @brief DynamicQuant 同时对row行进行dynamicquant, float ---> int8, 每一行出一个系数。 + * @param outLocal 输出tensor [row , col],支持和inputLocal是同一块空间 + * @param inputLocal 输入tensor [row , col] + * @param scale 输出每行的反量化系数 [1 , row] + * @param maxInt8Tensor [1 , row] 元素均为int8的最大值127 + * @param shareTmpUb 临时buffer 内部需要的空间为 [(Align(row * col, 8) + Align(row , 8) * ALIGN_BLOCK_SIZE) * + * sizeof(float)] + * @param row 待处理的行数 + * @param col 待处理的列数 + */ +__aicore__ inline void DynamicQuant(const LocalTensor &outputLocal, const LocalTensor &scale, + const LocalTensor &inputLocal, const LocalTensor &maxInt8Tensor, + const LocalTensor &shareTmpUb, uint64_t row, uint64_t col) +{ + constexpr uint64_t brcnNum = 8; // brcb一次处理8个数据 + uint64_t computeSize = col * row; + LocalTensor inputCopy = shareTmpUb.ReinterpretCast(); + LocalTensor rowMaxBrcb = inputCopy[Align(computeSize, (uint64_t)ALIGN_BLOCK_SIZE)]; + // abs(x) + Abs(inputCopy, inputLocal, computeSize); + AscendC::PipeBarrier(); + Rectangle rectangleParams{ + (uint32_t)row, (uint32_t)col, + (uint32_t)col // columnStride + }; + // rowMax(abs(x)) + RowMax(inputCopy, inputCopy, rectangleParams); + AscendC::PipeBarrier(); + + // scaleOut = rowMax(abs(x)) / 127 + Div(scale, inputCopy, maxInt8Tensor, row); + AscendC::PipeBarrier(); + + // 1 / scaleOut = 127 / rowMax(abs(x)) + Div(inputCopy, maxInt8Tensor, inputCopy, row); + AscendC::PipeBarrier(); + + Brcb(rowMaxBrcb, inputCopy, static_cast(CeilDivT(row, brcnNum)), {1, brcnNum}); + AscendC::PipeBarrier(); + + // x * 1 / scaleOut + RowMuls(outputLocal, inputLocal, rowMaxBrcb, rectangleParams); +} + +} // namespace MlaProlog +#endif // MLA_PROLOG_VECTOR_COMM_H \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/rms_norm.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/rms_norm.h new file mode 100644 index 0000000000000000000000000000000000000000..1067317bd53916021d9955802f8d4bdff9dbd4f7 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/rms_norm.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 rms_norm.h + * \brief + */ + +#ifndef RMS_NORM_H +#define RMS_NORM_H + +#include "mla_prolog_comm.h" +namespace MlaProlog { +/** + * @brief RmsNorm 对一行进行rmsnorm + * @param outLocal 输出tensor [1 * cnt],支持和inputLocal是同一块空间 + * @param inputLocal 输入tensor [1 * cnt] + * @param gammaLocal 系数gamma [1 * cnt] + * @param shareTmpUb 临时buffer 内部需要的空间为 [cnt * sizeof(float) + ALIGN_BLOCK_SIZE] + * @param rmsNormParams rms所需系数,包括 + reciprocal rmsnorm系数reciprocal + epsilon rmsnorm系数epsilon + row 处理的行数;预留参数,当前仅支持单个batch的处理,row为1,对应S1 + col 列数,对应H + */ +template +__aicore__ inline void RmsNorm(const LocalTensor &outLocal, const LocalTensor &inputLocal, + const LocalTensor &gammaLocal, const LocalTensor &shareTmpUb, + const RmsNormParam &rmsNormParams) +{ + uint64_t cnt = rmsNormParams.row * rmsNormParams.col; + LocalTensor xSquareLocal = shareTmpUb.ReinterpretCast(); + LocalTensor xSumLocal = xSquareLocal[cnt]; + Mul(xSquareLocal, inputLocal, inputLocal, cnt); + AscendC::PipeBarrier(); + + // calcNum >> 6 : calcNum / 64(FP32_REPEAT_ELEMENT_NUM) + uint64_t repeatTimesAdd = static_cast(cnt) >> 6; + // dstBlkStride, src0BlkStride, src1BlkStride, dstRepStride, src0RepStride, src1RepStride + BinaryRepeatParams addParams = {1, 1, 1, 0, 8, 0}; + Add(xSquareLocal, xSquareLocal[FP32_REPEAT_ELEMENT_NUM], xSquareLocal, FP32_REPEAT_ELEMENT_NUM, repeatTimesAdd - 1, + addParams); + AscendC::PipeBarrier(); + WholeReduceSum(xSumLocal, xSquareLocal, FP32_REPEAT_ELEMENT_NUM, 1, 8, 1, 8); + AscendC::PipeBarrier(); + + // Calc: xSum = xSum * reciprocal + Muls(xSumLocal, xSumLocal, rmsNormParams.reciprocal, 1); + AscendC::PipeBarrier(); + + // Calc: xSum = xSum + epsilon + Adds(xSumLocal, xSumLocal, rmsNormParams.epsilon, 1); + AscendC::PipeBarrier(); + + // Calc: xSum = sqrt(xSum) + Sqrt(xSumLocal, xSumLocal, 1); + AscendC::PipeBarrier(); + + // Calc: xSquare[1, 8] = brc(xSum[1,1]) + // dstBlkStride, dstRepStride + BrcbRepeatParams repeatParams = {1, 1}; + Brcb(xSquareLocal, xSumLocal, 1, repeatParams); + AscendC::PipeBarrier(); + + // Calc: inputLocal = inputLocal / xSquareLocal + uint64_t mask[2] = {UINT64_MAX, UINT64_MAX}; + // dstBlkStride, src0BlkStride, src1BlkStride, dstRepStride, src0RepStride, src1RepStride + BinaryRepeatParams divParams = {1, 1, 0, 8, 8, 0}; + Div(inputLocal, inputLocal, xSquareLocal, mask, cnt / 64, divParams); + + AscendC::PipeBarrier(); + + Cast(xSquareLocal, gammaLocal, RoundMode::CAST_NONE, cnt); + + AscendC::PipeBarrier(); + + Mul(outLocal, inputLocal, xSquareLocal, cnt); + + if (unlikely(rmsNormParams.isScaleEnable)) { + AscendC::PipeBarrier(); + Muls(outLocal, outLocal, rmsNormParams.scale, cnt); + } +} +} // namespace MlaProlog +#endif // MLA_PROLOG_RMS_NORM_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_dequant.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_dequant.h new file mode 100644 index 0000000000000000000000000000000000000000..48a17cd54d14bd0ffb8c65ae446f019425079ead --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_dequant.h @@ -0,0 +1,194 @@ +/** + * 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 service_dequant.h + * \brief + */ + +#ifndef SERVICE_DEQUANT_H +#define SERVICE_DEQUANT_H + +#include "mla_prolog_comm.h" +#include "mla_prolog_vector_comm.h" + +namespace MlaProlog { +/** + DequantSplitNQc 用于enableGroupComputeOpt场景 + 场景特征:半量化,BS = 1, headsize = 8 + * @brief 用于对Qc做反量化;按N方向切分的dequant,理解为做一个head的 + * @param outputGm 输出位置 + * @param inputGm 输入tensor + * @param deqScaleQcQrWGm deqScaleQcQr反量化系数,原shape[1,ND] + * @param deQuantScaleQcQrLocal deQuantScaleQcQr反量化系数,原shape[BS,1] + * @param shareTmpUb 临时buffer + * @param dequantRowColStrideParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + * @param oriCol 一列真实的长度 + * @param dstStride 目的数据行间的偏移 + * @param subBlockIdx_ 这是奇数核还是偶数核 + */ +// 用于enableGroupComputeOpt场景 +template +__aicore__ inline void +DequantSplitNQc(const GlobalTensor &outputGm, const GlobalTensor &inputGm, const GlobalTensor &deqScaleQcQrWGm, + const LocalTensor &deQuantScaleQcQrLocal, const LocalTensor &shareTmpUb, + Rectangle dequantRowColStrideParams, uint32_t oriCol, uint32_t dstStride, uint32_t subBlockIdx_) +{ + int64_t count = dequantRowColStrideParams.col * 1; + LocalTensor inputLocal = shareTmpUb.ReinterpretCast(); // count * sizeof(T) + LocalTensor scaleLocal = inputLocal[count + 16].template ReinterpretCast(); // count * sizeof(C) + LocalTensor computeLocal = scaleLocal[count + 16].template ReinterpretCast(); // count * sizeof(C) + LocalTensor outputLocal = computeLocal[count + 16].template ReinterpretCast(); // count * sizeof(O) + + DataCopyParams inputCopyParams{ + static_cast(1), static_cast(count * sizeof(T) / 32U), + static_cast((dequantRowColStrideParams.stride - dequantRowColStrideParams.col) * sizeof(T) / 32U), 0}; + + DataCopyParams outputCopyParams{static_cast(1), static_cast(count * sizeof(O) / 32U), 0, + static_cast(dstStride * sizeof(O) / 32U)}; + + Rectangle rectangleParams{ + (uint32_t)1, // row + (uint32_t)count, // col + (uint32_t)count // columnStride + }; + + AscendC::SetFlag(EVENT_ID0); + int64_t scaleOffset = count * subBlockIdx_; + DataCopy(scaleLocal, deqScaleQcQrWGm[scaleOffset], dequantRowColStrideParams.col); + for (int64_t rowOffset = 0; rowOffset < dequantRowColStrideParams.row; rowOffset++) { + int64_t outputOffset = rowOffset * oriCol + subBlockIdx_ * count; + int64_t inputOffset = rowOffset * oriCol + subBlockIdx_ * count; + AscendC::WaitFlag(EVENT_ID0); + DataCopy(inputLocal, inputGm[inputOffset], inputCopyParams); + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + // compute + Dequant(computeLocal, inputLocal, scaleLocal, deQuantScaleQcQrLocal, rectangleParams); + AscendC::PipeBarrier(); + // cast + Cast(outputLocal, computeLocal, RoundMode::CAST_RINT, count); + AscendC::SetFlag(EVENT_ID2); + // copy out + AscendC::WaitFlag(EVENT_ID2); + DataCopy(outputGm[outputOffset], outputLocal, count); + AscendC::SetFlag(EVENT_ID0); + } + AscendC::WaitFlag(EVENT_ID0); +} + +/** + * @brief DequantPerTokenQc 用于对Qc做反量化;按行做dequant流程,给oriRow * col的数据做反量化 + * @param outputGm 输出tensor + * @param inputGm 输入tensor + * @param deqScaleQcQrWGm deqScaleQcQr反量化系数,原shape[1,ND] + * @param deQuantScaleQcQrLocal deQuantScaleQcQr反量化系数,原shape[BS,1] + * @param shareTmpUb 临时buffer + * @param dequantRowColStrideParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + * @param oriRow 一共有多少行 +*/ +template +__aicore__ inline void +DequantPerTokenQc(const GlobalTensor &outputGm, const GlobalTensor &inputGm, + const GlobalTensor &deqScaleQcQrWGm, const LocalTensor deQuantScaleQcQrLocal, + const LocalTensor &shareTmpUb, Rectangle dequantRowColStrideParams, uint32_t oriRow) +{ + int64_t count = dequantRowColStrideParams.col * dequantRowColStrideParams.row; + + LocalTensor inputLocal = shareTmpUb.ReinterpretCast(); // count * sizeof(T) + LocalTensor scaleLocal = inputLocal[count + 16].template ReinterpretCast(); // count * sizeof(C) + LocalTensor computeLocal = scaleLocal[count + 16].template ReinterpretCast(); // count * sizeof(C) + LocalTensor outputLocal = computeLocal[count + 16].template ReinterpretCast(); // count * sizeof(O) + + DataCopyParams copyParams{ + static_cast(dequantRowColStrideParams.row), + static_cast(dequantRowColStrideParams.col * sizeof(T) / 32U), + static_cast((dequantRowColStrideParams.stride - dequantRowColStrideParams.col) * sizeof(T) / 32U), 0}; + + Rectangle rectangleParams{ + (uint32_t)1, // row + (uint32_t)count, // col + (uint32_t)count // columnStride + }; + + for (int64_t rowOffset = 0; rowOffset < oriRow; rowOffset += dequantRowColStrideParams.row) { + int64_t inputOffset = rowOffset * dequantRowColStrideParams.stride; + int64_t outputOffset = rowOffset * dequantRowColStrideParams.col; + // copy in + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + DataCopy(inputLocal, inputGm[inputOffset], copyParams); + DataCopy(scaleLocal, deqScaleQcQrWGm[inputOffset], copyParams); + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + // compute + Dequant(computeLocal, inputLocal, scaleLocal, deQuantScaleQcQrLocal, rectangleParams); + AscendC::PipeBarrier(); + // cast + Cast(outputLocal, computeLocal, RoundMode::CAST_RINT, count); + AscendC::SetFlag(EVENT_ID2); + // copy out + AscendC::WaitFlag(EVENT_ID2); + DataCopy(outputGm[outputOffset], outputLocal, count); + } +} + +/** + * @brief CastPerTokenQc 用于对Qc做类型转换;按行做cast流程,给oriRow * col的数据做类型转换 + * @param outputGm 输出tensor + * @param inputGm 输入tensor + * @param shareTmpUb 临时buffer + * @param castRowColStrideParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + * @param oriRow 一共有多少行 +*/ +template +__aicore__ inline void CastPerTokenQc(const GlobalTensor &outputGm, const GlobalTensor &inputGm, + const LocalTensor &shareTmpUb, Rectangle castRowColStrideParams, + uint32_t oriRow) +{ + int64_t count = castRowColStrideParams.col * castRowColStrideParams.row; + + LocalTensor inputLocal = shareTmpUb.ReinterpretCast(); // count * sizeof(T) + LocalTensor outputLocal = inputLocal[count + 16].template ReinterpretCast(); // count * sizeof(O) + + DataCopyParams copyParams{ + static_cast(castRowColStrideParams.row), + static_cast(castRowColStrideParams.col * sizeof(T) / 32U), + static_cast((castRowColStrideParams.stride - castRowColStrideParams.col) * sizeof(T) / 32U), 0}; + + for (int64_t rowOffset = 0; rowOffset < oriRow; rowOffset += castRowColStrideParams.row) { + int64_t inputOffset = castRowColStrideParams.stride * rowOffset; + int64_t outputOffset = castRowColStrideParams.col * rowOffset; + // copy in + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + DataCopy(inputLocal, inputGm[inputOffset], copyParams); + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + // cast + Cast(outputLocal, inputLocal, RoundMode::CAST_RINT, count); + AscendC::SetFlag(EVENT_ID2); + // copy out + AscendC::WaitFlag(EVENT_ID2); + DataCopy(outputGm[outputOffset], outputLocal, count); + } +} + +} // namespace MlaProlog +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_dynamic_quant_qn_mul_qr.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_dynamic_quant_qn_mul_qr.h new file mode 100644 index 0000000000000000000000000000000000000000..8f75136b51b5d74edc7719c7b5c1ad1eef0a941d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_dynamic_quant_qn_mul_qr.h @@ -0,0 +1,251 @@ +/** + * 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 service_dynamic_quant_qn_mul_qr.h + * \brief + */ + +#ifndef SERVICE_DYNAMIC_QUANT_H +#define SERVICE_DYNAMIC_QUANT_H + +#include "mla_prolog_comm.h" +#include "mla_prolog_vector_comm.h" + +namespace MlaProlog { +template +__aicore__ inline void +MulQr(const GlobalTensor &outputGmRope, const GlobalTensor &inputGmRope, LocalTensor outputLocalRope, + const LocalTensor &qrInputLocal, const LocalTensor &qrFp32Local, const LocalTensor &reciprocalLocal, + const LocalTensor &dequantScaleBrcbLocal, uint64_t row, uint64_t colRope, uint64_t subRowRope, + uint64_t qrOutputStrideRope, float quantScaleCkvRope, uint32_t MUL_QR_INPUT_COPY_READY, uint32_t MUL_QR) +{ + constexpr uint64_t computeBlockAlign = (ALIGN_BLOCK_SIZE / sizeof(C)); + constexpr uint64_t inputBlockAlign = (ALIGN_BLOCK_SIZE / sizeof(T)); + + uint64_t loopCntRope = CeilDivT(row, subRowRope); + uint64_t lastSubRowRope = row - (loopCntRope - 1) * subRowRope; + uint32_t computeSizeRope = subRowRope * colRope; + + // DataCopyParams : count len srcStrideIn dstStrideIn + DataCopyParams inputParamsRope{(uint16_t)row, (uint16_t)(colRope / inputBlockAlign), + (uint16_t)((qrOutputStrideRope - colRope) / inputBlockAlign), 0}; + DataCopyParams outputParamsRope{(uint16_t)(subRowRope), (uint16_t)(colRope / inputBlockAlign), 0, + (uint16_t)((qrOutputStrideRope - colRope) / inputBlockAlign)}; + + uint64_t inputGmRopeOffset = 0; + uint64_t dequantScaleOffset = 0; + uint64_t inputLocalRopeOffset = 0; + + + AscendC::WaitFlag(MUL_QR_INPUT_COPY_READY); + DataCopy(qrInputLocal, inputGmRope, inputParamsRope); + for (uint64_t loopIdx = 0; loopIdx < loopCntRope; loopIdx++) { + if (loopIdx == (loopCntRope - 1) && subRowRope != lastSubRowRope) { + subRowRope = lastSubRowRope; + computeSizeRope = subRowRope * colRope; + outputParamsRope.blockCount = subRowRope; + } + AscendC::SetFlag(MUL_QR); + AscendC::WaitFlag(MUL_QR); + + AscendC::SetFlag(MUL_QR); + AscendC::WaitFlag(MUL_QR); + + Cast(qrFp32Local, qrInputLocal[inputLocalRopeOffset], RoundMode::CAST_NONE, computeSizeRope); + AscendC::PipeBarrier(); + Duplicate(reciprocalLocal, quantScaleCkvRope, subRowRope * computeBlockAlign); + AscendC::PipeBarrier(); + // cal: quantScaleCkv / dequantScaleQn + Div(reciprocalLocal, reciprocalLocal, dequantScaleBrcbLocal[dequantScaleOffset], + subRowRope * computeBlockAlign); + AscendC::PipeBarrier(); + // cal: x * quantScaleCkv / dequantScaleQn + RowMuls(qrFp32Local, qrFp32Local, reciprocalLocal, + Rectangle{(uint32_t)subRowRope, (uint32_t)colRope, (uint32_t)colRope}); + AscendC::PipeBarrier(); + Cast(outputLocalRope, qrFp32Local, RoundMode::CAST_RINT, computeSizeRope); + AscendC::PipeBarrier(); + + AscendC::SetFlag(MUL_QR); + AscendC::WaitFlag(MUL_QR); + + DataCopy(outputGmRope[inputGmRopeOffset], outputLocalRope, outputParamsRope); + inputLocalRopeOffset += subRowRope * colRope; + inputGmRopeOffset += subRowRope * qrOutputStrideRope; + dequantScaleOffset += subRowRope * computeBlockAlign; + } + AscendC::SetFlag(MUL_QR_INPUT_COPY_READY); +} + +template +__aicore__ inline void DynamicQuantMultiRow(const GlobalTensor &outputGm, const LocalTensor &scaleOutputLocal, + const GlobalTensor &inputGm, const LocalTensor outputLocal, + const LocalTensor &inputHalf, const LocalTensor &inputLocal, + const LocalTensor &maxInt8Tensor, const LocalTensor &shareTmpUb, + uint64_t row, uint64_t col, uint64_t subRow, uint64_t queryOutStride, + uint32_t DYNAMIC_QUANT_INPUT_READY, uint32_t DYNAMIC_QUANT_OUTPUT_READY) +{ + constexpr uint64_t outputBlockAlign = (ALIGN_BLOCK_SIZE / sizeof(O)); + constexpr uint64_t inputBlockAlign = (ALIGN_BLOCK_SIZE / sizeof(T)); + // DataCopyParams : count len srcStrideIn dstStrideIn + DataCopyParams outParams{(uint16_t)subRow, (uint16_t)(col / outputBlockAlign), 0, + (uint16_t)((queryOutStride - col) / outputBlockAlign)}; + DataCopyParams inputParams{(uint16_t)subRow, (uint16_t)(col / inputBlockAlign), + (uint16_t)((queryOutStride - col) / inputBlockAlign), 0}; + + uint32_t computeSize = col * subRow; + uint64_t loopCnt = CeilDivT(row, subRow); + uint64_t lastSubRow = row - (loopCnt - 1) * subRow; + uint64_t inputGmOffset = 0; + uint64_t scaleOffset = 0; + + for (uint64_t loopIdx = 0; loopIdx < loopCnt; loopIdx++) { + if ((loopIdx == loopCnt - 1) && (lastSubRow != subRow)) { + subRow = lastSubRow; + computeSize = col * subRow; + outParams.blockCount = subRow; + inputParams.blockCount = subRow; + } + + AscendC::WaitFlag(DYNAMIC_QUANT_INPUT_READY); // 计算是否已经完成可以搬运 + DataCopy(inputHalf, inputGm[inputGmOffset], inputParams); + AscendC::SetFlag(DYNAMIC_QUANT_INPUT_READY); + AscendC::WaitFlag(DYNAMIC_QUANT_INPUT_READY); // 搬运是否已经完成可以计算 + + Cast(inputLocal, inputHalf, RoundMode::CAST_NONE, computeSize); + AscendC::SetFlag(DYNAMIC_QUANT_INPUT_READY); + AscendC::PipeBarrier(); + DynamicQuant(inputLocal, scaleOutputLocal[scaleOffset], inputLocal, maxInt8Tensor, shareTmpUb, subRow, col); + AscendC::PipeBarrier(); + // float -> half -> int + AscendC::WaitFlag(DYNAMIC_QUANT_OUTPUT_READY); // 搬运是否已经完成可以计算 + LocalTensor tmpf16Ub = outputLocal.template ReinterpretCast(); + Cast(tmpf16Ub, inputLocal, AscendC::RoundMode::CAST_ROUND, computeSize); + AscendC::PipeBarrier(); + // Calc: out = round(x / scaleOut) + LocalTensor tmpMMResCastTensor = outputLocal.template ReinterpretCast(); + Cast(tmpMMResCastTensor, tmpf16Ub, AscendC::RoundMode::CAST_ROUND, computeSize); + AscendC::SetFlag(DYNAMIC_QUANT_OUTPUT_READY); + AscendC::WaitFlag(DYNAMIC_QUANT_OUTPUT_READY); // 计算是否已经完成可以搬运 + + DataCopy(outputGm[inputGmOffset], tmpMMResCastTensor, outParams); + AscendC::SetFlag(DYNAMIC_QUANT_OUTPUT_READY); + inputGmOffset += subRow * queryOutStride; + scaleOffset += subRow; + } +} + +/** + * @brief DynamicQuantQnWithMulQr 流程中dynamicquant和ropeMul融合流程 + UB,流水,中间产物统筹规划 + * @tparam T mmQnOutputType -> bf16 + * @tparam C dequantScaleQNopeType -> float + * @tparam O queryOutputType -> int8 + * @param scaleOutputGm 动态量化参数输出GM位置 + * @param outputGm 动态量化结果输出GM位置 + * @param outputGmRope rope处理后的输出位置 + * @param inputGm dynamicQuant部分的输入 + * @param shareTmpUb 临时buffer空间 + * @param row + * @param col + * @param scaleOutStride 描述动态量化参数输出GM位置的偏移关系 + * @param queryOutStride 描述动态量化结果输出GM位置 + * @param inputGmRope + * @param quantScaleCkvRope + * @param colRope + * @param qrOutputStrideRope 描述rope处理后的输出位置 + */ +template +__aicore__ inline void DynamicQuantQnWithMulQr( + // Dynamic Quant With MulQr 输出 + const GlobalTensor &scaleOutputGm, const GlobalTensor &outputGm, const GlobalTensor &outputGmRope, + // Dynamic Quant 入参 + const GlobalTensor &inputGm, LocalTensor &shareTmpUb, uint64_t row, uint64_t col, + uint64_t scaleOutStride, uint64_t queryOutStride, + // Mul Qr 入参 + const GlobalTensor &inputGmRope, float quantScaleCkvRope, uint64_t colRope, uint64_t qrOutputStrideRope, + uint32_t cvRatio) +{ + if (col == 0 || row == 0) { + return; + } + // 常量 + constexpr uint32_t MUL_QR = EVENT_ID1; // 用于控制Mul_Qr的同步 + constexpr uint32_t DYNAMIC_QUANT_INPUT_READY = + EVENT_ID0; // dynamicquant输入的计算/搬运 是否已经完成可以开始下一轮的 搬运/计算 + constexpr uint32_t MUL_QR_INPUT_COPY_READY = EVENT_ID3; // 是否可以开始下一轮的MUL_QR_INPUT_COPY + constexpr uint32_t CALC_SCALE_FINISH = EVENT_ID0; // dynamicquant的scale是否计算完成可以开始搬运 + constexpr uint32_t DYNAMIC_QUANT_OUTPUT_READY = + EVENT_ID3; // dynamicquant输出的计算/搬运 是否已经完成可以开始下一轮的 搬运/计算 + + constexpr uint64_t inputBlockAlign = (ALIGN_BLOCK_SIZE / sizeof(T)); + constexpr uint64_t computeBlockAlign = (ALIGN_BLOCK_SIZE / sizeof(C)); + constexpr float maxInt8 = 127.0; + // Dynamic Quant 局部变量 + uint64_t rowStepSize = 8 * cvRatio; // 单次处理最大行数, cv1:1场景,改为8行进行计算,降低UB使用 + + uint64_t subRow = row < rowStepSize ? row : rowStepSize; + uint32_t brcbCnt = Align(subRow, computeBlockAlign); + uint32_t computeSize = subRow * col; + + // Rope Post Process 局部变量 + uint64_t rowStepSizeRope = 64; // 单次处理最大行数 + uint32_t loadRopeGmSize = row * colRope; + uint64_t subRowRope = row < rowStepSizeRope ? row : rowStepSizeRope; + uint32_t computeSizeRope = subRowRope * colRope; + + // Dynamic Quant & Rope Post Process UB Buffer分配 + LocalTensor inputHalf = shareTmpUb.ReinterpretCast(); + LocalTensor qrInputLocal = inputHalf[computeSize]; + LocalTensor outputLocalRope = qrInputLocal[inputBlockAlign + loadRopeGmSize]; + + LocalTensor inputLocal = outputLocalRope[inputBlockAlign + computeSizeRope].template ReinterpretCast(); + LocalTensor outputLocal = inputLocal[computeSize]; + LocalTensor maxInt8Tensor = outputLocal[computeSize]; + LocalTensor dynamicQuantUb = maxInt8Tensor[brcbCnt]; + LocalTensor scaleOutputLocal = dynamicQuantUb[computeSize + brcbCnt * computeBlockAlign]; + LocalTensor scaleBrcb = scaleOutputLocal[Align(row, computeBlockAlign)]; + + // Rope Post Process流程在Dynamic Quant流程结束,两者UB Buffer不会同时使用,故可以从起始位置开始重新计算,减少UB + // Buffer使用 + LocalTensor qrFp32Local = inputLocal; + LocalTensor reciprocalLocal = qrFp32Local[computeBlockAlign + computeSizeRope]; + + // Dynamic Quant + Duplicate(maxInt8Tensor, static_cast(maxInt8), brcbCnt); + AscendC::PipeBarrier(); + + DynamicQuantMultiRow(outputGm, scaleOutputLocal, inputGm, outputLocal, inputHalf, inputLocal, maxInt8Tensor, + dynamicQuantUb.template ReinterpretCast(), row, col, subRow, queryOutStride, + DYNAMIC_QUANT_INPUT_READY, DYNAMIC_QUANT_OUTPUT_READY); + + Brcb(scaleBrcb, scaleOutputLocal, CeilDivT(row, computeBlockAlign), {1, computeBlockAlign}); + AscendC::PipeBarrier(); + + // DataCopyParams : count len srcStrideIn dstStrideIn + DataCopyParams scaleOutCopyParams{(uint16_t)row, (uint16_t)sizeof(C), 0, + (uint16_t)((scaleOutStride - 1) * sizeof(C))}; + + AscendC::SetFlag(CALC_SCALE_FINISH); + AscendC::WaitFlag(CALC_SCALE_FINISH); + DataCopyPad(scaleOutputGm, scaleBrcb, scaleOutCopyParams); + + // qr rope 后的乘法 + MulQr(outputGmRope, inputGmRope, outputLocalRope, qrInputLocal, qrFp32Local, reciprocalLocal, scaleBrcb, row, + colRope, subRowRope, qrOutputStrideRope, quantScaleCkvRope, MUL_QR_INPUT_COPY_READY, MUL_QR); + + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); +} + +} // namespace MlaProlog + +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_gather_sin_cos.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_gather_sin_cos.h new file mode 100644 index 0000000000000000000000000000000000000000..037688a305e4d113cd2f66e6a1cdda46417b9392 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_gather_sin_cos.h @@ -0,0 +1,66 @@ +/** + * 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 service_gather_sin_cos.h + * \brief + */ + +#ifndef SERVICE_GATHER_SIN_COS_H +#define SERVICE_GATHER_SIN_COS_H + +#include "mla_prolog_comm.h" + +namespace MlaProlog { + +/** + * @brief GatherSinCos 读取rope所需的sin和cos系数,并进行预处理,rope中sin的-1系数会在此处融合进sin中; + * @param cosLocal cos搬运的位置; + * @param sinLocal sin搬运的位置;rope中sin的-1系数会在此处融合进sin中; + * @param cosGm cos在GM的位置,可以认为一个token有col个系数;整体连续排布 + * @param sinGm sin在GM的位置,同上 + * @param tokenIndex 从哪个token开始读取 + * @param curVecToken 读取多少个token的系数 + * @param shareTmpUb 临时buffer 内部需要的空间为 [2 * curVecToken * col * sizeof(bfloat16_t)] + * @param row 行数;预留参数 + * @param col 列数 + */ +template +__aicore__ inline void GatherSinCos(LocalTensor &cosLocal, LocalTensor &sinLocal, const GlobalTensor &cosGm, + const GlobalTensor &sinGm, int64_t tokenIndex, int64_t curVecToken, + LocalTensor &shareTmpUb, int64_t row, int64_t col) +{ + int64_t offset = tokenIndex * col; + int64_t curDataSize = curVecToken * col; + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + if constexpr (IsSameType::value) { + auto tmpUbBf16 = shareTmpUb.ReinterpretCast(); + DataCopy(tmpUbBf16, cosGm[offset], curDataSize); + DataCopy(tmpUbBf16[curDataSize], sinGm[offset], curDataSize); + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + Cast(cosLocal, tmpUbBf16, RoundMode::CAST_NONE, curDataSize); + Cast(sinLocal, tmpUbBf16[curDataSize], RoundMode::CAST_NONE, curDataSize); + AscendC::PipeBarrier(); + } else { + DataCopy(cosLocal, cosGm[offset], curDataSize); + DataCopy(sinLocal, sinGm[offset], curDataSize); + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + } + uint8_t blockNumPerRow = col / (ALIGN_BLOCK_SIZE / sizeof(O)); + Muls(sinLocal, sinLocal, -1.0f, col >> 1, curVecToken, {1, 1, blockNumPerRow, blockNumPerRow}); + AscendC::PipeBarrier(); +} + +} // namespace MlaProlog + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_matmul.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_matmul.h new file mode 100644 index 0000000000000000000000000000000000000000..d2c52ce57f075bc2f9083119636ef48592b6111f --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_matmul.h @@ -0,0 +1,569 @@ +/** + * 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 service_matmul.h + * \brief + */ + +#ifndef SERVICE_MATMUL_H +#define SERVICE_MATMUL_H + +#include "mla_prolog_comm.h" + +namespace MlaProlog { + +template +__aicore__ inline constexpr uint32_t GetC0Num() +{ + if (sizeof(SrcT) == sizeof(int8_t)) { + return 32; + } else if (sizeof(SrcT) == sizeof(float)) { + return 8; + } + return 16; +} + +constexpr uint8_t UNIT_FLAG_DISABLE = 0; // 0: disable: 不配置unitFlag +constexpr uint8_t UNIT_FLAG_SET = 0b11; // 3: enable: 在k的最后一轮循环,会将mmadParams.unitFlag设置为 0b11 +constexpr uint8_t UNIT_FLAG_CHECK = 0b10; // 2: enable: 将mmadParams.unitFlag设置为 0b10 + +/** + * @brief Struct to encapsulate all local tensor objects for matrix multiplication + * @tparam T Data type for A, B, and L0 tensors + * @tparam O_L0C Data type for C L0 tensor + */ +template +struct mmLocalTensors { + /** + * @brief Initialize all local tensors with buffer addresses from bufParam + * @param bufParam Buffer parameter object containing all buffer addresses + */ + __aicore__ inline void Init(const MMBufParams &bufParam) + { + aL0Tensor.SetAddr(bufParam.aL0BufAddr); + bL0Tensor.SetAddr(bufParam.bL0BufAddr); + cL0Tensor.SetAddr(bufParam.cL0BufAddr); + aL1Tensor.SetAddr(bufParam.aL1BufAddr); + bL1Tensor.SetAddr(bufParam.bL1BufAddr); + } + + LocalTensor aL0Tensor; + LocalTensor bL0Tensor; + LocalTensor cL0Tensor; + LocalTensor aL1Tensor; + LocalTensor bL1Tensor; +}; + +template +__aicore__ inline void CopyNZGmToL1(LocalTensor &l1Tensor, const GlobalTensor &gmSrcTensor, uint32_t srcN, + uint32_t srcD, uint32_t srcNstride) +{ + DataCopyParams param; + param.blockCount = CeilDivT(srcD, GetC0Num()); + param.blockLen = srcN; // 单位为32B srcN*16/16 + param.dstStride = 0; + param.srcStride = (srcNstride - srcN); // 单位为32B (srcNstride - srcN)*16/16 + DataCopy(l1Tensor, gmSrcTensor, param); +} + +template +__aicore__ inline void CopyNDGmToL1(LocalTensor &l1Tensor, const GlobalTensor &gmSrcTensor, uint32_t srcN, + uint32_t srcD, uint32_t srcDstride) +{ + Nd2NzParams nd2nzPara; + nd2nzPara.nValue = srcN; // 行数 + nd2nzPara.dValue = srcD; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + nd2nzPara.srcDValue = srcDstride; + nd2nzPara.dstNzC0Stride = CeilDivT(srcN, BLOCK_CUBE_SIZE) * BLOCK_CUBE_SIZE; // 对齐到16 单位 block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.ndNum = 1; + DataCopy(l1Tensor, gmSrcTensor, nd2nzPara); +} + + +template +__aicore__ inline void LoadL1A(const GlobalTensor &tensorAGm, const uint32_t mInput, const uint32_t kL1StepSize, + const uint32_t kInput, MMBufParams &bufParam) +{ + uint32_t bufIter = bufParam.aL1BufIter; + if constexpr (preload) { + bufIter += 1; + } + LocalTensor aL1Tensor; + aL1Tensor.SetAddr(bufParam.aL1BufAddr); + uint32_t aL1Offset = L1_A_SIZE / sizeof(T); + + AscendC::WaitFlag((bufIter & 1u) + A_EVENT0); + LocalTensor aL1 = aL1Tensor[(bufIter & 1u) * aL1Offset]; + CopyNDGmToL1(aL1, tensorAGm, mInput, kL1StepSize, kInput); + AscendC::SetFlag((bufIter & 1u) + A_EVENT0); +} + +template +__aicore__ inline void LoadL1B(const GlobalTensor &tensorBGm, const uint32_t nL1Size, const uint32_t nInput, + const uint32_t kL1StepSize, const uint32_t kInput, MMBufParams &bufParam) +{ + uint32_t bufIter = bufParam.bL1BufIter; + if constexpr (preload) { + bufIter += 1; + } + LocalTensor bL1Tensor; + bL1Tensor.SetAddr(bufParam.bL1BufAddr); + uint32_t bL1Offset = L1_B_SIZE / sizeof(T); + + AscendC::WaitFlag((bufIter & 1u) + B_EVENT0); + LocalTensor bL1 = bL1Tensor[(bufIter & 1u) * bL1Offset]; + if constexpr (loadFormat == DataFormat::NZ) { + CopyNZGmToL1(bL1, tensorBGm, kL1StepSize, nL1Size, kInput); + } else { + CopyNDGmToL1(bL1, tensorBGm, kInput, nL1Size, nInput); + } + AscendC::SetFlag((bufIter & 1u) + B_EVENT0); +} + +/** + * @brief 使用3D Pro模式将数据从L1加载到L0,可选择是否进行转置操作 + * @tparam T 张量的数据类型 + * @tparam enTranspose 是否启用转置操作(用于B矩阵) + * @param l0Tensor L0缓冲区中的目标张量 + * @param l1Tensor L1缓冲区中的源张量 + * @param mSize 行维度(对应A矩阵的m,B矩阵的k) + * @param kSize 列维度(对应A矩阵的k,B矩阵的n) + * @param l1StepSize L1缓冲区中的步长大小,用于B矩阵转置 + * @param kl1Size L1缓冲区中的大小,用于B矩阵转置 + */ +template +__aicore__ inline void LoadDataL1ToL0(const LocalTensor &l0Tensor, const LocalTensor &l1Tensor, + const uint32_t mSize, const uint32_t kSize, const uint32_t l1StepSize = 0) +{ + constexpr uint32_t FMATRIX_HEIGHT_UNIT = 16; + LocalTensor srcTensor = l1Tensor; + LoadData3DParamsV2 loadData3DV2; + + if constexpr (enTranspose) { + // LoadDataBL0K3DPro behavior: mSize=kSize, mSize=nSize, l1StepSize=kL1Size + loadData3DV2.l1H = l1StepSize / FMATRIX_HEIGHT_UNIT; + loadData3DV2.l1W = FMATRIX_HEIGHT_UNIT; + loadData3DV2.enTranspose = true; + } else { + // LoadDataAL0K3DPro behavior: mSize=mSize, mSize=kSize + loadData3DV2.l1H = mSize / FMATRIX_HEIGHT_UNIT; + loadData3DV2.l1W = FMATRIX_HEIGHT_UNIT; + } + loadData3DV2.channelSize = kSize; + loadData3DV2.mStartPt = 0; + loadData3DV2.kStartPt = 0; + loadData3DV2.mExtension = mSize; + loadData3DV2.kExtension = kSize; + + LoadData(l0Tensor, srcTensor, loadData3DV2); +} + +template +__aicore__ inline void LoadDataL1ToL0B(const LocalTensor &bL0Tensor, const LocalTensor &bL1Tensor, + const uint32_t kSize, const uint32_t nSize, const uint32_t kL1StepSize = 0) +{ + constexpr uint32_t LOAD_WIDTH = 32; + constexpr uint32_t STRIDE_HEIGHT = 32; + constexpr uint32_t DATA_BYTES_PER_REPEAT = 32; + + uint32_t kloops = kSize / (LOAD_WIDTH / sizeof(T)); + LocalTensor srcTensor = bL1Tensor; + for (uint32_t i = 0; i < kloops; i++) { + LoadData2dTransposeParams loadData2DParams; + loadData2DParams.repeatTimes = nSize / (DATA_BYTES_PER_REPEAT / sizeof(T)); + loadData2DParams.startIndex = 0; + loadData2DParams.srcStride = kL1StepSize / STRIDE_HEIGHT; + loadData2DParams.dstFracGap = 0; + loadData2DParams.dstGap = 1; + LocalTensor tmpSrcTensor; + tmpSrcTensor = srcTensor[i * STRIDE_HEIGHT * (DATA_BYTES_PER_REPEAT / sizeof(T))]; + // LoadData 不支持int8的转置,需要用 LoadDataWithTranspose + LoadDataWithTranspose(bL0Tensor[i * STRIDE_HEIGHT * nSize], tmpSrcTensor, loadData2DParams); + } +} + +template +__aicore__ inline void MatmulL0(MMBufParams &bufParam, const LocalTensor &aL1, const LocalTensor &bL1, + const LocalTensor &aL0Tensor, const LocalTensor &bL0Tensor, + const LocalTensor &cL0Tensor, const MmadParams &mmadParams, + const uint32_t kL1StepSize, const uint32_t kL1Size = 0) +{ + AscendC::WaitFlag((bufParam.aL0BufIter & 1u) + L0A_EVENT0); + LocalTensor aL0 = aL0Tensor[(bufParam.aL0BufIter & 1u) * (L0A_PP_SIZE / sizeof(T))]; + + LoadDataL1ToL0(aL0, aL1, mmadParams.m, mmadParams.k); + + AscendC::SetFlag((bufParam.aL0BufIter & 1u) + L0A_EVENT0); + AscendC::WaitFlag((bufParam.aL0BufIter & 1u) + L0A_EVENT0); + AscendC::WaitFlag((bufParam.bL0BufIter & 1u) + L0B_EVENT0); + + LocalTensor bL0 = bL0Tensor[(bufParam.bL0BufIter & 1u) * (L0B_PP_SIZE / sizeof(T))]; + if constexpr (std::is_same::value) { + LoadDataL1ToL0B(bL0, bL1, mmadParams.k, mmadParams.n, kL1StepSize); + } else { + LoadDataL1ToL0(bL0, bL1, mmadParams.k, mmadParams.n, kL1StepSize); + } + + AscendC::SetFlag((bufParam.bL0BufIter & 1u) + L0B_EVENT0); + AscendC::WaitFlag((bufParam.bL0BufIter & 1u) + L0B_EVENT0); + Mmad(cL0Tensor, aL0, bL0, mmadParams); + PipeBarrier(); + AscendC::SetFlag((bufParam.bL0BufIter & 1u) + L0B_EVENT0); + bufParam.bL0BufIter++; + AscendC::SetFlag((bufParam.aL0BufIter & 1u) + L0A_EVENT0); + bufParam.aL0BufIter++; +} + +template +__aicore__ inline void GetTensorC(const GlobalTensor &tensorCGm, const LocalTensor &cL0, const uint32_t mSize, + const uint32_t nSize, const uint32_t srcStride, const uint32_t dstStride, + MMBufParams &bufParam) +{ + FixpipeParamsV220 fixParams; + fixParams.srcStride = srcStride; // ((fixParams.mSize + 15) / 16) * 16 + fixParams.dstStride = dstStride; + fixParams.nSize = nSize; // 实现切片大小 + fixParams.mSize = mSize; // msdIterNum * gSize; // 有效数据不足16行,只需要输出部分行即可 + fixParams.ndNum = 1; + fixParams.unitFlag = enUnitFlag ? UNIT_FLAG_SET : UNIT_FLAG_DISABLE; + if constexpr (std::is_same::value && std::is_same::value) { + fixParams.quantPre = QuantMode_t::F322BF16; + } + if constexpr (!enUnitFlag) { + AscendC::SetFlag((bufParam.cL0BufIter & 1u) + L0C_EVENT0); + AscendC::WaitFlag((bufParam.cL0BufIter & 1u) + L0C_EVENT0); + } + Fixpipe(tensorCGm, cL0, fixParams); +} + + +/** + * @brief B矩阵数据加载到L1缓冲区的辅助函数 + * @tparam T B张量的数据类型 + * @tparam isContinuousCopy 是否使用连续复制模式 + * @param bL1 B矩阵L1张量 + * @param tensorBGm B矩阵GM张量 + * @param kL1StepSize L1中K维度的步长大小 + * @param subNL1SplitSize L1中N维度的分割大小 + * @param para MMParams参数 + * @param bufParam 缓冲区管理参数 + * @param nL1 当前N L1迭代 + * @param kL1 当前K L1迭代 + * @param kOffesetUnit K维度偏移单位 + */ +template +__aicore__ inline void LoadL1BGroupCompute(LocalTensor &bL1, const GlobalTensor &tensorBGm, + uint32_t subNL1SplitSize, const MMParams ¶, int64_t nL1, uint32_t kL1, + uint32_t kOffesetUnit) +{ + int64_t tensorBGmOffset = para.k * nL1 * para.baseN + kOffesetUnit * kL1; + auto tensorBGmForL1 = tensorBGm[tensorBGmOffset]; + if constexpr (isContinuousCopy) { + CopyNZGmToL1(bL1, tensorBGmForL1, para.kL1StepSize, subNL1SplitSize, para.k); + } else { + // 每次搬运两块K*64拼接成K*128 + CopyNZGmToL1(bL1, tensorBGmForL1, para.kL1StepSize, subNL1SplitSize >> 1, para.k); + LocalTensor b2L1 = bL1[(subNL1SplitSize * para.kL1StepSize) >> 1]; + auto tensorB2GmForL1 = tensorBGmForL1[DIM_HEAD_SIZE_QCQR * para.k]; + CopyNZGmToL1(b2L1, tensorB2GmForL1, para.kL1StepSize, subNL1SplitSize >> 1, para.k); + } +} + +/** + * @brief 将AB矩阵从GM加载到L1缓存以进行矩阵乘法运算 + * @tparam T 张量的数据类型 + * @tparam hasL1ALoaded A矩阵是否已经加载到L1中 + * @param tensorAGm GM中的A矩阵 + * @param tensorBGm GM中的B矩阵 + * @param kL1 当前K L1循环迭代次数 + * @param kL1Loops K L1循环的总次数 + * @param para 包含维度和步长信息的矩阵乘法参数 + * @param nL1Offset L1缓冲区中的N维度偏移 + * @param nL1Size L1缓冲区中的N维度大小 + * @param kOffesetUnit K维度寻址的偏移单位 + * @param bufParam L1缓冲区管理的参数对象 + */ +template +__aicore__ inline void LoadL1AB(const GlobalTensor &tensorAGm, const GlobalTensor &tensorBGm, uint32_t kL1, + uint32_t kL1Loops, const MMParams ¶, uint32_t nL1Offset, uint32_t nL1Size, + uint32_t kOffesetUnit, MMBufParams &bufParam) +{ + if (kL1 == 0) { + if constexpr (!hasL1ALoaded) { + LoadL1A(tensorAGm[para.kL1StepSize * kL1], para.m, para.kL1StepSize, para.orgKa, bufParam); + } + if constexpr (bLoadFormat == DataFormat::NZ) { + LoadL1B(tensorBGm[para.k * nL1Offset + kOffesetUnit * kL1], nL1Size, para.n, para.kL1StepSize, para.k, + bufParam); + } else { + LoadL1B(tensorBGm[para.kL1StepSize * kL1 * para.n + nL1Offset], nL1Size, para.n, + para.kL1StepSize, para.kL1StepSize, bufParam); + } + } + + if (kL1 + 1 < kL1Loops) { + if constexpr (!hasL1ALoaded) { + LoadL1A(tensorAGm[para.kL1StepSize * (kL1 + 1)], para.m, para.kL1StepSize, para.orgKa, bufParam); + } + if constexpr (bLoadFormat == DataFormat::NZ) { + LoadL1B(tensorBGm[para.k * nL1Offset + kOffesetUnit * (kL1 + 1)], nL1Size, para.n, + para.kL1StepSize, para.k, bufParam); + } else { + LoadL1B(tensorBGm[para.kL1StepSize * (kL1 + 1) * para.n + nL1Offset], nL1Size, + para.n, para.kL1StepSize, para.kL1StepSize, bufParam); + } + } +} + +/** + * @brief 执行矩阵乘法的K L0循环计算 + * @tparam T A和B矩阵的数据类型 + * @tparam O_L0C L0C缓存中的数据类型 + * @tparam enUnitFlag 是否启用unitFlag功能 + * @param cL0 L0缓存中的C矩阵张量 + * @param aL1 L1缓存中的A矩阵张量 + * @param bL1 L1缓存中的B矩阵张量 + * @param localTensors 矩阵乘法所需的本地张量对象 + * @param bufParam L1缓存管理的缓冲区参数对象 + * @param kL1 当前K L1循环迭代次数 + * @param kL1Loops K L1循环的总次数 + * @param stepK K L0步数 + * @param aOffsetUnit A矩阵L0寻址的偏移单位 + * @param bOffsetUnit B矩阵L0寻址的偏移单位 + * @param mmadParams 矩阵乘法参数 + * @param aOffset A矩阵计算的起始偏移 + * @param bOffset B矩阵计算的起始偏移 + */ +template +__aicore__ inline void MatmulL1(const LocalTensor &cL0, const LocalTensor &aL1, const LocalTensor &bL1, + const mmLocalTensors &localTensors, MMBufParams &bufParam, + const MMParams ¶, uint32_t kL1, uint32_t kL1Loops, MmadParams &mmadParams, + int64_t &aOffset) +{ + uint32_t bOffset = 0; + uint32_t mSize = Align(para.m, BLOCK_CUBE_SIZE); + uint32_t aOffsetUnit = mSize * para.baseK; + uint32_t bOffsetUnit = GetC0Num() * para.baseK; + + for (int64_t kL0Loops = 0; kL0Loops < para.stepK; kL0Loops++) { + mmadParams.cmatrixInitVal = ((kL0Loops == 0) && (kL1 == 0)); + if constexpr (enUnitFlag) { + mmadParams.unitFlag = + (kL1 == kL1Loops - 1) && (kL0Loops == para.stepK - 1) ? UNIT_FLAG_SET : UNIT_FLAG_CHECK; + } + MatmulL0(bufParam, aL1[aOffset], bL1[bOffset], localTensors.aL0Tensor, localTensors.bL0Tensor, cL0, + mmadParams, para.kL1StepSize, para.k); + bOffset += bOffsetUnit; // 32(Get)*256=8192 + aOffset += aOffsetUnit; // 16(BS)*256=4096 + } +} + +/** + * @brief MatmulSplitK 通过切分K轴,进行L1的数据管理和矩阵乘运算; 用于mmCq, mmCKvKr和mmQcQr。 + * @param tensorAGm A矩阵在GM的位置 + * @param tensorBGm B矩阵在GM的位置 + * @param tensorCGm C矩阵在GM的位置 + * @param para 表示matmul形状信息的结构体参数 + * @param bufParam 管理L1 buffer地址和同步计数的结构体参数 + * @param nL1Offset 本次计算中,L1 buffer内B矩阵在n轴上的偏移 + * @param nL1Size 本次计算中,L1 buffer内B矩阵在n轴上的计算量 + */ +template +__aicore__ inline void MatmulSplitK(const GlobalTensor &tensorCGm, const GlobalTensor &tensorAGm, + const GlobalTensor &tensorBGm, const MMParams ¶, MMBufParams &bufParam, + const uint32_t nL1Offset, const uint32_t nL1Size) +{ + using O_L0C = typename std::conditional::value, int32_t, float>::type; + + // 全局L1管理 + uint32_t kOffesetUnit = para.kL1StepSize * GetC0Num(); + uint32_t kL1Loops = CeilDivT(para.k, para.kL1StepSize); + uint32_t mSize = Align(para.m, BLOCK_CUBE_SIZE); + + mmLocalTensors localTensors; + localTensors.Init(bufParam); + + LocalTensor aL1, bL1; + + if constexpr (hasL1ALoaded) { + aL1 = localTensors.aL1Tensor[(bufParam.aL1BufIter & 1u) * L1_A_SIZE / sizeof(T)]; + } + + AscendC::WaitFlag((bufParam.cL0BufIter & 1u) + L0C_EVENT0); + LocalTensor cL0 = localTensors.cL0Tensor[(bufParam.cL0BufIter & 1u) * (L0C_PP_SIZE / sizeof(O_L0C))]; + + MmadParams mmadParams = MmadParams(mSize, nL1Size, para.baseK, UNIT_FLAG_DISABLE, false, true); + + int64_t aOffset = 0; + for (uint32_t kL1 = 0; kL1 < kL1Loops; kL1++) { + // Load data from global memory to L1 cache + LoadL1AB(tensorAGm, tensorBGm, kL1, kL1Loops, para, nL1Offset, nL1Size, + kOffesetUnit, bufParam); + + AscendC::WaitFlag((bufParam.bL1BufIter & 1u) + B_EVENT0); + bL1 = localTensors.bL1Tensor[(bufParam.bL1BufIter & 1u) * L1_B_SIZE / sizeof(T)]; + if constexpr (!hasL1ALoaded) { + AscendC::WaitFlag((bufParam.aL1BufIter & 1u) + A_EVENT0); + aL1 = localTensors.aL1Tensor[(bufParam.aL1BufIter & 1u) * L1_A_SIZE / sizeof(T)]; + aOffset = 0; + } + + // Perform core K L0 loops computation + MatmulL1(cL0, aL1, bL1, localTensors, bufParam, para, kL1, kL1Loops, mmadParams, + aOffset); + + AscendC::SetFlag((bufParam.bL1BufIter & 1u) + B_EVENT0); + bufParam.bL1BufIter++; + if constexpr (!hasL1ALoaded) { + AscendC::SetFlag((bufParam.aL1BufIter & 1u) + A_EVENT0); + bufParam.aL1BufIter++; + } + } + GetTensorC(tensorCGm[nL1Offset], cL0, para.m, nL1Size, mSize, para.orgKc, bufParam); + AscendC::SetFlag((bufParam.cL0BufIter & 1u) + L0C_EVENT0); + bufParam.cL0BufIter++; +} + +/** + * @brief MatmulGroupComputeAFullLoad + * A矩阵能够全载,通过切分K轴,进行L1的数据管理和矩阵乘运算,仅适用于算力分组场景下的mmQc和mmQr; + * @param tensorAGm A矩阵在GM的位置 + * @param tensorBGm B矩阵在GM的位置 + * @param tensorCGm C矩阵在GM的位置 + * @param para 表示matmul形状信息的结构体参数 + * @param bufParam 管理L1 buffer地址和同步计数的结构体参数 + */ +template +__aicore__ inline void MatmulGroupComputeAFullLoad(const GlobalTensor &tensorCGm, const GlobalTensor &tensorAGm, + const GlobalTensor &tensorBGm, const MMParams ¶, + MMBufParams &bufParam) +{ + using O_L0C = typename std::conditional::value, int32_t, float>::type; + // 全局L1管理 + uint32_t kOffesetUnit = GetC0Num() * para.kL1StepSize; + uint32_t mSize = Align(para.m, BLOCK_CUBE_SIZE); + uint32_t nL1loops = CeilDivT(para.n, para.baseN); + uint32_t kL1Loops = CeilDivT(para.k, para.kL1StepSize); + + mmLocalTensors localTensors; + localTensors.Init(bufParam); + + AscendC::WaitFlag((bufParam.aL1BufIter & 1u) + A_EVENT0); + LocalTensor aL1 = localTensors.aL1Tensor[(bufParam.aL1BufIter & 1u) * (L1_A_SIZE / sizeof(T))]; + CopyNDGmToL1(aL1, tensorAGm, para.m, para.k, para.k); + AscendC::SetFlag((bufParam.aL1BufIter & 1u) + A_EVENT0); + AscendC::WaitFlag((bufParam.aL1BufIter & 1u) + A_EVENT0); + + uint32_t subNL1SplitSize = para.baseN; + + MmadParams mmadParams = MmadParams(mSize, subNL1SplitSize, para.baseK, UNIT_FLAG_DISABLE, false, true); + + for (int64_t nL1 = 0; nL1 < nL1loops; nL1++) { + if (nL1 == nL1loops - 1) { + subNL1SplitSize = para.n - para.baseN * (nL1loops - 1); + mmadParams.n = subNL1SplitSize; + } + + AscendC::WaitFlag((bufParam.cL0BufIter & 1u) + L0C_EVENT0); + LocalTensor cL0 = localTensors.cL0Tensor[(bufParam.cL0BufIter & 1u) * (L0C_PP_SIZE / sizeof(O_L0C))]; + + int64_t aOffset = 0; + for (uint32_t kL1 = 0; kL1 < kL1Loops; kL1++) { + AscendC::WaitFlag((bufParam.bL1BufIter & 1u) + B_EVENT0); + LocalTensor bL1 = localTensors.bL1Tensor[(bufParam.bL1BufIter & 1u) * (L1_B_SIZE / sizeof(T))]; + LoadL1BGroupCompute(bL1, tensorBGm, subNL1SplitSize, para, nL1, kL1, kOffesetUnit); + AscendC::SetFlag((bufParam.bL1BufIter & 1u) + B_EVENT0); + AscendC::WaitFlag((bufParam.bL1BufIter & 1u) + B_EVENT0); + + // Perform core K L0 loops computation using shared function + MatmulL1(cL0, aL1, bL1, localTensors, bufParam, para, kL1, kL1Loops, mmadParams, + aOffset); + AscendC::SetFlag((bufParam.bL1BufIter & 1u) + B_EVENT0); + bufParam.bL1BufIter++; + } + GetTensorC(tensorCGm[nL1 * para.baseN], cL0, para.m, subNL1SplitSize, mSize, + para.orgKc, bufParam); + AscendC::SetFlag((bufParam.cL0BufIter & 1u) + L0C_EVENT0); + bufParam.cL0BufIter++; + } + AscendC::SetFlag((bufParam.aL1BufIter & 1u) + A_EVENT0); + bufParam.aL1BufIter++; +} + +/** + * @brief MatmulFullLoad A,B矩阵能够全载L1时的矩阵运算,用于mmQn; + * @param tensorAGm A矩阵在GM的位置 + * @param tensorBGm B矩阵在GM的位置 + * @param tensorCGm C矩阵在GM的位置 + * @param para 表示matmul形状信息的结构体参数 + * @param bufParam 管理L1 buffer地址和同步计数的结构体参数 + */ +template +__aicore__ inline void MatmulFullLoad(const GlobalTensor &tensorCGm, const GlobalTensor &tensorAGm, + const GlobalTensor &tensorBGm, const MMParams ¶, MMBufParams &bufParam) +{ + using O_L0C = typename std::conditional::value, int32_t, float>::type; + constexpr uint32_t aL1Offset = L1_A_SIZE / sizeof(T); + constexpr uint32_t bL1Offset = L1_B_SIZE / sizeof(T); + uint32_t mSize = Align(para.m, BLOCK_CUBE_SIZE); + + mmLocalTensors localTensors; + localTensors.Init(bufParam); + + LoadL1A(tensorAGm, para.m, para.k, para.orgKa, bufParam); + AscendC::WaitFlag((bufParam.aL1BufIter & 1u) + A_EVENT0); + LocalTensor aL1 = localTensors.aL1Tensor[aL1Offset * (bufParam.aL1BufIter & 1u)]; + + if constexpr (!hasL1BLoaded) { + LoadL1B(tensorBGm, para.n, para.n, para.k, para.k, bufParam); + AscendC::WaitFlag((bufParam.bL1BufIter & 1u) + B_EVENT0); + } + LocalTensor bL1 = localTensors.bL1Tensor[bL1Offset * (bufParam.bL1BufIter & 1u)]; + + uint32_t nSplitSize = 128; + uint32_t nloops = CeilDivT(para.n, nSplitSize); + uint32_t nSplitSizeAct = nSplitSize; + + MmadParams mmadParams = MmadParams(mSize, nSplitSizeAct, para.k, UNIT_FLAG_DISABLE, false, true); + + for (uint32_t n = 0; n < nloops; n++) { + if (n == nloops - 1) { + nSplitSizeAct = para.n - nSplitSize * (nloops - 1); + mmadParams.n = nSplitSizeAct; + } + // Perform matrix multiplication computation for current N-dimension split + if constexpr (enUnitFlag) { + mmadParams.unitFlag = UNIT_FLAG_SET; + } + AscendC::WaitFlag((bufParam.cL0BufIter & 1u) + L0C_EVENT0); + LocalTensor cL0 = localTensors.cL0Tensor[(bufParam.cL0BufIter & 1u) * (L0C_PP_SIZE / sizeof(O_L0C))]; + MatmulL0(bufParam, aL1, bL1[para.k * n * nSplitSize], localTensors.aL0Tensor, + localTensors.bL0Tensor, cL0, mmadParams, para.kL1StepSize); + GetTensorC(tensorCGm[n * nSplitSize], cL0, para.m, nSplitSizeAct, mSize, para.orgKc, + bufParam); + AscendC::SetFlag((bufParam.cL0BufIter & 1u) + L0C_EVENT0); + bufParam.cL0BufIter++; + } + + AscendC::SetFlag((bufParam.bL1BufIter & 1u) + B_EVENT0); + bufParam.bL1BufIter++; + AscendC::SetFlag((bufParam.aL1BufIter & 1u) + A_EVENT0); + bufParam.aL1BufIter++; +} + +} // namespace MlaProlog + + +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_rms_norm.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_rms_norm.h new file mode 100644 index 0000000000000000000000000000000000000000..5fd434d1ec59e3e4b521ee2ab83f5d530c44d6b8 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_rms_norm.h @@ -0,0 +1,140 @@ +/** + * 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 service_rms_norm.h + * \brief + */ + +#ifndef SERVICE_RMS_NORM_H +#define SERVICE_RMS_NORM_H + +#include "mla_prolog_comm.h" +#include "mla_prolog_vector_comm.h" + +#include "rms_norm.h" + +namespace MlaProlog { + +/** + * @brief RmsNormNormal rmsNorm流程 + * @param outputLocal 输出tensor,[B, S1, H] + * @param inputGm 输入tensor,[B, S1, H],dtype支持bf16,fp32,int32 + * @param gammaLocal 系数gamma [H],dtype只支持bf16 + * @param dequantScaleWDqLocal 权重w反量化系数 + * @param dequantScaleXLocal x反量化系数 + * @param shareTmpUb 临时buffer 所需空间[2 * cnt * sizeof(float) + ALIGN_BLOCK_SIZE] + ALIGN_BLOCK_SIZE = 32Bytes, cnt = row * col + * @param rmsNormParams rms所需系数,包括 + reciprocal rmsnorm系数reciprocal + epsilon rmsnorm系数epsilon + row 处理的行数;预留参数,当前仅支持单个batch的处理,row为1,对应S1 + col 列数,对应H + */ +template +__aicore__ inline void RmsNormNormal(const LocalTensor &outputLocal, const GlobalTensor &inputGm, + const LocalTensor &gammaLocal, + const LocalTensor &dequantScaleWDqLocal, + const LocalTensor &dequantScaleXLocal, + const LocalTensor &shareTmpUb, RmsNormParam &rmsNormParams) +{ + int64_t cnt = rmsNormParams.row * rmsNormParams.col; + LocalTensor xFp32Local = shareTmpUb.ReinterpretCast(); + + // load input [1, col] + DataCopyExtParams copyParams{1, static_cast(rmsNormParams.col * sizeof(T)), 0, 0, 0}; + DataCopyPadExtParams padParams{false, 0, 0, 0}; + + if constexpr (std::is_same::value) { + LocalTensor xInt32Local = shareTmpUb.ReinterpretCast(); + DataCopyPad(xInt32Local, inputGm, copyParams, padParams); + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + Rectangle rectangleParams{ + (uint32_t)rmsNormParams.row, (uint32_t)rmsNormParams.col, + (uint32_t)rmsNormParams.col // columnStride + }; + Dequant(xFp32Local, xInt32Local, dequantScaleWDqLocal, dequantScaleXLocal, rectangleParams); + AscendC::PipeBarrier(); + } else { + LocalTensor inputLocal = xFp32Local[rmsNormParams.col].template ReinterpretCast(); + DataCopyPad(inputLocal, inputGm, copyParams, padParams); + + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + // Cast input to fp32 [1, col] + Cast(xFp32Local, inputLocal, RoundMode::CAST_NONE, cnt); + AscendC::PipeBarrier(); + } + LocalTensor rmsnormShareUB = xFp32Local[rmsNormParams.col]; + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + + if constexpr (std::is_same::value) { + RmsNorm(outputLocal, xFp32Local, gammaLocal, rmsnormShareUB.template ReinterpretCast(), rmsNormParams); + AscendC::PipeBarrier(); + } else { + RmsNorm(xFp32Local, xFp32Local, gammaLocal, rmsnormShareUB.template ReinterpretCast(), rmsNormParams); + // Cast xFp32 to outputLocal + AscendC::PipeBarrier(); + Cast(outputLocal, xFp32Local, RoundMode::CAST_RINT, cnt); + AscendC::PipeBarrier(); + } +} + +/** + * @brief RmsNormDynamicQuant rmsNorm + dynamicQuant融合流程 + 目前C均为float + * @param outputLocal 输出tensor,[B, S1, H], 量化完后为int8 + * @param outputScales dynamicQuant计算系数输出 + * @param inputGm 输入tensor,[B, S1, H],dtype支持bf16,fp32,int32 + * @param gammaLocal 输入tensor,[H, ], dtype只支持bf16 + * @param smoothLocal dynamicQuant平滑参数 + * @param dequantScaleWDqLocal 权重w反量化系数 + * @param dequantScaleXLocal x反量化系数 + * @param shareTmpUb 临时buffer 所需空间[(4 * cnt + 8) * sizeof(float)] cnt = row * col + * @param rmsNormParams rms所需系数,包括 + reciprocal rmsnorm系数reciprocal + epsilon rmsnorm系数epsilon + row 处理的行数;预留参数,当前仅支持单个batch的处理,row为1,对应S1 + col 列数,对应H + * @param enableSmoothScalesCq 表示是否有smoothGm的需求 + */ +template +__aicore__ inline void +RmsNormDynamicQuant(const LocalTensor &outputLocal, const LocalTensor &outputScales, + const GlobalTensor &inputGm, const LocalTensor &gammaLocal, + const LocalTensor &smoothLocal, const LocalTensor &dequantScaleWDqLocal, + const LocalTensor &dequantScaleXLocal, const LocalTensor &shareTmpUb, + RmsNormParam &rmsNormParams, bool enableSmoothScalesCq = true) +{ + int64_t cnt = rmsNormParams.row * rmsNormParams.col; + LocalTensor xFp32Local = shareTmpUb.ReinterpretCast(); + RmsNormNormal(xFp32Local, inputGm, gammaLocal, dequantScaleWDqLocal, dequantScaleXLocal, + shareTmpUb[rmsNormParams.col * sizeof(C)], rmsNormParams); + AscendC::PipeBarrier(); + if (enableSmoothScalesCq) { + Mul(xFp32Local, xFp32Local, smoothLocal, cnt); + } + AscendC::PipeBarrier(); + LocalTensor maxInt8Tensor = shareTmpUb.ReinterpretCast()[cnt]; + int64_t rowAlign = Align(rmsNormParams.row, FP32_BLOCK_ELEMENT_NUM); + Duplicate(maxInt8Tensor, static_cast(127.0), rowAlign); + AscendC::PipeBarrier(); + DynamicQuant(xFp32Local, outputScales, xFp32Local, maxInt8Tensor, shareTmpUb[(cnt + rowAlign) * sizeof(C)], + rmsNormParams.row, rmsNormParams.col); + AscendC::PipeBarrier(); + CastFP32ToINT8(outputLocal, xFp32Local, shareTmpUb, cnt); + AscendC::PipeBarrier(); +} + +} // namespace MlaProlog + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_rope.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_rope.h new file mode 100644 index 0000000000000000000000000000000000000000..399853a9b5fcba756bdb64a07de9c50ffebbf02c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_rope.h @@ -0,0 +1,71 @@ +/** + * 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 service_rope.h + * \brief + */ + +#ifndef SERVICE_ROPE_H +#define SERVICE_ROPE_H + +namespace MlaProlog { +/** + * @brief RotaryPosEmb, 同时做row行的RotaryPosEmb,每一行的元素为col + * @param outputLocal 输出tensor [row * col],支持和inputLocal是同一块空间 + * @param inputLocal 输入tensor [row * col] + * @param cosLocal cos系数tensor [(row - 1) * sinCosRepStride + col] + * @param sinLocal sin系数tensor [(row - 1) * sinCosRepStride + col] - 1 应已在sin中 + * @param shareTmpUb 临时buffer 内部需要的空间为 [2 * row * col * sizeof(C)] + * @param row 待处理的行数 + * @param col 待处理的列数 col <= 512 / sizeof(C) + * @param sinCosRepStride 行与行之间sin/cos系数的偏移,单位为元素个数。 + */ +template +__aicore__ inline void RotaryPosEmb(const LocalTensor &outputLocal, const LocalTensor &inputLocal, + const LocalTensor &cosLocal, const LocalTensor &sinLocal, + const LocalTensor &shareTmpUb, uint64_t row, uint64_t col, + uint8_t sinCosRepStride) +{ + uint64_t cnt = row * col; + uint64_t rsvdCnt = 0; + LocalTensor reArrLocal = shareTmpUb.ReinterpretCast(); + LocalTensor outputLocalSinTmp = shareTmpUb.ReinterpretCast()[cnt]; + GatherMaskParams gatherMaskParams = { + 1, // repeatTimes + 1, // src0BlockStride + 0, // src0RepeatStride + 0 // src1RepeatStride + }; + // 取奇数索引元素 + GatherMask(reArrLocal, inputLocal, 1, true, col * row, gatherMaskParams, rsvdCnt); + // 取偶数索引元素 + GatherMask(reArrLocal[cnt >> 1], inputLocal, 2, true, col * row, gatherMaskParams, rsvdCnt); + AscendC::PipeBarrier(); + uint8_t blockNumPerRow = col / (ALIGN_BLOCK_SIZE / sizeof(C)); + uint8_t blockNumPerRowHalf = blockNumPerRow >> 1; + uint8_t blockNumSinCosRepStride = sinCosRepStride / (ALIGN_BLOCK_SIZE / sizeof(C)); + BinaryRepeatParams mulParams = { + 1, // dstBlkStrideIn + 1, // src0BlkStrideIn + 1, // src1BlkStrideIn + blockNumPerRow, // dstRepStrideIn + blockNumPerRowHalf, // src0RepStrideIn + blockNumSinCosRepStride // src1RepStrideIn + }; + Mul(outputLocal, reArrLocal, cosLocal, col >> 1, row, mulParams); + Mul(outputLocal[col >> 1], reArrLocal[cnt >> 1], cosLocal[col >> 1], col >> 1, row, mulParams); + Mul(outputLocalSinTmp, reArrLocal[cnt >> 1], sinLocal, col >> 1, row, mulParams); + Mul(outputLocalSinTmp[col >> 1], reArrLocal, sinLocal[col >> 1], col >> 1, row, mulParams); + AscendC::PipeBarrier(); + Add(outputLocal, outputLocal, outputLocalSinTmp, cnt); +} +} // namespace MlaProlog +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_rotary_position_embedding.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_rotary_position_embedding.h new file mode 100644 index 0000000000000000000000000000000000000000..cbe5256d929a67a610529b92537d6a696d15b139 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_rotary_position_embedding.h @@ -0,0 +1,203 @@ +/** + * 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 service_rotary_position_embedding.h + * \brief + */ + +#ifndef SERVICE_ROTARY_POSITION_EMBEDDING_H +#define SERVICE_ROTARY_POSITION_EMBEDDING_H + +#include "mla_prolog_comm.h" +#include "mla_prolog_vector_comm.h" +#include "service_rope.h" + +namespace MlaProlog { + +template +__aicore__ inline void PreprocessRopeInput(const GlobalTensor &inputGm, LocalTensor &shareTmpUb, + const Rectangle &ropeParams, LocalTensor &kFp32Local, + LocalTensor &kLocal, LocalTensor &ropeShareUB, + LocalTensor &kFp32OutputLocal, int64_t cnt) +{ + kLocal = shareTmpUb.ReinterpretCast(); + + int64_t baseOffset; + if constexpr (std::is_same::value) { + baseOffset = cnt; + } else { + baseOffset = cnt >> 1; + } + kFp32Local = shareTmpUb.ReinterpretCast()[baseOffset]; + + DataCopyExtParams copyParams{static_cast(ropeParams.row), + static_cast(sizeof(T) * ropeParams.col), + static_cast(sizeof(T) * (ropeParams.stride - ropeParams.col)), 0, 0}; + DataCopyPadExtParams padParams{false, 0, 0, 0}; + + if constexpr (std::is_same::value) { + DataCopyPad(kFp32Local, inputGm, copyParams, padParams); + } else { + DataCopyPad(kLocal, inputGm, copyParams, padParams); + } + ropeShareUB = shareTmpUb.ReinterpretCast()[baseOffset + cnt]; + // RotaryPosEmb内部需要 2*cnt + kFp32OutputLocal = shareTmpUb.ReinterpretCast()[baseOffset + cnt * 3]; +} + +/** + * @brief RotaryPosEmbPerTensor 对一个tensor进行RotartPosEmb,tensor的维度为[row * col] + 行与行之间sin/cos公用; + C:ropeComputType, float + * @param outputLocal 输出tensor + * @param inputGm 输入tensor + * @param cosLocal cos系数 + * @param sinLocal sin系数 + * @param shareTmpUb 临时buffer,需要大小为 cnt * 5 * sizeof(float) + * @param ropeParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + * @param channelDeqScaleGm 量化参数;该tensor的每个元素不同 + * @param scale 量化参数;该tensor共用 + */ +template +__aicore__ inline void RotaryPosEmbPerTensor(LocalTensor &outputLocal, const GlobalTensor &inputGm, + const LocalTensor &cosLocal, const LocalTensor &sinLocal, + LocalTensor &shareTmpUb, Rectangle ropeParams, + LocalTensor channelDeqScaleLocal = LocalTensor(), + LocalTensor scale = LocalTensor()) +{ + LocalTensor kLocal; + LocalTensor kFp32Local; + LocalTensor ropeShareUB; + LocalTensor kFp32OutputLocal; + int64_t cnt = ropeParams.row * ropeParams.col; + PreprocessRopeInput(inputGm, shareTmpUb, ropeParams, kFp32Local, kLocal, ropeShareUB, kFp32OutputLocal, cnt); + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + + if constexpr (std::is_same::value || enableDequant) { // 反量化 + Rectangle rectangleParams{(uint32_t)1, (uint32_t)cnt, (uint32_t)cnt}; // row, col, columnStride + if constexpr (std::is_same::value) { + Dequant(kFp32Local, kFp32Local, channelDeqScaleLocal, scale, rectangleParams); + } else { + Dequant(kFp32Local, kLocal, channelDeqScaleLocal, scale, rectangleParams); + } + AscendC::PipeBarrier(); + } else if constexpr (std::is_same::value) { + Cast(kFp32Local, kLocal, RoundMode::CAST_NONE, cnt); + AscendC::PipeBarrier(); + } + if constexpr (std::is_same::value) { + RotaryPosEmb(outputLocal, kFp32Local, cosLocal, sinLocal, ropeShareUB.template ReinterpretCast(), + ropeParams.row, ropeParams.col, 0); + AscendC::PipeBarrier(); + } else { + RotaryPosEmb(kFp32OutputLocal, kFp32Local, cosLocal, sinLocal, ropeShareUB.template ReinterpretCast(), + ropeParams.row, ropeParams.col, 0); + AscendC::PipeBarrier(); + Cast(outputLocal, kFp32OutputLocal, RoundMode::CAST_RINT, cnt); + AscendC::PipeBarrier(); + } +} + +/** + * @brief RotaryPosEmbPerHead 进行row行col列的RotaryPosEmb + 每行的量化系数,sin/cos均不同 + C:ropeComputType,float + * @param outputLocal 输出tensor + * @param inputGm 输入tensor + * @param cosLocal cos系数 + * @param sinLocal sin系数 + * @param shareTmpUb 临时buffer + * @param ropeParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + * @param strideScale 一段的真实长度,描述channelDeqScaledGm数据排布 + * @param channelDeqScaleGm 量化参数:最终使用shape[1,col] + * @param deQuantScale 量化参数;最终使用shape[row,8] + */ +template +__aicore__ inline void RotaryPosEmbPerHead(LocalTensor &outputLocal, const GlobalTensor &inputGm, + const LocalTensor &cosLocal, const LocalTensor &sinLocal, + LocalTensor &shareTmpUb, Rectangle ropeParams, int64_t strideScale, + GlobalTensor channelDeqScaleGm = GlobalTensor(), + LocalTensor deQuantScale = LocalTensor()) +{ + // 在 BS = 1 场景可能存在有row为零的情况,提前返回减少运算 + if (ropeParams.row == 0U) { + return; + } + + int64_t cnt = ropeParams.col * ropeParams.row; + LocalTensor kFp32Local; + LocalTensor kLocal; + LocalTensor ropeShareUB; + LocalTensor kFp32OutputLocal; + PreprocessRopeInput(inputGm, shareTmpUb, ropeParams, kFp32Local, kLocal, ropeShareUB, kFp32OutputLocal, cnt); + // scale参数可以和rope使用的空间复用 + LocalTensor scaleLocal = ropeShareUB; + AscendC::SetFlag(EVENT_ID0); + AscendC::WaitFlag(EVENT_ID0); + if constexpr (std::is_same::value || enableDequant) { // 反量化 + DataCopyExtParams copyParams1{static_cast(1), static_cast(ropeParams.col * sizeof(C)), + static_cast((strideScale - ropeParams.col) * sizeof(C)), 0, 0}; + DataCopyPadExtParams padParams1{false, 0, 0, 0}; + DataCopyPad(scaleLocal, channelDeqScaleGm, copyParams1, padParams1); // 复用内存 + AscendC::SetFlag(EVENT_ID1); + AscendC::WaitFlag(EVENT_ID1); + + uint8_t blockNumPerRow = ropeParams.col / (ALIGN_BLOCK_SIZE / sizeof(C)); + // row col stride + Rectangle rectangleParams{(uint32_t)ropeParams.row, (uint32_t)ropeParams.col, (uint32_t)ropeParams.col}; + if constexpr (std::is_same::value) { + Dequant(kFp32Local, kFp32Local, scaleLocal, deQuantScale, rectangleParams); + } else { + Dequant(kFp32Local, kLocal, scaleLocal, deQuantScale, rectangleParams); + } + } else if constexpr (std::is_same::value) { + Cast(kFp32Local, kLocal, RoundMode::CAST_NONE, cnt); + } + AscendC::PipeBarrier(); + RotaryPosEmb(kFp32OutputLocal, kFp32Local, cosLocal, sinLocal, ropeShareUB.template ReinterpretCast(), + ropeParams.row, ropeParams.col, ropeParams.col); + AscendC::PipeBarrier(); + + if constexpr (std::is_same::value) { + DataCopy(outputLocal, kFp32OutputLocal, cnt); + } else { + Cast(outputLocal, kFp32OutputLocal, RoundMode::CAST_RINT, cnt); + } + AscendC::PipeBarrier(); +} + +template +__aicore__ inline void RopePostQuantPerChannel(LocalTensor &outputLocal, LocalTensor &inputLocal, + LocalTensor &quantScaleLocal, LocalTensor &shareTmpUb, + int64_t cnt) +{ + LocalTensor inFp32; + if constexpr (!std::is_same::value) { + inFp32 = shareTmpUb.ReinterpretCast()[cnt]; + Cast(inFp32, inputLocal, RoundMode::CAST_NONE, cnt); + AscendC::PipeBarrier(); + } else { + inFp32 = inputLocal; + } + Mul(inFp32, inFp32, quantScaleLocal, cnt); + AscendC::PipeBarrier(); + CastFP32ToINT8(outputLocal, inFp32, shareTmpUb, cnt); + AscendC::PipeBarrier(); +} +} // namespace MlaProlog +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_scatter_cache.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_scatter_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..d1a0725ceef92765b3be7cd4e16e1ca67a28cd46 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch22/service_scatter_cache.h @@ -0,0 +1,123 @@ +/** + * 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 service_scatter_cache.h + * \brief + */ + +#ifndef SERVICE_SCATTER_CACHE_H +#define SERVICE_SCATTER_CACHE_H + +#include "mla_prolog_comm.h" + +namespace MlaProlog { +struct ScatterCacheParams { + int64_t blockSize; + int64_t paTokenIndex; + int64_t row; + int64_t col; + int64_t stride; + int64_t seqLength; + int64_t tokenIndex; +}; +/** + * @brief PA场景,将inputLocal中的数据scatter到cacheGm,支持ND和Nz cache + * @param cacheGm 输出tensor + * ND [blockNum, blockSize, col] + * Nz [blockNum, ceil(col/col0), blockSize, col0] + * @param inputLocal 输入tensor,[row, col],一行对应一个token,只支持单行数据处理,row为1 + * @param scatterCacheParams 所需相关参数,包括 + blockSize KV blocks的大小 + paTokenIndex 待处理token在cache中的全局index,取值[0, blockNum*blockSize) + row 待处理的行数 + col 待处理的列数,需满足32 bytes对齐 + */ + +template +__aicore__ inline void ScatterCacheUnAligned(const GlobalTensor &cacheGm, const LocalTensor &inputLocal, + const ScatterCacheParams &scatterCacheParams) +{ + if (scatterCacheParams.paTokenIndex < 0 && IS_NZ) { + return; + } + // blockCount, blockLen, srcStride, dstStride + DataCopyParams dataCopyParams{1, static_cast(scatterCacheParams.col * sizeof(T)), 0, 0}; + DataCopyPad(cacheGm[scatterCacheParams.paTokenIndex * scatterCacheParams.stride], inputLocal, dataCopyParams); +} + +template +__aicore__ inline void ScatterCacheMultiRows(GlobalTensor &cacheGm, const LocalTensor &inputLocal, + const ScatterCacheParams &scatterCacheParams, int64_t rowsInCurBatch, + int64_t cacheOffset, int64_t nextBatchOffset) +{ + if (cacheOffset < 0) { + return; + } + int64_t copyCnt = rowsInCurBatch * scatterCacheParams.col; + + if constexpr (IS_NZ) { + constexpr uint8_t col0 = ALIGN_BLOCK_SIZE / sizeof(T); + DataCopyParams copyParams{static_cast(scatterCacheParams.col / col0), 1, 0, + static_cast(scatterCacheParams.blockSize - 1)}; + DataCopy(cacheGm[cacheOffset], inputLocal, copyParams); + if (rowsInCurBatch != scatterCacheParams.row) { + for (int row = 0; row < scatterCacheParams.row - rowsInCurBatch; ++row) { + DataCopy(cacheGm[nextBatchOffset + col0 * row], inputLocal[copyCnt + col0 * row], copyParams); + } + } + } else { + DataCopy(cacheGm[cacheOffset], inputLocal, copyCnt); + if (rowsInCurBatch != scatterCacheParams.row) { + DataCopy(cacheGm[nextBatchOffset], inputLocal[copyCnt], + (scatterCacheParams.row - rowsInCurBatch) * scatterCacheParams.col); + } + } +} + +template +__aicore__ inline void ScatterCache(const GlobalTensor &cacheGm, const LocalTensor &inputLocal, + const ScatterCacheParams &scatterCacheParams) +{ + if (scatterCacheParams.paTokenIndex < 0) { + return; + } + if constexpr (IS_NZ) { + constexpr uint8_t col0 = ALIGN_BLOCK_SIZE / sizeof(T); + int64_t cacheOffset = scatterCacheParams.paTokenIndex / scatterCacheParams.blockSize * + scatterCacheParams.blockSize * scatterCacheParams.stride + + scatterCacheParams.paTokenIndex % scatterCacheParams.blockSize * col0; + DataCopyParams copyParams{static_cast(scatterCacheParams.col / col0), 1, 0, + static_cast(scatterCacheParams.blockSize - 1)}; + DataCopy(cacheGm[cacheOffset], inputLocal, copyParams); + } else { + DataCopy(cacheGm[scatterCacheParams.paTokenIndex * scatterCacheParams.stride], inputLocal, + scatterCacheParams.col); + } +} + +template +__aicore__ inline void MaterializeOffsetsWithHeadSize(int64_t pageTokenOffset, int64_t tokenOffsetInPage, + int64_t rowsThisStep, bool spill, int64_t nextPageId, + int64_t headSize, CkvkrParams &ckvkrParams) +{ + ckvkrParams.rowsInCurBatch = rowsThisStep; + if constexpr (!IS_NZ) { + ckvkrParams.cacheOffset = (tokenOffsetInPage + pageTokenOffset) * headSize; + } else { + constexpr uint8_t col0 = ALIGN_BLOCK_SIZE / sizeof(T); + ckvkrParams.cacheOffset = pageTokenOffset * headSize + tokenOffsetInPage * col0; + } + ckvkrParams.nextBatchOffset = (spill && nextPageId >= 0) ? nextPageId * headSize : 0; +} + +} // namespace MlaProlog + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/kernel_mla_prolog_split_m.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/kernel_mla_prolog_split_m.h new file mode 100644 index 0000000000000000000000000000000000000000..5177fee50b5aac985e3dcf7f29819ce657142a83 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/kernel_mla_prolog_split_m.h @@ -0,0 +1,1780 @@ +/** + * 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 kernel_mla_prolog_split_m.h + * \brief + */ + +#ifndef KERNEL_MLA_PROLOG_SPLIT_M_H +#define KERNEL_MLA_PROLOG_SPLIT_M_H + +#include "mla_prolog_comm.h" +#include "mla_prolog_vector_comm.h" +#include "service_matmul.h" +#include "service_rms_norm.h" +#include "service_gather_sin_cos.h" +#include "service_rotary_position_embedding.h" +#include "service_scatter_cache.h" +#include "service_dequant.h" +#include "service_dynamic_quant_qn_mul_qr.h" +#include "../mla_prolog_tiling_data.h" +#include "../mla_prolog_template_tiling_key.h" + +namespace MlaProlog { +template +class MlaPrologV3SplitM { +public: + static constexpr bool isPertile = MLAPT::isPertile; + + using mmInputType = typename MLAPT::mmInputType; + using mmQcQrInputType = typename MLAPT::mmQcQrInputType; + using mmQnInputType = typename MLAPT::mmQnInputType; + using mmCqOutputType = typename MLAPT::mmCqOutputType; + using mmCkvKrOutputType = typename MLAPT::mmCkvKrOutputType; + using mmQcQrOutputType = typename MLAPT::mmQcQrOutputType; + using mmQnOutputType = typename MLAPT::mmQnOutputType; + using rmsNormGammaType = typename MLAPT::rmsNormGammaType; + using rmsNormComputType = typename MLAPT::rmsNormComputType; + using rmsNormCqOutputType = typename MLAPT::rmsNormCqOutputType; + using rmsNormCkvOutputType = typename MLAPT::rmsNormCkvOutputType; + using ropeSinCosType = typename MLAPT::ropeSinCosType; + using ropeComputType = typename MLAPT::ropeComputType; + using ropeOutputType = typename MLAPT::ropeOutputType; + using queryOutputType = typename std::conditional::type; + using kvCacheType = typename MLAPT::kvCacheType; + using krCacheType = typename MLAPT::krCacheType; + using dequantScaleQNopeType = typename MLAPT::dequantScaleQNopeType; + using dequantScaleQNormType = typename MLAPT::dequantScaleQNormType; + using dequantScaleType = typename MLAPT::dequantScaleType; + + MMParams mmCqParam_; + MMParams mmCkvKrParam_; + MMParams mmQcQrParam_; + MMParams mmQnParam_; + + __aicore__ inline MlaPrologV3SplitM(TPipe *pipe, const optiling::MlaPrologTilingData *__restrict tilingData, + const optiling::MlaPrologBaseParams *__restrict baseParams) + : pipe_(pipe), tilingData_(tilingData), baseParams_(baseParams) + { + } + + __aicore__ inline void Init(__gm__ uint8_t *tokenX, __gm__ uint8_t *weightDq, __gm__ uint8_t *weightUqQr, + __gm__ uint8_t *weightUk, __gm__ uint8_t *weightDkvKr, __gm__ uint8_t *rmsnormGammaCq, + __gm__ uint8_t *rmsnormGammaCkv, __gm__ uint8_t *ropeSin, __gm__ uint8_t *ropeCos, + __gm__ uint8_t *cacheIndex, __gm__ uint8_t *kvCache, __gm__ uint8_t *krCache, + __gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *deqScaleQcQrW, __gm__ uint8_t *dequantScaleWDkvkr, + __gm__ uint8_t *quantScaleCkv, __gm__ uint8_t *quantScaleCkr, + __gm__ uint8_t *smoothScaleCq, __gm__ uint8_t *actualSeqLen, + __gm__ uint8_t *kNopeClipAlpha, __gm__ uint8_t *queryOut, __gm__ uint8_t *queryRopeOut, + __gm__ uint8_t *dequantScaleQNopeOut, __gm__ uint8_t *queryNormOut, + __gm__ uint8_t *dequantScaleQNormOut, __gm__ uint8_t *workspace); + __aicore__ inline void Process(); + +private: + __aicore__ inline void CopyGlobalParams(); + __aicore__ inline void OutputInit(__gm__ uint8_t *actualSeqLen, __gm__ uint8_t *queryOut, + __gm__ uint8_t *queryRopeOut, __gm__ uint8_t *dequantScaleQNopeOut, + __gm__ uint8_t *queryNormOut, __gm__ uint8_t *dequantScaleQNormOut); + __aicore__ inline void ScaleInit(__gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *deqScaleQcQrW, __gm__ uint8_t *dequantScaleWDkvkr, + __gm__ uint8_t *quantScaleCkv, __gm__ uint8_t *quantScaleCkr, + __gm__ uint8_t *smoothScaleCq, __gm__ uint8_t *kNopeClipAlpha); + __aicore__ inline void WorkspaceInit(__gm__ uint8_t *workspace); + __aicore__ inline void MmParamInit(); + __aicore__ inline void MmCqParamInit(); + __aicore__ inline void MmCkvKrParamInit(); + __aicore__ inline void MmQcQrParamInit(); + __aicore__ inline void MmQnParamInit(); + __aicore__ inline void CubeBufferInit(); + __aicore__ inline void VectorBufferInit(); + __aicore__ inline void UpdateStepBatchParams(int64_t curMSize); + __aicore__ inline void ComputeBlkScatterOffsets(GlobalTensor indexGm, int64_t tokenIndex, int64_t rows, + CkvkrParams &rmsNormAndScatterCkvParams, + CkvkrParams &ropeAndScatterKrParams); + template + __aicore__ inline void AicProcess(AicOffset &aicOffset, int64_t batchOffset, int64_t mmQnLoops); + template + __aicore__ inline void AivProcess(AivOffset &aivOffset, int64_t batchOffset, int64_t curMSize, + int64_t numHeadOffset, int64_t mmQnLoops); + template + __aicore__ inline void + MatmulSplitM(const GlobalTensor &tensorResGm, const GlobalTensor &tensorAGm, const GlobalTensor &tensorBGm, + const MMParams &mmPara, const UsedBlockParams &mmBlockParams, + const GlobalTensor &tensorAScaleGm = {}, const GlobalTensor &tensorBScaleGm = {}); + __aicore__ inline void MatmulQcQr(AicOffset &aicOffset); + template + __aicore__ inline void MatmulQnSyncDynamicQuantAndMulQr(int64_t qcOffset, int64_t weightUkOffset, + int64_t qnResOffset, int64_t mmQnLoops); + __aicore__ inline void CopyInSinCos(int64_t tokenIndex, int64_t curVecToken, int64_t batchOffset, int64_t curMSize); + __aicore__ inline void RmsNormCq(int64_t tokenIndex, int64_t rmsNormCqOffset, int64_t rmsNormCqResOffset, + int64_t curVecToken, int64_t curBlockTokenOffset); + __aicore__ inline void RopeAndScatterKr(LocalTensor &dequantScaleXLocal, LocalTensor &shareTmpUb, + LocalTensor &cosLocalCkvKr, + LocalTensor &sinLocalCkvKr, + CkvkrParams ropeAndScatterKrParams); + __aicore__ inline void ScatterKr(LocalTensor &outputKrLocal, CkvkrParams ropeAndScatterKrParams); + __aicore__ inline void RmsNormAndScatterCkv(LocalTensor &dequantScaleXLocal, + LocalTensor &shareTmpUb, + LocalTensor &cosLocalCkvKr, + LocalTensor &sinLocalCkvKr, + CkvkrParams rmsNormAndScatterCkvParams); + __aicore__ inline void RmsNormAndQuantizeCkv(LocalTensor &outputLocal, + LocalTensor &rmsNormShareTmpUb, + LocalTensor &dequantScaleXLocal, RmsNormParam rmsNormParams, + CkvkrParams rmsNormAndScatterCkvParams); + __aicore__ inline void ScatterCkv(LocalTensor &outputLocal, CkvkrParams rmsNormAndScatterCkvParams); + __aicore__ inline void RmsNormRopeScatterCkvKr(int64_t tokenIndex, int64_t rmsNormCkvOffset, int64_t ropeKrOffset, + int64_t curVecToken); + // 低时延算力分组场景 + __aicore__ inline void QcQrSplit(int64_t curVecToken, int64_t curBlockTokenOffset, int64_t curMSize, + int64_t mmQnPreDequantOffset, int64_t mmQnPreDequantResOffset, + int64_t ropeQrOffset, int64_t ropeQrResOffset); + __aicore__ inline void DynamicQuantQnAndMulQrSyncMMQn(int64_t batchOffset, int64_t curMSize, int64_t numHeadOffset, + int64_t mmQnLoops); + +private: + TPipe *pipe_; + const optiling::MlaPrologTilingData *__restrict tilingData_; + const optiling::MlaPrologBaseParams *__restrict baseParams_; + uint32_t blockIdx_ = 0U; + uint32_t cubeBlockIdx_ = 0U; // AIV上使用AIC的blockIdx + int64_t vectorRow_ = 1; + int64_t curVectorBlockNum_; + int64_t vectorCoreNum_; + uint64_t dequantScaleCqSize_ = 1; + uint32_t curStepVecFrontToken_; + uint32_t curStepVecFrontListNum_; + uint32_t curStepVecBackToken_; + uint32_t curVecTokenMax_; + bool enableSmoothScalesCq_; + static constexpr uint32_t cvRatio_ = MLAPT::cvRatio; // 默认cv 1:2 + static constexpr bool isFp8E8m0 = std::is_same::value; + + uint32_t mSubSize_ = 0; + uint32_t mOffsetStart_ = 0; + + struct DequantTool { + GlobalTensor deQuantScaleCqGm_; + TBuf deQuantScaleCqBuffer_; // 用于临时存储每一行的Scale,以及汇总最终每一行的Scale参数 + LocalTensor deQuantScaleCqLocal_; + __aicore__ inline DequantTool() + { + } + }; + + // 算子分组开关 + DequantTool dequantTool_; + + // GM + GlobalTensor tokenXGm_; + GlobalTensor weightDqGm_; + GlobalTensor weightUqQrGm_; + GlobalTensor weightUkGm_; + GlobalTensor weightDkvKrGm_; + GlobalTensor rmsnormGammaCqGm_; + GlobalTensor rmsnormGammaCkvGm_; + GlobalTensor ropeSinGm_; + GlobalTensor ropeCosGm_; + GlobalTensor cacheIndexGm_; + GlobalTensor kvCacheGm_; + GlobalTensor krCacheGm_; + GlobalTensor qrOutGm_; + + GlobalTensor dequantScaleXGm_; + GlobalTensor dequantScaleWDqGm_; + GlobalTensor dequantScaleWDkvkrGm_; + GlobalTensor smoothScaleCqGm_; + GlobalTensor deqScaleQcQrW_; // per-channel反量化参数 + GlobalTensor quantScaleCkvGm_; + GlobalTensor quantScaleCkrGm_; + + GlobalTensor actualSeqLenGm_; + GlobalTensor kNopeClipAlphaGm_; + + GlobalTensor rmsNormCqResGm_; + GlobalTensor mmCqResGm_; + GlobalTensor mmCkvKrResGm_; + GlobalTensor mmQcQrResGm_; + GlobalTensor mmQcQrResDequantGm_; + GlobalTensor mmQnResGm_; + GlobalTensor dequantScaleQNopeGm_; + GlobalTensor queryOutGm_; + GlobalTensor dequantScaleQNormGm_; + + // UB + TBuf sincosBuffer_; + TBuf shareBuffer_; + TBuf dequantScaleWDqBuffer_; + TBuf dequantScaleWDkvKrBuffer_; + TBuf rmsnormGammaCqBuffer_; + TBuf rmsnormGammaCkvBuffer_; + TBuf smoothScaleCqBuffer_; + TBuf quantScaleCkvBuffer_; + TBuf quantScaleCkrBuffer_; + TBuf stepActualSeqBuffer_; + + LocalTensor cosLocal_; + LocalTensor sinLocal_; + LocalTensor dequantScaleWDqLocal_; + LocalTensor dequantScaleWDkvKrLocal_; + LocalTensor rmsnormGammaCqLocal_; + LocalTensor rmsnormGammaCkvLocal_; + LocalTensor smoothScaleCqLocal_; + LocalTensor quantScaleCkvLocal_; + LocalTensor quantScaleCkrLocal_; + LocalTensor stepActualSeqLocal_; + + struct ActSeqState { + bool inited = false; // whether state is initialized for the run + int64_t curBatch = 0; // current batch index for the running token index + int64_t prevPrefix = 0; // prefix sum of seq lengths up to (curBatch - 1) + int64_t curPrefix = 0; // prefix sum of seq lengths up to curBatch (exclusive high bound) + int64_t prevIndexOffset = 0; // prefix sum of blocks up to (curBatch - 1) + int64_t curIndexOffset = 0; // prefix sum of blocks up to curBatch + }; + ActSeqState actSeqState_; + int64_t blockSpanPerBatch_ = 0; // blockNum * blockSize + + TBuf aBufL1_; + TBuf bBufL1_; + LocalTensor aL1Tensor_; + LocalTensor bL1Tensor_; + MMBufParams bufParam_; + TBuf aBufL0_; + TBuf bBufL0_; + TBuf cBufL0_; + TBuf zeroBuf_; + LocalTensor zeroSrc_; +}; + + +template +__aicore__ inline void MlaPrologV3SplitM::Init( + __gm__ uint8_t *tokenX, __gm__ uint8_t *weightDq, __gm__ uint8_t *weightUqQr, __gm__ uint8_t *weightUk, + __gm__ uint8_t *weightDkvKr, __gm__ uint8_t *rmsnormGammaCq, __gm__ uint8_t *rmsnormGammaCkv, + __gm__ uint8_t *ropeSin, __gm__ uint8_t *ropeCos, __gm__ uint8_t *cacheIndex, __gm__ uint8_t *kvCache, + __gm__ uint8_t *krCache, __gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *deqScaleQcQrW, __gm__ uint8_t *dequantScaleWDkvkr, __gm__ uint8_t *quantScaleCkv, + __gm__ uint8_t *quantScaleCkr, __gm__ uint8_t *smoothScaleCq, __gm__ uint8_t *actualSeqLen, + __gm__ uint8_t *kNopeClipAlpha, __gm__ uint8_t *queryOut, __gm__ uint8_t *queryRopeOut, + __gm__ uint8_t *dequantScaleQNopeOut, __gm__ uint8_t *queryNormOut, __gm__ uint8_t *dequantScaleQNormOut, + __gm__ uint8_t *workspace) +{ + blockIdx_ = GetBlockIdx(); // cube:0-23 vec:0-47 + if ASCEND_IS_AIV { + cubeBlockIdx_ = blockIdx_ / cvRatio_; + } else { + cubeBlockIdx_ = blockIdx_; + } + curVectorBlockNum_ = static_cast(baseParams_->stepBatchSize); + vectorCoreNum_ = static_cast(baseParams_->vectorBlockNum); + curVecTokenMax_ = (curVectorBlockNum_ + vectorCoreNum_ - 1) / vectorCoreNum_; + enableSmoothScalesCq_ = smoothScaleCq == nullptr ? false : true; + // GM + tokenXGm_.SetGlobalBuffer((__gm__ mmInputType *)tokenX); + weightDqGm_.SetGlobalBuffer((__gm__ mmInputType *)weightDq); // NZ + weightUqQrGm_.SetGlobalBuffer((__gm__ mmQcQrInputType *)weightUqQr); // NZ + weightUkGm_.SetGlobalBuffer((__gm__ mmQnInputType *)weightUk); + weightDkvKrGm_.SetGlobalBuffer((__gm__ mmInputType *)weightDkvKr); // NZ + rmsnormGammaCqGm_.SetGlobalBuffer((__gm__ rmsNormGammaType *)rmsnormGammaCq); + rmsnormGammaCkvGm_.SetGlobalBuffer((__gm__ rmsNormGammaType *)rmsnormGammaCkv); + ropeSinGm_.SetGlobalBuffer((__gm__ ropeSinCosType *)ropeSin); + ropeCosGm_.SetGlobalBuffer((__gm__ ropeSinCosType *)ropeCos); + if constexpr (MLAPT::cacheMode != CACHE_MODE::ND) { + cacheIndexGm_.SetGlobalBuffer((__gm__ int64_t *)cacheIndex); + } + kvCacheGm_.SetGlobalBuffer((__gm__ kvCacheType *)kvCache); + krCacheGm_.SetGlobalBuffer((__gm__ krCacheType *)krCache); + + OutputInit(actualSeqLen, queryOut, queryRopeOut, dequantScaleQNopeOut, queryNormOut, dequantScaleQNormOut); + ScaleInit(dequantScaleX, dequantScaleWDq, deqScaleQcQrW, dequantScaleWDkvkr, quantScaleCkv, quantScaleCkr, + smoothScaleCq, kNopeClipAlpha); + MmParamInit(); + WorkspaceInit(workspace); + if ASCEND_IS_AIV { + VectorBufferInit(); + } else { + CubeBufferInit(); + constexpr int64_t zeroChunk = 512; + pipe_->InitBuffer(zeroBuf_, zeroChunk * sizeof(float)); + zeroSrc_ = zeroBuf_.Get(); + Duplicate(zeroSrc_, static_cast(0), zeroChunk); + } +} + +template +__aicore__ inline void +MlaPrologV3SplitM::OutputInit(__gm__ uint8_t *actualSeqLen, __gm__ uint8_t *queryOut, + __gm__ uint8_t *queryRopeOut, __gm__ uint8_t *dequantScaleQNopeOut, + __gm__ uint8_t *queryNormOut, __gm__ uint8_t *dequantScaleQNormOut) +{ + qrOutGm_.SetGlobalBuffer((__gm__ ropeOutputType *)queryRopeOut); + if constexpr (((std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value)) && + !isPertile) { + dequantScaleQNopeGm_.SetGlobalBuffer((__gm__ dequantScaleQNopeType *)dequantScaleQNopeOut); + queryOutGm_.SetGlobalBuffer((__gm__ queryOutputType *)queryOut); + } else { + mmQnResGm_.SetGlobalBuffer((__gm__ mmQnOutputType *)queryOut); + } + if (baseParams_->queryNormFlag == 1U) { + rmsNormCqResGm_.SetGlobalBuffer((__gm__ mmQcQrInputType *)queryNormOut); + if constexpr (IsFullQuantMode()) { + dequantScaleQNormGm_.SetGlobalBuffer((__gm__ dequantScaleQNormType *)dequantScaleQNormOut); + } + } + if constexpr (MLAPT::actualSeqMode == ACTUAL_SEQ_MODE::EN_Q_LEN) { + actualSeqLenGm_.SetGlobalBuffer((__gm__ int32_t *)actualSeqLen); + } +} + +template +__aicore__ inline void +MlaPrologV3SplitM::ScaleInit(__gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *deqScaleQcQrW, __gm__ uint8_t *dequantScaleWDkvkr, + __gm__ uint8_t *quantScaleCkv, __gm__ uint8_t *quantScaleCkr, + __gm__ uint8_t *smoothScaleCq, __gm__ uint8_t *kNopeClipAlpha) +{ + if constexpr (IsFullQuantMode()) { + dequantScaleXGm_.SetGlobalBuffer((__gm__ dequantScaleType *)dequantScaleX); + dequantScaleWDqGm_.SetGlobalBuffer((__gm__ dequantScaleType *)dequantScaleWDq); + dequantScaleWDkvkrGm_.SetGlobalBuffer((__gm__ dequantScaleType *)dequantScaleWDkvkr); + } + if constexpr (std::is_same::value && isFp8E8m0) { + deqScaleQcQrW_.SetGlobalBuffer((__gm__ dequantScaleType *)deqScaleQcQrW); + quantScaleCkvGm_.SetGlobalBuffer((__gm__ float *)quantScaleCkv); + } + + if constexpr (isPertile) { + kNopeClipAlphaGm_.SetGlobalBuffer((__gm__ float *)kNopeClipAlpha); + } +} + +template +__aicore__ inline void MlaPrologV3SplitM::MmParamInit() +{ + MmCqParamInit(); + MmCkvKrParamInit(); + MmQcQrParamInit(); + MmQnParamInit(); +} + +template +__aicore__ inline void MlaPrologV3SplitM::MmCqParamInit() +{ + mmCqParam_.m = baseParams_->stepBatchSize; + mmCqParam_.n = baseParams_->mm1SingleCoreN; // 1536 / 24 = 64 + mmCqParam_.k = baseParams_->headSizeX; // 7168 + mmCqParam_.needSetOrgShape = 1; + mmCqParam_.orgM = mmCqParam_.m; + mmCqParam_.orgN = mmCqParam_.n; + mmCqParam_.orgKa = mmCqParam_.k; + mmCqParam_.orgKb = mmCqParam_.k; + mmCqParam_.orgKc = baseParams_->headSizeCq; // 1536 + mmCqParam_.baseK = + (sizeof(mmInputType) == ONE_BYTE_TYPE_SIZE) ? 256 : 128; // 128KB / (128 max baseN * 4 stepK * sizeof(type)) + mmCqParam_.baseN = (std::is_same::value && isFp8E8m0) ? 64 : 128; + mmCqParam_.stepK = 4; + if ((mmCqParam_.k / mmCqParam_.baseK) % mmCqParam_.stepK != 0) { + mmCqParam_.stepK = 3; // support k = 7680, mmInputType int8, no tail + } + mmCqParam_.kL1StepSize = mmCqParam_.baseK * mmCqParam_.stepK; + mmCqParam_.kScale = mmCqParam_.k / FP8_E4M3_BLOCK_SIZE; +} + +template +__aicore__ inline void MlaPrologV3SplitM::MmCkvKrParamInit() +{ + mmCkvKrParam_.m = baseParams_->stepBatchSize; + mmCkvKrParam_.n = baseParams_->mm2SingleCoreN; + mmCkvKrParam_.k = baseParams_->headSizeX; // 7168 + mmCkvKrParam_.needSetOrgShape = 1; + mmCkvKrParam_.orgM = mmCkvKrParam_.m; + mmCkvKrParam_.orgN = mmCkvKrParam_.n; + mmCkvKrParam_.orgKa = mmCkvKrParam_.k; + mmCkvKrParam_.orgKb = mmCkvKrParam_.k; + mmCkvKrParam_.orgKc = (baseParams_->headSizeCkv + baseParams_->dimHeadRope); // 576 + mmCkvKrParam_.baseK = + (sizeof(mmInputType) == sizeof(int8_t)) ? 256 : 128; // 128KB / (128 max baseN * 4 stepK * sizeof(type)) + mmCkvKrParam_.baseN = (std::is_same::value && isFp8E8m0) ? 64 : 128; + mmCkvKrParam_.stepK = 4; + if ((mmCkvKrParam_.k / mmCkvKrParam_.baseK) % mmCkvKrParam_.stepK != 0) { + mmCkvKrParam_.stepK = 3; // support k = 7680, mmInputType int8, no tail + } + mmCkvKrParam_.kL1StepSize = mmCkvKrParam_.baseK * mmCkvKrParam_.stepK; + mmCkvKrParam_.kScale = mmCkvKrParam_.k / FP8_E4M3_BLOCK_SIZE; +} + +template +__aicore__ inline void MlaPrologV3SplitM::MmQcQrParamInit() +{ + mmQcQrParam_.m = baseParams_->stepBatchSize; + mmQcQrParam_.n = baseParams_->mm3SingleCoreN; + mmQcQrParam_.k = baseParams_->headSizeCq; // 1536 + mmQcQrParam_.needSetOrgShape = 1; + mmQcQrParam_.orgM = mmQcQrParam_.m; + mmQcQrParam_.orgN = mmQcQrParam_.n; + mmQcQrParam_.orgKa = mmQcQrParam_.k; + mmQcQrParam_.orgKb = mmQcQrParam_.k; + mmQcQrParam_.orgKc = (baseParams_->headSizeQc + baseParams_->headSizeQr); // (128 * 32 + 64 * 32) + mmQcQrParam_.baseK = (sizeof(mmQcQrInputType) == sizeof(int8_t)) ? 128 : 64; + if constexpr (MLAPT::enableGroupComputeOpt) { + mmQcQrParam_.baseN = 128; + } else { + mmQcQrParam_.baseN = 128; + } + mmQcQrParam_.stepK = 4; + mmQcQrParam_.kL1StepSize = mmQcQrParam_.baseK * mmQcQrParam_.stepK; + mmQcQrParam_.kScale = mmQcQrParam_.k / FP8_E4M3_BLOCK_SIZE; +} + + +template +__aicore__ inline void MlaPrologV3SplitM::MmQnParamInit() +{ + mmQnParam_.m = baseParams_->stepBatchSize; + mmQnParam_.n = baseParams_->headSizeCkv; // 512 + mmQnParam_.k = baseParams_->dimHeadSizeQc; // 128, 这里numHeadSize被分核,matmul设置里不体现 + mmQnParam_.needSetOrgShape = 1; + mmQnParam_.orgM = mmQnParam_.m; + mmQnParam_.orgN = mmQnParam_.n; + if constexpr (std::is_same::value || std::is_same::value) { + mmQnParam_.orgKa = baseParams_->headSizeQc; + } else { + mmQnParam_.orgKa = baseParams_->headSizeQc + baseParams_->headSizeQr; + } + mmQnParam_.orgKb = baseParams_->dimHeadSizeQc; + mmQnParam_.orgKc = baseParams_->headSizeCkv * baseParams_->numHeadSize; + mmQnParam_.baseN = 128; + mmQnParam_.baseK = 128; + mmQnParam_.stepK = 1; + if ((mmQnParam_.k > mmQnParam_.baseK) && (mmQnParam_.k % mmQnParam_.baseK != 0)) { + mmQnParam_.baseK = 64; + mmQnParam_.stepK = 3; // support D = 192 + } + mmQnParam_.kL1StepSize = mmQnParam_.baseK * mmQnParam_.stepK; + mmQnParam_.kScale = mmQnParam_.k / FP8_E4M3_BLOCK_SIZE; +} + +template +__aicore__ inline void MlaPrologV3SplitM::VectorBufferInit() +{ + pipe_->InitBuffer(rmsnormGammaCqBuffer_, baseParams_->headSizeCq * sizeof(rmsNormGammaType)); // [1, 1536] bf16 + rmsnormGammaCqLocal_ = rmsnormGammaCqBuffer_.Get(); + + pipe_->InitBuffer(rmsnormGammaCkvBuffer_, baseParams_->headSizeCkv * sizeof(rmsNormGammaType)); // [1, 512] bf16 + rmsnormGammaCkvLocal_ = rmsnormGammaCkvBuffer_.Get(); + + if constexpr (std::is_same::value) { + pipe_->InitBuffer(quantScaleCkrBuffer_, baseParams_->dimHeadRope * sizeof(float)); // [1, 64] + quantScaleCkrLocal_ = quantScaleCkrBuffer_.Get(); + } + + if constexpr (IsFullQuantMode()) { + if constexpr (std::is_same::value || + (std::is_same::value && !isFp8E8m0)) { + pipe_->InitBuffer(quantScaleCkvBuffer_, ALIGN_BLOCK_SIZE); + } else { + pipe_->InitBuffer(quantScaleCkvBuffer_, baseParams_->headSizeCkv * sizeof(float)); // [1, 512] + } + quantScaleCkvLocal_ = quantScaleCkvBuffer_.Get(); + } + + // 预留brcb的空间 + pipe_->InitBuffer(dequantTool_.deQuantScaleCqBuffer_, (baseParams_->stepBatchSize + 7) * ALIGN_BLOCK_SIZE); + dequantTool_.deQuantScaleCqLocal_ = dequantTool_.deQuantScaleCqBuffer_.template Get(); + + if constexpr (MLAPT::enableDequantOpt) { + // 在ropeQr进行切M处理后,会复用shareBuffer的内存,不需要额外申请 + // 开启开关后会按照head切分rope qr,此时需要加载一半batchsize数量的sin和cos值 + // 需要2倍的空间分别存储sin和cos + pipe_->InitBuffer(sincosBuffer_, 2 * baseParams_->dimHeadRope * sizeof(ropeComputType) * + ((baseParams_->stepBatchSize + 1) >> 1)); + } else { + // 需要2倍的空间分别存储sin和cos + pipe_->InitBuffer(sincosBuffer_, + 2 * baseParams_->dimHeadRope * sizeof(ropeComputType) * curVecTokenMax_); // [2, 64] float + } + + uint64_t usedAddr; + if constexpr (MLAPT::enableDequantOpt) { + cosLocal_ = sincosBuffer_.Get(); + sinLocal_ = cosLocal_[baseParams_->dimHeadRope * ((baseParams_->stepBatchSize + 1) >> 1)]; + usedAddr = reinterpret_cast( + sinLocal_[baseParams_->dimHeadRope * ((baseParams_->stepBatchSize + 1) >> 1)].GetPhyAddr()); + } else { + cosLocal_ = sincosBuffer_.Get(); + sinLocal_ = cosLocal_[baseParams_->dimHeadRope * curVecTokenMax_]; + usedAddr = reinterpret_cast(sinLocal_[baseParams_->dimHeadRope * curVecTokenMax_].GetPhyAddr()); + } + + constexpr int64_t zeroChunk = 512; + pipe_->InitBuffer(zeroBuf_, zeroChunk * sizeof(float)); + zeroSrc_ = zeroBuf_.Get(); + Duplicate(zeroSrc_, static_cast(0), zeroChunk); + + // 由于shareBuffer属于各个vector操作临时申请内存的区域内存使用不固定,建议shareBuffer始终放在最后,防止写入shareBuffer越界导致前面固定申请的UB内存被踩。 + pipe_->InitBuffer(shareBuffer_, MAX_UB_SIZE - usedAddr - zeroChunk * sizeof(float)); +} + +template +__aicore__ inline void MlaPrologV3SplitM::CubeBufferInit() +{ + // cube相关Buffer初始化 + pipe_->InitBuffer(aBufL1_, L1_A_SIZE * 2); + pipe_->InitBuffer(bBufL1_, L1_B_SIZE * 2); + + SetFlag(A_EVENT0); + SetFlag(A_EVENT1); + SetFlag(B_EVENT0); + SetFlag(B_EVENT1); + aL1Tensor_ = aBufL1_.Get(); + bL1Tensor_ = bBufL1_.Get(); + bufParam_.aL1BufAddr = aBufL1_.GetBufferAddr(aL1Tensor_.GetBufferHandle()); + bufParam_.bL1BufAddr = bBufL1_.GetBufferAddr(bL1Tensor_.GetBufferHandle()); + + pipe_->InitBuffer(aBufL0_, L0A_PP_SIZE * 2); // 64K + pipe_->InitBuffer(bBufL0_, L0B_PP_SIZE * 2); // 64K + pipe_->InitBuffer(cBufL0_, L0C_PP_SIZE * 2); // 128K + + SetFlag(L0A_EVENT0); + SetFlag(L0A_EVENT1); + SetFlag(L0B_EVENT0); + SetFlag(L0B_EVENT1); + + SetFlag(L0C_EVENT0); + SetFlag(L0C_EVENT1); + + SetFlag(SCALE_EVENT); + + bufParam_.aL0BufAddr = aBufL0_.GetBufferAddr(aBufL0_.Get().GetBufferHandle()); + bufParam_.bL0BufAddr = bBufL0_.GetBufferAddr(bBufL0_.Get().GetBufferHandle()); + bufParam_.cL0BufAddr = cBufL0_.GetBufferAddr(cBufL0_.Get().GetBufferHandle()); +} + +/* + * workspace管理 + * 1. 常驻:dequantTool_.deQuantScaleCqGm_ stepBs * 32 Byte + * 2. 中间结果: + * tokenXGm_──────>mmCkvKrResGm_ + * | [stepBS, HCkv + Dr] + * | (bf16 | int32) + * └─────────>mmCqResGm_──────>rmsNormCqResGm_──────>mmQcQrResGm_──────>mmQcQrResDequantGm_──────>mmQnResGm_ + * [stepBS, HCq] [stepBS, HCq] [stepBS, N1, D + Dr] [stepBS, N1, D] [stepBS, N1, + * HCkv] (bf16 | int32) (bf16 | int8) (bf16 | int32) (bf16) (bf16) + */ +template +__aicore__ inline void MlaPrologV3SplitM::WorkspaceInit(__gm__ uint8_t *workspace) +{ + int64_t workspaceOffset = 0; + if constexpr (std::is_same::value && isFp8E8m0) { + dequantScaleCqSize_ = baseParams_->headSizeCq / FP8_E4M3_BLOCK_SIZE; + } + dequantScaleCqSize_ = Align(dequantScaleCqSize_, BYTE_BLOCK); + + if constexpr (MLAPT::enableGroupComputeOpt || MLAPT::enableDequantOpt) { + dequantTool_.deQuantScaleCqGm_.SetGlobalBuffer((__gm__ dequantScaleType *)(workspace + workspaceOffset)); + workspaceOffset += baseParams_->stepBatchSize * dequantScaleCqSize_ * baseParams_->mm1BlockNum; + } + // query_norm_flag有影响 + mmCqResGm_.SetGlobalBuffer((__gm__ mmCqOutputType *)(workspace + workspaceOffset)); // aicOffset.cqResOffset + if (baseParams_->queryNormFlag == 0U) { + // 全量化场景下`mmCqResGm_`与`rmsNormCqResGm_`的dtype不同,无法共用workspace,此处需要偏移`mmCqResGm_`占用的大小; + if constexpr (!std::is_same::value) { + workspaceOffset += static_cast(baseParams_->stepBatchSize) * + static_cast(baseParams_->headSizeCq) * baseParams_->mm1BlockNum * + static_cast(sizeof(mmCqOutputType)); + } + // 不返回queryNorm时,rmsNormCq结果放在workspace + rmsNormCqResGm_.SetGlobalBuffer((__gm__ rmsNormCqOutputType *)(workspace + workspaceOffset)); + workspaceOffset += static_cast(baseParams_->stepBatchSize) * baseParams_->mm1BlockNum * + static_cast(baseParams_->headSizeCq) * sizeof(rmsNormCqOutputType); + } else { + // 返回queryNorm时,rmsNormCq结果直接输出gm,此处需要偏移`mmCqResGm_`占用的大小 + workspaceOffset += static_cast(baseParams_->stepBatchSize) * + static_cast(baseParams_->headSizeCq) * baseParams_->mm1BlockNum * + static_cast(sizeof(mmCqOutputType)); + } + + mmCkvKrResGm_.SetGlobalBuffer((__gm__ mmCkvKrOutputType *)(workspace + workspaceOffset)); + workspaceOffset += static_cast(baseParams_->stepBatchSize) * + static_cast(baseParams_->headSizeCkv + baseParams_->dimHeadRope) * + baseParams_->mm2BlockNum * sizeof(mmCkvKrOutputType); + + mmQcQrResGm_.SetGlobalBuffer((__gm__ mmQcQrOutputType *)(workspace + workspaceOffset)); // aicOffset.qcQrResOffset + + if constexpr (IsFullQuantMode()) { + workspaceOffset += static_cast(baseParams_->stepBatchSize) * + static_cast(baseParams_->headSizeQc + baseParams_->headSizeQr) * + baseParams_->mm3BlockNum * sizeof(mmQcQrOutputType); + } + + mmQcQrResDequantGm_.SetGlobalBuffer( + (__gm__ mmQnInputType *)(workspace + workspaceOffset)); // qcOffset mmQnPreDequantResOffset + workspaceOffset += + static_cast(baseParams_->stepBatchSize) * static_cast(baseParams_->numHeadSize) * + static_cast(baseParams_->dimHeadSizeQc) * baseParams_->mm4BlockNum * sizeof(mmQnInputType); + if constexpr (((std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value)) && + !isPertile) { + workspaceOffset += + static_cast(baseParams_->stepBatchSize) * static_cast(baseParams_->numHeadSize) * + static_cast(baseParams_->dimHeadSizeQc) * baseParams_->mm4BlockNum * sizeof(mmQnInputType); + mmQnResGm_.SetGlobalBuffer((__gm__ mmQnOutputType *)(workspace + workspaceOffset)); // aicOffset.qnResOffset + } +} + +template +__aicore__ inline void MlaPrologV3SplitM::UpdateStepBatchParams(int64_t curMSize) +{ + mmCqParam_.m = curMSize; + mmCkvKrParam_.m = curMSize; + mmQcQrParam_.m = curMSize; + mmQnParam_.m = curMSize; + curVectorBlockNum_ = curMSize; +} + +/* + * MlaPrologV3算子计算&CV流水同步流程 + * ┌───────────────── token_x ─────────────────┐ + * | ▼ + * | MatmulCkvKr + * ▼ | wait mm CkvKr(0x1) + * MatmulCq ▼ + * | wait mm Cq(0x1) ┌─────────────────┐ + * ▼ ▼ ▼ + * RmsNorm(Cq) RmsNorm(Ckv) Rope(Kr) + * | wait rmsNorm cq(0x1) | | + * ▼ ▼ ▼ + * ┌───────MatmulQcQr───────┐ Scatter(Ckv) Scatter(Kr) + * | wait mm Qc(0x1) | | | + * ▼ | ▼ ▼ + * DequantQc | kv_cache_out kr_cache_out + * | wait dequant qc(0x1) | wait mm Qr(0x2) + * ▼ ▼ + * MatmulQn Rope(Qr) + * | wait mm Qn(0x1) | + * DynamicQuantQn──┐ | + * | ▼ | + * ▼ dequant_scale_out ▼ + * query_out query_rope_out + * 注:仅为表明基本计算与CV同步流程,仅包含了影响CV同步的量化分支,其余量化分支应参考设计文档。 + */ +template +__aicore__ inline void MlaPrologV3SplitM::Process() +{ + constexpr bool needQnDynamicQuant = + ((std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value)) && + !isPertile; + int64_t numHeadOffset = 0; + int64_t mmQnLoops = baseParams_->mm4SingleCoreBatch; + + // moffsetStart_ 当前核处理的token起始偏移 + // mSubSize_ 当前核处理的token数量 + // curMsize 当前step内处理的token数量 + // maxMOffset 当前核处理的token结束偏移 + // mSubCoreNum 前多少个核需要多处理1个token + if (cubeBlockIdx_ < baseParams_->mSubCoreNum) { + mSubSize_ = baseParams_->mSubSize; + mOffsetStart_ = mSubSize_ * cubeBlockIdx_; + } else { + mSubSize_ = baseParams_->mSubSize - 1; + mOffsetStart_ = + baseParams_->mSubSize * baseParams_->mSubCoreNum + mSubSize_ * (cubeBlockIdx_ - baseParams_->mSubCoreNum); + } + + // AIC的offset参数 + AicOffset aicOffset; + + // AIV的offset参数 + AivOffset aivOffset; + + // 需要考虑BS合轴的尾块情况 + int64_t maxMOffset = mOffsetStart_ + mSubSize_; + for (int64_t mOffset = mOffsetStart_; mOffset < maxMOffset; mOffset += baseParams_->stepBatchSize) { + int64_t curMSize = + (maxMOffset - mOffset) < baseParams_->stepBatchSize ? (maxMOffset - mOffset) : baseParams_->stepBatchSize; + + UpdateStepBatchParams(curMSize); + // AIV核用MTE3 DMA清零对应的AIC workspace (UB→GM仅AIV的MTE3支持) + if ASCEND_IS_AIV { + if (cubeBlockIdx_ < baseParams_->mm1BlockNum && (blockIdx_ % cvRatio_ == 0)) { + int64_t stepBS = static_cast(baseParams_->stepBatchSize); + int64_t cbIdx = static_cast(cubeBlockIdx_); + LocalTensor zeroSrc = zeroBuf_.Get(); + constexpr int64_t zeroChunk = 512; + Duplicate(zeroSrc, static_cast(0), zeroChunk); + + int64_t cqN = stepBS * static_cast(baseParams_->headSizeCq); + int64_t ckvN = stepBS * static_cast(baseParams_->headSizeCkv + baseParams_->dimHeadRope); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + for (int64_t off = 0; off < cqN; off += zeroChunk) { + int64_t len = (cqN - off < zeroChunk) ? (cqN - off) : zeroChunk; + DataCopy(mmCqResGm_[cbIdx * cqN + off], zeroSrc, static_cast(len)); + } + for (int64_t off = 0; off < ckvN; off += zeroChunk) { + int64_t len = (ckvN - off < zeroChunk) ? (ckvN - off) : zeroChunk; + DataCopy(mmCkvKrResGm_[cbIdx * ckvN + off], zeroSrc, static_cast(len)); + } + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + } + CrossCoreSetFlag(SYNC_MODE_CUBE_VEC); + } + + if ASCEND_IS_AIC { + AicProcess(aicOffset, mOffset, mmQnLoops); + } + if ASCEND_IS_AIV { + AivProcess(aivOffset, mOffset, curMSize, numHeadOffset, mmQnLoops); + } + } + + if ASCEND_IS_AIC { + WaitFlag(A_EVENT0); + WaitFlag(A_EVENT1); + WaitFlag(B_EVENT0); + WaitFlag(B_EVENT1); + + WaitFlag(L0A_EVENT0); + WaitFlag(L0A_EVENT1); + WaitFlag(L0B_EVENT0); + WaitFlag(L0B_EVENT1); + + WaitFlag(L0C_EVENT0); + WaitFlag(L0C_EVENT1); + WaitFlag(SCALE_EVENT); + } +} + +template +template +__aicore__ inline void MlaPrologV3SplitM::AicProcess(AicOffset &aicOffset, int64_t mOffset, int64_t mmQnLoops) +{ + int64_t tokenXOffset = mOffset * static_cast(baseParams_->headSizeX); + int64_t dequantScaleXOffset = mOffset * static_cast(baseParams_->headSizeX) / 32; // mxfp8需要除32 + aicOffset.weightDqOffset = 0; + aicOffset.dequantScaleWDqOffset = 0; + aicOffset.cqResOffset = baseParams_->stepBatchSize * baseParams_->headSizeCq * cubeBlockIdx_; + + CrossCoreWaitFlag(SYNC_MODE_CUBE_VEC); + + // MatmulCq ──> RmsNorm(Cq) [K-outer: kL1→nb→stepK] + if constexpr (std::is_same::value && isFp8E8m0) { + if (cubeBlockIdx_ < baseParams_->mm1BlockNum) { + MatmulSplitMKOuter( + mmCqResGm_[aicOffset.cqResOffset], tokenXGm_[tokenXOffset], weightDqGm_[aicOffset.weightDqOffset], + mmCqParam_, bufParam_, dequantScaleXGm_[dequantScaleXOffset], + dequantScaleWDqGm_[aicOffset.dequantScaleWDqOffset]); + } + } + + CrossCoreSetFlag(FINISH_MM_CQ); + + aicOffset.weightDkvKrOffset = 0; + aicOffset.dequantScaleWDkvKrOffset = 0; + aicOffset.ckvKrResOffset = + baseParams_->stepBatchSize * (baseParams_->headSizeCkv + baseParams_->dimHeadRope) * cubeBlockIdx_; + + // MatmulCkvKr ──> RmsNorm(Ckv) / Rope(Kr) [K-outer: kL1→nb→stepK] + if constexpr (std::is_same::value && isFp8E8m0) { + if (cubeBlockIdx_ < baseParams_->mm2BlockNum) { + MatmulSplitMKOuter( + mmCkvKrResGm_[aicOffset.ckvKrResOffset], tokenXGm_[tokenXOffset], + weightDkvKrGm_[aicOffset.weightDkvKrOffset], mmCkvKrParam_, bufParam_, + dequantScaleXGm_[dequantScaleXOffset], dequantScaleWDkvkrGm_[aicOffset.dequantScaleWDkvKrOffset]); + } + } + + PipeBarrier(); + CrossCoreSetFlag(FINISH_MM_CKVKR); + CrossCoreWaitFlag(FINISH_VEC_RMSNORM_CQ); + + // 设置 MatmulQcQr 需要的 offset + if constexpr (std::is_same::value && isFp8E8m0) { + if (baseParams_->queryNormFlag == 1U) { + aicOffset.rmsNormCqResOffset = mOffset * baseParams_->headSizeCq; + } else { + aicOffset.rmsNormCqResOffset = baseParams_->stepBatchSize * baseParams_->headSizeCq * cubeBlockIdx_; + } + aicOffset.dequantScaleCqOffset = baseParams_->stepBatchSize * cubeBlockIdx_ * dequantScaleCqSize_; + aicOffset.weightUqQrOffset = 0; + aicOffset.dequantScaleWuqqrOffset = 0; + aicOffset.qcQrResOffset = + baseParams_->stepBatchSize * (baseParams_->headSizeQc + baseParams_->headSizeQr) * cubeBlockIdx_; + MatmulQcQr(aicOffset); + } + + if constexpr (std::is_same::value && isFp8E8m0) { + WaitFlag(SCALE_EVENT); + } + + if constexpr (!needQnDynamicQuant) { + aicOffset.qnResOffset = mOffset * baseParams_->headSizeCkv * baseParams_->numHeadSize; + } else { + aicOffset.qnResOffset = + baseParams_->stepBatchSize * baseParams_->numHeadSize * baseParams_->headSizeCkv * cubeBlockIdx_; + } + + aicOffset.qcOffset = + baseParams_->stepBatchSize * baseParams_->numHeadSize * baseParams_->dimHeadSizeQc * cubeBlockIdx_; + aicOffset.weightUkOffset = 0; + MatmulQnSyncDynamicQuantAndMulQr(aicOffset.qcOffset, aicOffset.weightUkOffset, + aicOffset.qnResOffset, mmQnLoops); + if constexpr (std::is_same::value && isFp8E8m0) { + SetFlag(SCALE_EVENT); + } +} + +template +template +__aicore__ inline void MlaPrologV3SplitM::AivProcess(AivOffset &aivOffset, int64_t mOffset, int64_t curMSize, + int64_t numHeadOffset, int64_t mmQnLoops) +{ + if (mOffset == mOffsetStart_) { + // 只需要搬运一次 + CopyGlobalParams(); + } + + uint64_t isBackVec = blockIdx_ % cvRatio_; + curStepVecBackToken_ = curMSize / cvRatio_; + curStepVecFrontListNum_ = curMSize % cvRatio_; + + aivOffset.curVecToken = + curStepVecBackToken_ + isBackVec * curStepVecFrontListNum_; // 当前核中每个vec处理多少个token + aivOffset.curBlockTokenOffset = isBackVec * curStepVecBackToken_; // 当前核中每个vec在这个m中的偏移 + + int64_t tokenIndex = mOffset + aivOffset.curBlockTokenOffset; + int64_t curTokenStart = mOffset + aivOffset.curBlockTokenOffset; + int64_t curTokenEnd = mOffset + aivOffset.curBlockTokenOffset + aivOffset.curVecToken; + + CopyInSinCos(curTokenStart, aivOffset.curVecToken, mOffset, curMSize); + + CrossCoreWaitFlag(FINISH_MM_CQ); + + aivOffset.rmsNormCqOffset = baseParams_->stepBatchSize * baseParams_->headSizeCq * cubeBlockIdx_ + + baseParams_->headSizeCq * aivOffset.curBlockTokenOffset; + int64_t rmsNormCqResOffset; + if (baseParams_->queryNormFlag == 1U) { + rmsNormCqResOffset = tokenIndex * baseParams_->headSizeCq; + } else { + rmsNormCqResOffset = aivOffset.rmsNormCqOffset; + } + RmsNormCq(curTokenStart, aivOffset.rmsNormCqOffset, rmsNormCqResOffset, aivOffset.curVecToken, + aivOffset.curBlockTokenOffset); + + CrossCoreSetFlag(FINISH_VEC_RMSNORM_CQ); + CrossCoreWaitFlag(FINISH_MM_CKVKR); + + aivOffset.rmsNormCkvOffset = + baseParams_->stepBatchSize * (baseParams_->headSizeCkv + baseParams_->dimHeadRope) * cubeBlockIdx_ + + (baseParams_->headSizeCkv + baseParams_->dimHeadRope) * aivOffset.curBlockTokenOffset; + + aivOffset.ropeKrOffset = baseParams_->headSizeCkv + aivOffset.rmsNormCkvOffset; // 512 + (512 + 64) * idx + RmsNormRopeScatterCkvKr(tokenIndex, aivOffset.rmsNormCkvOffset, aivOffset.ropeKrOffset, aivOffset.curVecToken); + + aivOffset.mmQnPreDequantOffset = + ((baseParams_->stepBatchSize) * (baseParams_->headSizeQc + baseParams_->headSizeQr) * cubeBlockIdx_) + + (baseParams_->headSizeQc + baseParams_->headSizeQr) * aivOffset.curBlockTokenOffset; + + aivOffset.mmQnPreDequantResOffset = + baseParams_->stepBatchSize * baseParams_->numHeadSize * baseParams_->dimHeadSizeQc * cubeBlockIdx_ + + baseParams_->dimHeadSizeQc * baseParams_->numHeadSize * aivOffset.curBlockTokenOffset; + aivOffset.ropeQrOffset = + (baseParams_->stepBatchSize * (baseParams_->headSizeQc + baseParams_->headSizeQr) * cubeBlockIdx_) + + baseParams_->dimHeadSizeQc + + (baseParams_->headSizeQc + baseParams_->headSizeQr) * aivOffset.curBlockTokenOffset; + aivOffset.ropeQrResOffset = (baseParams_->headSizeQr) * (aivOffset.curBlockTokenOffset + mOffset); + + QcQrSplit(aivOffset.curVecToken, aivOffset.curBlockTokenOffset, curMSize, aivOffset.mmQnPreDequantOffset, + aivOffset.mmQnPreDequantResOffset, aivOffset.ropeQrOffset, aivOffset.ropeQrResOffset); + + if constexpr (needQnDynamicQuant) { + DynamicQuantQnAndMulQrSyncMMQn(mOffset, curMSize, numHeadOffset, mmQnLoops); + } +} + +template +template +__aicore__ inline void +MlaPrologV3SplitM::MatmulSplitM(const GlobalTensor &tensorResGm, const GlobalTensor &tensorAGm, + const GlobalTensor &tensorBGm, const MMParams &mmPara, + const UsedBlockParams &mmBlockParams, const GlobalTensor &tensorAScaleGm, + const GlobalTensor &tensorBScaleGm) +{ + if constexpr (needCheckEmptyTensor) { + if constexpr (MLAPT::emptyMode == EMPTY_TENSOR_MODE::EMPTY_CACHE) { + return; + } + } + if (blockIdx_ < mmBlockParams.blockStartIdx || blockIdx_ >= mmBlockParams.blockEndIdx) { + return; + } + // 用于enableGroupComputeOpt场景 + if constexpr (needCheckAFullLoad) { + constexpr uint32_t mSize = + (sizeof(mmQcQrInputType) == sizeof(int8_t)) ? INT8_AFULLLOAD_MAX_MSIZE : BF16_AFULLLOAD_MAX_MSIZE; + bool isAFullLoad = (mmQcQrParam_.m <= mSize) ? true : false; + if (isAFullLoad) { + MatmulGroupComputeAFullLoad(tensorResGm, tensorAGm, tensorBGm, mmPara, + bufParam_); + return; + } + } + + uint32_t nInput = mmPara.n; + uint32_t nL1SplitSize = mmPara.baseN; + uint32_t nL1loops = CeilDivT(nInput, nL1SplitSize); + uint32_t subNL1SplitSize = nL1SplitSize; + for (int64_t nL1 = 0; nL1 < nL1loops; nL1++) { + if (nL1 == nL1loops - 1) { + subNL1SplitSize = nInput - (nL1loops - 1) * nL1SplitSize; + } + MatmulSplitK(tensorResGm, tensorAGm, tensorBGm, mmPara, bufParam_, nL1 * nL1SplitSize, subNL1SplitSize, + tensorAScaleGm, tensorBScaleGm); + } +} + +template +__aicore__ inline void MlaPrologV3SplitM::MatmulQcQr(AicOffset &aicOffset) +{ + if (blockIdx_ >= baseParams_->mm3BlockNum) { + return; + } + // RmsNorm(Cq) ──> MatmulQcQr ──> MatmulQn + // └──> Rope(Qr) + // [32, 1536] * [1536, 32*(128+64)] = [32, 32*192] + constexpr uint32_t mSize = + (sizeof(mmQcQrInputType) == sizeof(int8_t)) ? INT8_AFULLLOAD_MAX_MSIZE : BF16_AFULLLOAD_MAX_MSIZE; + bool isAFullLoad = (mmQcQrParam_.m <= mSize) ? true : false; + + uint32_t nInput = mmQcQrParam_.n; + uint32_t nL1SplitSize = mmQcQrParam_.baseN; + uint32_t nL1loops = CeilDivT(nInput, nL1SplitSize); + uint32_t subNL1SplitSize = nL1SplitSize; + if (isAFullLoad) { + if constexpr (std::is_same::value && isFp8E8m0) { + uint32_t offsetL1B = L1_B_SIZE / 2 / sizeof(rmsNormCqOutputType); + LoadL1AAndScale( + rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + dequantTool_.deQuantScaleCqGm_[aicOffset.dequantScaleCqOffset], mmQcQrParam_.m, mmQcQrParam_.k, + mmQcQrParam_.k, mmQcQrParam_.kScale, offsetL1B, bufParam_); + } + WaitFlag(A_EVENT0 + (bufParam_.aL1BufIter & 1u)); + } + + for (int64_t nL1 = 0; nL1 < nL1loops; nL1++) { + if (nL1 == nL1loops - 1) { + subNL1SplitSize = nInput - (nL1loops - 1) * nL1SplitSize; + } + if constexpr (std::is_same::value && isFp8E8m0) { + if (isAFullLoad) { + MatmulSplitK( + mmQcQrResGm_[aicOffset.qcQrResOffset], rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + weightUqQrGm_[aicOffset.weightUqQrOffset], mmQcQrParam_, bufParam_, nL1 * nL1SplitSize, + subNL1SplitSize, dequantTool_.deQuantScaleCqGm_[aicOffset.dequantScaleCqOffset], + deqScaleQcQrW_[aicOffset.dequantScaleWuqqrOffset]); + } else { + MatmulSplitK( + mmQcQrResGm_[aicOffset.qcQrResOffset], rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + weightUqQrGm_[aicOffset.weightUqQrOffset], mmQcQrParam_, bufParam_, nL1 * nL1SplitSize, + subNL1SplitSize, dequantTool_.deQuantScaleCqGm_[aicOffset.dequantScaleCqOffset], + deqScaleQcQrW_[aicOffset.dequantScaleWuqqrOffset]); + } + } + if constexpr (MLAPT::enableDequantOpt) { + uint32_t spacing = CeilDivT(nL1loops, static_cast(MAX_SYNC_FLAG_COUNT - 1)); + if (nL1 % spacing == 0 || (nL1 + 1) == static_cast(nL1loops)) { + CrossCoreSetFlag<0x2, PIPE_FIX>(FINISH_MM_QCQR_SPLIT_N); + } + if ((nL1 + 1) % spacing == 0 || (nL1 + 1) == static_cast(nL1loops)) { + CrossCoreSetFlag<0x2, PIPE_FIX>(FINISH_MM_QCQR_SPLIT_BATCH); + } + } + } + if (isAFullLoad) { + SetFlag(A_EVENT0 + (bufParam_.aL1BufIter & 1u)); + bufParam_.aL1BufIter++; + } +} + +template +template +__aicore__ inline void +MlaPrologV3SplitM::MatmulQnSyncDynamicQuantAndMulQr(int64_t qcOffset, int64_t weightUkOffset, + int64_t qnResOffset, int64_t subLoopTimes) +{ + if (blockIdx_ >= baseParams_->mm4BlockNum) { + return; + } + + // MatmulQcQr ──> MatmulQn ──> query_out + // [32, 128] * [128, 512] = [32, 512] + // [32, 2, 128] * [2, 128, 512] = [32, 2, 512] + + for (int64_t i = 0; i < subLoopTimes; i++) { + uint32_t coarse = CeilDivT(static_cast(subLoopTimes), static_cast(MAX_SYNC_FLAG_COUNT - 1)); + if (i % coarse == 0) { + CrossCoreWaitFlag(FINISH_VEC_DEQUANT_QC_SPLIT_N); + } else if ((subLoopTimes - CeilDivT(static_cast(subLoopTimes), coarse)) <= MAX_SYNC_FLAG_COUNT) { + CrossCoreWaitFlag(FINISH_VEC_DEQUANT_QC_SPLIT_N_GAP); + } + + // Qn 用 MatmulSplitK 避免 L0A 溢出:每 L0 步 128×64=8192<16384,bf16 无 scale + for (int64_t nL1 = 0; nL1 < mmQnParam_.n; nL1 += mmQnParam_.baseN) { + uint32_t subN = static_cast((nL1 + mmQnParam_.baseN > mmQnParam_.n) ? (mmQnParam_.n - nL1) : + mmQnParam_.baseN); + MatmulSplitK( + mmQnResGm_[qnResOffset], mmQcQrResDequantGm_[qcOffset], weightUkGm_[weightUkOffset], mmQnParam_, + bufParam_, static_cast(nL1), subN); + } + + if constexpr (std::is_same::value || std::is_same::value || + std::is_same::value) { + qcOffset += static_cast(baseParams_->dimHeadSizeQc); + } + weightUkOffset += + static_cast(baseParams_->dimHeadSizeQc) * static_cast(baseParams_->headSizeCkv); + qnResOffset += static_cast(baseParams_->headSizeCkv); + } + PipeBarrier(); + if constexpr (needQnDynamicQuant) { + CrossCoreSetFlag(FINISH_MM_QN_SPLIT_N); + } +} + +template +__aicore__ inline void MlaPrologV3SplitM::CopyInSinCos(int64_t tokenIndex, int64_t curVecToken, + int64_t batchOffset, int64_t curMSize) +{ + LocalTensor shareTmpUb = shareBuffer_.Get(); + if constexpr (MLAPT::enableDequantOpt) { + // 如果是切N场景,mm3的每个C核都会做rope + if (cubeBlockIdx_ >= baseParams_->mm3BlockNum) { + return; + } + // 如果curStepBatchSize是偶数,则两个核平分;如果curStepBatchSize是奇数,则奇数核比偶数核多分一个 + // >> 1 是将curStepBatchSize分到每个vec核上; + uint32_t subBlockIdx_ = blockIdx_ % cvRatio_; + int64_t offset = (curMSize / cvRatio_) * subBlockIdx_ + batchOffset; + GatherSinCos(cosLocal_, sinLocal_, ropeCosGm_, ropeSinGm_, offset, + (curMSize + cvRatio_ - 1) / cvRatio_, shareTmpUb, vectorRow_, + baseParams_->dimHeadRope); + } else { + if (cubeBlockIdx_ >= baseParams_->mm3BlockNum) { + return; + } + GatherSinCos(cosLocal_, sinLocal_, ropeCosGm_, ropeSinGm_, tokenIndex, + curVecToken, shareTmpUb, vectorRow_, baseParams_->dimHeadRope); + } +} + +template +__aicore__ inline void MlaPrologV3SplitM::CopyGlobalParams() +{ + // rmsnormGammaCq + DataCopy(rmsnormGammaCqLocal_, rmsnormGammaCqGm_, baseParams_->headSizeCq); + + // rmsnormGammaCkv + DataCopy(rmsnormGammaCkvLocal_, rmsnormGammaCkvGm_, baseParams_->headSizeCkv); + + // quantScaleCkv + + if constexpr (IsFullQuantMode() && !isPertile) { + if constexpr (std::is_same::value || + (std::is_same::value && !isFp8E8m0)) { + DataCopyExtParams quantCopyParams{1, sizeof(float), 0, 0, 0}; + DataCopyPadExtParams quantPadParams{false, 0, 0, 0}; + DataCopyPad(quantScaleCkvLocal_, quantScaleCkvGm_, quantCopyParams, quantPadParams); + } else { + DataCopy(quantScaleCkvLocal_, quantScaleCkvGm_, baseParams_->headSizeCkv); + } + } + + // quantScaleCkr + if constexpr (std::is_same::value) { + DataCopyExtParams quantCopyParams{1, static_cast(baseParams_->dimHeadRope * sizeof(float)), 0, 0, 0}; + DataCopyPadExtParams quantPadParams{false, 0, 0, 0}; + DataCopyPad(quantScaleCkrLocal_, quantScaleCkrGm_, quantCopyParams, quantPadParams); + } +} + + +/** + * @brief RmsNormCq流程,融合了dynamicquant + 内部所需空间约为 curVecToken(128) * 8*4 + 8*4 + (4*vectorRow_*baseParams_->headSizeCq + 8)*4 = 28.0625K + */ +template +__aicore__ inline void MlaPrologV3SplitM::RmsNormCq(int64_t tokenIndex, int64_t rmsNormCqOffset, + int64_t rmsNormCqResOffset, int64_t curVecToken, + int64_t curBlockTokenOffset) +{ + if (blockIdx_ < 0 || blockIdx_ >= cvRatio_ * baseParams_->mm1BlockNum) { + return; + } + + uint64_t dequantScaleCqElementNum = dequantScaleCqSize_ / sizeof(dequantScaleType); + LocalTensor outputLocal = shareBuffer_.Get(); + LocalTensor dequantScaleQcQr = + outputLocal[baseParams_->headSizeCq].template ReinterpretCast(); + LocalTensor dequantScaleXLocal = + dequantScaleQcQr[curVecToken * dequantScaleCqElementNum].template ReinterpretCast(); + + uint64_t dequantScaleXSize = 1; + if constexpr (std::is_same::value && isFp8E8m0) { + dequantScaleXSize = baseParams_->headSizeX / FP8_E4M3_BLOCK_SIZE; + } + uint64_t dequantScaleXElementNum = Align(dequantScaleXSize, BYTE_BLOCK) / sizeof(float); + LocalTensor shareTmpUb = dequantScaleXLocal[dequantScaleXElementNum].template ReinterpretCast(); + int64_t stepTokenIndex = tokenIndex; + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVecToken; curVecTokenIdx++) { + // MatmulCq ──> RmsNorm(Cq) ──> MatmulQcQr + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); // wait for vector operations to finish + uint64_t scaleOffset; + if constexpr (std::is_same::value && isFp8E8m0) { + scaleOffset = curVecTokenIdx * dequantScaleCqElementNum; + } else { + scaleOffset = curVecTokenIdx * FP32_BLOCK_ELEMENT_NUM; + } + RmsNormParam rmsNormParams = {baseParams_->reciprocalCq, // reciprocal + baseParams_->epsilonCq, // epsilon + static_cast(vectorRow_), // row + baseParams_->headSizeCq, // col + baseParams_->qcQrScale, + baseParams_->isQcQrScaleEnable}; + + + if constexpr (IsFullQuantMode()) { + RmsNormDynamicQuant(outputLocal, dequantScaleQcQr[scaleOffset], + mmCqResGm_[rmsNormCqOffset], rmsnormGammaCqLocal_, + smoothScaleCqLocal_, dequantScaleWDqLocal_, dequantScaleXLocal, + shareTmpUb, rmsNormParams, enableSmoothScalesCq_); + } + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + // RmsNorm(Cq)的结果拷进mmCqResGm_中,用于MatmulQcQr的A矩阵 + DataCopy(rmsNormCqResGm_[rmsNormCqResOffset], outputLocal, baseParams_->headSizeCq); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + rmsNormCqOffset += baseParams_->headSizeCq; + rmsNormCqResOffset += baseParams_->headSizeCq; + tokenIndex++; + } + + if constexpr (std::is_same::value && isFp8E8m0) { + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + DataCopy(dequantTool_.deQuantScaleCqGm_[(curBlockTokenOffset + baseParams_->stepBatchSize * cubeBlockIdx_) * + dequantScaleCqElementNum], + dequantScaleQcQr, curVecToken * dequantScaleCqElementNum); + } + if (unlikely(baseParams_->queryNormFlag == 1U)) { + if constexpr (std::is_same::value && isFp8E8m0) { + DataCopyPad( + dequantScaleQNormGm_[stepTokenIndex * + static_cast((baseParams_->headSizeCq / FP8_E4M3_BLOCK_SIZE))], + dequantScaleQcQr, + {static_cast(curVecToken), + static_cast(sizeof(dequantScaleQNormType) * (baseParams_->headSizeCq / FP8_E4M3_BLOCK_SIZE)), + 0, 0}); + } + } +} + +template +__aicore__ inline void MlaPrologV3SplitM::ComputeBlkScatterOffsets(GlobalTensor indexGm, + int64_t tokenIndex, int64_t rows, + CkvkrParams &rmsNormAndScatterCkvParams, + CkvkrParams &ropeAndScatterKrParams) +{ + int64_t batchTokenIndex = 0; + int64_t batchIndexOffset = 0; + int64_t batchSeqSize = 0; + int64_t rowsThisStep = 0; + int64_t nextPageId = 0; + bool spill = false; + + if constexpr (MLAPT::actualSeqMode == ACTUAL_SEQ_MODE::DISABLED) { + const int64_t batchIndex = tokenIndex / baseParams_->seq1Size; + batchTokenIndex = tokenIndex % baseParams_->seq1Size; + batchSeqSize = baseParams_->seq1Size; + batchIndexOffset = batchIndex * CeilDivT(batchSeqSize, static_cast(baseParams_->blockSize)); + } else { + while (actSeqState_.curBatch + 1 < static_cast(baseParams_->batchSize) && + tokenIndex >= actSeqState_.curPrefix) { + actSeqState_.curBatch += 1; + actSeqState_.prevPrefix = actSeqState_.curPrefix; + actSeqState_.curPrefix = actualSeqLenGm_(actSeqState_.curBatch); + actSeqState_.prevIndexOffset = actSeqState_.curIndexOffset; + actSeqState_.curIndexOffset += CeilDivT(actSeqState_.curPrefix - actSeqState_.prevPrefix, + static_cast(baseParams_->blockSize)); + } + batchTokenIndex = tokenIndex - actSeqState_.prevPrefix; + batchSeqSize = actSeqState_.curPrefix - actSeqState_.prevPrefix; + batchIndexOffset = actSeqState_.prevIndexOffset; + } + + int64_t indexOffset = batchIndexOffset + batchTokenIndex / baseParams_->blockSize; + int64_t paBlkId = indexGm(indexOffset); + + int64_t pageTokenOffset = paBlkId * baseParams_->blockSize; + int64_t tokenOffsetInPage = batchTokenIndex % baseParams_->blockSize; + + int64_t leftRowsInPage = baseParams_->blockSize - tokenOffsetInPage; + if (leftRowsInPage >= rows) { + rowsThisStep = rows; + spill = false; + nextPageId = -1; + } else { + rowsThisStep = rows - leftRowsInPage; + spill = true; + nextPageId = indexGm(indexOffset + 1); + } + + MaterializeOffsetsWithHeadSize( + pageTokenOffset, tokenOffsetInPage, rowsThisStep, spill, nextPageId, baseParams_->headSizeCkv, + rmsNormAndScatterCkvParams); + + MaterializeOffsetsWithHeadSize( + pageTokenOffset, tokenOffsetInPage, rowsThisStep, spill, nextPageId, baseParams_->dimHeadRope, + ropeAndScatterKrParams); +} + +template +__aicore__ inline void MlaPrologV3SplitM::RmsNormAndScatterCkv(LocalTensor &dequantScaleXLocal, + LocalTensor &shareTmpUb, + LocalTensor &cosLocalCkvKr, + LocalTensor &sinLocalCkvKr, + CkvkrParams rmsNormAndScatterCkvParams) +{ + // MatmulCkvKr ──> RmsNorm(Ckv) ──> Scatter(Ckv) + LocalTensor outputLocal = shareTmpUb.ReinterpretCast(); + int32_t outputLocalSize = vectorRow_ * baseParams_->headSizeCkv * sizeof(kvCacheType); + if constexpr (isPertile) { // pertile量化场景,按照concat的最长长度申请内存 + int32_t tileNum = baseParams_->headSizeCkv / baseParams_->tileSize; + outputLocalSize = vectorRow_ * (baseParams_->headSizeCkv * sizeof(kvCacheType) + tileNum * sizeof(float)); + outputLocalSize = Align(outputLocalSize, static_cast(BYTE_BLOCK)); + } + LocalTensor rmsNormShareTmpUb = shareTmpUb[outputLocalSize].template ReinterpretCast(); + + RmsNormParam rmsNormParams = { + baseParams_->reciprocalCkv, // reciprocal + baseParams_->epsilonCkv, // epsilon + static_cast(vectorRow_), // row + baseParams_->headSizeCkv, // col + baseParams_->kcScale, // scale + baseParams_->isKcScaleEnable, // isScaleEnable + }; + + if constexpr (IsFullQuantMode()) { + RmsNormAndQuantizeCkv(outputLocal, rmsNormShareTmpUb, dequantScaleXLocal, rmsNormParams, + rmsNormAndScatterCkvParams); + } else { + RmsNormNormal( + outputLocal, mmCkvKrResGm_[rmsNormAndScatterCkvParams.offset], rmsnormGammaCkvLocal_, + dequantScaleWDkvKrLocal_, dequantScaleXLocal, rmsNormShareTmpUb, rmsNormParams); + } + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + // Scatter(Ckv) + // RmsNorm(Ckv) ──> Scatter(Ckv) ──> kv_cache_out + ScatterCkv(outputLocal, rmsNormAndScatterCkvParams); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); +} + +template +__aicore__ inline void MlaPrologV3SplitM::RmsNormAndQuantizeCkv(LocalTensor &outputLocal, + LocalTensor &rmsNormShareTmpUb, + LocalTensor &dequantScaleXLocal, + RmsNormParam rmsNormParams, + CkvkrParams rmsNormAndScatterCkvParams) +{ + // row = vectorRow_ = 1 col = baseParams_->headSizeCkv + LocalTensor inputLocal = rmsNormShareTmpUb.ReinterpretCast(); + LocalTensor sharedBuf = + inputLocal[vectorRow_ * baseParams_->headSizeCkv].template ReinterpretCast(); + RmsNormNormal( + inputLocal, mmCkvKrResGm_[rmsNormAndScatterCkvParams.offset], rmsnormGammaCkvLocal_, dequantScaleWDkvKrLocal_, + dequantScaleXLocal, sharedBuf, rmsNormParams); + + DataSyncBarrier(); + + if constexpr (isPertile) { + float kNopeClipAlpha = isFp8E8m0 ? 1.0f : kNopeClipAlphaGm_.GetValue(0); + PerTileQuantParams perTileQuantParams = { + static_cast(baseParams_->tileSize), // baseParams_->tileSize + static_cast(baseParams_->headSizeCkv / baseParams_->tileSize), // tileNum + kNopeClipAlpha, // alpha + static_cast(vectorRow_), // row + baseParams_->headSizeCkv // col + }; + if constexpr (std::is_same::value) { + QuantPerTile(outputLocal, inputLocal, sharedBuf, perTileQuantParams); + } else { + QuantPerTile8Bit(outputLocal, inputLocal, perTileQuantParams); + } + } else { + Rectangle rectangleParams{ + static_cast(vectorRow_), // row + static_cast(baseParams_->headSizeCkv), // col + static_cast(baseParams_->headSizeCkv) // columnStride + }; + if constexpr (std::is_same::value || + std::is_same::value) { + QuantPerTensor(outputLocal, inputLocal, quantScaleCkvLocal_, sharedBuf, rectangleParams); + } else { + QuantPerChannel(outputLocal, inputLocal, quantScaleCkvLocal_, sharedBuf, rectangleParams); + } + } + PipeBarrier(); +} + +template +__aicore__ inline void MlaPrologV3SplitM::ScatterCkv(LocalTensor &outputLocal, + CkvkrParams rmsNormAndScatterCkvParams) +{ + if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_NZ) || (MLAPT::cacheMode == CACHE_MODE::PA_BSND) || + (MLAPT::cacheMode == CACHE_MODE::ND)) { + int64_t paTokenIndex; + if constexpr (MLAPT::cacheMode == CACHE_MODE::ND) { + paTokenIndex = rmsNormAndScatterCkvParams.tokenIndex; + } else { + paTokenIndex = cacheIndexGm_(rmsNormAndScatterCkvParams.tokenIndex); + } + ScatterCache( + kvCacheGm_, outputLocal, + ScatterCacheParams{baseParams_->blockSize, paTokenIndex, vectorRow_, baseParams_->headSizeCkv, + baseParams_->dtileSize}); + // 刷新量化scale + if (isPertile && baseParams_->quantScaleRepoMode == 1U) { + // BSND: + int32_t tileNum = baseParams_->headSizeCkv / baseParams_->tileSize; + LocalTensor quantScaleCkvInt8Tensor = + outputLocal[vectorRow_ * baseParams_->headSizeCkv].template ReinterpretCast(); + int64_t startOffset = 0; + int64_t startColOffset = baseParams_->headSizeCkv; + if (baseParams_->ckvkrRepoMode == 1U) { + startColOffset += baseParams_->headSizeKr * sizeof(krCacheType); + } + if constexpr ((MLAPT::cacheMode != CACHE_MODE::PA_NZ)) { + startOffset = startColOffset; + } + + ScatterCacheUnAligned( + kvCacheGm_[startOffset], quantScaleCkvInt8Tensor, + ScatterCacheParams{baseParams_->blockSize, paTokenIndex, vectorRow_, + static_cast(tileNum * sizeof(float)), baseParams_->dtileSize}); + } + } else { + // 使用 已计算好的偏移参数 + ScatterCacheMultiRows( + kvCacheGm_, outputLocal, + ScatterCacheParams{baseParams_->blockSize, rmsNormAndScatterCkvParams.cacheOffset, vectorRow_, + baseParams_->headSizeCkv, baseParams_->seq1Size, rmsNormAndScatterCkvParams.tokenIndex}, + rmsNormAndScatterCkvParams.rowsInCurBatch, rmsNormAndScatterCkvParams.cacheOffset, + rmsNormAndScatterCkvParams.nextBatchOffset); + } +} + +template +__aicore__ inline void MlaPrologV3SplitM::RopeAndScatterKr(LocalTensor &dequantScaleXLocal, + LocalTensor &shareTmpUb, + LocalTensor &cosLocalCkvKr, + LocalTensor &sinLocalCkvKr, + CkvkrParams ropeAndScatterKrParams) +{ + // MatmulCkvKr ──> Rope(Ckv) ──> Scatter(Kr) + LocalTensor outputKrLocal = shareTmpUb.ReinterpretCast(); + LocalTensor ropeShareTmpUb = outputKrLocal[baseParams_->dimHeadRope].template ReinterpretCast(); + int64_t stride = baseParams_->headSizeCkv + baseParams_->headSizeKr; // 512 + 64 + + LocalTensor cosLocal; + LocalTensor sinLocal; + if constexpr (MLAPT::enableDequantOpt) { + cosLocal = cosLocalCkvKr[baseParams_->dimHeadRope * ropeAndScatterKrParams.curVecTokenIdx]; + sinLocal = sinLocalCkvKr[baseParams_->dimHeadRope * ropeAndScatterKrParams.curVecTokenIdx]; + } else { + cosLocal = cosLocal_[baseParams_->dimHeadRope * ropeAndScatterKrParams.curVecTokenIdx]; + sinLocal = sinLocal_[baseParams_->dimHeadRope * ropeAndScatterKrParams.curVecTokenIdx]; + } + Rectangle ropeParams{ + static_cast(vectorRow_), // row + static_cast(baseParams_->dimHeadRope), // col + static_cast(stride) // stride + }; + + if constexpr ((std::is_same::value || + (std::is_same::value && !isFp8E8m0)) && + std::is_same::value) { + LocalTensor sharedBuf = + ropeShareTmpUb.ReinterpretCast()[baseParams_->dimHeadRope * sizeof(ropeSinCosType)]; + // input为int32_t需在rope中做反量化, intput为float根据模板参数判断是否做反量化 + RotaryPosEmbPerTensor( + outputKrLocal, mmCkvKrResGm_[ropeAndScatterKrParams.offset], cosLocal, sinLocal, sharedBuf, ropeParams, + dequantScaleWDkvKrLocal_[baseParams_->headSizeCkv], dequantScaleXLocal); + } else if constexpr (std::is_same::value) { + LocalTensor inputLocal = ropeShareTmpUb.ReinterpretCast(); + LocalTensor sharedBuf = + ropeShareTmpUb.ReinterpretCast()[baseParams_->dimHeadRope * sizeof(ropeSinCosType)]; + RotaryPosEmbPerTensor::value>( + inputLocal, mmCkvKrResGm_[ropeAndScatterKrParams.offset], cosLocal, sinLocal, sharedBuf, ropeParams); + RopePostQuantPerChannel(outputKrLocal, inputLocal, quantScaleCkrLocal_, sharedBuf, + vectorRow_ * baseParams_->dimHeadRope); + } else { + RotaryPosEmbPerTensor( + outputKrLocal, mmCkvKrResGm_[ropeAndScatterKrParams.offset], cosLocal, sinLocal, ropeShareTmpUb, + ropeParams); + } + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + // scatter(Kr) + // Rope(Kr) ──> Scatter(Kr) ──> kr_cache_out + ScatterKr(outputKrLocal, ropeAndScatterKrParams); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); +} + +template +__aicore__ inline void MlaPrologV3SplitM::ScatterKr(LocalTensor &outputKrLocal, + CkvkrParams ropeAndScatterKrParams) +{ + int64_t paTokenIndex; + if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_NZ) || (MLAPT::cacheMode == CACHE_MODE::PA_BSND) || + (MLAPT::cacheMode == CACHE_MODE::ND)) { + paTokenIndex = cacheIndexGm_(ropeAndScatterKrParams.tokenIndex); + if constexpr (MLAPT::cacheMode == CACHE_MODE::ND) { + paTokenIndex = ropeAndScatterKrParams.tokenIndex; + } + if (isPertile && baseParams_->ckvkrRepoMode == 1) { + int64_t startOffset; + if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_NZ)) { + constexpr uint8_t col0 = ALIGN_BLOCK_SIZE / sizeof(kvCacheType); + startOffset = CeilDiv(baseParams_->headSizeCkv, col0) * col0 * baseParams_->blockSize; // 列方向的偏移 + } else { + startOffset = baseParams_->headSizeCkv; + } + LocalTensor outputKrInt8Tensor = outputKrLocal.template ReinterpretCast(); + ScatterCache( + kvCacheGm_[startOffset], outputKrInt8Tensor, + ScatterCacheParams{baseParams_->blockSize, paTokenIndex, vectorRow_, + static_cast(baseParams_->dimHeadRope * sizeof(krCacheType)), + baseParams_->dtileSize}); + } else { + ScatterCache( + krCacheGm_, outputKrLocal, + ScatterCacheParams{baseParams_->blockSize, paTokenIndex, vectorRow_, baseParams_->dimHeadRope, + baseParams_->dimHeadRope}); + } + } else if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_BLK_BSND) || (MLAPT::cacheMode == CACHE_MODE::PA_BLK_NZ)) { + // 使用 已计算好的偏移参数 + ScatterCacheMultiRows( + krCacheGm_, outputKrLocal, + ScatterCacheParams{baseParams_->blockSize, ropeAndScatterKrParams.cacheOffset, vectorRow_, + baseParams_->dimHeadRope, baseParams_->seq1Size, ropeAndScatterKrParams.tokenIndex}, + ropeAndScatterKrParams.rowsInCurBatch, ropeAndScatterKrParams.cacheOffset, + ropeAndScatterKrParams.nextBatchOffset); + } else { + int64_t batchTokenIndex = 0; + int64_t batchIndex = 0; + int64_t batchSeqSize = 0; + int64_t batchIndexOffset = 0; + int64_t rowsInCurBatch = 0; + int64_t cacheOffset = 0; + int64_t nextBatchOffset = 0; + } +} + +template +__aicore__ inline void MlaPrologV3SplitM::RmsNormRopeScatterCkvKr(int64_t tokenIndex, int64_t rmsNormCkvOffset, + int64_t ropeKrOffset, int64_t curVecToken) +{ + if (blockIdx_ < 0 || blockIdx_ >= cvRatio_ * baseParams_->mm2BlockNum) { + return; + } + LocalTensor dequantScaleXLocal = shareBuffer_.Get(); + LocalTensor cosLocalCkvKr = + dequantScaleXLocal[FP32_BLOCK_ELEMENT_NUM].template ReinterpretCast(); + LocalTensor sinLocalCkvKr = cosLocalCkvKr[baseParams_->dimHeadRope * curVecToken]; + LocalTensor shareTmpUb = + sinLocalCkvKr[baseParams_->dimHeadRope * curVecToken].template ReinterpretCast(); + if constexpr (MLAPT::enableDequantOpt) { + GatherSinCos(cosLocalCkvKr, sinLocalCkvKr, ropeCosGm_, ropeSinGm_, tokenIndex, + curVecToken, shareTmpUb, vectorRow_, baseParams_->dimHeadRope); + } + if constexpr (MLAPT::emptyMode == EMPTY_TENSOR_MODE::EMPTY_CACHE) { + return; + } + + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVecToken; curVecTokenIdx++) { + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + if constexpr (std::is_same::value || + (std::is_same::value && !isFp8E8m0)) { + DataCopyPad(dequantScaleXLocal, dequantScaleXGm_[tokenIndex], {1, sizeof(float), 0, 0}, {false, 0, 0, 0}); + } + + CkvkrParams rmsNormAndScatterCkvParams{tokenIndex, rmsNormCkvOffset, curVecTokenIdx, 0, 0, 0}; + + CkvkrParams ropeAndScatterKrParams{tokenIndex, ropeKrOffset, curVecTokenIdx, 0, 0, 0}; + + if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_BLK_BSND) || (MLAPT::cacheMode == CACHE_MODE::PA_BLK_NZ)) { + ComputeBlkScatterOffsets(cacheIndexGm_, tokenIndex, vectorRow_, rmsNormAndScatterCkvParams, + ropeAndScatterKrParams); + } + + RmsNormAndScatterCkv(dequantScaleXLocal, shareTmpUb, cosLocalCkvKr, sinLocalCkvKr, rmsNormAndScatterCkvParams); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + RopeAndScatterKr(dequantScaleXLocal, shareTmpUb, cosLocalCkvKr, sinLocalCkvKr, ropeAndScatterKrParams); + + tokenIndex += 1; + rmsNormCkvOffset += static_cast(baseParams_->headSizeCkv + baseParams_->dimHeadRope); + ropeKrOffset += static_cast(baseParams_->headSizeCkv + baseParams_->dimHeadRope); + } +} + +template +__aicore__ inline void MlaPrologV3SplitM::QcQrSplit(int64_t curVecToken, int64_t curBlockTokenOffset, + int64_t curMSize, int64_t mmQcQrOffset, + int64_t mmQnPreDequantResOffset, int64_t ropeQrOffset, + int64_t ropeQrResOffset) +{ + if (cubeBlockIdx_ >= baseParams_->mm3BlockNum) { + return; + } + + DataCopyParams inputCopyParams{ + static_cast(curVecToken), + static_cast(baseParams_->dimHeadSizeQc * sizeof(mmQcQrOutputType) / ALIGN_BLOCK_SIZE), + static_cast((baseParams_->headSizeQc + baseParams_->headSizeQr - baseParams_->dimHeadSizeQc) * + sizeof(mmQcQrOutputType) / ALIGN_BLOCK_SIZE), + 0}; + + LocalTensor shareTmpUb = shareBuffer_.Get(); + LocalTensor inputLocal = shareTmpUb.ReinterpretCast(); + LocalTensor outputLocal = inputLocal.template ReinterpretCast(); + + Rectangle dequantParams{ + static_cast(curVecToken), // row + baseParams_->dimHeadSizeQc, // col + baseParams_->dimHeadSizeQc // columnStride + }; + DataCopyParams outputCopyParams{ + static_cast(curVecToken), + static_cast(baseParams_->dimHeadSizeQc * sizeof(mmQnInputType) / ALIGN_BLOCK_SIZE), 0, + static_cast((baseParams_->headSizeQc - baseParams_->dimHeadSizeQc) * sizeof(mmQnInputType) / + ALIGN_BLOCK_SIZE)}; + + DataCopyParams outputRopeParams{ + static_cast(curVecToken), + static_cast(baseParams_->dimHeadRope * sizeof(ropeOutputType) / ALIGN_BLOCK_SIZE), 0, + static_cast((baseParams_->headSizeQr - baseParams_->dimHeadRope) * sizeof(ropeOutputType) / + ALIGN_BLOCK_SIZE)}; + + Rectangle ropeParams{ + static_cast(curVecToken), // row + baseParams_->dimHeadRope, // col + static_cast(baseParams_->numHeadSize * + (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope)) // stride + }; + int64_t ropeStride = static_cast(baseParams_->numHeadSize) * + static_cast(baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope); + uint32_t deqScaleOffset = 0; + + int64_t deqScaleQcQrWOffset = 0; + uint32_t colOffsetCube = 0; + uint32_t colOffsetVec = 0; + uint32_t colOffsetVecEnd = 0; + uint32_t colOffsetRope = 0; + // cube一次处理row*colCube,对应的两个vec一次处理row*colQc,两vec之间切row + // 等cube生产足够数据了以后,vec开始消费 + uint32_t qcCount = 0; + uint32_t splitCount = 0; + uint32_t totalLoops = CeilDivT(mmQcQrParam_.n, mmQcQrParam_.baseN); + uint32_t totalQcLoops = CeilDivT(mmQcQrParam_.n, (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope)); + + for (uint32_t colOffsetCube = 0; colOffsetCube < mmQcQrParam_.n; colOffsetCube += mmQcQrParam_.baseN) { + colOffsetVecEnd = colOffsetCube + mmQcQrParam_.baseN; + if (colOffsetVecEnd > mmQcQrParam_.n) { // 当oriCol不被colCube整除时,mm最后一个base块需要刷新col end + colOffsetVecEnd = mmQcQrParam_.n; + } + uint32_t qcQrSpacing = CeilDivT(totalLoops, static_cast(MAX_SYNC_FLAG_COUNT - 1)); + if (splitCount % qcQrSpacing == 0 || splitCount == totalLoops - 1) { + CrossCoreWaitFlag(FINISH_MM_QCQR_SPLIT_N); + } + if (splitCount % qcQrSpacing == 0) { + CrossCoreWaitFlag(FINISH_MM_QCQR_SPLIT_BATCH); + } + while (colOffsetVec + baseParams_->dimHeadSizeQc <= colOffsetVecEnd) { // 循环singleNumHeadSize次 + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + DataCopy(inputLocal, mmQcQrResGm_[mmQcQrOffset], inputCopyParams); + + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + + Cast(outputLocal, inputLocal, RoundMode::CAST_RINT, curVecToken * baseParams_->dimHeadSizeQc); + + SetFlag(EVENT_ID2); + WaitFlag(EVENT_ID2); + + DataCopy(mmQcQrResDequantGm_[mmQnPreDequantResOffset], outputLocal, outputCopyParams); + { + uint32_t qcSpacing = CeilDivT(totalQcLoops, static_cast(MAX_SYNC_FLAG_COUNT - 1)); + if ((qcCount + 1) % qcSpacing == 0 || qcCount + 1 == totalQcLoops) { + CrossCoreSetFlag(FINISH_VEC_DEQUANT_QC_SPLIT_N); + } else if ((totalQcLoops - CeilDivT(totalQcLoops, qcSpacing)) <= + static_cast(MAX_SYNC_FLAG_COUNT)) { + CrossCoreSetFlag(FINISH_VEC_DEQUANT_QC_SPLIT_N_GAP); + } + } + colOffsetVec += (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope); + mmQcQrOffset += (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope); + mmQnPreDequantResOffset += baseParams_->dimHeadSizeQc; + qcCount++; + } + + while (colOffsetRope + baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope <= + colOffsetVecEnd) { // 循环singleNumHeadSize次 + + GlobalTensor outputGmRope = qrOutGm_[ropeQrResOffset]; + + LocalTensor shareTmpUb = shareBuffer_.Get(); + LocalTensor outputLocalRope = shareTmpUb.ReinterpretCast(); + LocalTensor ropeShareTmpUb = + outputLocalRope[curVecToken * baseParams_->dimHeadRope].template ReinterpretCast(); + + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + + RotaryPosEmbPerHead( + outputLocalRope, mmQcQrResGm_[ropeQrOffset], cosLocal_, sinLocal_, ropeShareTmpUb, ropeParams, + ropeStride); + + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + + DataCopy(qrOutGm_[ropeQrResOffset], outputLocalRope, outputRopeParams); + + colOffsetRope += (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope); + ropeQrOffset += (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope); + ropeQrResOffset += baseParams_->dimHeadRope; + } + splitCount++; + } + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); +} + +template +__aicore__ inline void +MlaPrologV3SplitM::DynamicQuantQnAndMulQrSyncMMQn(int64_t batchOffset, int64_t curStepBatchSize, + int64_t numHeadOffset, int64_t mmQnLoops) +{ + // 如果curStepBatchSize是偶数,则两个核平分;如果curStepBatchSize是奇数,则奇数核比偶数核多分一个 + // >> 1 是将curStepBatchSize分到每个vec核上; + int64_t curStepBatchSizeVec = (curStepBatchSize + (blockIdx_ % cvRatio_)) >> 1; + if (blockIdx_ >= baseParams_->mm4BlockNum * cvRatio_) { + return; + } + + // 等待前面的Qr部分完成 + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + constexpr uint32_t DYNAMIC_QUANT_INPUT_READY = EVENT_ID0; + constexpr uint32_t MUL_QR_INPUT_COPY_READY = EVENT_ID3; + constexpr uint32_t DYNAMIC_QUANT_OUTPUT_READY = EVENT_ID3; + + int64_t blockBatchOffset = (blockIdx_ % cvRatio_) * (curStepBatchSize / cvRatio_); + int64_t totalSizeCkv = + static_cast(baseParams_->numHeadSize) * static_cast(baseParams_->headSizeCkv); + // 由于两个vec核分curStepBatchSize,各处理curStepBatchSize/2,blockIdx_ & 1 表示是否为第二个vec核 + int64_t dynamicQuantQueryOffset = + baseParams_->stepBatchSize * baseParams_->numHeadSize * baseParams_->headSizeCkv * cubeBlockIdx_ + + blockBatchOffset * totalSizeCkv + numHeadOffset * static_cast(baseParams_->headSizeCkv); + int64_t dynamicQuantQueryResOffset = batchOffset * totalSizeCkv + blockBatchOffset * totalSizeCkv + + numHeadOffset * static_cast(baseParams_->headSizeCkv); + int64_t scaleQueryNopeOffset = batchOffset * static_cast(baseParams_->numHeadSize) + + blockBatchOffset * static_cast(baseParams_->numHeadSize) + numHeadOffset; + int64_t queryOutStride = totalSizeCkv; + int64_t qrOutputStride = + static_cast(baseParams_->numHeadSize) * static_cast(baseParams_->dimHeadRope); + int64_t qrPostProcessResOffset = batchOffset * static_cast(baseParams_->headSizeQr) + + numHeadOffset * static_cast(baseParams_->dimHeadRope) + + blockBatchOffset * static_cast(baseParams_->headSizeQr); + + LocalTensor shareTmpUb = shareBuffer_.Get(); + + float quantScaleCkv = quantScaleCkvGm_.GetValue(0); + + // Dynamic Quant + SetFlag(DYNAMIC_QUANT_OUTPUT_READY); + SetFlag(DYNAMIC_QUANT_INPUT_READY); + + // Rope Post Process + SetFlag(MUL_QR_INPUT_COPY_READY); + CrossCoreWaitFlag(FINISH_MM_QN_SPLIT_N); + // per-head循环 + for (int64_t loopIdx = 0; loopIdx < mmQnLoops; loopIdx++) { + DynamicQuantQnWithMulQr( + dequantScaleQNopeGm_[scaleQueryNopeOffset], queryOutGm_[dynamicQuantQueryResOffset], + qrOutGm_[qrPostProcessResOffset], mmQnResGm_[dynamicQuantQueryOffset], shareTmpUb, curStepBatchSizeVec, + baseParams_->headSizeCkv, baseParams_->numHeadSize, queryOutStride, + // Rope Post Process + qrOutGm_[qrPostProcessResOffset], quantScaleCkv, baseParams_->dimHeadRope, qrOutputStride, cvRatio_); + dynamicQuantQueryOffset += baseParams_->headSizeCkv; + scaleQueryNopeOffset += 1; + dynamicQuantQueryResOffset += baseParams_->headSizeCkv; + qrPostProcessResOffset += baseParams_->dimHeadRope; + } + // Rope Post Process + WaitFlag(MUL_QR_INPUT_COPY_READY); + // Dynamic Quant + WaitFlag(DYNAMIC_QUANT_INPUT_READY); + WaitFlag(DYNAMIC_QUANT_OUTPUT_READY); +} + +} // namespace MlaProlog + +#endif // MLA_PROLOG_V3_SPLIT_M \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/kernel_mla_prolog_split_n.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/kernel_mla_prolog_split_n.h new file mode 100644 index 0000000000000000000000000000000000000000..95fc31392e84367b3cb27398b6423e8afdbecf52 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/kernel_mla_prolog_split_n.h @@ -0,0 +1,2372 @@ +/** + * 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 kernel_mla_prolog_split_n.h + * \brief + */ + +#ifndef KERNEL_MLA_PROLOG_SPLIT_N_H +#define KERNEL_MLA_PROLOG_SPLIT_N_H + +#include "mla_prolog_comm.h" +#include "mla_prolog_vector_comm.h" +#include "service_matmul.h" +#include "service_rms_norm.h" +#include "service_gather_sin_cos.h" +#include "service_rotary_position_embedding.h" +#include "service_scatter_cache.h" +#include "service_dequant.h" +#include "service_dynamic_quant_qn_mul_qr.h" +#include "../mla_prolog_tiling_data.h" +#include "../mla_prolog_template_tiling_key.h" + +namespace MlaProlog { +template +class MlaPrologVecS1CubS2 { +public: + static constexpr bool isPertile = MLAPT::isPertile; + + using mmInputType = typename MLAPT::mmInputType; + using mmQcQrInputType = typename MLAPT::mmQcQrInputType; + using mmQnInputType = typename MLAPT::mmQnInputType; + using mmCqOutputType = typename MLAPT::mmCqOutputType; + using mmCkvKrOutputType = typename MLAPT::mmCkvKrOutputType; + using mmQcQrOutputType = typename MLAPT::mmQcQrOutputType; + using mmQnOutputType = typename MLAPT::mmQnOutputType; + using rmsNormGammaType = typename MLAPT::rmsNormGammaType; + using rmsNormComputType = typename MLAPT::rmsNormComputType; + using rmsNormCqOutputType = typename MLAPT::rmsNormCqOutputType; + using rmsNormCkvOutputType = typename MLAPT::rmsNormCkvOutputType; + using ropeSinCosType = typename MLAPT::ropeSinCosType; + using ropeComputType = typename MLAPT::ropeComputType; + using ropeOutputType = typename MLAPT::ropeOutputType; + using queryOutputType = typename std::conditional::type; + using kvCacheType = typename MLAPT::kvCacheType; + using krCacheType = typename MLAPT::krCacheType; + using dequantScaleQNopeType = typename MLAPT::dequantScaleQNopeType; + using dequantScaleQNormType = typename MLAPT::dequantScaleQNormType; + using dequantScaleType = typename MLAPT::dequantScaleType; + + MMParams mmCqParam_; + MMParams mmCkvKrParam_; + MMParams mmQcQrParam_; + MMParams mmQnParam_; + + __aicore__ inline MlaPrologVecS1CubS2(TPipe *pipe, const optiling::MlaPrologTilingData *__restrict tilingData, + const optiling::MlaPrologBaseParams *__restrict baseParams) + : pipe_(pipe), tilingData_(tilingData), baseParams_(baseParams) + { + } + + __aicore__ inline void Init(__gm__ uint8_t *tokenX, __gm__ uint8_t *weightDq, __gm__ uint8_t *weightUqQr, + __gm__ uint8_t *weightUk, __gm__ uint8_t *weightDkvKr, __gm__ uint8_t *rmsnormGammaCq, + __gm__ uint8_t *rmsnormGammaCkv, __gm__ uint8_t *ropeSin, __gm__ uint8_t *ropeCos, + __gm__ uint8_t *cacheIndex, __gm__ uint8_t *kvCache, __gm__ uint8_t *krCache, + __gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *deqScaleQcQrW, __gm__ uint8_t *dequantScaleWDkvkr, + __gm__ uint8_t *quantScaleCkv, __gm__ uint8_t *quantScaleCkr, + __gm__ uint8_t *smoothScaleCq, __gm__ uint8_t *actualSeqLen, + __gm__ uint8_t *kNopeClipAlpha, __gm__ uint8_t *queryOut, __gm__ uint8_t *queryRopeOut, + __gm__ uint8_t *dequantScaleQNopeOut, __gm__ uint8_t *queryNormOut, + __gm__ uint8_t *dequantScaleQNormOut, __gm__ uint8_t *workspace); + __aicore__ inline void Process(); + +private: + __aicore__ inline void CopyGlobalParams(); + __aicore__ inline void OutputInit(__gm__ uint8_t *actualSeqLen, __gm__ uint8_t *queryOut, + __gm__ uint8_t *queryRopeOut, __gm__ uint8_t *dequantScaleQNopeOut, + __gm__ uint8_t *queryNormOut, __gm__ uint8_t *dequantScaleQNormOut); + __aicore__ inline void ScaleInit(__gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *deqScaleQcQrW, __gm__ uint8_t *dequantScaleWDkvkr, + __gm__ uint8_t *quantScaleCkv, __gm__ uint8_t *quantScaleCkr, + __gm__ uint8_t *smoothScaleCq, __gm__ uint8_t *kNopeClipAlpha); + __aicore__ inline void WorkspaceInit(__gm__ uint8_t *workspace); + __aicore__ inline void MmParamInit(); + __aicore__ inline void MmCqParamInit(); + __aicore__ inline void MmCkvKrParamInit(); + __aicore__ inline void MmQcQrParamInit(); + __aicore__ inline void MmQnParamInit(); + __aicore__ inline void CubeBufferInit(); + __aicore__ inline void VectorBufferInit(); + __aicore__ inline void UpdateStepBatchParams(int64_t curStepBatchSize); + __aicore__ inline void ComputeAicOffset(AicOffset &aicOffset, int64_t numHeadOffset); + __aicore__ inline void ComputeBlkScatterOffsets(GlobalTensor indexGm, int64_t tokenIndex, int64_t rows, + CkvkrParams &rmsNormAndScatterCkvParams, + CkvkrParams &ropeAndScatterKrParams); + __aicore__ inline void ComputeAivOffset(AivOffset &aivOffset, int64_t batchOffset); + template + __aicore__ inline void AicProcess(AicOffset &aicOffset, int64_t batchOffset, int64_t mmQnLoops); + template + __aicore__ inline void AivProcess(AivOffset &aivOffset, int64_t batchOffset, int64_t curStepBatchSize, + int64_t numHeadOffset, int64_t mmQnLoops); + template + __aicore__ inline void + MatmulSplitN(const GlobalTensor &tensorResGm, const GlobalTensor &tensorAGm, const GlobalTensor &tensorBGm, + const MMParams &mmPara, const UsedBlockParams &mmBlockParams, + const GlobalTensor &tensorAScaleGm = {}, const GlobalTensor &tensorBScaleGm = {}); + __aicore__ inline void MatmulAndSyncQcQr(AicOffset &aicOffset); + __aicore__ inline void MatmulQcQr(AicOffset &aicOffset); + __aicore__ inline void PreloadQnAndSync(AicOffset &aicOffset, int64_t mmQnLoops); + __aicore__ inline void MatmulQnWeightPreload(int64_t weightUkOffset); + template + __aicore__ inline void MatmulQnSyncDynamicQuantAndMulQr(int64_t qcOffset, int64_t weightUkOffset, + int64_t qnResOffset, int64_t mmQnLoops); + __aicore__ inline void CopyInSinCos(int64_t tokenIndex, int64_t curVecToken, int64_t batchOffset, + int64_t curStepBatchSize); + __aicore__ inline void RmsNormCq(int64_t tokenIndex, int64_t rmsNormCqOffset, int64_t rmsNormCqResOffset, + int64_t curVecToken, int64_t curBlockTokenOffset); + __aicore__ inline void CopyDequantScaleCq(uint64_t dequantScaleCqElementNum, + LocalTensor &dequantScaleQcQr, int64_t curVecToken, + int64_t curBlockTokenOffset); + __aicore__ inline void CopyQueryNormScale(int64_t stepTokenIndex, LocalTensor &dequantScaleQcQr, + int64_t curVecToken); + __aicore__ inline void RopeAndScatterKr(LocalTensor &dequantScaleXLocal, LocalTensor &shareTmpUb, + LocalTensor &cosLocalCkvKr, + LocalTensor &sinLocalCkvKr, + CkvkrParams ropeAndScatterKrParams); + __aicore__ inline void ScatterKr(LocalTensor &outputKrLocal, CkvkrParams ropeAndScatterKrParams); + __aicore__ inline void RmsNormAndScatterCkv(LocalTensor &dequantScaleXLocal, + LocalTensor &shareTmpUb, + LocalTensor &cosLocalCkvKr, + LocalTensor &sinLocalCkvKr, + CkvkrParams rmsNormAndScatterCkvParams); + __aicore__ inline void RmsNormAndQuantizeCkv(LocalTensor &outputLocal, + LocalTensor &rmsNormShareTmpUb, + LocalTensor &dequantScaleXLocal, RmsNormParam rmsNormParams, + CkvkrParams rmsNormAndScatterCkvParams); + __aicore__ inline void ScatterCkv(LocalTensor &outputLocal, CkvkrParams rmsNormAndScatterCkvParams); + __aicore__ inline void RmsNormRopeScatterCkvKr(int64_t tokenIndex, int64_t rmsNormCkvOffset, int64_t ropeKrOffset, + int64_t curVecToken); + __aicore__ inline void RopeQr(int64_t ropeQrOffset, int64_t ropeQrResOffset, int64_t curVecToken, + int64_t curBlockTokenOffset); + __aicore__ inline void DequantQc(int64_t mmQnPreDequantOffset, int64_t mmQnPreDequantResOffset, int64_t curVecToken, + int64_t curBlockTokenOffset); + __aicore__ inline void CastQc(int64_t mmQnPreCastOffset, int64_t mmQnPreCastResOffset, int64_t curVecToken); + // 低时延算力分组场景 + template + __aicore__ inline void DequantQcAndRopeQc(AivOffset &aivOffset, int64_t batchOffset, int64_t curStepBatchSize, + int64_t numHeadOffset, int64_t mmQnLoops); + __aicore__ inline void DequantQcSplitNGroupCase(int64_t mmQnPreDequantOffset, int64_t mmQnPreDequantResOffset, + int64_t qcQrScaleOffset); + __aicore__ inline void RopeQrSplitNGroupCase(int64_t ropeQrOffset, int64_t ropeQrResOffset); + __aicore__ inline void DequantQcQrSplitN(const DequantQcQrSplitNParams &dequantQcQrSplitN); + __aicore__ inline void CastQcQrSplitN(const CastQcQrSplitNParams &castQcQrSplitN); + __aicore__ inline void RopeQrSplitN(const RopeQrSplitNParams &ropeQrSplitNParams); + __aicore__ inline void DequantAndRopeSplitNSyncMMQcQr(int64_t mmQnPreDequantOffset, int64_t mmQnPreDequantResOffset, + int64_t ropeQrOffset, int64_t ropeQrResOffset); + __aicore__ inline void DynamicQuantQnAndMulQrSyncMMQn(int64_t batchOffset, int64_t curStepBatchSize, + int64_t numHeadOffset, int64_t mmQnLoops); + + TPipe *pipe_; + const optiling::MlaPrologTilingData *__restrict tilingData_; + const optiling::MlaPrologBaseParams *__restrict baseParams_; + uint32_t blockIdx_ = 0U; + uint32_t cubeBlockIdx_ = 0U; // AIV上使用AIC的blockIdx + int64_t vectorRow_ = 1; + int64_t curVectorBlockNum_; + int64_t vectorCoreNum_; + uint64_t dequantScaleCqSize_ = 1; + uint32_t curStepVecFrontToken_; + uint32_t curStepVecFrontListNum_; + uint32_t curStepVecBackToken_; + uint32_t curVecTokenMax_; + bool enableSmoothScalesCq_; + static constexpr uint32_t cvMode = MLAPT::cvRatio; // 编译态,默认cv1:2 + static constexpr bool isFp8E8m0 = std::is_same::value; + uint32_t cvRatio_ = 2U; // 默认cv 1:2 + + struct DequantTool { + GlobalTensor deQuantScaleCqGm_; + TBuf deQuantScaleCqBuffer_; // 用于临时存储每一行的Scale,以及汇总最终每一行的Scale参数 + LocalTensor deQuantScaleCqLocal_; + __aicore__ inline DequantTool() + { + } + }; + + // 算子分组开关 + DequantTool dequantTool_; + + // GM + GlobalTensor tokenXGm_; + GlobalTensor weightDqGm_; + GlobalTensor weightUqQrGm_; + GlobalTensor weightUkGm_; + GlobalTensor weightDkvKrGm_; + GlobalTensor cacheIndexGm_; + GlobalTensor rmsnormGammaCqGm_; + GlobalTensor rmsnormGammaCkvGm_; + GlobalTensor ropeSinGm_; + GlobalTensor ropeCosGm_; + GlobalTensor kvCacheGm_; + GlobalTensor krCacheGm_; + GlobalTensor qrOutGm_; + + GlobalTensor dequantScaleXGm_; + GlobalTensor dequantScaleWDqGm_; + GlobalTensor dequantScaleWDkvkrGm_; + GlobalTensor smoothScaleCqGm_; + GlobalTensor deqScaleQcQrW_; // per-channel反量化参数 + GlobalTensor quantScaleCkvGm_; + GlobalTensor quantScaleCkrGm_; + + GlobalTensor actualSeqLenGm_; + GlobalTensor kNopeClipAlphaGm_; + + GlobalTensor rmsNormCqResGm_; + GlobalTensor mmCqResGm_; + GlobalTensor mmCkvKrResGm_; + GlobalTensor mmQcQrResGm_; + GlobalTensor mmQcQrResDequantGm_; + GlobalTensor mmQnResGm_; + GlobalTensor dequantScaleQNopeGm_; + GlobalTensor queryOutGm_; + GlobalTensor dequantScaleQNormGm_; + + // UB + TBuf sincosBuffer_; + TBuf shareBuffer_; + TBuf dequantScaleWDqBuffer_; + TBuf dequantScaleWDkvKrBuffer_; + TBuf rmsnormGammaCqBuffer_; + TBuf rmsnormGammaCkvBuffer_; + TBuf smoothScaleCqBuffer_; + TBuf quantScaleCkvBuffer_; + TBuf quantScaleCkrBuffer_; + TBuf stepActualSeqBuffer_; + + LocalTensor cosLocal_; + LocalTensor sinLocal_; + LocalTensor dequantScaleWDqLocal_; + LocalTensor dequantScaleWDkvKrLocal_; + LocalTensor rmsnormGammaCqLocal_; + LocalTensor rmsnormGammaCkvLocal_; + LocalTensor smoothScaleCqLocal_; + LocalTensor quantScaleCkvLocal_; + LocalTensor quantScaleCkrLocal_; + LocalTensor stepActualSeqLocal_; + + struct ActSeqState { + bool inited = false; // whether state is initialized for the run + int64_t curBatch = 0; // current batch index for the running token index + int64_t prevPrefix = 0; // prefix sum of seq lengths up to (curBatch - 1) + int64_t curPrefix = 0; // prefix sum of seq lengths up to curBatch (exclusive high bound) + int64_t prevIndexOffset = 0; // prefix sum of blocks up to (curBatch - 1) + int64_t curIndexOffset = 0; // prefix sum of blocks up to curBatch + }; + ActSeqState actSeqState_; + int64_t blockSpanPerBatch_ = 0; // blockNum * blockSize + + TBuf aBufL1_; + TBuf bBufL1_; + LocalTensor aL1Tensor_; + LocalTensor bL1Tensor_; + MMBufParams bufParam_; + TBuf aBufL0_; + TBuf bBufL0_; + TBuf cBufL0_; +}; + +template +__aicore__ inline void MlaPrologVecS1CubS2::Init( + __gm__ uint8_t *tokenX, __gm__ uint8_t *weightDq, __gm__ uint8_t *weightUqQr, __gm__ uint8_t *weightUk, + __gm__ uint8_t *weightDkvKr, __gm__ uint8_t *rmsnormGammaCq, __gm__ uint8_t *rmsnormGammaCkv, + __gm__ uint8_t *ropeSin, __gm__ uint8_t *ropeCos, __gm__ uint8_t *cacheIndex, __gm__ uint8_t *kvCache, + __gm__ uint8_t *krCache, __gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *deqScaleQcQrW, __gm__ uint8_t *dequantScaleWDkvkr, __gm__ uint8_t *quantScaleCkv, + __gm__ uint8_t *quantScaleCkr, __gm__ uint8_t *smoothScaleCq, __gm__ uint8_t *actualSeqLen, + __gm__ uint8_t *kNopeClipAlpha, __gm__ uint8_t *queryOut, __gm__ uint8_t *queryRopeOut, + __gm__ uint8_t *dequantScaleQNopeOut, __gm__ uint8_t *queryNormOut, __gm__ uint8_t *dequantScaleQNormOut, + __gm__ uint8_t *workspace) +{ + cvRatio_ = GetSubBlockNum(); // CV1:2场景返回2,其他场景返回1 + blockIdx_ = GetBlockIdx(); // cube:0-23 vec:0-47 + if ASCEND_IS_AIC { + cubeBlockIdx_ = blockIdx_; + } else { + cubeBlockIdx_ = blockIdx_ / cvRatio_; + } + curVectorBlockNum_ = static_cast(baseParams_->stepBatchSize); + vectorCoreNum_ = static_cast(baseParams_->vectorBlockNum); // aivNum 48 + if (cvMode == 1 && cvRatio_ == 2) { // 编译态cv1:1,运行态cv1:2 + if (vectorCoreNum_ < curVectorBlockNum_) { + vectorCoreNum_ = vectorCoreNum_ * 2; // 修正为运行态vector数目 + } + } + curVecTokenMax_ = (curVectorBlockNum_ + vectorCoreNum_ - 1) / vectorCoreNum_; + enableSmoothScalesCq_ = smoothScaleCq == nullptr ? false : true; + // GM + tokenXGm_.SetGlobalBuffer((__gm__ mmInputType *)tokenX); + weightDqGm_.SetGlobalBuffer((__gm__ mmInputType *)weightDq); // NZ + weightUqQrGm_.SetGlobalBuffer((__gm__ mmQcQrInputType *)weightUqQr); // NZ + weightUkGm_.SetGlobalBuffer((__gm__ mmQnInputType *)weightUk); + weightDkvKrGm_.SetGlobalBuffer((__gm__ mmInputType *)weightDkvKr); // NZ + rmsnormGammaCqGm_.SetGlobalBuffer((__gm__ rmsNormGammaType *)rmsnormGammaCq); + rmsnormGammaCkvGm_.SetGlobalBuffer((__gm__ rmsNormGammaType *)rmsnormGammaCkv); + ropeSinGm_.SetGlobalBuffer((__gm__ ropeSinCosType *)ropeSin); + ropeCosGm_.SetGlobalBuffer((__gm__ ropeSinCosType *)ropeCos); + if constexpr (MLAPT::cacheMode != CACHE_MODE::ND) { + cacheIndexGm_.SetGlobalBuffer((__gm__ int64_t *)cacheIndex); + } + kvCacheGm_.SetGlobalBuffer((__gm__ kvCacheType *)kvCache); + krCacheGm_.SetGlobalBuffer((__gm__ krCacheType *)krCache); + + OutputInit(actualSeqLen, queryOut, queryRopeOut, dequantScaleQNopeOut, queryNormOut, dequantScaleQNormOut); + ScaleInit(dequantScaleX, dequantScaleWDq, deqScaleQcQrW, dequantScaleWDkvkr, quantScaleCkv, quantScaleCkr, + smoothScaleCq, kNopeClipAlpha); + MmParamInit(); + WorkspaceInit(workspace); + if ASCEND_IS_AIV { + VectorBufferInit(); + } else { + CubeBufferInit(); + } +} + +template +__aicore__ inline void +MlaPrologVecS1CubS2::OutputInit(__gm__ uint8_t *actualSeqLen, __gm__ uint8_t *queryOut, + __gm__ uint8_t *queryRopeOut, __gm__ uint8_t *dequantScaleQNopeOut, + __gm__ uint8_t *queryNormOut, __gm__ uint8_t *dequantScaleQNormOut) +{ + qrOutGm_.SetGlobalBuffer((__gm__ ropeOutputType *)queryRopeOut); + if constexpr (((std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value)) && + !isPertile) { + dequantScaleQNopeGm_.SetGlobalBuffer((__gm__ dequantScaleQNopeType *)dequantScaleQNopeOut); + queryOutGm_.SetGlobalBuffer((__gm__ queryOutputType *)queryOut); + } else { + mmQnResGm_.SetGlobalBuffer((__gm__ mmQnOutputType *)queryOut); + } + if (baseParams_->queryNormFlag == 1U) { + rmsNormCqResGm_.SetGlobalBuffer((__gm__ mmQcQrInputType *)queryNormOut); + + if constexpr (IsFullQuantMode()) { + dequantScaleQNormGm_.SetGlobalBuffer((__gm__ dequantScaleQNormType *)dequantScaleQNormOut); + } + } + if constexpr (MLAPT::actualSeqMode == ACTUAL_SEQ_MODE::EN_Q_LEN) { + actualSeqLenGm_.SetGlobalBuffer((__gm__ int32_t *)actualSeqLen); + } +} + +template +__aicore__ inline void +MlaPrologVecS1CubS2::ScaleInit(__gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *deqScaleQcQrW, __gm__ uint8_t *dequantScaleWDkvkr, + __gm__ uint8_t *quantScaleCkv, __gm__ uint8_t *quantScaleCkr, + __gm__ uint8_t *smoothScaleCq, __gm__ uint8_t *kNopeClipAlpha) +{ + if constexpr (IsFullQuantMode()) { + dequantScaleXGm_.SetGlobalBuffer((__gm__ dequantScaleType *)dequantScaleX); + dequantScaleWDqGm_.SetGlobalBuffer((__gm__ dequantScaleType *)dequantScaleWDq); + dequantScaleWDkvkrGm_.SetGlobalBuffer((__gm__ dequantScaleType *)dequantScaleWDkvkr); + } + + if constexpr (IsFullQuantMode()) { + smoothScaleCqGm_.SetGlobalBuffer((__gm__ float *)smoothScaleCq); + deqScaleQcQrW_.SetGlobalBuffer((__gm__ dequantScaleType *)deqScaleQcQrW); + quantScaleCkvGm_.SetGlobalBuffer((__gm__ float *)quantScaleCkv); + quantScaleCkrGm_.SetGlobalBuffer((__gm__ float *)quantScaleCkr); + } else if constexpr (std::is_same::value && isFp8E8m0) { + deqScaleQcQrW_.SetGlobalBuffer((__gm__ dequantScaleType *)deqScaleQcQrW); + quantScaleCkvGm_.SetGlobalBuffer((__gm__ float *)quantScaleCkv); + } + + if constexpr (isPertile) { + kNopeClipAlphaGm_.SetGlobalBuffer((__gm__ float *)kNopeClipAlpha); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MmParamInit() +{ + MmCqParamInit(); + MmCkvKrParamInit(); + MmQcQrParamInit(); + MmQnParamInit(); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MmCqParamInit() +{ + mmCqParam_.m = baseParams_->stepBatchSize; // 32 + if (cubeBlockIdx_ == baseParams_->mm1BlockNum - 1) { + mmCqParam_.n = baseParams_->headSizeCq - baseParams_->mm1SingleCoreN * cubeBlockIdx_; + } else { + mmCqParam_.n = baseParams_->mm1SingleCoreN; // 1536 / 24 = 64 + } + mmCqParam_.k = baseParams_->headSizeX; // 7168 + mmCqParam_.needSetOrgShape = 1; + mmCqParam_.orgM = mmCqParam_.m; + mmCqParam_.orgN = mmCqParam_.n; + mmCqParam_.orgKa = mmCqParam_.k; + mmCqParam_.orgKb = mmCqParam_.k; + mmCqParam_.orgKc = baseParams_->headSizeCq; // 1536 + mmCqParam_.baseK = + (sizeof(mmInputType) == ONE_BYTE_TYPE_SIZE) ? 256 : 128; // 128KB / (128 max baseN * 4 stepK * sizeof(type)) + mmCqParam_.baseN = (std::is_same::value && isFp8E8m0) ? 64 : 128; + mmCqParam_.stepK = 4; + if ((mmCqParam_.k / mmCqParam_.baseK) % mmCqParam_.stepK != 0) { + mmCqParam_.stepK = 3; // support k = 7680, mmInputType int8, no tail + } + mmCqParam_.kL1StepSize = mmCqParam_.baseK * mmCqParam_.stepK; + mmCqParam_.kScale = mmCqParam_.k / FP8_E4M3_BLOCK_SIZE; +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MmCkvKrParamInit() +{ + mmCkvKrParam_.m = baseParams_->stepBatchSize; // 32 + if (cubeBlockIdx_ == baseParams_->mm2BlockNum - 1) { + mmCkvKrParam_.n = + baseParams_->headSizeCkv + baseParams_->headSizeKr - baseParams_->mm2SingleCoreN * cubeBlockIdx_; + } else { + mmCkvKrParam_.n = baseParams_->mm2SingleCoreN; + } + mmCkvKrParam_.k = baseParams_->headSizeX; // 7168 + mmCkvKrParam_.needSetOrgShape = 1; + mmCkvKrParam_.orgM = mmCkvKrParam_.m; + mmCkvKrParam_.orgN = mmCkvKrParam_.n; + mmCkvKrParam_.orgKa = mmCkvKrParam_.k; + mmCkvKrParam_.orgKb = mmCkvKrParam_.k; + mmCkvKrParam_.orgKc = (baseParams_->headSizeCkv + baseParams_->dimHeadRope); // 576 + mmCkvKrParam_.baseK = + (sizeof(mmInputType) == ONE_BYTE_TYPE_SIZE) ? 256 : 128; // 128KB / (128 max baseN * 4 stepK * sizeof(type)) + mmCkvKrParam_.baseN = 128; + mmCkvKrParam_.stepK = 4; + if ((mmCkvKrParam_.k / mmCkvKrParam_.baseK) % mmCkvKrParam_.stepK != 0) { + mmCkvKrParam_.stepK = 3; // support k = 7680, mmInputType int8, no tail + } + mmCkvKrParam_.kL1StepSize = mmCkvKrParam_.baseK * mmCkvKrParam_.stepK; + mmCkvKrParam_.kScale = mmCkvKrParam_.k / FP8_E4M3_BLOCK_SIZE; +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MmQcQrParamInit() +{ + mmQcQrParam_.m = baseParams_->stepBatchSize; // 32 + if constexpr (MLAPT::enableGroupComputeOpt) { + // 算力分组仅考虑G8 Qc Qr(8+4核), n固定128, 这里不处理尾核 + mmQcQrParam_.n = baseParams_->mm3SingleCoreN; + } else { + if (cubeBlockIdx_ == baseParams_->mm3BlockNum - 1) { + mmQcQrParam_.n = + baseParams_->headSizeQc + baseParams_->headSizeQr - baseParams_->mm3SingleCoreN * cubeBlockIdx_; + } else { + mmQcQrParam_.n = baseParams_->mm3SingleCoreN; + } + } + + mmQcQrParam_.k = baseParams_->headSizeCq; // 1536 + mmQcQrParam_.needSetOrgShape = 1; + mmQcQrParam_.orgM = mmQcQrParam_.m; + mmQcQrParam_.orgN = mmQcQrParam_.n; + mmQcQrParam_.orgKa = mmQcQrParam_.k; + mmQcQrParam_.orgKb = mmQcQrParam_.k; + mmQcQrParam_.orgKc = (baseParams_->headSizeQc + baseParams_->headSizeQr); // (128 * 32 + 64 * 32) + mmQcQrParam_.baseK = (sizeof(mmQcQrInputType) == ONE_BYTE_TYPE_SIZE) ? 128 : 64; + if constexpr (MLAPT::enableGroupComputeOpt) { + mmQcQrParam_.baseN = 128; + } else { + if constexpr (std::is_same::value && + isFp8E8m0) { // FP8全量化场景下L1B用满,修改baseN会造成内存踩踏 + mmQcQrParam_.baseN = 128; + } else { + if (mmQcQrParam_.m <= 64) { // FP8全量化场景,scale需要额外占用L1,该优化不适用 + mmQcQrParam_.baseN = 256; + } else { + mmQcQrParam_.baseN = 128; + } + } + } + mmQcQrParam_.stepK = 4; + mmQcQrParam_.kL1StepSize = mmQcQrParam_.baseK * mmQcQrParam_.stepK; + mmQcQrParam_.kScale = mmQcQrParam_.k / FP8_E4M3_BLOCK_SIZE; +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MmQnParamInit() +{ + mmQnParam_.m = baseParams_->stepBatchSize; // 32 + mmQnParam_.n = baseParams_->headSizeCkv; // 512 + mmQnParam_.k = baseParams_->dimHeadSizeQc; // 128, 这里numHeadSize被分核,matmul设置里不体现 + mmQnParam_.needSetOrgShape = 1; + mmQnParam_.orgM = mmQnParam_.m; + mmQnParam_.orgN = mmQnParam_.n; + if constexpr (std::is_same::value || std::is_same::value) { + mmQnParam_.orgKa = baseParams_->headSizeQc; + } else { + mmQnParam_.orgKa = baseParams_->headSizeQc + baseParams_->headSizeQr; + } + mmQnParam_.orgKb = baseParams_->dimHeadSizeQc; + mmQnParam_.orgKc = baseParams_->headSizeCkv * baseParams_->numHeadSize; + mmQnParam_.baseN = 128; + mmQnParam_.baseK = 128; + mmQnParam_.stepK = 1; + if ((mmQnParam_.k > mmQnParam_.baseK) && (mmQnParam_.k % mmQnParam_.baseK != 0)) { + mmQnParam_.baseK = 64; + mmQnParam_.stepK = 3; // support D = 192 + } + mmQnParam_.kL1StepSize = mmQnParam_.baseK * mmQnParam_.stepK; + mmQnParam_.kScale = mmQnParam_.k / FP8_E4M3_BLOCK_SIZE; +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::VectorBufferInit() +{ + // 暂存已分配UB大小,其余为shareBuffer + uint64_t usedBytes = 0; + if constexpr (IsFullQuantMode()) { + uint64_t dequantScaleWDqSize = baseParams_->headSizeCq * sizeof(float); + pipe_->InitBuffer(dequantScaleWDqBuffer_, dequantScaleWDqSize); // [1, 1536] + dequantScaleWDqLocal_ = dequantScaleWDqBuffer_.Get(); + usedBytes += dequantScaleWDqSize; + + uint64_t dequantScaleWDkvKrSize = (baseParams_->headSizeCkv + baseParams_->dimHeadRope) * sizeof(float); + pipe_->InitBuffer(dequantScaleWDkvKrBuffer_, dequantScaleWDkvKrSize); // [1, 512 + 64] + dequantScaleWDkvKrLocal_ = dequantScaleWDkvKrBuffer_.Get(); + usedBytes += dequantScaleWDkvKrSize; + } + uint64_t rmsnormGammaCqSize = baseParams_->headSizeCq * sizeof(rmsNormGammaType); + pipe_->InitBuffer(rmsnormGammaCqBuffer_, rmsnormGammaCqSize); // [1, 1536] bf16 + rmsnormGammaCqLocal_ = rmsnormGammaCqBuffer_.Get(); + usedBytes += rmsnormGammaCqSize; + + uint64_t rmsnormGammaCkvSize = baseParams_->headSizeCkv * sizeof(rmsNormGammaType); + pipe_->InitBuffer(rmsnormGammaCkvBuffer_, rmsnormGammaCkvSize); // [1, 512] bf16 + rmsnormGammaCkvLocal_ = rmsnormGammaCkvBuffer_.Get(); + usedBytes += rmsnormGammaCkvSize; + + if constexpr (IsFullQuantMode()) { + if (enableSmoothScalesCq_) { + uint64_t smoothScaleCqSize = baseParams_->headSizeCq * sizeof(float); + pipe_->InitBuffer(smoothScaleCqBuffer_, smoothScaleCqSize); // [1, 1536] + smoothScaleCqLocal_ = smoothScaleCqBuffer_.Get(); + usedBytes += smoothScaleCqSize; + } + } + + if constexpr (std::is_same::value) { + uint64_t quantScaleCkrSize = baseParams_->dimHeadRope * sizeof(float); + pipe_->InitBuffer(quantScaleCkrBuffer_, baseParams_->dimHeadRope * sizeof(float)); // [1, 64] + quantScaleCkrLocal_ = quantScaleCkrBuffer_.Get(); + usedBytes += quantScaleCkrSize; + } + + if constexpr (IsFullQuantMode()) { + uint64_t quantScaleCkvSize = 0; + if constexpr (std::is_same::value || + std::is_same::value) { + quantScaleCkvSize = ALIGN_BLOCK_SIZE; + pipe_->InitBuffer(quantScaleCkvBuffer_, quantScaleCkvSize); + } else { // per_channel量化场景走else分支 + quantScaleCkvSize = baseParams_->headSizeCkv * sizeof(float); + pipe_->InitBuffer(quantScaleCkvBuffer_, quantScaleCkvSize); // [1, 512] + } + quantScaleCkvLocal_ = quantScaleCkvBuffer_.Get(); + usedBytes += quantScaleCkvSize; + } + + // 预留brcb的空间 + uint64_t deQuantScaleCqSize = (baseParams_->stepBatchSize + 7) * ALIGN_BLOCK_SIZE; + pipe_->InitBuffer(dequantTool_.deQuantScaleCqBuffer_, deQuantScaleCqSize); + dequantTool_.deQuantScaleCqLocal_ = dequantTool_.deQuantScaleCqBuffer_.template Get(); + usedBytes += deQuantScaleCqSize; + + uint64_t sincosSize = 0; + if constexpr (MLAPT::enableDequantOpt) { + // 在ropeQr进行切N处理后,会复用shareBuffer的内存,不需要额外申请 + // 开启开关后会按照head切分rope qr,此时需要加载一半batchsize数量的sin和cos值 + // 需要2倍的空间分别存储sin和cos + sincosSize = 2 * baseParams_->dimHeadRope * sizeof(ropeComputType) * + ((baseParams_->stepBatchSize + cvRatio_ - 1) / cvRatio_); + pipe_->InitBuffer(sincosBuffer_, sincosSize); + } else { + // 需要2倍的空间分别存储sin和cos + sincosSize = 2 * baseParams_->dimHeadRope * sizeof(ropeComputType) * curVecTokenMax_; + pipe_->InitBuffer(sincosBuffer_, sincosSize); // [2, 64] float + } + usedBytes += sincosSize; + + if constexpr (MLAPT::enableDequantOpt) { + cosLocal_ = sincosBuffer_.Get(); + sinLocal_ = cosLocal_[baseParams_->dimHeadRope * ((baseParams_->stepBatchSize + cvRatio_ - 1) / cvRatio_)]; + } else { + cosLocal_ = sincosBuffer_.Get(); + sinLocal_ = cosLocal_[baseParams_->dimHeadRope * curVecTokenMax_]; + } + + if constexpr (MLAPT::actualSeqMode == ACTUAL_SEQ_MODE::EN_Q_LEN) { + uint64_t stepActualSeqSize = baseParams_->stepBatchSize * sizeof(int64_t); + pipe_->InitBuffer(stepActualSeqBuffer_, stepActualSeqSize); // [1, stepBatchSize] + stepActualSeqLocal_ = stepActualSeqBuffer_.Get(); + usedBytes += stepActualSeqSize; + } + + // 由于shareBuffer属于各个vector操作临时申请内存的区域内存使用不固定,建议shareBuffer始终放在最后 + // 防止写入shareBuffer越界导致前面固定申请的UB内存被踩。 + pipe_->InitBuffer(shareBuffer_, MAX_UB_SIZE - usedBytes); + CrossCoreSetFlag(FINISH_VEC_CKVKR); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::CubeBufferInit() +{ + // cube相关Buffer初始化 + pipe_->InitBuffer(aBufL1_, L1_A_SIZE * 2); + pipe_->InitBuffer(bBufL1_, L1_B_SIZE * 2); + + SetFlag(A_EVENT0); + SetFlag(A_EVENT1); + SetFlag(B_EVENT0); + SetFlag(B_EVENT1); + aL1Tensor_ = aBufL1_.Get(); + bL1Tensor_ = bBufL1_.Get(); + bufParam_.aL1BufAddr = aBufL1_.GetBufferAddr(aL1Tensor_.GetBufferHandle()); + bufParam_.bL1BufAddr = bBufL1_.GetBufferAddr(bL1Tensor_.GetBufferHandle()); + + pipe_->InitBuffer(aBufL0_, L0A_PP_SIZE * 2); // 64K + pipe_->InitBuffer(bBufL0_, L0B_PP_SIZE * 2); // 64K + pipe_->InitBuffer(cBufL0_, L0C_PP_SIZE * 2); // 128K + + SetFlag(L0A_EVENT0); + SetFlag(L0A_EVENT1); + SetFlag(L0B_EVENT0); + SetFlag(L0B_EVENT1); + + SetFlag(L0C_EVENT0); + SetFlag(L0C_EVENT1); + + SetFlag(SCALE_EVENT); + + bufParam_.aL0BufAddr = aBufL0_.GetBufferAddr(aBufL0_.Get().GetBufferHandle()); + bufParam_.bL0BufAddr = bBufL0_.GetBufferAddr(bBufL0_.Get().GetBufferHandle()); + bufParam_.cL0BufAddr = cBufL0_.GetBufferAddr(cBufL0_.Get().GetBufferHandle()); +} + +/* + * workspace管理 + * 1. 常驻:dequantTool_.deQuantScaleCqGm_ stepBs * 32 Byte + * 2. 中间结果: + * tokenXGm_──────>mmCkvKrResGm_ + * | [stepBS, HCkv + Dr] + * | (bf16 | int32) + * └─────────>mmCqResGm_──────>rmsNormCqResGm_──────>mmQcQrResGm_──────>mmQcQrResDequantGm_──────>mmQnResGm_ + * [stepBS, HCq] [stepBS, HCq] [stepBS, N1, D + Dr] [stepBS, N1, D] [stepBS, N1, + * HCkv] (bf16 | int32) (bf16 | int8) (bf16 | int32) (bf16) (bf16) + */ +template +__aicore__ inline void MlaPrologVecS1CubS2::WorkspaceInit(__gm__ uint8_t *workspace) +{ + int64_t workspaceOffset = 0; + if constexpr (std::is_same::value && isFp8E8m0) { + dequantScaleCqSize_ = baseParams_->headSizeCq / FP8_E4M3_BLOCK_SIZE; + } + dequantScaleCqSize_ = Align(dequantScaleCqSize_, BYTE_BLOCK); + if constexpr (MLAPT::enableGroupComputeOpt || MLAPT::enableDequantOpt) { + dequantTool_.deQuantScaleCqGm_.SetGlobalBuffer((__gm__ dequantScaleType *)(workspace + workspaceOffset)); + workspaceOffset += baseParams_->stepBatchSize * dequantScaleCqSize_; + } + + mmCkvKrResGm_.SetGlobalBuffer((__gm__ mmCkvKrOutputType *)(workspace + workspaceOffset)); + workspaceOffset += static_cast(baseParams_->stepBatchSize) * + static_cast(baseParams_->headSizeCkv + baseParams_->dimHeadRope) * + static_cast(sizeof(mmCkvKrOutputType)); + + mmCqResGm_.SetGlobalBuffer((__gm__ mmCqOutputType *)(workspace + workspaceOffset)); + + if (baseParams_->queryNormFlag == 0U) { + // 全量化场景下`mmCqResGm_`与`rmsNormCqResGm_`的dtype不同,无法共用workspace,此处需要偏移`mmCqResGm_`占用的大小; + if constexpr (!std::is_same::value) { + workspaceOffset += static_cast(baseParams_->stepBatchSize) * + static_cast(baseParams_->headSizeCq) * + static_cast(sizeof(mmCqOutputType)); + } + // 不返回queryNorm时,rmsNormCq结果放在workspace + rmsNormCqResGm_.SetGlobalBuffer((__gm__ rmsNormCqOutputType *)(workspace + workspaceOffset)); + workspaceOffset += static_cast(baseParams_->stepBatchSize) * + static_cast(baseParams_->headSizeCq) * sizeof(rmsNormCqOutputType); + } else { + // 返回queryNorm时,rmsNormCq结果直接输出gm,此处需要偏移`mmCqResGm_`占用的大小 + workspaceOffset += static_cast(baseParams_->stepBatchSize) * + static_cast(baseParams_->headSizeCq) * static_cast(sizeof(mmCqOutputType)); + } + + mmQcQrResGm_.SetGlobalBuffer((__gm__ mmQcQrOutputType *)(workspace + workspaceOffset)); + if constexpr (IsFullQuantMode()) { + workspaceOffset += static_cast(baseParams_->stepBatchSize) * + static_cast(baseParams_->headSizeQc + baseParams_->headSizeQr) * + static_cast(sizeof(mmQcQrOutputType)); + } + + mmQcQrResDequantGm_.SetGlobalBuffer((__gm__ mmQnInputType *)(workspace + workspaceOffset)); + if constexpr (((std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value)) && + !isPertile) { + workspaceOffset += static_cast(baseParams_->stepBatchSize) * + static_cast(baseParams_->numHeadSize) * + static_cast(baseParams_->dimHeadSizeQc) * sizeof(mmQnInputType); + mmQnResGm_.SetGlobalBuffer((__gm__ mmQnOutputType *)(workspace + workspaceOffset)); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::UpdateStepBatchParams(int64_t curStepBatchSize) +{ + mmCqParam_.m = curStepBatchSize; + mmCkvKrParam_.m = curStepBatchSize; + mmQcQrParam_.m = curStepBatchSize; + mmQnParam_.m = curStepBatchSize; + curVectorBlockNum_ = curStepBatchSize; +} + +/* + * MlaProlog算子计算&CV流水同步流程 + * ┌───────────────── token_x ─────────────────┐ + * | ▼ + * | MatmulCkvKr + * ▼ | wait mm CkvKr(0x1) + * MatmulCq ▼ + * | wait mm Cq(0x1) ┌─────────────────┐ + * ▼ ▼ ▼ + * RmsNorm(Cq) RmsNorm(Ckv) Rope(Kr) + * | wait rmsNorm cq(0x1) | | + * ▼ ▼ ▼ + * ┌───────MatmulQcQr───────┐ Scatter(Ckv) Scatter(Kr) + * | wait mm Qc(0x1) | | | + * ▼ | ▼ ▼ + * DequantQc | kv_cache_out kr_cache_out + * | wait dequant qc(0x1) | wait mm Qr(0x2) + * ▼ ▼ + * MatmulQn Rope(Qr) + * | wait mm Qn(0x1) | + * DynamicQuantQn──┐ | + * | ▼ | + * ▼ dequant_scale_out ▼ + * query_out query_rope_out + * 注:仅为表明基本计算与CV同步流程,仅包含了影响CV同步的量化分支,其余量化分支应参考设计文档。 + */ +template +__aicore__ inline void MlaPrologVecS1CubS2::Process() +{ + constexpr bool needQnDynamicQuant = + ((std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value) || + (std::is_same::value && std::is_same::value)) && + !isPertile; + int64_t numHeadOffset = cubeBlockIdx_ * baseParams_->mm4SingleCoreBatch; + int64_t mmQnLoops; + if (cubeBlockIdx_ == baseParams_->mm4BlockNum - 1) { + mmQnLoops = static_cast(baseParams_->numHeadSize) - numHeadOffset; + } else { + mmQnLoops = static_cast(baseParams_->mm4SingleCoreBatch); + } + + // AIC的offset参数 + AicOffset aicOffset; + ComputeAicOffset(aicOffset, numHeadOffset); + + // AIV的offset参数 + AivOffset aivOffset; + ComputeAivOffset(aivOffset, 0); + + int64_t bsSize = static_cast(baseParams_->tokenSize); + // 需要考虑BS合轴的尾块情况 + for (int64_t batchOffset = 0; batchOffset < bsSize; + batchOffset += static_cast(baseParams_->stepBatchSize)) { + if constexpr (MLAPT::actualSeqMode == ACTUAL_SEQ_MODE::EN_Q_LEN) { + if (!actSeqState_.inited) { + actSeqState_.curBatch = 0; + actSeqState_.prevPrefix = 0; + actSeqState_.curPrefix = (baseParams_->batchSize > 0) ? actualSeqLenGm_(0) : 0; + actSeqState_.inited = true; + actSeqState_.prevIndexOffset = 0; + actSeqState_.curIndexOffset = + CeilDivT(actSeqState_.curPrefix, static_cast(baseParams_->blockSize)); + } + } + int64_t curStepBatchSize = bsSize - batchOffset; + if (curStepBatchSize < static_cast(baseParams_->stepBatchSize)) { + UpdateStepBatchParams(curStepBatchSize); // 320 - 256 + if (batchOffset != 0) { + ComputeAivOffset(aivOffset, batchOffset); + } + } else { + curStepBatchSize = static_cast(baseParams_->stepBatchSize); + } + if ASCEND_IS_AIC { + AicProcess(aicOffset, batchOffset, mmQnLoops); + } + if ASCEND_IS_AIV { + AivProcess(aivOffset, batchOffset, curStepBatchSize, numHeadOffset, mmQnLoops); + } + } + if ASCEND_IS_AIC { + WaitFlag(A_EVENT0); + WaitFlag(A_EVENT1); + WaitFlag(B_EVENT0); + WaitFlag(B_EVENT1); + + WaitFlag(L0A_EVENT0); + WaitFlag(L0A_EVENT1); + WaitFlag(L0B_EVENT0); + WaitFlag(L0B_EVENT1); + + WaitFlag(L0C_EVENT0); + WaitFlag(L0C_EVENT1); + + WaitFlag(SCALE_EVENT); + CrossCoreWaitFlag(FINISH_VEC_CKVKR); + } +} + +template +template +__aicore__ inline void MlaPrologVecS1CubS2::AicProcess(AicOffset &aicOffset, int64_t batchOffset, + int64_t mmQnLoops) +{ + int64_t tokenXOffset = batchOffset * static_cast(baseParams_->headSizeX); + int64_t dequantScaleXOffset = batchOffset * static_cast(baseParams_->headSizeX) / 32; + GlobalTensor scaleAGm{}; + GlobalTensor scaleBGmDq{}; + GlobalTensor scaleBGmDkvKr{}; + if constexpr (std::is_same::value && isFp8E8m0) { + scaleAGm = dequantScaleXGm_[dequantScaleXOffset]; + scaleBGmDq = dequantScaleWDqGm_[aicOffset.dequantScaleWDqOffset]; + scaleBGmDkvKr = dequantScaleWDkvkrGm_[aicOffset.dequantScaleWDkvKrOffset]; + } + // MatmulCq ──> RmsNorm(Cq) + // [32, 7168] * [7168, 1536] = [32, 1536] + MatmulSplitN( + mmCqResGm_[aicOffset.cqResOffset], tokenXGm_[tokenXOffset], weightDqGm_[aicOffset.weightDqOffset], mmCqParam_, + UsedBlockParams{0, baseParams_->mm1BlockNum}, scaleAGm, scaleBGmDq); + CrossCoreSetFlag(FINISH_MM_CQ); + // MatmulCkvKr ──> RmsNorm(Ckv) + // └──> Rope(Kr) + // [32, 7168] * [7168, 512+64] = [32, 576] + CrossCoreWaitFlag(FINISH_VEC_CKVKR); + MatmulSplitN( + mmCkvKrResGm_[aicOffset.ckvKrResOffset], tokenXGm_[tokenXOffset], weightDkvKrGm_[aicOffset.weightDkvKrOffset], + mmCkvKrParam_, UsedBlockParams{0, baseParams_->mm2BlockNum}, scaleAGm, scaleBGmDkvKr); + CrossCoreSetFlag(FINISH_MM_CKVKR); + CrossCoreWaitFlag(FINISH_VEC_RMSNORM_CQ); + + if constexpr (std::is_same::value && isFp8E8m0) { + MatmulQcQr(aicOffset); + } else { + MatmulAndSyncQcQr(aicOffset); + } + if constexpr (std::is_same::value && isFp8E8m0) { + WaitFlag(SCALE_EVENT); // FP8场景下Scale不做db,需要等scale用完才能做mmQn + } + PreloadQnAndSync(aicOffset, mmQnLoops); + MatmulQnSyncDynamicQuantAndMulQr(aicOffset.qcOffset, aicOffset.weightUkOffset, + aicOffset.qnResOffset, mmQnLoops); + if constexpr (std::is_same::value && isFp8E8m0) { + SetFlag(SCALE_EVENT); // FP8场景下Scale不做db,需要mmQn用完才能做下一轮 + } + if constexpr (!needQnDynamicQuant) { + // MatmulQn的结果直接输出到 queryOut, qnOffset需要按Batch轴偏移 + aicOffset.qnResOffset += static_cast(baseParams_->stepBatchSize) * + static_cast(baseParams_->headSizeCkv) * + static_cast(baseParams_->numHeadSize); + } + if (unlikely(baseParams_->queryNormFlag == 1U)) { + aicOffset.rmsNormCqResOffset += + static_cast(baseParams_->stepBatchSize) * static_cast(baseParams_->headSizeCq); + } +} + +template +template +__aicore__ inline void MlaPrologVecS1CubS2::AivProcess(AivOffset &aivOffset, int64_t batchOffset, + int64_t curStepBatchSize, int64_t numHeadOffset, + int64_t mmQnLoops) +{ + int64_t tokenIndex = batchOffset + aivOffset.curBlockTokenOffset; + int64_t rmsNormCqResOffset = + baseParams_->queryNormFlag == 1U ? tokenIndex * baseParams_->headSizeCq : aivOffset.rmsNormCqOffset; + + if (batchOffset == 0) { + // 只需要搬运一次 + CopyGlobalParams(); + } + CopyInSinCos(tokenIndex, aivOffset.curVecToken, batchOffset, curStepBatchSize); + CrossCoreWaitFlag(FINISH_MM_CQ); + WaitAllCore(FINISH_VEC_ALL); + RmsNormCq(tokenIndex, aivOffset.rmsNormCqOffset, rmsNormCqResOffset, aivOffset.curVecToken, + aivOffset.curBlockTokenOffset); + // 由于RmsNormCq和MatmulQcQr的分核策略不一样,需要等所有vector上的RmsNormCq执行完成后才能启动MatmulQcQr + // 需要所有vector核上的RmsNormCq执行完成后,才发起MatmulQcQr的执行 + WaitAllCore(FINISH_VEC_ALL); + + // 聚合全部scale结果 + if constexpr ((MLAPT::enableDequantOpt || MLAPT::enableGroupComputeOpt) && + IsFullQuantMode()) { + DataCopy(dequantTool_.deQuantScaleCqLocal_, dequantTool_.deQuantScaleCqGm_, + ALIGN_BLOCK_SIZE / sizeof(float) * baseParams_->stepBatchSize); + } + CrossCoreSetFlag(FINISH_VEC_RMSNORM_CQ); + CrossCoreWaitFlag(FINISH_MM_CKVKR); + WaitAllCore(FINISH_VEC_ALL); + RmsNormRopeScatterCkvKr(tokenIndex, aivOffset.rmsNormCkvOffset, aivOffset.ropeKrOffset, aivOffset.curVecToken); + CrossCoreSetFlag(FINISH_VEC_CKVKR); + + DequantQcAndRopeQc(aivOffset, batchOffset, curStepBatchSize, numHeadOffset, mmQnLoops); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::ComputeAicOffset(AicOffset &aicOffset, int64_t numHeadOffset) +{ + aicOffset.cqResOffset = baseParams_->mm1SingleCoreN * blockIdx_; // 64 * idx + aicOffset.weightDqOffset = static_cast(baseParams_->headSizeX) * aicOffset.cqResOffset; // 7168 * 64 * idx + aicOffset.dequantScaleWDqOffset = + static_cast(baseParams_->headSizeX) / 32 * aicOffset.cqResOffset; // 7168 * 64 * idx + + aicOffset.ckvKrResOffset = baseParams_->mm2SingleCoreN * blockIdx_; // (512 + 64) / 9 * idx = 64 * idx + aicOffset.weightDkvKrOffset = static_cast(baseParams_->headSizeX) * + aicOffset.ckvKrResOffset; // 7168 * (512 + 64) / 9 * idx = 7168 * 64 * idx + aicOffset.dequantScaleWDkvKrOffset = static_cast(baseParams_->headSizeX) / 32 * + aicOffset.ckvKrResOffset; // 7168 * (512 + 64) / 9 * idx = 7168 * 64 * idx + + if constexpr (MLAPT::enableGroupComputeOpt) { + aicOffset.weightUqOffset = static_cast(baseParams_->headSizeCq) * + (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope) * + blockIdx_; // 1536 * (32 * 128 + 32 * 64) / 24 * idx = 1536 * 256 * idx + aicOffset.weightQrOffset = static_cast(baseParams_->headSizeCq) * + (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope) * 2 * + (blockIdx_ - QC_CORE_NUM) + + static_cast(baseParams_->headSizeCq) * baseParams_->dimHeadSizeQc; + aicOffset.qCResOffset = baseParams_->dimHeadSizeQc * blockIdx_; + aicOffset.qRResOffset = + baseParams_->stepBatchSize * baseParams_->dimHeadSizeQc * QC_CORE_NUM + + baseParams_->dimHeadRope * 2 * (blockIdx_ - QC_CORE_NUM); // m=baseParams_->stepBatchSize + } else { + aicOffset.qcQrResOffset = baseParams_->mm3SingleCoreN * blockIdx_; // 192 * idx + aicOffset.weightUqQrOffset = + static_cast(baseParams_->headSizeCq) * + aicOffset.qcQrResOffset; // 1536 * (32 * 128 + 32 * 64) / 24 * idx = 1536 * 256 * idx + aicOffset.dequantScaleWuqqrOffset = aicOffset.weightUqQrOffset / 32; + } + + if (cubeBlockIdx_ < baseParams_->mm4BlockNum) { + if constexpr (std::is_same::value || std::is_same::value) { + aicOffset.qcOffset = static_cast(baseParams_->dimHeadSizeQc) * numHeadOffset; // 128 * idx + } else { + aicOffset.qcOffset = static_cast(baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope) * + numHeadOffset; // (128 + 64) * idx + } + aicOffset.weightUkOffset = static_cast(baseParams_->dimHeadSizeQc) * + static_cast(baseParams_->headSizeCkv) * numHeadOffset; // (128 * 512) * idx + aicOffset.qnResOffset = static_cast(baseParams_->headSizeCkv) * numHeadOffset; // BS, N, Dq + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::ComputeAivOffset(AivOffset &aivOffset, int64_t batchOffset) +{ + curStepVecBackToken_ = curVectorBlockNum_ / static_cast(vectorCoreNum_); + curStepVecFrontListNum_ = curVectorBlockNum_ % static_cast(vectorCoreNum_); + curStepVecFrontToken_ = curStepVecFrontListNum_ == 0 ? curStepVecBackToken_ : curStepVecBackToken_ + 1; + + aivOffset.curVecToken = blockIdx_ < curStepVecFrontListNum_ ? curStepVecFrontToken_ : curStepVecBackToken_; + aivOffset.curBlockTokenOffset = blockIdx_ < curStepVecFrontListNum_ ? + blockIdx_ * aivOffset.curVecToken : + blockIdx_ * aivOffset.curVecToken + curStepVecFrontListNum_; + aivOffset.rmsNormCqOffset = baseParams_->headSizeCq * aivOffset.curBlockTokenOffset; // 1536 * idx + aivOffset.rmsNormCkvOffset = + (baseParams_->headSizeCkv + baseParams_->dimHeadRope) * aivOffset.curBlockTokenOffset; // (512 + 64) * idx + aivOffset.ropeKrOffset = baseParams_->headSizeCkv + aivOffset.rmsNormCkvOffset; // 512 + (512 + 64) * idx + if constexpr (!MLAPT::enableDequantOpt) { + aivOffset.mmQnPreDequantOffset = + (baseParams_->headSizeQc + baseParams_->headSizeQr) * aivOffset.curBlockTokenOffset; + aivOffset.mmQnPreDequantResOffset = baseParams_->headSizeQc * aivOffset.curBlockTokenOffset; + aivOffset.ropeQrOffset = static_cast(baseParams_->dimHeadSizeQc) + + static_cast(baseParams_->numHeadSize) * + static_cast(baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope) * + aivOffset.curBlockTokenOffset; // 128 + 32 * (128 + 64) * idx + aivOffset.ropeQrResOffset = + static_cast(baseParams_->headSizeQr) * + (aivOffset.curBlockTokenOffset + batchOffset); // 32 * 64 * idx; // 按BS合轴切分step + } + + // 以下的Offset均是与batchOffset无关的,仅初始化一次即可。 + if (batchOffset == 0) { + if constexpr (MLAPT::enableDequantOpt) { + aivOffset.mmQnPreDequantOffset = baseParams_->mm3SingleCoreN * cubeBlockIdx_; // qcQrResOffset + aivOffset.mmQnPreDequantResOffset = baseParams_->mm3SingleCoreN / + (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope) * + baseParams_->dimHeadSizeQc * cubeBlockIdx_; + aivOffset.ropeQrOffset = aivOffset.mmQnPreDequantOffset + baseParams_->dimHeadSizeQc; + aivOffset.ropeQrResOffset = + (baseParams_->mm3SingleCoreN / (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope)) * + baseParams_->dimHeadRope * cubeBlockIdx_; + } + + if constexpr (MLAPT::enableGroupComputeOpt) { + aivOffset.qcScaleOffsetSplitN = + (baseParams_->headSizeQc + baseParams_->headSizeQr) / QC_CORE_NUM * (blockIdx_ / cvRatio_); + aivOffset.mmQnPreDequantResOffset = (baseParams_->headSizeQc) / QC_CORE_NUM * (blockIdx_ / cvRatio_); + aivOffset.mmQnPreDequantOffset = aivOffset.mmQnPreDequantResOffset; + aivOffset.ropeQrResSplitNOffset = (blockIdx_ - QC_CORE_NUM * cvRatio_) * baseParams_->dimHeadRope; + aivOffset.ropeQrSplitNOffset = baseParams_->headSizeQc + aivOffset.ropeQrResSplitNOffset; + } + } +} + +// Mlaprolog 支持int8进int32出以及mxfp8进fp32出, 参考MatmulQcQr +template +template +__aicore__ inline void +MlaPrologVecS1CubS2::MatmulSplitN(const GlobalTensor &tensorResGm, const GlobalTensor &tensorAGm, + const GlobalTensor &tensorBGm, const MMParams &mmPara, + const UsedBlockParams &mmBlockParams, const GlobalTensor &tensorAScaleGm, + const GlobalTensor &tensorBScaleGm) +{ + if constexpr (needCheckEmptyTensor && MLAPT::emptyMode == EMPTY_TENSOR_MODE::EMPTY_CACHE) { + return; + } + if (blockIdx_ < mmBlockParams.blockStartIdx || blockIdx_ >= mmBlockParams.blockEndIdx) { + return; + } + // 用于enableGroupComputeOpt场景 + if constexpr (needCheckAFullLoad) { + constexpr uint32_t mSize = + (sizeof(mmQcQrInputType) == sizeof(int8_t)) ? INT8_AFULLLOAD_MAX_MSIZE : BF16_AFULLLOAD_MAX_MSIZE; + bool isAFullLoad = (mmQcQrParam_.m <= mSize) ? true : false; + if (isAFullLoad) { + MatmulGroupComputeAFullLoad(tensorResGm, tensorAGm, tensorBGm, mmPara, + bufParam_); + return; + } + } + uint32_t nInput = mmPara.n; + uint32_t nL1SplitSize = mmPara.baseN; + uint32_t nL1loops = CeilDivT(nInput, nL1SplitSize); + uint32_t subNL1SplitSize = nL1SplitSize; + for (int64_t nL1 = 0; nL1 < nL1loops; nL1++) { + if (nL1 == nL1loops - 1) { + subNL1SplitSize = nInput - (nL1loops - 1) * nL1SplitSize; + } + MatmulSplitK(tensorResGm, tensorAGm, tensorBGm, mmPara, bufParam_, nL1 * nL1SplitSize, subNL1SplitSize, + tensorAScaleGm, tensorBScaleGm); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MatmulAndSyncQcQr(AicOffset &aicOffset) +{ + if constexpr (MLAPT::enableGroupComputeOpt) { + // MatmulQc + // 复用mmCqResGm_ workspace + MatmulSplitN( + mmQcQrResGm_[aicOffset.qCResOffset], rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + weightUqQrGm_[aicOffset.weightUqOffset], mmQcQrParam_, UsedBlockParams{0, QC_CORE_NUM}); + CrossCoreSetFlag(FINISH_MM_QC); + // MatmulQr + MatmulSplitN( + mmQcQrResGm_[aicOffset.qRResOffset], rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + weightUqQrGm_[aicOffset.weightQrOffset], mmQcQrParam_, + UsedBlockParams{QC_CORE_NUM, QC_CORE_NUM + QR_CORE_NUM}); + } else { + MatmulQcQr(aicOffset); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MatmulQcQr(AicOffset &aicOffset) +{ + if (blockIdx_ >= baseParams_->mm3BlockNum) { + return; + } + // RmsNorm(Cq) ──> MatmulQcQr ──> MatmulQn + // └──> Rope(Qr) + // [32, 1536] * [1536, 32*(128+64)] = [32, 32*192] + constexpr uint32_t mSize = + (sizeof(mmQcQrInputType) == sizeof(int8_t)) ? INT8_AFULLLOAD_MAX_MSIZE : BF16_AFULLLOAD_MAX_MSIZE; + bool isAFullLoad = (mmQcQrParam_.m <= mSize) ? true : false; + + uint32_t nInput = mmQcQrParam_.n; + uint32_t nL1SplitSize = mmQcQrParam_.baseN; + uint32_t nL1loops = CeilDivT(nInput, nL1SplitSize); + uint32_t subNL1SplitSize = nL1SplitSize; + if (isAFullLoad) { + if constexpr (std::is_same::value && isFp8E8m0) { + uint32_t offsetL1B = + L1_B_SIZE / 2 / sizeof(rmsNormCqOutputType); // // 2表示scale起始地址固定从L1B上ping的64k开始 + WaitFlag(SCALE_EVENT); + LoadL1AAndScale( + rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + dequantTool_.deQuantScaleCqGm_[aicOffset.dequantScaleCqOffset], mmQcQrParam_.m, mmQcQrParam_.k, + mmQcQrParam_.k, mmQcQrParam_.kScale, offsetL1B, bufParam_); + SetFlag(SCALE_EVENT); + } else { + LoadL1A(rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], mmQcQrParam_.m, mmQcQrParam_.k, mmQcQrParam_.k, + bufParam_); + } + WaitFlag(A_EVENT0 + (bufParam_.aL1BufIter & 1u)); + } + + for (int64_t nL1 = 0; nL1 < nL1loops; nL1++) { + if (nL1 == nL1loops - 1) { + subNL1SplitSize = nInput - (nL1loops - 1) * nL1SplitSize; + } + if constexpr (std::is_same::value && isFp8E8m0) { + if (isAFullLoad) { + MatmulSplitK( + mmQcQrResGm_[aicOffset.qcQrResOffset], rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + weightUqQrGm_[aicOffset.weightUqQrOffset], mmQcQrParam_, bufParam_, nL1 * nL1SplitSize, + subNL1SplitSize, dequantTool_.deQuantScaleCqGm_[aicOffset.dequantScaleCqOffset], + deqScaleQcQrW_[aicOffset.dequantScaleWuqqrOffset]); + } else { + MatmulSplitK( + mmQcQrResGm_[aicOffset.qcQrResOffset], rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + weightUqQrGm_[aicOffset.weightUqQrOffset], mmQcQrParam_, bufParam_, nL1 * nL1SplitSize, + subNL1SplitSize, dequantTool_.deQuantScaleCqGm_[aicOffset.dequantScaleCqOffset], + deqScaleQcQrW_[aicOffset.dequantScaleWuqqrOffset]); + } + } else { + if (isAFullLoad) { + MatmulSplitK( + mmQcQrResGm_[aicOffset.qcQrResOffset], rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + weightUqQrGm_[aicOffset.weightUqQrOffset], mmQcQrParam_, bufParam_, nL1 * nL1SplitSize, + subNL1SplitSize); + } else { + MatmulSplitK( + mmQcQrResGm_[aicOffset.qcQrResOffset], rmsNormCqResGm_[aicOffset.rmsNormCqResOffset], + weightUqQrGm_[aicOffset.weightUqQrOffset], mmQcQrParam_, bufParam_, nL1 * nL1SplitSize, + subNL1SplitSize); + } + } + if constexpr (MLAPT::enableDequantOpt) { + CrossCoreSetFlag<0x2, PIPE_FIX>(FINISH_MM_QCQR_SPLIT_N); + } + } + if (isAFullLoad) { + SetFlag(A_EVENT0 + (bufParam_.aL1BufIter & 1u)); + bufParam_.aL1BufIter++; + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::PreloadQnAndSync(AicOffset &aicOffset, int64_t mmQnLoops) +{ + MatmulQnWeightPreload(aicOffset.weightUkOffset); + if constexpr (MLAPT::enableGroupComputeOpt) { + CrossCoreSetFlag(FINISH_MM_QR); + } else if constexpr (MLAPT::enableDequantOpt) { + // enableDequantOpt分支的CV同步由更细粒度的子函数控制 + return; + } else { + CrossCoreSetFlag(FINISH_MM_QCQR); + } + + if constexpr (IsFullQuantMode()) { + CrossCoreWaitFlag(FINISH_VEC_DEQUANT_QC); + } else { + WaitAllCore(FINISH_MM_ALL); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::MatmulQnWeightPreload(int64_t weightUkOffset) +{ + uint32_t maxBlockIdx = MLAPT::enableGroupComputeOpt ? QC_CORE_NUM : baseParams_->mm4BlockNum; + if (blockIdx_ >= maxBlockIdx) { + return; + } + if (mmQnParam_.k > mmQnParam_.baseK) { + return; + } + int64_t weightOffset = weightUkOffset; + LoadL1B(weightUkGm_[weightOffset], mmQnParam_.n, mmQnParam_.n, mmQnParam_.k, + mmQnParam_.k, bufParam_); + WaitFlag(B_EVENT0 + (bufParam_.bL1BufIter & 1u)); + weightOffset += static_cast(baseParams_->dimHeadSizeQc) * static_cast(baseParams_->headSizeCkv); +} + +template +template +__aicore__ inline void +MlaPrologVecS1CubS2::MatmulQnSyncDynamicQuantAndMulQr(int64_t qcOffset, int64_t weightUkOffset, + int64_t qnResOffset, int64_t subLoopTimes) +{ + uint32_t maxBlockIdx = MLAPT::enableGroupComputeOpt ? QC_CORE_NUM : baseParams_->mm4BlockNum; + if (blockIdx_ >= maxBlockIdx) { + return; + } + // MatmulQcQr ──> MatmulQn ──> query_out + // [32, 128] * [128, 512] = [32, 512] + // [32, 2, 128] * [2, 128, 512] = [32, 2, 512] + bool needSparseSync = subLoopTimes > MAX_SYNC_FLAG_COUNT; + for (int64_t i = 0; i < subLoopTimes; i++) { + if constexpr (MLAPT::enableDequantOpt) { + if (!needSparseSync || i % 2 == 0 || i == subLoopTimes - 1) { + CrossCoreWaitFlag(FINISH_VEC_DEQUANT_QC_SPLIT_N); + } + } + if (unlikely(mmQnParam_.baseK < mmQnParam_.k)) { + uint32_t nInput = baseParams_->headSizeCkv; + uint32_t nL1SplitSize = mmQnParam_.baseN; + uint32_t nL1loops = CeilDivT(nInput, nL1SplitSize); + uint32_t subNL1SplitSize = nL1SplitSize; + for (int64_t nL1 = 0; nL1 < nL1loops; nL1++) { + if (nL1 == nL1loops - 1) { + subNL1SplitSize = nInput - (nL1loops - 1) * nL1SplitSize; + } + MatmulSplitK( + mmQnResGm_[qnResOffset], mmQcQrResDequantGm_[qcOffset], weightUkGm_[weightUkOffset], mmQnParam_, + bufParam_, nL1 * nL1SplitSize, subNL1SplitSize); + } + } else { + if (i < 1) { + MatmulFullLoad( + mmQnResGm_[qnResOffset], mmQcQrResDequantGm_[qcOffset], weightUkGm_[weightUkOffset], mmQnParam_, + bufParam_); + } else { + MatmulFullLoad( + mmQnResGm_[qnResOffset], mmQcQrResDequantGm_[qcOffset], weightUkGm_[weightUkOffset], mmQnParam_, + bufParam_); + } + } + if constexpr (std::is_same::value || std::is_same::value || + std::is_same::value) { + qcOffset += static_cast(baseParams_->dimHeadSizeQc); + } else { + qcOffset += static_cast(baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope); + } + weightUkOffset += + static_cast(baseParams_->dimHeadSizeQc) * static_cast(baseParams_->headSizeCkv); + qnResOffset += static_cast(baseParams_->headSizeCkv); + + if constexpr (needQnDynamicQuant) { + CrossCoreSetFlag(FINISH_MM_QN_SPLIT_N); + } + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::CopyInSinCos(int64_t tokenIndex, int64_t curVecToken, + int64_t batchOffset, int64_t curStepBatchSize) +{ + LocalTensor shareTmpUb = shareBuffer_.Get(); + if constexpr (MLAPT::enableDequantOpt) { + // 如果是切N场景,mm3的每个C核都会做rope + if (cubeBlockIdx_ >= baseParams_->mm3BlockNum) { + return; + } + // 如果curStepBatchSize是偶数,则两个核平分;如果curStepBatchSize是奇数,则奇数核比偶数核多分一个 + // >> 1 是将curStepBatchSize分到每个vec核上; + uint32_t subBlockIdx_ = blockIdx_ % cvRatio_; + int64_t offset = (curStepBatchSize / cvRatio_) * subBlockIdx_ + batchOffset; + GatherSinCos(cosLocal_, sinLocal_, ropeCosGm_, ropeSinGm_, offset, + (curStepBatchSize + cvRatio_ - 1) / cvRatio_, shareTmpUb, + vectorRow_, baseParams_->dimHeadRope); + } else { + if (blockIdx_ >= curVectorBlockNum_) { + return; + } + GatherSinCos(cosLocal_, sinLocal_, ropeCosGm_, ropeSinGm_, tokenIndex, + curVecToken, shareTmpUb, vectorRow_, baseParams_->dimHeadRope); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::CopyGlobalParams() +{ + // dequantScaleWDq + if constexpr (IsFullQuantMode()) { + DataCopyExtParams dequantCopyParams{1, static_cast(baseParams_->headSizeCq * sizeof(float)), 0, 0, 0}; + DataCopyPadExtParams dequantPadParams{false, 0, 0, 0}; + DataCopyPad(dequantScaleWDqLocal_, dequantScaleWDqGm_, dequantCopyParams, dequantPadParams); + } + + // rmsnormGammaCq + DataCopy(rmsnormGammaCqLocal_, rmsnormGammaCqGm_, baseParams_->headSizeCq); + + // rmsnormGammaCkv + DataCopy(rmsnormGammaCkvLocal_, rmsnormGammaCkvGm_, baseParams_->headSizeCkv); + + // smoothScaleCq + + if constexpr (IsFullQuantMode()) { + if (enableSmoothScalesCq_) { + DataCopyExtParams smoothCopyParams{1, static_cast(baseParams_->headSizeCq * sizeof(float)), 0, 0, + 0}; + DataCopyPadExtParams smoothPadParams{false, 0, 0, 0}; + DataCopyPad(smoothScaleCqLocal_, smoothScaleCqGm_, smoothCopyParams, smoothPadParams); + } + } + + // dequantScaleWDkvKr + if constexpr (IsFullQuantMode()) { + DataCopyExtParams dequantCopyParams{ + 1, static_cast((baseParams_->headSizeCkv + baseParams_->dimHeadRope) * sizeof(float)), 0, 0, 0}; + DataCopyPadExtParams dequantPadParams{false, 0, 0, 0}; + DataCopyPad(dequantScaleWDkvKrLocal_, dequantScaleWDkvkrGm_, dequantCopyParams, dequantPadParams); + } + + // quantScaleCkv + + if constexpr (IsFullQuantMode() && !isPertile) { + if constexpr (std::is_same::value || + std::is_same::value) { + DataCopyExtParams quantCopyParams{1, sizeof(float), 0, 0, 0}; + DataCopyPadExtParams quantPadParams{false, 0, 0, 0}; + DataCopyPad(quantScaleCkvLocal_, quantScaleCkvGm_, quantCopyParams, quantPadParams); + } else { // per_channel量化场景走else分支 + DataCopy(quantScaleCkvLocal_, quantScaleCkvGm_, baseParams_->headSizeCkv); + } + } + + // quantScaleCkr + if constexpr (std::is_same::value) { + DataCopyExtParams quantCopyParams{1, static_cast(baseParams_->dimHeadRope * sizeof(float)), 0, 0, 0}; + DataCopyPadExtParams quantPadParams{false, 0, 0, 0}; + DataCopyPad(quantScaleCkrLocal_, quantScaleCkrGm_, quantCopyParams, quantPadParams); + } +} + + +/** + * @brief RmsNormCq流程,融合了dynamicquant + 内部所需空间约为 curVecToken(128) * 8*4 + 8*4 + (4*vectorRow_*baseParams_->headSizeCq + 8)*4 = 28.0625K + */ +template +__aicore__ inline void MlaPrologVecS1CubS2::RmsNormCq(int64_t tokenIndex, int64_t rmsNormCqOffset, + int64_t rmsNormCqResOffset, int64_t curVecToken, + int64_t curBlockTokenOffset) +{ + if (blockIdx_ >= curVectorBlockNum_) { + return; + } + uint64_t dequantScaleXSize = 1; + if constexpr (std::is_same::value && isFp8E8m0) { + dequantScaleXSize = baseParams_->headSizeX / FP8_E4M3_BLOCK_SIZE; + } + uint64_t dequantScaleCqElementNum = dequantScaleCqSize_ / sizeof(dequantScaleType); + uint64_t dequantScaleXElementNum = Align(dequantScaleXSize, BYTE_BLOCK) / sizeof(float); + int64_t stepTokenIndex = tokenIndex; + LocalTensor outputLocal = shareBuffer_.Get(); + LocalTensor dequantScaleQcQr = + outputLocal[baseParams_->headSizeCq].template ReinterpretCast(); + LocalTensor dequantScaleXLocal = + dequantScaleQcQr[curVecToken * dequantScaleCqElementNum].template ReinterpretCast(); + LocalTensor shareTmpUb = dequantScaleXLocal[dequantScaleXElementNum].template ReinterpretCast(); + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVecToken; curVecTokenIdx++) { + // MatmulCq ──> RmsNorm(Cq) ──> MatmulQcQr + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); // wait for vector operations to finish + + // dequantScaleXGm_ [BS , 1] 每个每个token对应一个系数,此处扩展为一个DataBlock + if constexpr (std::is_same::value || + (std::is_same::value && !isFp8E8m0)) { + DataCopyPad(dequantScaleXLocal, dequantScaleXGm_[tokenIndex], {1, sizeof(float), 0, 0}, {false, 0, 0, 0}); + } + + uint64_t scaleOffset = curVecTokenIdx * dequantScaleCqElementNum; + RmsNormParam rmsNormParams = { + baseParams_->reciprocalCq, // reciprocal + baseParams_->epsilonCq, // epsilon + static_cast(vectorRow_), // row + baseParams_->headSizeCq, // col + baseParams_->qcQrScale, // scale + baseParams_->isQcQrScaleEnable, // isScaleEnable + }; + + if constexpr (IsFullQuantMode()) { + RmsNormDynamicQuant(outputLocal, dequantScaleQcQr[scaleOffset], + mmCqResGm_[rmsNormCqOffset], rmsnormGammaCqLocal_, + smoothScaleCqLocal_, dequantScaleWDqLocal_, dequantScaleXLocal, + shareTmpUb, rmsNormParams, enableSmoothScalesCq_); + } else { + RmsNormNormal( + outputLocal, mmCqResGm_[rmsNormCqOffset], rmsnormGammaCqLocal_, dequantScaleWDqLocal_, + dequantScaleXLocal, shareTmpUb, rmsNormParams); + } + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + // RmsNorm(Cq)的结果拷进mmCqResGm_中,用于MatmulQcQr的A矩阵 + DataCopy(rmsNormCqResGm_[rmsNormCqResOffset], outputLocal, baseParams_->headSizeCq); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + rmsNormCqOffset += static_cast(baseParams_->headSizeCq); + rmsNormCqResOffset += static_cast(baseParams_->headSizeCq); + tokenIndex++; + } + + CopyDequantScaleCq(dequantScaleCqElementNum, dequantScaleQcQr, curVecToken, curBlockTokenOffset); + CopyQueryNormScale(stepTokenIndex, dequantScaleQcQr, curVecToken); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::CopyDequantScaleCq(uint64_t dequantScaleCqElementNum, + LocalTensor &dequantScaleQcQr, + int64_t curVecToken, int64_t curBlockTokenOffset) +{ + if constexpr (std::is_same::value && isFp8E8m0) { + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + DataCopy(dequantTool_.deQuantScaleCqGm_[curBlockTokenOffset * dequantScaleCqElementNum], dequantScaleQcQr, + curVecToken * dequantScaleCqElementNum); + } else { + Brcb(dequantTool_.deQuantScaleCqLocal_[curBlockTokenOffset * FP32_BLOCK_ELEMENT_NUM], dequantScaleQcQr, + curVecToken, {1, 1}); + if constexpr (MLAPT::enableDequantOpt || MLAPT::enableGroupComputeOpt) { + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + DataCopy(dequantTool_.deQuantScaleCqGm_[curBlockTokenOffset * FP32_BLOCK_ELEMENT_NUM], + dequantTool_.deQuantScaleCqLocal_[curBlockTokenOffset * FP32_BLOCK_ELEMENT_NUM], + FP32_BLOCK_ELEMENT_NUM * curVecToken); + } + } +} +template +__aicore__ inline void MlaPrologVecS1CubS2::CopyQueryNormScale(int64_t stepTokenIndex, + LocalTensor &dequantScaleQcQr, + int64_t curVecToken) +{ + if (unlikely(baseParams_->queryNormFlag == 1U)) { + if constexpr (IsFullQuantMode()) { + DataCopyPad(dequantScaleQNormGm_[stepTokenIndex], dequantScaleQcQr, + {static_cast(curVecToken), sizeof(dequantScaleQNormType), 0, 0}); + } else if constexpr (std::is_same::value && isFp8E8m0) { + DataCopyPad( + dequantScaleQNormGm_[stepTokenIndex * + static_cast((baseParams_->headSizeCq / FP8_E4M3_BLOCK_SIZE))], + dequantScaleQcQr, + {static_cast(curVecToken), + static_cast(sizeof(dequantScaleQNormType) * (baseParams_->headSizeCq / FP8_E4M3_BLOCK_SIZE)), + 0, 0}); + } + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::ComputeBlkScatterOffsets(GlobalTensor indexGm, + int64_t tokenIndex, int64_t rows, + CkvkrParams &rmsNormAndScatterCkvParams, + CkvkrParams &ropeAndScatterKrParams) +{ + int64_t batchTokenIndex = 0; + int64_t batchSeqSize = 0; + int64_t batchIndexOffset = 0; + int64_t rowsThisStep = 0; + int64_t nextPageId = 0; + bool spill = false; + + // Advance batch cursor until the token index falls in [prevPrefix, curPrefix) + // curPrefix is an exclusive upper bound for the current batch + if constexpr (MLAPT::actualSeqMode == ACTUAL_SEQ_MODE::DISABLED) { + const int64_t batchIndex = tokenIndex / baseParams_->seq1Size; + batchTokenIndex = tokenIndex % baseParams_->seq1Size; + batchSeqSize = baseParams_->seq1Size; + batchIndexOffset = + batchIndex * CeilDivT(batchSeqSize, static_cast(baseParams_->blockSize)); // cacheIndex的offset + } else { + while (actSeqState_.curBatch + 1 < static_cast(baseParams_->batchSize) && + tokenIndex >= actSeqState_.curPrefix) { + actSeqState_.curBatch += 1; + actSeqState_.prevPrefix = actSeqState_.curPrefix; + actSeqState_.curPrefix = actualSeqLenGm_(actSeqState_.curBatch); + actSeqState_.prevIndexOffset = actSeqState_.curIndexOffset; + actSeqState_.curIndexOffset += CeilDivT(actSeqState_.curPrefix - actSeqState_.prevPrefix, + static_cast(baseParams_->blockSize)); + } + batchTokenIndex = tokenIndex - actSeqState_.prevPrefix; + batchSeqSize = actSeqState_.curPrefix - actSeqState_.prevPrefix; + batchIndexOffset = actSeqState_.prevIndexOffset; + } + + int64_t indexOffset = batchIndexOffset + batchTokenIndex / baseParams_->blockSize; + int64_t paBlkId = indexGm(indexOffset); // 取cacheIdx + + int64_t pageTokenOffset = paBlkId * baseParams_->blockSize; + int64_t tokenOffsetInPage = batchTokenIndex % baseParams_->blockSize; + + int64_t leftRowsInPage = baseParams_->blockSize - tokenOffsetInPage; + if (leftRowsInPage >= rows) { + rowsThisStep = rows; + spill = false; + nextPageId = -1; + } else { + rowsThisStep = rows - leftRowsInPage; + spill = true; + nextPageId = indexGm(indexOffset + 1); + } + + // --- Materialize for RMSNorm/CKV --- + MaterializeOffsetsWithHeadSize( + pageTokenOffset, tokenOffsetInPage, rowsThisStep, spill, nextPageId, baseParams_->headSizeCkv, + rmsNormAndScatterCkvParams); + + MaterializeOffsetsWithHeadSize( + pageTokenOffset, tokenOffsetInPage, rowsThisStep, spill, nextPageId, baseParams_->dimHeadRope, + ropeAndScatterKrParams); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::RmsNormAndScatterCkv(LocalTensor &dequantScaleXLocal, + LocalTensor &shareTmpUb, + LocalTensor &cosLocalCkvKr, + LocalTensor &sinLocalCkvKr, + CkvkrParams rmsNormAndScatterCkvParams) +{ + // MatmulCkvKr ──> RmsNorm(Ckv) ──> Scatter(Ckv) + LocalTensor outputLocal = shareTmpUb.ReinterpretCast(); + uint32_t outputLocalSize = vectorRow_ * baseParams_->headSizeCkv * sizeof(kvCacheType); + if constexpr (isPertile) { // pertile量化场景,按照concat的最长长度申请内存 + uint32_t tileNum = baseParams_->headSizeCkv / baseParams_->tileSize; + outputLocalSize = vectorRow_ * (baseParams_->headSizeCkv * sizeof(kvCacheType) + tileNum * sizeof(float)); + outputLocalSize = Align(outputLocalSize, static_cast(BYTE_BLOCK)); + } + LocalTensor rmsNormShareTmpUb = shareTmpUb[outputLocalSize].template ReinterpretCast(); + + RmsNormParam rmsNormParams = { + baseParams_->reciprocalCkv, // reciprocal + baseParams_->epsilonCkv, // epsilon + static_cast(vectorRow_), // row + baseParams_->headSizeCkv, // col + baseParams_->kcScale, // scale + baseParams_->isKcScaleEnable, // isScaleEnable + }; + if constexpr (IsFullQuantMode()) { + RmsNormAndQuantizeCkv(outputLocal, rmsNormShareTmpUb, dequantScaleXLocal, rmsNormParams, + rmsNormAndScatterCkvParams); + } else { + RmsNormNormal( + outputLocal, mmCkvKrResGm_[rmsNormAndScatterCkvParams.offset], rmsnormGammaCkvLocal_, + dequantScaleWDkvKrLocal_, dequantScaleXLocal, rmsNormShareTmpUb, rmsNormParams); + } + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + // Scatter(Ckv) + // RmsNorm(Ckv) ──> Scatter(Ckv) ──> kv_cache_out + ScatterCkv(outputLocal, rmsNormAndScatterCkvParams); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::RmsNormAndQuantizeCkv(LocalTensor &outputLocal, + LocalTensor &rmsNormShareTmpUb, + LocalTensor &dequantScaleXLocal, + RmsNormParam rmsNormParams, + CkvkrParams rmsNormAndScatterCkvParams) +{ + // row = vectorRow_ = 1 col = baseParams_->headSizeCkv + LocalTensor inputLocal = rmsNormShareTmpUb.ReinterpretCast(); + LocalTensor sharedBuf = + inputLocal[vectorRow_ * baseParams_->headSizeCkv].template ReinterpretCast(); + RmsNormNormal( + inputLocal, mmCkvKrResGm_[rmsNormAndScatterCkvParams.offset], rmsnormGammaCkvLocal_, dequantScaleWDkvKrLocal_, + dequantScaleXLocal, sharedBuf, rmsNormParams); + + DataSyncBarrier(); + + if constexpr (isPertile) { + float kNopeClipAlpha = isFp8E8m0 ? 1.0f : kNopeClipAlphaGm_.GetValue(0); + PerTileQuantParams perTileQuantParams = { + static_cast(baseParams_->tileSize), // baseParams_->tileSize + static_cast(baseParams_->headSizeCkv / baseParams_->tileSize), // tileNum + kNopeClipAlpha, // alpha + static_cast(vectorRow_), // row + baseParams_->headSizeCkv // col + }; + if constexpr (std::is_same::value) { + QuantPerTile(outputLocal, inputLocal, sharedBuf, perTileQuantParams); + } else { + QuantPerTile8Bit(outputLocal, inputLocal, perTileQuantParams); + } + } else { + Rectangle rectangleParams{ + static_cast(vectorRow_), // row + static_cast(baseParams_->headSizeCkv), // col + static_cast(baseParams_->headSizeCkv) // columnStride + }; + if constexpr (std::is_same::value || + std::is_same::value) { + QuantPerTensor(outputLocal, inputLocal, quantScaleCkvLocal_, sharedBuf, rectangleParams); + } else { + QuantPerChannel(outputLocal, inputLocal, quantScaleCkvLocal_, sharedBuf, rectangleParams); + } + } + PipeBarrier(); +} + + +template +__aicore__ inline void MlaPrologVecS1CubS2::ScatterCkv(LocalTensor &outputLocal, + CkvkrParams rmsNormAndScatterCkvParams) +{ + if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_NZ) || (MLAPT::cacheMode == CACHE_MODE::PA_BSND) || + (MLAPT::cacheMode == CACHE_MODE::ND)) { + int64_t paTokenIndex; + if constexpr (MLAPT::cacheMode == CACHE_MODE::ND) { + paTokenIndex = rmsNormAndScatterCkvParams.tokenIndex; + } else { + paTokenIndex = cacheIndexGm_(rmsNormAndScatterCkvParams.tokenIndex); + } + ScatterCache( + kvCacheGm_, outputLocal, + ScatterCacheParams{baseParams_->blockSize, paTokenIndex, vectorRow_, baseParams_->headSizeCkv, + baseParams_->dtileSize}); + // 刷新量化scale + if (isPertile && baseParams_->quantScaleRepoMode == 1U) { + // BSND: + uint32_t tileNum = baseParams_->headSizeCkv / baseParams_->tileSize; + LocalTensor quantScaleCkvInt8Tensor = + outputLocal[vectorRow_ * baseParams_->headSizeCkv].template ReinterpretCast(); + int64_t startOffset = 0; + int64_t startColOffset = baseParams_->headSizeCkv; + if (baseParams_->ckvkrRepoMode == 1U) { + startColOffset += baseParams_->headSizeKr * sizeof(krCacheType); + } + if constexpr ((MLAPT::cacheMode != CACHE_MODE::PA_NZ)) { + startOffset = startColOffset; + } + + ScatterCacheUnAligned( + kvCacheGm_[startOffset], quantScaleCkvInt8Tensor, + ScatterCacheParams{baseParams_->blockSize, paTokenIndex, vectorRow_, + static_cast(tileNum * sizeof(float)), baseParams_->dtileSize}); + } + } else { + ScatterCacheMultiRows( + kvCacheGm_, outputLocal, + ScatterCacheParams{baseParams_->blockSize, rmsNormAndScatterCkvParams.cacheOffset, vectorRow_, + baseParams_->headSizeCkv, baseParams_->headSizeCkv, baseParams_->seq1Size, + rmsNormAndScatterCkvParams.tokenIndex}, + rmsNormAndScatterCkvParams.rowsInCurBatch, rmsNormAndScatterCkvParams.cacheOffset, + rmsNormAndScatterCkvParams.nextBatchOffset); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::RopeAndScatterKr(LocalTensor &dequantScaleXLocal, + LocalTensor &shareTmpUb, + LocalTensor &cosLocalCkvKr, + LocalTensor &sinLocalCkvKr, + CkvkrParams ropeAndScatterKrParams) +{ + // MatmulCkvKr ──> Rope(Ckv) ──> Scatter(Kr) + LocalTensor outputKrLocal = shareTmpUb.ReinterpretCast(); + LocalTensor ropeShareTmpUb = outputKrLocal[baseParams_->dimHeadRope].template ReinterpretCast(); + int64_t stride = static_cast(baseParams_->headSizeCkv + baseParams_->headSizeKr); // 512 + 64 + + LocalTensor cosLocal; + LocalTensor sinLocal; + if constexpr (MLAPT::enableDequantOpt) { + cosLocal = cosLocalCkvKr[baseParams_->dimHeadRope * ropeAndScatterKrParams.curVecTokenIdx]; + sinLocal = sinLocalCkvKr[baseParams_->dimHeadRope * ropeAndScatterKrParams.curVecTokenIdx]; + } else { + cosLocal = cosLocal_[baseParams_->dimHeadRope * ropeAndScatterKrParams.curVecTokenIdx]; + sinLocal = sinLocal_[baseParams_->dimHeadRope * ropeAndScatterKrParams.curVecTokenIdx]; + } + Rectangle ropeParams{ + static_cast(vectorRow_), // row + static_cast(baseParams_->dimHeadRope), // col + static_cast(stride) // stride + }; + if constexpr ((std::is_same::value || + (std::is_same::value && !isFp8E8m0)) && + std::is_same::value) { + LocalTensor sharedBuf = + ropeShareTmpUb.ReinterpretCast()[baseParams_->dimHeadRope * sizeof(ropeSinCosType)]; + // input为int32_t需在rope中做反量化, intput为float根据模板参数判断是否做反量化 + RotaryPosEmbPerTensor( + outputKrLocal, mmCkvKrResGm_[ropeAndScatterKrParams.offset], cosLocal, sinLocal, sharedBuf, ropeParams, + dequantScaleWDkvKrLocal_[baseParams_->headSizeCkv], dequantScaleXLocal); + } else if constexpr (std::is_same::value) { + LocalTensor inputLocal = ropeShareTmpUb.ReinterpretCast(); + LocalTensor sharedBuf = + ropeShareTmpUb.ReinterpretCast()[baseParams_->dimHeadRope * sizeof(ropeSinCosType)]; + RotaryPosEmbPerTensor::value>( + inputLocal, mmCkvKrResGm_[ropeAndScatterKrParams.offset], cosLocal, sinLocal, sharedBuf, ropeParams); + RopePostQuantPerChannel(outputKrLocal, inputLocal, quantScaleCkrLocal_, sharedBuf, + vectorRow_ * baseParams_->dimHeadRope); + } else { + RotaryPosEmbPerTensor( + outputKrLocal, mmCkvKrResGm_[ropeAndScatterKrParams.offset], cosLocal, sinLocal, ropeShareTmpUb, + ropeParams); + } + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + // scatter(Kr) + // Rope(Kr) ──> Scatter(Kr) ──> kr_cache_out + ScatterKr(outputKrLocal, ropeAndScatterKrParams); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::ScatterKr(LocalTensor &outputKrLocal, + CkvkrParams ropeAndScatterKrParams) +{ + int64_t paTokenIndex; + if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_NZ) || (MLAPT::cacheMode == CACHE_MODE::PA_BSND) || + (MLAPT::cacheMode == CACHE_MODE::ND)) { + if constexpr (MLAPT::cacheMode == CACHE_MODE::ND) { + paTokenIndex = ropeAndScatterKrParams.tokenIndex; + } else { + paTokenIndex = cacheIndexGm_(ropeAndScatterKrParams.tokenIndex); + } + if (isPertile && baseParams_->ckvkrRepoMode == 1U) { + int64_t startOffset; + if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_NZ)) { + constexpr uint8_t col0 = ALIGN_BLOCK_SIZE / sizeof(kvCacheType); + startOffset = CeilDiv(baseParams_->headSizeCkv, col0) * col0 * baseParams_->blockSize; // 列方向的偏移 + } else { + startOffset = baseParams_->headSizeCkv; + } + LocalTensor outputKrInt8Tensor = outputKrLocal.template ReinterpretCast(); + ScatterCache( + kvCacheGm_[startOffset], outputKrInt8Tensor, + ScatterCacheParams{baseParams_->blockSize, paTokenIndex, vectorRow_, + static_cast(baseParams_->dimHeadRope * sizeof(krCacheType)), + baseParams_->dtileSize}); + } else { + ScatterCache( + krCacheGm_, outputKrLocal, + ScatterCacheParams{baseParams_->blockSize, paTokenIndex, vectorRow_, baseParams_->dimHeadRope, + baseParams_->dimHeadRope}); + } + } else { + ScatterCacheMultiRows( + krCacheGm_, outputKrLocal, + ScatterCacheParams{baseParams_->blockSize, ropeAndScatterKrParams.cacheOffset, vectorRow_, + baseParams_->dimHeadRope, baseParams_->dimHeadRope, baseParams_->seq1Size, + ropeAndScatterKrParams.tokenIndex}, + ropeAndScatterKrParams.rowsInCurBatch, ropeAndScatterKrParams.cacheOffset, + ropeAndScatterKrParams.nextBatchOffset); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::RmsNormRopeScatterCkvKr(int64_t tokenIndex, int64_t rmsNormCkvOffset, + int64_t ropeKrOffset, int64_t curVecToken) +{ + if (blockIdx_ >= curVectorBlockNum_) { + return; + } + LocalTensor dequantScaleXLocal = shareBuffer_.Get(); + LocalTensor cosLocalCkvKr = + dequantScaleXLocal[FP32_BLOCK_ELEMENT_NUM].template ReinterpretCast(); + LocalTensor sinLocalCkvKr = cosLocalCkvKr[baseParams_->dimHeadRope * curVecToken]; + LocalTensor shareTmpUb = + sinLocalCkvKr[baseParams_->dimHeadRope * curVecToken].template ReinterpretCast(); + if constexpr (MLAPT::enableDequantOpt) { + GatherSinCos(cosLocalCkvKr, sinLocalCkvKr, ropeCosGm_, ropeSinGm_, tokenIndex, + curVecToken, shareTmpUb, vectorRow_, baseParams_->dimHeadRope); + } + if constexpr (MLAPT::emptyMode == EMPTY_TENSOR_MODE::EMPTY_CACHE) { + return; + } + + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVecToken; curVecTokenIdx++) { + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + if constexpr (std::is_same::value || + (std::is_same::value && !isFp8E8m0)) { + DataCopyPad(dequantScaleXLocal, dequantScaleXGm_[tokenIndex], {1, sizeof(float), 0, 0}, {false, 0, 0, 0}); + } + + CkvkrParams rmsNormAndScatterCkvParams{tokenIndex, rmsNormCkvOffset, curVecTokenIdx, 0, 0, 0}; + + CkvkrParams ropeAndScatterKrParams{tokenIndex, ropeKrOffset, curVecTokenIdx, 0, 0, 0}; + + if constexpr ((MLAPT::cacheMode == CACHE_MODE::PA_BLK_BSND) || (MLAPT::cacheMode == CACHE_MODE::PA_BLK_NZ)) { + // --- Compute headSize-independent variables once --- + ComputeBlkScatterOffsets(cacheIndexGm_, tokenIndex, vectorRow_, rmsNormAndScatterCkvParams, + ropeAndScatterKrParams); + } + + RmsNormAndScatterCkv(dequantScaleXLocal, shareTmpUb, cosLocalCkvKr, sinLocalCkvKr, rmsNormAndScatterCkvParams); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + RopeAndScatterKr(dequantScaleXLocal, shareTmpUb, cosLocalCkvKr, sinLocalCkvKr, ropeAndScatterKrParams); + + tokenIndex += 1; + rmsNormCkvOffset += static_cast(baseParams_->headSizeCkv + baseParams_->dimHeadRope); + ropeKrOffset += static_cast(baseParams_->headSizeCkv + baseParams_->dimHeadRope); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::RopeQr(int64_t ropeQrOffset, int64_t ropeQrResOffset, + int64_t curVecToken, int64_t curBlockTokenOffset) +{ + if (blockIdx_ >= curVectorBlockNum_) { + return; + } + uint64_t stride = static_cast(baseParams_->dimHeadRope + baseParams_->dimHeadSizeQc); + + LocalTensor outputLocal; + LocalTensor channelDeqScaleLocal = shareBuffer_.Get(); + if constexpr (IsFullQuantMode()) { + uint64_t row = baseParams_->numHeadSize; + uint64_t col = baseParams_->dimHeadRope; + DataCopyExtParams copyParams{static_cast(row), static_cast(col * sizeof(float)), + static_cast((stride - col) * sizeof(float)), 0, 0}; + DataCopyPadExtParams padParams{false, 0, 0, 0}; + DataCopyPad(channelDeqScaleLocal, deqScaleQcQrW_[baseParams_->dimHeadSizeQc], copyParams, + padParams); // 复用内存 + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + + outputLocal = channelDeqScaleLocal[row * col].template ReinterpretCast(); + } else { + outputLocal = shareBuffer_.Get(); + } + LocalTensor ropeShareTmpUb = outputLocal[baseParams_->headSizeQr].template ReinterpretCast(); + + // row, col, stride + Rectangle ropeParams{baseParams_->numHeadSize, baseParams_->dimHeadRope, static_cast(stride)}; + + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVecToken; curVecTokenIdx++) { + // MatmulQcQr ──> Rope(Qr) ──> query_rope_out + if constexpr (IsFullQuantMode()) { + RotaryPosEmbPerTensor( + outputLocal, mmQcQrResGm_[ropeQrOffset], cosLocal_[baseParams_->dimHeadRope * curVecTokenIdx], + sinLocal_[baseParams_->dimHeadRope * curVecTokenIdx], ropeShareTmpUb, ropeParams, channelDeqScaleLocal, + dequantTool_.deQuantScaleCqLocal_[(curBlockTokenOffset + curVecTokenIdx) * FP32_BLOCK_ELEMENT_NUM]); + } else { + RotaryPosEmbPerTensor( + outputLocal, mmQcQrResGm_[ropeQrOffset], cosLocal_[baseParams_->dimHeadRope * curVecTokenIdx], + sinLocal_[baseParams_->dimHeadRope * curVecTokenIdx], ropeShareTmpUb, ropeParams); + } + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + DataCopy(qrOutGm_[ropeQrResOffset], outputLocal, baseParams_->headSizeQr); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + ropeQrOffset += static_cast(baseParams_->numHeadSize) * + static_cast(baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope); + ropeQrResOffset += static_cast(baseParams_->headSizeQr); + } +} + +// 用于enableGroupComputeOpt场景 BS = 1 , G = 8 +template +__aicore__ inline void MlaPrologVecS1CubS2::RopeQrSplitNGroupCase(int64_t ropeQrOffset, int64_t ropeQrResOffset) +{ + if (blockIdx_ < QC_CORE_NUM * cvRatio_ || blockIdx_ >= (QC_CORE_NUM + QR_CORE_NUM) * cvRatio_) { + return; + } + + uint32_t row = baseParams_->numHeadSize / QC_CORE_NUM; + uint32_t col = baseParams_->dimHeadRope; + int64_t stride = col; + int64_t strideScale = static_cast(baseParams_->dimHeadRope + baseParams_->dimHeadSizeQc); + int64_t deqScaleOffset = baseParams_->dimHeadSizeQc + row * + (baseParams_->dimHeadSizeQc + baseParams_->dimHeadRope) * + (blockIdx_ - QC_CORE_NUM * cvRatio_); + LocalTensor channelDeqScaleLocal = shareBuffer_.Get(); + DataCopyExtParams copyParams{static_cast(row), static_cast(col * sizeof(float)), + static_cast((strideScale - col) * sizeof(float)), 0, 0}; + DataCopyPadExtParams padParams{false, 0, 0, 0}; + DataCopyPad(channelDeqScaleLocal, deqScaleQcQrW_[deqScaleOffset], copyParams, padParams); // 复用内存 + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + + LocalTensor outputLocal = + channelDeqScaleLocal[row * col].template ReinterpretCast(); + LocalTensor ropeShareTmpUb = outputLocal[baseParams_->headSizeQr].template ReinterpretCast(); + + Rectangle ropeParams{ + static_cast(col), // row + static_cast(col), // col + static_cast(stride) // stride + }; + + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVectorBlockNum_; curVecTokenIdx++) { + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + // sharetmp共用,待V算完再执行MTE2搬运规避风险 + GatherSinCos(cosLocal_, sinLocal_, ropeCosGm_, ropeSinGm_, + curVecTokenIdx * baseParams_->dimHeadRope, 1, ropeShareTmpUb, + vectorRow_, baseParams_->dimHeadRope); + + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + + RotaryPosEmbPerTensor( + outputLocal, mmQcQrResGm_[ropeQrOffset], cosLocal_, sinLocal_, ropeShareTmpUb, ropeParams, + channelDeqScaleLocal, dequantTool_.deQuantScaleCqLocal_); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + DataCopy(qrOutGm_[ropeQrResOffset], outputLocal, row * col); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + ropeQrOffset += static_cast(baseParams_->numHeadSize) * static_cast(baseParams_->dimHeadRope); + ropeQrResOffset += static_cast(baseParams_->headSizeQr); + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::RopeQrSplitN(const RopeQrSplitNParams &ropeQrSplitNParams) +{ + uint32_t ropeCnt = ropeQrSplitNParams.ropeCnt; + uint32_t colQr = baseParams_->dimHeadRope; + uint32_t deQuantScaleCqOffset = ropeQrSplitNParams.deQuantScaleCqOffset; + DataCopyParams outputRopeParams{ + static_cast(ropeCnt), static_cast(colQr * sizeof(ropeOutputType) / ALIGN_BLOCK_SIZE), 0, + static_cast(ropeQrSplitNParams.ropeDstStride * sizeof(ropeOutputType) / ALIGN_BLOCK_SIZE)}; + + Rectangle ropeParams{ + ropeCnt, // row + colQr, // col + static_cast(ropeQrSplitNParams.ropeStride) // stride + }; + + GlobalTensor inputGmRope = mmQcQrResGm_[ropeQrSplitNParams.ropeQrOffset]; + GlobalTensor outputGmRope = qrOutGm_[ropeQrSplitNParams.ropeQrResOffset]; + + LocalTensor shareTmpUb = shareBuffer_.Get(); + LocalTensor outputLocalRope = shareTmpUb.ReinterpretCast(); + LocalTensor ropeShareTmpUb = outputLocalRope[ropeCnt * colQr].template ReinterpretCast(); + + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + if constexpr (IsFullQuantMode()) { + GlobalTensor deqScaleRope = deqScaleQcQrW_[ropeQrSplitNParams.ropeQrOffset]; + RotaryPosEmbPerHead( + outputLocalRope, inputGmRope[ropeQrSplitNParams.inputOffsetRope], + cosLocal_[ropeQrSplitNParams.sinCosOffset], sinLocal_[ropeQrSplitNParams.sinCosOffset], ropeShareTmpUb, + ropeParams, ropeQrSplitNParams.ropeStride, deqScaleRope[ropeQrSplitNParams.deqScaleOffset], + dequantTool_.deQuantScaleCqLocal_[deQuantScaleCqOffset]); + } else { + RotaryPosEmbPerHead( + outputLocalRope, inputGmRope[ropeQrSplitNParams.inputOffsetRope], + cosLocal_[ropeQrSplitNParams.sinCosOffset], sinLocal_[ropeQrSplitNParams.sinCosOffset], ropeShareTmpUb, + ropeParams, ropeQrSplitNParams.ropeStride); + } + + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + + DataCopy(outputGmRope[ropeQrSplitNParams.outputOffsetRope], outputLocalRope, outputRopeParams); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::CastQcQrSplitN(const CastQcQrSplitNParams &castQcQrSplitN) +{ + uint32_t row = mmQcQrParam_.m; + uint32_t colQc = baseParams_->dimHeadSizeQc; + uint32_t colQcSingle = colQc / cvRatio_; + uint32_t count = row * colQcSingle; + + DataCopyParams inputCopyParams{ + static_cast(row), static_cast(colQcSingle * sizeof(mmQcQrOutputType) / ALIGN_BLOCK_SIZE), + static_cast(castQcQrSplitN.srcStride * sizeof(mmQcQrOutputType) / ALIGN_BLOCK_SIZE), 0}; + + DataCopyParams outputCopyParams{ + static_cast(row), static_cast(colQcSingle * sizeof(mmQnInputType) / ALIGN_BLOCK_SIZE), 0, + static_cast(castQcQrSplitN.dstStride * sizeof(mmQnInputType) / ALIGN_BLOCK_SIZE)}; + + + GlobalTensor inputGm = mmQcQrResGm_[castQcQrSplitN.mmQnPreCastOffset]; + GlobalTensor outputGm = mmQcQrResDequantGm_[castQcQrSplitN.mmQnPreCastResOffset]; + + LocalTensor shareTmpUb = shareBuffer_.Get(); + LocalTensor inputLocal = shareTmpUb.ReinterpretCast(); + LocalTensor outputLocal = inputLocal.template ReinterpretCast(); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + DataCopy(inputLocal, inputGm[castQcQrSplitN.inputOffset], inputCopyParams); + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + // cast + Cast(outputLocal, inputLocal, RoundMode::CAST_RINT, count); + SetFlag(EVENT_ID2); + // copy out + WaitFlag(EVENT_ID2); + DataCopy(outputGm[castQcQrSplitN.outputOffset], outputLocal, outputCopyParams); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::DequantQcQrSplitN(const DequantQcQrSplitNParams &dequantQcQrSplitN) +{ + uint32_t row = mmQcQrParam_.m; + uint32_t colQc = baseParams_->dimHeadSizeQc; + uint32_t colQcSingle = colQc / cvRatio_; + uint32_t count = row * colQcSingle; + + DataCopyParams inputCopyParams{ + static_cast(row), static_cast(colQcSingle * sizeof(mmQcQrOutputType) / ALIGN_BLOCK_SIZE), + static_cast(dequantQcQrSplitN.srcStride * sizeof(mmQcQrOutputType) / ALIGN_BLOCK_SIZE), 0}; + + DataCopyParams outputCopyParams{ + static_cast(row), static_cast(colQcSingle * sizeof(mmQnInputType) / ALIGN_BLOCK_SIZE), 0, + static_cast(dequantQcQrSplitN.dstStride * sizeof(mmQnInputType) / ALIGN_BLOCK_SIZE)}; + + + GlobalTensor inputGm = mmQcQrResGm_[dequantQcQrSplitN.mmQnPreDequantOffset]; + GlobalTensor scale1Gm = deqScaleQcQrW_[dequantQcQrSplitN.mmQnPreDequantOffset]; + GlobalTensor outputGm = mmQcQrResDequantGm_[dequantQcQrSplitN.mmQnPreDequantResOffset]; + + LocalTensor shareTmpUb = shareBuffer_.Get(); + LocalTensor scale2Local = dequantTool_.deQuantScaleCqLocal_; + LocalTensor inputLocal = shareTmpUb.ReinterpretCast(); + // 可以和inputLocal共享内存地址,减少UB使用 + LocalTensor computeLocal = shareTmpUb.ReinterpretCast(); + LocalTensor scaleLocal = inputLocal[count + FP32_BLOCK_ELEMENT_NUM].template ReinterpretCast(); + // outputLocal比scaleLocal占用UB少,且不会同时使用,故可以复用UB内存 + LocalTensor outputLocal = scaleLocal.template ReinterpretCast(); + + Rectangle dequantParams{ + row, // row + colQcSingle, // col + colQcSingle // columnStride + }; + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + DataCopy(inputLocal, inputGm[dequantQcQrSplitN.inputOffset], inputCopyParams); + DataCopy(scaleLocal, scale1Gm[dequantQcQrSplitN.inputOffset], colQcSingle); + SetFlag(EVENT_ID1); + // cast + WaitFlag(EVENT_ID1); + Dequant(computeLocal, inputLocal, scaleLocal, scale2Local, dequantParams); + AscendC::PipeBarrier(); + // cast + Cast(outputLocal, computeLocal, RoundMode::CAST_RINT, count); + SetFlag(EVENT_ID2); + // copy out + WaitFlag(EVENT_ID2); + DataCopy(outputGm[dequantQcQrSplitN.outputOffset], outputLocal, outputCopyParams); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::DequantAndRopeSplitNSyncMMQcQr(int64_t mmQnPreDequantOffset, + int64_t mmQnPreDequantResOffset, + int64_t ropeQrOffset, + int64_t ropeQrResOffset) +{ + if (cubeBlockIdx_ >= baseParams_->mm3BlockNum) { + return; + } + // mmQcQr一个C核算stepBatchSize * singleN,每两个V核做对应C核输出的Qc部分的dequant + // singleN一定整除(dimHeadSizeQc + dimHeadSizeQc),保证dequant能找到dimHeadSizeQc部分的起始位置 + uint32_t subBlockIdx_ = blockIdx_ % cvRatio_; + uint32_t colCube = mmQcQrParam_.baseN; + uint32_t colQc = baseParams_->dimHeadSizeQc; + uint32_t colQr = baseParams_->dimHeadRope; + uint32_t oriCol = mmQcQrParam_.n; + uint32_t colOffsetCube = 0; + + // DequantSplitN参数 + uint32_t srcStride = baseParams_->headSizeQc + baseParams_->headSizeQr - baseParams_->dimHeadSizeQc / cvRatio_; + uint32_t dstStride = baseParams_->headSizeQc - baseParams_->dimHeadSizeQc / cvRatio_; + uint32_t colQcSingle = colQc / cvRatio_; + uint32_t colOffsetVec = 0; + uint32_t inputOffset = subBlockIdx_ * colQcSingle; + uint32_t outputOffset = inputOffset; + + // RopeQrSplitN参数 + uint32_t ropeDstStride = baseParams_->headSizeQr - colQr; + // CV1:2和1:1,M轴方向切成2块处理 + uint32_t ropeCntDown = mmQcQrParam_.m / 2; + // cv1:1时,为了防止UB内存溢出,每次处理一半的数量 + uint32_t ropeCnt = cvRatio_ == 1 ? ropeCntDown : (mmQcQrParam_.m + subBlockIdx_) / cvRatio_; + int64_t ropeStride = static_cast(baseParams_->numHeadSize) * static_cast(colQc + colQr); + uint32_t inputOffsetRope = ropeCntDown * subBlockIdx_ * ropeStride; + uint32_t outputOffsetRope = ropeCntDown * subBlockIdx_ * baseParams_->headSizeQr; + uint32_t deqScaleOffset = 0; + uint32_t colOffsetRope = 0; + uint32_t deQuantScaleCqOffset = ropeCntDown * subBlockIdx_ * FP32_BLOCK_ELEMENT_NUM; + // cube一次处理row*colCube,对应的两个vec一次处理row*colQc,两vec之间切colQc + // 等cube生产足够数据了以后,vec开始消费 + uint32_t dequantLoopCount = 0; + uint32_t totalDequantLoops = CeilDiv(oriCol, (colQc + colQr)); + bool needSparseSync = totalDequantLoops > MAX_SYNC_FLAG_COUNT; + while (colOffsetCube < oriCol) { // 循环CeilDiv(oriCol, colCube)次 + colOffsetCube += colCube; + if (colOffsetCube > oriCol) { // 当oriCol不被colCube整除时,mm最后一个base块需要刷新col end + colOffsetCube = oriCol; + } + CrossCoreWaitFlag(FINISH_MM_QCQR_SPLIT_N); + // DequantSplitN + while (colOffsetVec + colQc <= colOffsetCube) { // 循环singleNumHeadSize次 + if constexpr (IsFullQuantMode()) { + DequantQcQrSplitN(DequantQcQrSplitNParams{mmQnPreDequantOffset, mmQnPreDequantResOffset, inputOffset, + outputOffset, srcStride, dstStride}); + } else if constexpr (std::is_same::value && isFp8E8m0) { + CastQcQrSplitN(CastQcQrSplitNParams{mmQnPreDequantOffset, mmQnPreDequantResOffset, inputOffset, + outputOffset, srcStride, dstStride}); + } + if (!needSparseSync || dequantLoopCount % 2 == 0 || dequantLoopCount == totalDequantLoops - 1) { + CrossCoreSetFlag(FINISH_VEC_DEQUANT_QC_SPLIT_N); + } + dequantLoopCount++; + colOffsetVec += (colQc + colQr); + inputOffset += (colQc + colQr); + outputOffset += colQc; + } + // RopeQrSplitN + while ((colOffsetRope + colQc + colQr) <= colOffsetCube) { + RopeQrSplitN(RopeQrSplitNParams{ropeQrOffset, ropeQrResOffset, inputOffsetRope, deqScaleOffset, + outputOffsetRope, ropeStride, ropeDstStride, deQuantScaleCqOffset, 0, + ropeCnt}); + // cv1:1时,还需处理第二次,第二次在第一次的基础上计算偏移等 + if (cvRatio_ == 1) { + RopeQrSplitN(RopeQrSplitNParams{ + ropeQrOffset, ropeQrResOffset, static_cast(inputOffsetRope + ropeCntDown * ropeStride), + deqScaleOffset, static_cast(outputOffsetRope + ropeCntDown * baseParams_->headSizeQr), + ropeStride, ropeDstStride, ropeCntDown * FP32_BLOCK_ELEMENT_NUM, + ropeCntDown * baseParams_->dimHeadRope, (mmQcQrParam_.m + 1) / 2}); + } + + colOffsetRope += (colQc + colQr); + inputOffsetRope += (colQc + colQr); + deqScaleOffset += (colQc + colQr); + outputOffsetRope += colQr; + } + } +} + +template +template +__aicore__ inline void MlaPrologVecS1CubS2::DequantQcAndRopeQc(AivOffset &aivOffset, int64_t batchOffset, + int64_t curStepBatchSize, int64_t numHeadOffset, + int64_t mmQnLoops) +{ + // 根据不同分支条件处理 + if constexpr (MLAPT::enableGroupComputeOpt) { + CrossCoreWaitFlag(FINISH_MM_QC); + DequantQcSplitNGroupCase(aivOffset.mmQnPreDequantOffset, aivOffset.mmQnPreDequantResOffset, + aivOffset.qcScaleOffsetSplitN); + CrossCoreSetFlag(FINISH_VEC_DEQUANT_QC); + CrossCoreWaitFlag(FINISH_MM_QR); + RopeQrSplitNGroupCase(aivOffset.ropeQrSplitNOffset, aivOffset.ropeQrResSplitNOffset); + } else { + if constexpr (MLAPT::enableDequantOpt) { + DequantAndRopeSplitNSyncMMQcQr(aivOffset.mmQnPreDequantOffset, aivOffset.mmQnPreDequantResOffset, + aivOffset.ropeQrOffset, aivOffset.ropeQrResOffset); + } else if constexpr (IsFullQuantMode()) { + CrossCoreWaitFlag(FINISH_MM_QCQR); + WaitAllCore(FINISH_VEC_ALL); + DequantQc(aivOffset.mmQnPreDequantOffset, aivOffset.mmQnPreDequantResOffset, aivOffset.curVecToken, + aivOffset.curBlockTokenOffset); + WaitAllCore(FINISH_VEC_ALL); + CrossCoreSetFlag(FINISH_VEC_DEQUANT_QC); + RopeQr(aivOffset.ropeQrOffset, aivOffset.ropeQrResOffset, aivOffset.curVecToken, + aivOffset.curBlockTokenOffset); + } else if constexpr (std::is_same::value && isFp8E8m0) { + CrossCoreWaitFlag(FINISH_MM_QCQR); + WaitAllCore(FINISH_VEC_ALL); + CastQc(aivOffset.mmQnPreDequantOffset, aivOffset.mmQnPreDequantResOffset, aivOffset.curVecToken); + WaitAllCore(FINISH_VEC_ALL); + CrossCoreSetFlag(FINISH_VEC_DEQUANT_QC); + RopeQr(aivOffset.ropeQrOffset, aivOffset.ropeQrResOffset, aivOffset.curVecToken, + aivOffset.curBlockTokenOffset); + } else { + CrossCoreWaitFlag(FINISH_MM_QCQR); + WaitAllCore(FINISH_VEC_ALL); + RopeQr(aivOffset.ropeQrOffset, aivOffset.ropeQrResOffset, aivOffset.curVecToken, + aivOffset.curBlockTokenOffset); + } + + if constexpr (needQnDynamicQuant && !(MLAPT::enableDequantOpt)) { + // 非切N场景,需要等待全部rope的结果做完并搬到GM + WaitAllCore(FINISH_VEC_ALL); + } + if constexpr (needQnDynamicQuant) { + DynamicQuantQnAndMulQrSyncMMQn(batchOffset, curStepBatchSize, numHeadOffset, mmQnLoops); + } + aivOffset.ropeQrResOffset += + static_cast(baseParams_->stepBatchSize) * static_cast(baseParams_->headSizeQr); + } +} + +// 用于算力切分dequant切N场景 +template +__aicore__ inline void MlaPrologVecS1CubS2::DequantQcSplitNGroupCase(int64_t mmQnPreDequantOffset, + int64_t mmQnPreDequantResOffset, + int64_t qcQrScaleOffset) +{ + if (blockIdx_ >= QC_CORE_NUM * cvRatio_) { + return; + } + uint32_t subBlockIdx_ = blockIdx_ % cvRatio_; + uint32_t oriCol = (baseParams_->headSizeQc) / QC_CORE_NUM; + uint32_t curCol = (baseParams_->headSizeQc) / (QC_CORE_NUM * cvRatio_); + uint32_t srcStride = baseParams_->headSizeQc - curCol; + uint32_t dstStride = baseParams_->headSizeQc - curCol; + LocalTensor shareTmpUb = shareBuffer_.Get(); + Rectangle rectangleParams{ + static_cast(mmQcQrParam_.m), // row + static_cast(curCol), // col + static_cast(baseParams_->headSizeQc) // columnStride + }; + DequantSplitNQc(mmQcQrResDequantGm_[mmQnPreDequantResOffset], mmQcQrResGm_[mmQnPreDequantOffset], + deqScaleQcQrW_[qcQrScaleOffset], dequantTool_.deQuantScaleCqLocal_, shareTmpUb, rectangleParams, + oriCol, dstStride, subBlockIdx_); +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::DequantQc(int64_t mmQnPreDequantOffset, + int64_t mmQnPreDequantResOffset, int64_t curVecToken, + int64_t curBlockTokenOffset) +{ + if (blockIdx_ >= curVectorBlockNum_) { + return; + } + + Rectangle rectangleParams{ + static_cast(baseParams_->stepNumHeadDequant), // row + static_cast(baseParams_->dimHeadSizeQc), // col + static_cast(baseParams_->dimHeadRope + baseParams_->dimHeadSizeQc) // columnStride + }; + + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVecToken; curVecTokenIdx++) { + LocalTensor shareTmpUb = shareBuffer_.Get(); + DequantPerTokenQc( + mmQcQrResDequantGm_[mmQnPreDequantResOffset], mmQcQrResGm_[mmQnPreDequantOffset], deqScaleQcQrW_, + dequantTool_.deQuantScaleCqLocal_[(curBlockTokenOffset + curVecTokenIdx) * FP32_BLOCK_ELEMENT_NUM], + shareTmpUb, rectangleParams, baseParams_->numHeadSize); + mmQnPreDequantOffset += baseParams_->headSizeQc + baseParams_->headSizeQr; + mmQnPreDequantResOffset += baseParams_->headSizeQc; + } +} + +template +__aicore__ inline void MlaPrologVecS1CubS2::CastQc(int64_t mmQnPreCastOffset, int64_t mmQnPreCastResOffset, + int64_t curVecToken) +{ + if (blockIdx_ >= curVectorBlockNum_) { + return; + } + + Rectangle rectangleCastParams{ + static_cast(baseParams_->stepNumHeadDequant), // row + static_cast(baseParams_->dimHeadSizeQc), // col + static_cast(baseParams_->dimHeadRope + baseParams_->dimHeadSizeQc) // columnStride + }; + + for (int64_t curVecTokenIdx = 0; curVecTokenIdx < curVecToken; curVecTokenIdx++) { + LocalTensor shareTmpUb = shareBuffer_.Get(); + CastPerTokenQc(mmQcQrResDequantGm_[mmQnPreCastResOffset], mmQcQrResGm_[mmQnPreCastOffset], shareTmpUb, + rectangleCastParams, baseParams_->numHeadSize); + + mmQnPreCastOffset += baseParams_->headSizeQc + baseParams_->headSizeQr; + mmQnPreCastResOffset += baseParams_->headSizeQc; + } +} + +template +__aicore__ inline void +MlaPrologVecS1CubS2::DynamicQuantQnAndMulQrSyncMMQn(int64_t batchOffset, int64_t curStepBatchSize, + int64_t numHeadOffset, int64_t mmQnLoops) +{ + // 如果curStepBatchSize是偶数,则两个核平分;如果curStepBatchSize是奇数,则奇数核比偶数核多分一个 + // >> 1 是将curStepBatchSize分到每个vec核上; + int64_t curStepBatchSizeVec = (curStepBatchSize + (blockIdx_ % cvRatio_)) / cvRatio_; + if (blockIdx_ >= baseParams_->mm4BlockNum * cvRatio_) { + return; + } + // 等待前面的Qr部分完成 + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + + constexpr uint32_t DYNAMIC_QUANT_INPUT_READY = EVENT_ID0; + constexpr uint32_t MUL_QR_INPUT_COPY_READY = EVENT_ID3; + constexpr uint32_t DYNAMIC_QUANT_OUTPUT_READY = EVENT_ID3; + + int64_t blockBatchOffset = (blockIdx_ % cvRatio_) * (curStepBatchSize / cvRatio_); + int64_t totalSizeCkv = + static_cast(baseParams_->numHeadSize) * static_cast(baseParams_->headSizeCkv); + // 由于两个vec核分curStepBatchSize,各处理curStepBatchSize/2,blockIdx_ & 1 表示是否为第二个vec核 + int64_t dynamicQuantQueryOffset = + blockBatchOffset * totalSizeCkv + numHeadOffset * static_cast(baseParams_->headSizeCkv); + int64_t dynamicQuantQueryResOffset = batchOffset * totalSizeCkv + blockBatchOffset * totalSizeCkv + + numHeadOffset * static_cast(baseParams_->headSizeCkv); + int64_t scaleQueryNopeOffset = batchOffset * static_cast(baseParams_->numHeadSize) + + blockBatchOffset * static_cast(baseParams_->numHeadSize) + numHeadOffset; + int64_t queryOutStride = totalSizeCkv; + int64_t qrOutputStride = + static_cast(baseParams_->numHeadSize) * static_cast(baseParams_->dimHeadRope); + int64_t qrPostProcessResOffset = batchOffset * static_cast(baseParams_->headSizeQr) + + numHeadOffset * static_cast(baseParams_->dimHeadRope) + + blockBatchOffset * static_cast(baseParams_->headSizeQr); + + + LocalTensor shareTmpUb = shareBuffer_.Get(); + + float quantScaleCkv = quantScaleCkvGm_.GetValue(0); + + // Dynamic Quant + SetFlag(DYNAMIC_QUANT_OUTPUT_READY); + SetFlag(DYNAMIC_QUANT_INPUT_READY); + + // Rope Post Process + SetFlag(MUL_QR_INPUT_COPY_READY); + // per-head循环 + for (int64_t loopIdx = 0; loopIdx < mmQnLoops; loopIdx++) { + CrossCoreWaitFlag(FINISH_MM_QN_SPLIT_N); + DynamicQuantQnWithMulQr( + dequantScaleQNopeGm_[scaleQueryNopeOffset], queryOutGm_[dynamicQuantQueryResOffset], + qrOutGm_[qrPostProcessResOffset], mmQnResGm_[dynamicQuantQueryOffset], shareTmpUb, curStepBatchSizeVec, + baseParams_->headSizeCkv, baseParams_->numHeadSize, queryOutStride, + // Rope Post Process + qrOutGm_[qrPostProcessResOffset], quantScaleCkv, baseParams_->dimHeadRope, qrOutputStride, cvRatio_); + + dynamicQuantQueryOffset += static_cast(baseParams_->headSizeCkv); + scaleQueryNopeOffset += 1; + dynamicQuantQueryResOffset += static_cast(baseParams_->headSizeCkv); + qrPostProcessResOffset += static_cast(baseParams_->dimHeadRope); + } + // Rope Post Process + WaitFlag(MUL_QR_INPUT_COPY_READY); + // Dynamic Quant + WaitFlag(DYNAMIC_QUANT_INPUT_READY); + WaitFlag(DYNAMIC_QUANT_OUTPUT_READY); +} + +} // namespace MlaProlog + +#endif // MLA_PROLOG_VEC_S1_CUB_S2_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/mla_prolog_comm.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/mla_prolog_comm.h new file mode 100644 index 0000000000000000000000000000000000000000..60d122e3f371bfabfaf4c61e8301163b0b64275e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/mla_prolog_comm.h @@ -0,0 +1,408 @@ +/** + * 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 mla_prolog_comm.h + * \brief + */ + +#ifndef MLA_PROLOG_COMM_H +#define MLA_PROLOG_COMM_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" + +using namespace AscendC; + +namespace MlaProlog { + +template +__aicore__ inline T CeilDivT(T num1, T num2) +{ + if (num2 == 0) { + return static_cast(0); + } + return (num1 + num2 - 1) / num2; +} + +template +__aicore__ inline T Align(T num, T rnd) +{ + return (((rnd) == 0) ? 0 : (((num) + (rnd)-1) / (rnd) * (rnd))); +} + +enum class CACHE_MODE : uint8_t { + ND = static_cast(0), // BSND or TND + PA_BSND = static_cast(1), + PA_NZ = static_cast(2), + PA_BLK_BSND = static_cast(3), + PA_BLK_NZ = static_cast(4), + PA_BS = static_cast(5) +}; + +enum class SCENARIO : uint8_t { + RESERVED = static_cast(0), + NO_QUANT = static_cast(1), + QUANT = static_cast(2) +}; + +enum class QUANT_MODE : uint8_t { + NO_QUANT = static_cast(0), + PARTIAL_QUANT_KV_NO_QUANT = static_cast(1), + PARTIAL_QUANT_KV_QUANT_PER_CHANNEL = static_cast(2), + FULL_QUANT_KV_NO_QUANT = static_cast(3), + FULL_QUANT_KV_QUANT_PER_TENSOR = static_cast(4), + PARTIAL_QUANT_KV_QUANT_PERTILE = static_cast(5), + FULL_QUANT_KV_QUANT_PERTILE = static_cast(6), + MXFP8_FULL_QUANT_KV_NO_QUANT = static_cast(7), + MXFP8_FULL_QUANT_KV_QUANT_PER_TENSOR = static_cast(8), + MXFP8_FULL_QUANT_KV_QUANT_PER_TILE = static_cast(9), + FP8_FULL_QUANT_KV_NO_QUANT = static_cast(10), + FP8_FULL_QUANT_KV_QUANT_PER_TENSOR = static_cast(11), + HIF8_FULL_QUANT_KV_NO_QUANT = static_cast(12), + HIF8_FULL_QUANT_KV_QUANT_PER_TENSOR = static_cast(13), + FP8_FULL_QUANT_KV_QUANT_PER_TILE = static_cast(14), + HIF8_FULL_QUANT_KV_QUANT_PER_TILE = static_cast(15) +}; + +enum class EMPTY_TENSOR_MODE : uint8_t { + NON_EMPTY = static_cast(0), + EMPTY_CACHE = static_cast(1), + EMPTY_QUERY = static_cast(2), +}; + +enum class ACTUAL_SEQ_MODE : uint8_t { + DISABLED = static_cast(0), + EN_Q_LEN = static_cast(1), +}; + +enum class SPLIT_M_MODE : uint8_t { + DISABLED = static_cast(0), + ENABLED = static_cast(1), +}; + +enum class ROPE_MODE : uint8_t { + INTERLEAVE_HALF = static_cast(0), + HALF = static_cast(1), +}; + +constexpr uint64_t BYTE_BLOCK = 32UL; +constexpr uint8_t ALIGN_BLOCK_SIZE = 32; // 32B对齐 +constexpr uint32_t BLOCK_CUBE_SIZE = 16; // L1上m轴16对齐 +constexpr uint32_t FP8_TWO = 2; // L1上scale的存储方式为2个fp8类型存成1个bf16 +constexpr uint32_t REPEAT_BLOCK_BYTE = 256; +constexpr uint32_t REPEAT_STRIDE_UP_BOUND = 256; // repeat stride 不能超过256 +constexpr uint32_t FP32_BLOCK_ELEMENT_NUM = ALIGN_BLOCK_SIZE / sizeof(float); +constexpr uint32_t FP16_BLOCK_ELEMENT_NUM = ALIGN_BLOCK_SIZE / sizeof(half); +constexpr uint32_t FP32_REPEAT_ELEMENT_NUM = REPEAT_BLOCK_BYTE / sizeof(float); +constexpr uint32_t MAX_UB_SIZE = 192 * 1024; // 最大的UB大小 +constexpr uint32_t DIM_HEAD_SIZE_QCQR = 192; // 算力分组方案D + Dr = 192 +constexpr uint32_t QC_CORE_NUM = 8; // 算力分组方案QC占用8核 +constexpr uint32_t QR_CORE_NUM = 4; // 算力分组方案QR占用4核 +constexpr uint32_t INT8_AFULLLOAD_MAX_MSIZE = 64; // 计算mmQcQr时,int8类型的A矩阵在msize小于等于64可以全载L1 +constexpr uint32_t BF16_AFULLLOAD_MAX_MSIZE = 32; // 计算mmQcQr时,bf16类型的A矩阵在msize小于等于32可以全载L1 +constexpr uint32_t ONE_BYTE_TYPE_SIZE = 1; // 数据类型int8_t fp8大小为1字节 +constexpr uint32_t FP8_E4M3_BLOCK_SIZE = 32; +constexpr uint32_t K_STEP_SIZE_32 = 32; // for move left or right +constexpr uint32_t SHIFTS_UNIT = 4; +constexpr uint32_t UNIT_SIZE = 512; +constexpr uint32_t ROUND_UP_UNIT = 15; // for round up +constexpr uint32_t MAX_SYNC_FLAG_COUNT = 15; // 同一个flagId的计数器最多设置15次 + +constexpr int SYNC_MODE_ALL_CUBE = 0x0; +constexpr int SYNC_MODE_CUBE_VEC = 0x2; +constexpr int SYNC_MODE_ALL_VEC = 0x0; + +constexpr int FINISH_MM_CQ = 0x6; +constexpr int FINISH_MM_CKVKR = 0x6; +constexpr int FINISH_MM_QCQR = 0x6; +constexpr int FINISH_MM_QR = 0x8; // 算力分组场景 +constexpr int FINISH_MM_QC = 0x6; // 算力分组场景 +constexpr int FINISH_MM_ALL = 0x7; + +constexpr int FINISH_VEC_RMSNORM_CQ = 0x6; +constexpr int FINISH_VEC_DEQUANT_QC = 0x6; +constexpr int FINISH_VEC_CKVKR = 0x9; +constexpr int FINISH_VEC_ALL = 0x7; + +constexpr int FINISH_MM_QCQR_SPLIT_N = 0XA; +constexpr int FINISH_MM_QCQR_SPLIT_BATCH = 0x3; +constexpr int FINISH_VEC_DEQUANT_QC_SPLIT_N = 0X7; +constexpr int FINISH_VEC_DEQUANT_QC_SPLIT_N_GAP = 0X1; +constexpr int FINISH_MM_QN_SPLIT_N = 0X8; + +#ifdef ENABLE_DUMP_DATA +#define DO_DUMP_DATA(srcTensor, id, len) DumpTensor(srcTensor, id, len) +#else +#define DO_DUMP_DATA(srcTensor, id, len) +#endif + +class NoneType {}; + +using FP8E4M3 = fp8_e4m3fn_t; + +using FP8E8M0 = fp8_e8m0_t; + +using HIF8 = hifloat8_t; + +// mte2 <> mte1 +#define SCALE_EVENT EVENT_ID3 +#define A_EVENT0 EVENT_ID4 +#define A_EVENT1 EVENT_ID5 +#define B_EVENT0 EVENT_ID6 +#define B_EVENT1 EVENT_ID7 + +// m <> mte1 +#define L0A_EVENT0 EVENT_ID3 +#define L0A_EVENT1 EVENT_ID4 +#define L0B_EVENT0 EVENT_ID5 +#define L0B_EVENT1 EVENT_ID6 + +// fix <> m +#define L0C_EVENT0 EVENT_ID3 +#define L0C_EVENT1 EVENT_ID4 + +constexpr uint32_t L1_A_SIZE = 128 * 1024; // 512 / 4 +constexpr uint32_t L1_B_SIZE = 128 * 1024; // 512 / 4 +constexpr uint32_t L0A_PP_SIZE = 32 * 1024; +constexpr uint32_t L0B_PP_SIZE = 32 * 1024; +constexpr uint32_t L0C_PP_SIZE = 64 * 1024; + + +/* + 非量化 半量化(kv非量化) 半量化(kv量化) int8全量化(kv非量化) int8全量化(kv量化) 半量化(kv per-tile量化) int8全量化(kv per-tile量化) Mxfp8量化(kv非量化) Mxfp8量化(kv量化) Mxfp8量化(kv per-tile量化) fp8全量化(kv非量化) fp8全量化(kv量化) hif8全量化(kv非量化) hif8全量化(kv量化) + cacheMode PA_BSND/PA_BLK_BSND PA_BSND/PA_BLK_BSND PA_BSND/PA_BLK_BSND PA_BSND/PA_BLK_BSND PA_BSND/PA_BLK_BSND PA_BSND/BSND/TND PA_BSND/BSND/TND PA_BSND/PA_BLK_BSND PA_BSND/PA_BLK_BSND PA_BSND/BSND/TND PA_BSND/PA_BLK_BSND PA_BSND/PA_BLK_BSND PA_BSND/PA_BLK_BSND PA_BSND/PA_BLK_BSND + /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ /PA_NZ/PA_BLK_NZ + /BSND/TND /BSND/TND /BSND/TND /BSND/TND /BSND/TND /BSND/TND /BSND/TND /BSND/TND /BSND/TND /BSND/TND /BSND/TND + enableDequantOpt false true/false true/false true/false true/false true true true true true true/false true/false true/false true/false + enableGroupDequantOpt false true/false true/false false false false false false false false false false false false + quantMode 0 1 2 3 4 5 6 7 8 9 10 11 12 13 + tokenXType(复用mmInputType) bfloat16_t bfloat16_t bfloat16_t int8_t int8_t bfloat16_t int8_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t hifloat8_t hifloat8_t + WdqType(复用mmInputType) bfloat16_t bfloat16_t bfloat16_t int8_t int8_t bfloat16_t int8_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t hifloat8_t hifloat8_t + WuqqrType(复用mmQcQrInputType) bfloat16_t int8_t int8_t int8_t int8_t int8_t int8_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t hifloat8_t hifloat8_t + WukType(复用mmQnInputType) bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + WdkvkrType(复用mmInputType) bfloat16_t bfloat16_t bfloat16_t int8_t int8_t bfloat16_t int8_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t hifloat8_t hifloat8_t + rmsNormGammaType bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + gammaCkvType(复用rmsNormGammaType)bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + ropeSinCosType bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + cosType(复用ropeSinCosType) bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + cacheIndexType int64_t int64_t int64_t int64_t int64_t int64_t int64_t int64_t int64_t int64_t int64_t int64_t int64_t int64_t + kvCacheType bfloat16_t bfloat16_t int8_t bfloat16_t int8_t int8_t int8_t bfloat16_t fp8_e4m3fn_t fp8_e4m3fn_t bfloat16_t fp8_e4m3fn_t bfloat16_t hifloat8_t + krCacheType bfloat16_t bfloat16_t int8_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + deqScaleXType / / / float float / float fp8_e8m0_t fp8_e8m0_t fp8_e8m0_t float float float float + deqScaleWdqType / / / float float / float fp8_e8m0_t fp8_e8m0_t fp8_e8m0_t float float float float + deqScaleWuqqrType / float float float float float float fp8_e8m0_t fp8_e8m0_t fp8_e8m0_t float float float float + deqScaleWdkvkrType / / / float float / float fp8_e8m0_t fp8_e8m0_t fp8_e8m0_t float float float float + quantScaleCkvType / / float / float / / / float / / float / float + quantScaleCkrType / / float / / / / / / / / / / / + smoothScaleCqType / float float float float float float / / / float float float float + queryOutputType bfloat16_t bfloat16_t int8_t bfloat16_t int8_t bfloat16_t bfloat16_t bfloat16_t fp8_e4m3fn_t bfloat16_t bfloat16_t fp8_e4m3fn_t bfloat16_t hifloat8_t + ropeOutputType bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + dequantScaleQNopeType / / / / float / / / float / / float / float + queryNormType(复用mmQcQrInputType)bfloat16_t int8_t int8_t int8_t int8_t int8_t int8_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t hifloat8_t hifloat8_t + dequantScaleQNormType / float float float float float float fp8_e8m0_t fp8_e8m0_t fp8_e8m0_t float float float float + mmInputType bfloat16_t bfloat16_t bfloat16_t int8_t int8_t bfloat16_t int8_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t hifloat8_t hifloat8_t + mmCqOutputType bfloat16_t bfloat16_t bfloat16_t int32_t int32_t bfloat16_t int32_t float float float float float float float + mmCkvKrInputType(复用mmInputType) bfloat16_t bfloat16_t bfloat16_t int8_t int8_t bfloat16_t int8_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t hifloat8_t hifloat8_t + mmCkvKrOutputType bfloat16_t bfloat16_t bfloat16_t int32_t int32_t bfloat16_t int32_t float float float float float float float + mmQcQrInputType bfloat16_t int8_t int8_t int8_t int8_t int8_t int8_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t hifloat8_t hifloat8_t + mmQcQrOutputType bfloat16_t bfloat16_t bfloat16_t int32_t int32_t bfloat16_t int32_t float float float float float float float + mmQnInputType bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + mmQnOutputType bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t bfloat16_t + rmsNormComputType float float float float float float float float float float float float float float + rmsNormCqOutputType bfloat16_t int8_t int8_t int8_t int8_t int8_t int8_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t fp8_e4m3fn_t hifloat8_t hifloat8_t + rmsNormCkvOutputType bfloat16_t bfloat16_t int8_t bfloat16_t int8_t int8_t int8_t bfloat16_t fp8_e4m3fn_t fp8_e4m3fn_t bfloat16_t fp8_e4m3fn_t bfloat16_t hifloat8_t + ropeComputType float float float float float float float float float float float float float float +*/ + +template +struct MLAPType { + // 如果是 FP8 或 HIF8,输出 float;如果是 int8,输出 int32_t;否则输出 bfloat16_t + template + using GetMatmulOutType_t = typename std::conditional< + std::is_same::value || std::is_same::value, float, + typename std::conditional::value, int32_t, bfloat16_t>::type>::type; + + using mmInputType = X_T; // tokenX的类型与weight的类型一致 + using mmQcQrInputType = W_T; + using mmQnInputType = bfloat16_t; // matmul计算Qn的输入类型 + using mmCqOutputType = GetMatmulOutType_t; // matmul计算Cq的输出类型 + using mmCkvKrOutputType = GetMatmulOutType_t; // matmul计算QcQr的输出类型 + using mmQcQrOutputType = GetMatmulOutType_t; // matmul计算Qn的输出类型 + using mmQnOutputType = bfloat16_t; // matmul计算Qn的输出类型 + using rmsNormGammaType = bfloat16_t; // gamma的输入类型 + using rmsNormComputType = float; + using rmsNormCqOutputType = W_T; + using rmsNormCkvOutputType = C_T; + using ropeSinCosType = bfloat16_t; // sin cos的输入类型 + using ropeComputType = float; + using ropeOutputType = bfloat16_t; + using kvCacheType = C_T; // kvcache的类型 + // 如果是 X_T 为 bfloat16_t && C_T 为 int8_t 且不是 pertile (半量化kv perchannel量化), 则为 int8_t;否则为 + // bfloat16_t + using krCacheType = typename std::conditional::value && + std::is_same::value && !IS_PERTILE, + int8_t, bfloat16_t>::type; + using dequantScaleQNopeType = float; // dequantScaleQNope的类型 + using dequantScaleQNormType = D_S; // dequantScaleQNorm的类型 + using dequantScaleType = D_S; + + static constexpr CACHE_MODE cacheMode = C_M; + static constexpr bool enableDequantOpt = ENABLE_DEQUANT_OPT; + static constexpr bool enableGroupComputeOpt = ENABLE_GROUP_COMPUTE_OPT; + static constexpr EMPTY_TENSOR_MODE emptyMode = EMPTY_MODE; + static constexpr ACTUAL_SEQ_MODE actualSeqMode = SEQ_MODE; + static constexpr bool isPertile = IS_PERTILE; + static constexpr uint32_t cvRatio = CV_RATIO; // 默认C:V 1:2 +}; + +struct MMParams { + uint32_t m; + uint32_t n; + uint32_t k; + uint32_t orgM; + uint32_t orgN; + uint32_t orgKa; + uint32_t orgKb; + uint32_t orgKc; + uint32_t baseM; + uint32_t baseN; + uint32_t baseK; + uint32_t stepK; + uint32_t needSetOrgShape; + uint32_t kL1StepSize; + uint32_t kScale; +}; + +struct MMBufParams { + uint32_t aL1BufIter = 0; + uint32_t bL1BufIter = 0; + TBuffAddr aL1BufAddr; + TBuffAddr bL1BufAddr; + uint32_t aL0BufIter = 0; + uint32_t bL0BufIter = 0; + uint32_t cL0BufIter = 0; + TBuffAddr aL0BufAddr; + TBuffAddr bL0BufAddr; + TBuffAddr cL0BufAddr; +}; + +struct AicOffset { + int64_t weightDqOffset = 0; + int64_t weightUqQrOffset = 0; + int64_t weightUqOffset = 0; + int64_t weightQrOffset = 0; + int64_t weightUkOffset = 0; + int64_t weightDkvKrOffset = 0; + int64_t dequantScaleWDqOffset = 0; + int64_t dequantScaleWDkvKrOffset = 0; + int64_t dequantScaleCqOffset = 0; + int64_t dequantScaleWuqqrOffset = 0; + int64_t cqResOffset = 0; + int64_t rmsNormCqResOffset = 0; + int64_t ckvKrResOffset = 0; + int64_t qcQrResOffset = 0; + int64_t qCResOffset = 0; + int64_t qRResOffset = 0; + int64_t qcOffset = 0; + int64_t qnResOffset = 0; +}; + +struct AivOffset { + int64_t curVecToken = 0; + int64_t curBlockTokenOffset = 0; + int64_t rmsNormCqOffset = 0; + int64_t rmsNormCqResOffset = 0; + int64_t rmsNormCkvOffset = 0; + int64_t mmQnPreDequantOffset = 0; + int64_t mmQnPreDequantResOffset = 0; + int64_t ropeKrOffset = 0; + int64_t ropeQrOffset = 0; + int64_t ropeQrResOffset = 0; + int64_t ropeQrSplitNOffset = 0; + int64_t ropeQrResSplitNOffset = 0; + int64_t qcScaleOffsetSplitN = 0; +}; + +struct UsedBlockParams { + uint32_t blockStartIdx; + uint32_t blockEndIdx; +}; + +struct CkvkrParams { + int64_t tokenIndex; + int64_t offset; + int64_t curVecTokenIdx; + int64_t rowsInCurBatch; + int64_t cacheOffset; + int64_t nextBatchOffset; +}; + + +struct RopeQrSplitNParams { + int64_t ropeQrOffset; + int64_t ropeQrResOffset; + uint32_t inputOffsetRope; + uint32_t deqScaleOffset; + uint32_t outputOffsetRope; + int64_t ropeStride; + uint32_t ropeDstStride; + uint32_t deQuantScaleCqOffset; + uint32_t sinCosOffset; + uint32_t ropeCnt; +}; + +struct DequantQcQrSplitNParams { + int64_t mmQnPreDequantOffset; + int64_t mmQnPreDequantResOffset; + uint32_t inputOffset; + uint32_t outputOffset; + uint32_t srcStride; + uint32_t dstStride; +}; + +struct CastQcQrSplitNParams { + int64_t mmQnPreCastOffset; + int64_t mmQnPreCastResOffset; + uint32_t inputOffset; + uint32_t outputOffset; + uint32_t srcStride; + uint32_t dstStride; +}; + +template +__aicore__ inline void WaitAllCore(uint16_t flagId) +{ + CrossCoreSetFlag(flagId); + CrossCoreWaitFlag(flagId); +} + +template +__aicore__ constexpr bool IsFullQuantMode() +{ + constexpr bool IS_FP8_E8M0 = std::is_same::value; + if constexpr (EXCLUDE_MXFP8) { + // Pattern A: INT8 ‖ HIF8 ‖ (FP8E4M3 && !IS_FP8_E8M0) + return std::is_same::value || std::is_same::value || + (std::is_same::value && !IS_FP8_E8M0); + } else { + // Pattern B: INT8 ‖ FP8E4M3 ‖ HIF8 + return std::is_same::value || std::is_same::value || + std::is_same::value; + } +} + +} +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/mla_prolog_vector_comm.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/mla_prolog_vector_comm.h new file mode 100644 index 0000000000000000000000000000000000000000..8f39fafc0664e46b357b809a345158cb70b0c21b --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/mla_prolog_vector_comm.h @@ -0,0 +1,459 @@ +/** + * 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 mla_prolog_comm.h + * \brief 存放各种vector的公共组件 + */ + +#ifndef MLA_PROLOG_VECTOR_COMM_H +#define MLA_PROLOG_VECTOR_COMM_H + +#include "vf/vf_quant_pertensor.h" +#include "vf/vf_quant_perchannel.h" +#include "vf/vf_dynamic_quant.h" +#include "vf/vf_dequant.h" + +#include "mla_prolog_comm.h" +namespace MlaProlog { + +struct Rectangle { + uint32_t row; + uint32_t col; + uint32_t stride; +}; + +struct RmsNormParam { + float reciprocal; + float epsilon; + uint32_t row; + uint32_t col; + float scale; + uint16_t isScaleEnable; +}; + +struct PerTileQuantParams { + uint32_t tileSize; + uint32_t tileNum; + float alpha; + uint32_t row; + uint32_t col; +}; + +/** + * @brief RowMuls muls by row, 每行的元素乘以相同的元素,该元素需要扩展到一个数据块; + * dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] * src1Ub[i, 0 : 7] + * @param dstUb 输出tensor [row, columnStride] + * @param src0Ub 输入tensor [row, columnStride] + * @param src1Ub 输入tensor [row, FP32_BLOCK_ELEMENT_NUM] + * @param rectangleParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + */ +template +__aicore__ inline void RowMuls(LocalTensor dstUb, LocalTensor src0Ub, LocalTensor src1Ub, + const Rectangle &rectangleParams) +{ + uint32_t repeatElementNum = FP32_REPEAT_ELEMENT_NUM; + uint32_t blockElementNum = FP32_BLOCK_ELEMENT_NUM; + + if constexpr (std::is_same::value) { + // 此限制由于每个repeat至多连续读取256B数据 + repeatElementNum = FP32_REPEAT_ELEMENT_NUM * 2; // 256/4 * 2 = 128 + blockElementNum = FP32_BLOCK_ELEMENT_NUM * 2; // 32/4 * 2 = 16 + } + + // 每次只能连续读取256B的数据进行计算,故每次只能处理256B/sizeof(dType)= + // 列方向分dLoop次,每次处理8列数据 + uint32_t dLoop = rectangleParams.col / repeatElementNum; + uint32_t dRemain = rectangleParams.col % repeatElementNum; + // REPEAT_STRIDE_UP_BOUND=256,此限制由于src0RepStride数据类型为uint8至多256个datablock间距 + if (rectangleParams.stride < REPEAT_STRIDE_UP_BOUND * blockElementNum) { + // dstBlkStrideIn src0BlkStrideIn src1BlkStrideIn dstRepStrideIn src0RepStrideIn src1RepStrideIn + BinaryRepeatParams repeatParams{1, + 1, + 0, + static_cast(rectangleParams.stride / blockElementNum), + static_cast(rectangleParams.stride / blockElementNum), + 1}; + + // 如果以列为repeat所处理的次数小于行处理次数,则以列方式处理。反之则以行进行repeat处理 + if (dLoop <= rectangleParams.row) { + uint32_t offset = 0; + for (uint32_t i = 0; i < dLoop; i++) { + Mul(dstUb[offset], src0Ub[offset], src1Ub, repeatElementNum, rectangleParams.row, repeatParams); + offset += repeatElementNum; + } + } else { + repeatParams.src0RepStride = 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + repeatParams.src1RepStride = 0; + repeatParams.dstRepStride = 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + for (uint32_t i = 0; i < rectangleParams.row; i++) { + Mul(dstUb[i * rectangleParams.stride], src0Ub[i * rectangleParams.stride], src1Ub[i * blockElementNum], + repeatElementNum, dLoop, repeatParams); + } + } + + // 最后一次完成[row, dRemain] * [row, blockElementNum] 只计算有效部分 + if (dRemain > 0) { + Mul(dstUb[dLoop * repeatElementNum], src0Ub[dLoop * repeatElementNum], src1Ub, dRemain, rectangleParams.row, + repeatParams); + } + } else { + // dstBlkStrideIn src0BlkStrideIn src1BlkStrideIn dstRepStrideIn src0RepStrideIn src1RepStrideIn + // 8 : 每个repeat为256B数据,正好8个datablock + BinaryRepeatParams repeatParams{1, 1, 0, 8, 8, 0}; + + // 每次计算一行,共计算dealRowCount行 + for (uint32_t i = 0; i < rectangleParams.row; i++) { + // 计算一行中的dLoop个repeat,每个repeat计算256/block_size个data_block + Mul(dstUb[i * rectangleParams.stride], src0Ub[i * rectangleParams.stride], src1Ub[i * blockElementNum], + repeatElementNum, dLoop, repeatParams); + // 计算一行中的尾块 + if (dRemain > 0) { + Mul(dstUb[i * rectangleParams.stride + dLoop * repeatElementNum], + src0Ub[i * rectangleParams.stride + dLoop * repeatElementNum], src1Ub[i * blockElementNum], dRemain, + 1, repeatParams); + } + } + } +} + +/** + * @brief RowMax max by row, 按行求最大值 + * @param dstUb 输出tensor [row, 1] + dstUb[i] = max(srcUb[i, :]) + * @param srcUb 输入tensor [row, columnStride] + * @param rectangleParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + */ +__aicore__ inline void RowMax(LocalTensor &dstUb, LocalTensor &srcUb, const Rectangle rectangleParams) +{ + uint32_t dtypeMask = FP32_REPEAT_ELEMENT_NUM; + uint32_t blockCount = rectangleParams.col / dtypeMask; + uint32_t remain = rectangleParams.col % dtypeMask; + + BinaryRepeatParams repeatParamsMax; + repeatParamsMax.src0BlkStride = 1; + repeatParamsMax.src1BlkStride = 1; + repeatParamsMax.dstBlkStride = 1; + repeatParamsMax.src0RepStride = rectangleParams.stride / FP32_BLOCK_ELEMENT_NUM; + repeatParamsMax.src1RepStride = rectangleParams.stride / FP32_BLOCK_ELEMENT_NUM; + repeatParamsMax.dstRepStride = rectangleParams.stride / FP32_BLOCK_ELEMENT_NUM; + if (blockCount > 0 && remain > 0) { + Max(srcUb, srcUb, srcUb[blockCount * dtypeMask], remain, rectangleParams.row, repeatParamsMax); + PipeBarrier(); + } + + for (uint32_t columnLoopCount = blockCount >> 1; columnLoopCount > 0; + columnLoopCount = blockCount >> 1) { // 2: 每次处理2个block + blockCount = (blockCount + 1) >> 1; // 2: 每次处理2个block + for (uint32_t j = 0; j < columnLoopCount; j++) { + Max(srcUb[j * dtypeMask], srcUb[j * dtypeMask], srcUb[(j + blockCount) * dtypeMask], dtypeMask, + rectangleParams.row, repeatParamsMax); + } + PipeBarrier(); + } + + WholeReduceMax(dstUb, srcUb, (rectangleParams.col < dtypeMask) ? rectangleParams.col : dtypeMask, + rectangleParams.row, 1, 1, rectangleParams.stride / FP32_BLOCK_ELEMENT_NUM, + ReduceOrder::ORDER_ONLY_VALUE); +} + +/** + * @brief Dequant 对[row * col]的tensor进行反量化。需要输入一个行向量和列向量,共同构成反量化的矩阵。 + outputLocal [i,j] = inputLocal[i,j] * scaleLocal[j] * scale2Local [i] + * @param outputLocal 输出tensor [row , col] + * @param inputLocal 输入tensor [row , col] + * @param scaleLocal [1,col] 量化系数;行向量 + * @param scale2Local [row,8] 量化系数;列向量,8为float扩充为32Bytes + * @param rectangleParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + */ +template +__aicore__ inline void Dequant(const LocalTensor &outputLocal, const LocalTensor &inputLocal, + const LocalTensor &scaleLocal, const LocalTensor &scale2Local, + const Rectangle &rectangleParams) +{ + DequantVf(outputLocal, inputLocal, scaleLocal, scale2Local, rectangleParams.row, rectangleParams.col, + rectangleParams.stride); +} + +/** + * @brief CastFP32ToINT8 将float类型cast为int8,路径为float--------->int32--------->half---------->int8 + CAST_RINT CAST_ROUND CAST_TRUNC + * @param outputLocal 输出tensor [cnt] + * @param inputLocal 输入tensor [cnt] + * @param shareTmpUb 临时buffer 内部需要的空间为 [cnt * 4] 4 : sizeof(int32) + * @param cnt tensor长度 + */ +template +__aicore__ inline void CastFP32ToINT8(const LocalTensor outLocal, const LocalTensor &inputLocal, + const LocalTensor &shareTmpUb, uint64_t cnt) +{ + LocalTensor int32 = shareTmpUb.ReinterpretCast(); + LocalTensor tmpHalf = shareTmpUb.ReinterpretCast(); + Cast(int32, inputLocal, RoundMode::CAST_RINT, cnt); + PipeBarrier(); + SetDeqScale(static_cast(1.0)); + PipeBarrier(); + Cast(tmpHalf, int32, RoundMode::CAST_ROUND, cnt); + PipeBarrier(); + Cast(outLocal, tmpHalf, RoundMode::CAST_TRUNC, cnt); +} + +// divs by row, 每行的元素除以相同的元素 +// dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] / src1Ub[i, 0 : 7] +// src0Ub:[dealRowCount, columnCount], src1Ub:[dealRowCount, FP32_BLOCK_ELEMENT_NUM] dstUb:[dealRowCount, +// columnCount] +__aicore__ inline void RowClips(LocalTensor &dstUb, const LocalTensor &src0Ub, + const LocalTensor &maxUb, const LocalTensor &minUb, uint32_t dealRowCount, + uint32_t columnCount, uint32_t actualColumnCount) +{ + uint32_t dtypeMask = FP32_REPEAT_ELEMENT_NUM; + uint32_t dLoop = actualColumnCount / dtypeMask; + uint32_t dRemain = actualColumnCount % dtypeMask; + + BinaryRepeatParams repeatParams; + repeatParams.src0BlkStride = 1; + repeatParams.src1BlkStride = 0; + repeatParams.dstBlkStride = 1; + repeatParams.src0RepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; + repeatParams.src1RepStride = 1; + repeatParams.dstRepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; + uint32_t offset = 0; + + for (uint32_t i = 0; i < dLoop; i++) { + Min(dstUb[offset], src0Ub[offset], maxUb, dtypeMask, dealRowCount, repeatParams); + PipeBarrier(); + Max(dstUb[offset], dstUb[offset], minUb, dtypeMask, dealRowCount, repeatParams); + offset += dtypeMask; + } + + if (dRemain > 0) { + Min(dstUb[dLoop * dtypeMask], src0Ub[dLoop * dtypeMask], maxUb, dRemain, dealRowCount, repeatParams); + PipeBarrier(); + Max(dstUb[dLoop * dtypeMask], dstUb[dLoop * dtypeMask], minUb, dRemain, dealRowCount, repeatParams); + } +} + +__aicore__ inline void PerTileClipWithAlpha(LocalTensor &dstClipUb, LocalTensor &aMax, + LocalTensor &aMaxBrcb, const LocalTensor &srcUb, + const LocalTensor &shareTmpUb, + const PerTileQuantParams &perTileQuantParams) +{ + constexpr uint32_t brcnNum = 8; // brcn一次性处理8个数据 + uint32_t srcSize = perTileQuantParams.row * perTileQuantParams.col; + uint32_t maxAlphaSize = perTileQuantParams.row * perTileQuantParams.tileNum * FP32_BLOCK_ELEMENT_NUM; + + LocalTensor absSrcUb = shareTmpUb.template ReinterpretCast(); + LocalTensor maxAlpha = absSrcUb[Align(srcSize, FP32_BLOCK_ELEMENT_NUM)]; + LocalTensor minAlpha = maxAlpha[Align(maxAlphaSize, FP32_BLOCK_ELEMENT_NUM)]; + + Abs(absSrcUb, srcUb, srcSize); + PipeBarrier(); + + Rectangle rectangleParams{ + static_cast(perTileQuantParams.row * perTileQuantParams.tileNum), + static_cast(perTileQuantParams.tileSize), + static_cast(perTileQuantParams.tileSize) // columnStride + }; + RowMax(aMax, absSrcUb, rectangleParams); + PipeBarrier(); + Brcb(aMaxBrcb, aMax, (CeilDivT((perTileQuantParams.row * perTileQuantParams.tileNum), brcnNum)), {1, brcnNum}); + PipeBarrier(); + + Muls(maxAlpha, aMaxBrcb, perTileQuantParams.alpha, maxAlphaSize); + Muls(minAlpha, aMaxBrcb, -perTileQuantParams.alpha, maxAlphaSize); + PipeBarrier(); + + RowClips(dstClipUb, srcUb, maxAlpha, minAlpha, perTileQuantParams.row * perTileQuantParams.tileNum, + perTileQuantParams.tileSize, perTileQuantParams.tileSize); + PipeBarrier(); +} + +/** + * @brief DynamicQuant 对row行进行dynamicquant, float ---> int8, 每一行出一个系数。 + * @param outputLocal 输出tensor [row , col],支持和inputLocal是同一块空间 + * @param scale 输出每行的反量化系数 [row] + * @param inputLocal 输入tensor [row , col] + * @param rowMax [row] 一行的最大值 + * @param rowMaxBrcb [row, 8] 一行的最大值,brcb扩充为8的倍数 + * @param shareTmpUb 临时buffer 内部需要的空间为 [row * col * sizeof(float)] + * @param row 待处理的行数 + * @param col 待处理的列数 + */ +__aicore__ inline void DynamicQuant(const LocalTensor &outputLocal, const LocalTensor &scale, + const LocalTensor &inputLocal, const LocalTensor &aMax, + const LocalTensor &rowMaxBrcb, const LocalTensor &shareTmpUb, + float alpha, uint64_t row, uint64_t col) +{ + constexpr float maxInt8 = 127.0f; + int32_t aMaxSizeAlign = Align(static_cast(row), FP32_BLOCK_ELEMENT_NUM); + LocalTensor aMaxAlpha = shareTmpUb.ReinterpretCast(); + LocalTensor dupTensor = aMaxAlpha[aMaxSizeAlign]; + LocalTensor scaleReciprocal = dupTensor[aMaxSizeAlign]; + LocalTensor scaleReciprocalBrcb = scaleReciprocal[aMaxSizeAlign]; + + Duplicate(dupTensor, 1.0f, row); + Muls(aMaxAlpha, aMax, alpha, row); + PipeBarrier(); + Muls(scale, aMaxAlpha, 1.0f / maxInt8, row); + PipeBarrier(); + Div(scaleReciprocal, dupTensor, scale, row); + PipeBarrier(); + Brcb(scaleReciprocalBrcb, scaleReciprocal, CeilDivT(row, 8UL), {1, 8}); + PipeBarrier(); + RowMuls(outputLocal, inputLocal, scaleReciprocalBrcb, + Rectangle{static_cast(row), static_cast(col), static_cast(col)}); + PipeBarrier(); +} + +/** + * @brief QuantPerChannel 同时对row行进行FP32到int8的per-channel量化操作。一行中的每一列用不同的量化参数。 + outLocal[i, j] = inputLocal[i, j] * quantScaleLocal[j] + * @param outLocal 输出tensor [row , col] + * @param inputLocal 输入tensor [row , col] + * @param quantScaleLocal quant系数 [1 , col] + * @param shareTmpUb 临时buffer 内部需要的空间为 [row * col * 4],源自CastFP32ToINT8 + * @param rectangleParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + */ +template +__aicore__ inline void QuantPerChannel(const LocalTensor &outLocal, const LocalTensor &inputLocal, + const LocalTensor &quantScaleLocal, const LocalTensor &shareTmpUb, + const Rectangle &rectangleParams) +{ + QuantPerChannelVf(outLocal, inputLocal, quantScaleLocal, rectangleParams.row, rectangleParams.col, + rectangleParams.stride); +} + +/** + * @brief QuantPerTensor 同时对row行进行FP32到int8的per-tensor量化操作。一行内共用同一个量化系数。 + outLocal[i , j] = inputLocal[i , j] * quantScaleLocal[i] + * @param outLocal 输出tensor [row , col] + * @param inputLocal 输入tensor [row , col] + * @param quantScaleLocal quant系数 [row , 8]; 8 : 32Bytes对齐 + * @param shareTmpUb 临时buffer 内部需要的空间为 [row * col * 4],源自CastFP32ToINT8 + * @param rectangleParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + */ +template +__aicore__ inline void QuantPerTensor(const LocalTensor &outLocal, const LocalTensor &inputLocal, + const LocalTensor &quantScaleLocal, const LocalTensor &shareTmpUb, + const Rectangle &rectangleParams) +{ + QuantPerTensorVF(outLocal, inputLocal, quantScaleLocal, rectangleParams.row, rectangleParams.col); +} + +/** + * @brief QuantPerTile 对输入tensor进行per-tile量化操作,FP32->fp8 e4m3/hifloat8,每个tile出一个量化系数。 + 量化流程:先对输入的每行的每个tile做动态量化,最后转换为fp8/hif8. + * @param outLocal 输出tensor [row * col],量化后的fp8/hif8数据,后续跟随scale数据 + * @param inputLocal 输入tensor [row * col] + * @param shareTmpUb 临时buffer,内部需要空间为: + * [Align(row * tileNum, 8) + row * tileNum * 8 + 其他中间计算所需空间] * sizeof(float) + * @param perTileQuantParams 描述pertile量化的参数,包括 + * tileSize 每个tile的大小 + * tileNum 每行的tile数量 + * alpha clip的alpha系数 + * row 待处理的行数 + * col 待处理的列数 (col = tileSize * tileNum) + */ +template +__aicore__ inline void QuantPerTile8Bit(const LocalTensor &outLocal, const LocalTensor &inputLocal, + const PerTileQuantParams &perTileQuantParams) +{ + LocalTensor quantScaleLocal = + outLocal[perTileQuantParams.row * perTileQuantParams.col].template ReinterpretCast(); + QuantPerTileVF(outLocal, inputLocal, quantScaleLocal, perTileQuantParams.row, + perTileQuantParams.col, perTileQuantParams.tileSize); +} + +__aicore__ inline void QuantPerTile(const LocalTensor &outLocal, const LocalTensor &inputLocal, + const LocalTensor &shareTmpUb, + const PerTileQuantParams &perTileQuantParams) +{ + LocalTensor scale = + outLocal[perTileQuantParams.row * perTileQuantParams.col].template ReinterpretCast(); + + LocalTensor clipOut = inputLocal; + uint32_t aMaxSizeAlign = + Align(static_cast(perTileQuantParams.row * perTileQuantParams.tileNum), FP32_BLOCK_ELEMENT_NUM); + uint32_t aMaxBrcbSize = perTileQuantParams.row * perTileQuantParams.tileNum * FP32_BLOCK_ELEMENT_NUM; + LocalTensor aMax = shareTmpUb.template ReinterpretCast(); + LocalTensor aMaxBrcb = aMax[aMaxSizeAlign]; + LocalTensor sharedBuf = aMaxBrcb[aMaxBrcbSize].template ReinterpretCast(); + + PerTileClipWithAlpha(clipOut, aMax, aMaxBrcb, inputLocal, sharedBuf, perTileQuantParams); + + LocalTensor quantOut = clipOut; + DynamicQuant(quantOut, scale, clipOut, aMax, aMaxBrcb, sharedBuf, perTileQuantParams.alpha, + perTileQuantParams.row * perTileQuantParams.tileNum, perTileQuantParams.tileSize); + PipeBarrier(); + CastFP32ToINT8(outLocal, quantOut, sharedBuf, perTileQuantParams.row * perTileQuantParams.col); +} + +/** + * @brief DynamicQuant 同时对row行进行dynamicquant, float ---> int8, 每一行出一个系数。 + * @param outLocal 输出tensor [row , col],支持和inputLocal是同一块空间 + * @param inputLocal 输入tensor [row , col] + * @param scale 输出每行的反量化系数 [1 , row] + * @param maxInt8Tensor [1 , row] 元素均为int8的最大值127 + * @param shareTmpUb 临时buffer 内部需要的空间为 [(Align(row * col, 8) + Align(row , 8) * ALIGN_BLOCK_SIZE) * + * sizeof(float)] + * @param row 待处理的行数 + * @param col 待处理的列数 + */ +__aicore__ inline void DynamicQuant(const LocalTensor &outputLocal, const LocalTensor &scale, + const LocalTensor &inputLocal, const LocalTensor &maxInt8Tensor, + const LocalTensor &shareTmpUb, uint64_t row, uint64_t col) +{ + constexpr uint64_t brcnNum = 8; // brcb一次处理8个数据 + uint64_t computeSize = row * col; + LocalTensor inputCopy = shareTmpUb.ReinterpretCast(); + LocalTensor rowMaxBrcb = inputCopy[Align(computeSize, static_cast(ALIGN_BLOCK_SIZE))]; + // abs(x) + Abs(inputCopy, inputLocal, computeSize); + PipeBarrier(); + Rectangle rectangleParams{ + static_cast(row), static_cast(col), + static_cast(col) // columnStride + }; + // rowMax(abs(x)) + RowMax(inputCopy, inputCopy, rectangleParams); + PipeBarrier(); + + // scaleOut = rowMax(abs(x)) / 127 + Div(scale, inputCopy, maxInt8Tensor, row); + PipeBarrier(); + + // 1 / scaleOut = 127 / rowMax(abs(x)) + Div(inputCopy, maxInt8Tensor, inputCopy, row); + PipeBarrier(); + + Brcb(rowMaxBrcb, inputCopy, static_cast(CeilDivT(row, brcnNum)), {1, brcnNum}); + PipeBarrier(); + + // x * 1 / scaleOut + RowMuls(outputLocal, inputLocal, rowMaxBrcb, rectangleParams); +} + +} // namespace MlaProlog +#endif // MLA_PROLOG_VECTOR_COMM_H \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_dequant.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_dequant.h new file mode 100644 index 0000000000000000000000000000000000000000..cc0571151836e58bb2dad883215a6f9e6ac8d0c9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_dequant.h @@ -0,0 +1,195 @@ +/** + * 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 service_dequant.h + * \brief + */ + +#ifndef SERVICE_DEQUANT_H +#define SERVICE_DEQUANT_H + +#include "mla_prolog_comm.h" +#include "mla_prolog_vector_comm.h" + +namespace MlaProlog { + +/** + * @brief DequantPerTokenQc 用于对Qc做反量化;按行做dequant流程,给oriRow * col的数据做反量化 + * @param outputGm 输出tensor + * @param inputGm 输入tensor + * @param deqScaleQcQrWGm deqScaleQcQr反量化系数,原shape[1,ND] + * @param deQuantScaleQcQrLocal deQuantScaleQcQr反量化系数,原shape[BS,1] + * @param shareTmpUb 临时buffer + * @param dequantRowColStrideParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + * @param oriRow 一共有多少行 +*/ +template +__aicore__ inline void +DequantPerTokenQc(const GlobalTensor &outputGm, const GlobalTensor &inputGm, + const GlobalTensor &deqScaleQcQrWGm, const LocalTensor deQuantScaleQcQrLocal, + const LocalTensor &shareTmpUb, Rectangle dequantRowColStrideParams, uint32_t oriRow) +{ + int64_t count = dequantRowColStrideParams.row * dequantRowColStrideParams.col; + + LocalTensor inputLocal = shareTmpUb.ReinterpretCast(); // count * sizeof(T) + LocalTensor scaleLocal = inputLocal[count + 16].template ReinterpretCast(); // count * sizeof(C) + LocalTensor computeLocal = scaleLocal[count + 16].template ReinterpretCast(); // count * sizeof(C) + LocalTensor outputLocal = computeLocal[count + 16].template ReinterpretCast(); // count * sizeof(O) + + DataCopyParams copyParams{ + static_cast(dequantRowColStrideParams.row), + static_cast(dequantRowColStrideParams.col * sizeof(T) / 32U), + static_cast((dequantRowColStrideParams.stride - dequantRowColStrideParams.col) * sizeof(T) / 32U), 0}; + + Rectangle rectangleParams{ + static_cast(1), // row + static_cast(count), // col + static_cast(count) // columnStride + }; + + for (int64_t rowOffset = 0; rowOffset < oriRow; rowOffset += dequantRowColStrideParams.row) { + int64_t inputOffset = rowOffset * dequantRowColStrideParams.stride; + int64_t outputOffset = rowOffset * dequantRowColStrideParams.col; + // copy in + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + DataCopy(inputLocal, inputGm[inputOffset], copyParams); + DataCopy(scaleLocal, deqScaleQcQrWGm[inputOffset], copyParams); + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + // compute + Dequant(computeLocal, inputLocal, scaleLocal, deQuantScaleQcQrLocal, rectangleParams); + AscendC::PipeBarrier(); + // cast + Cast(outputLocal, computeLocal, RoundMode::CAST_RINT, count); + SetFlag(EVENT_ID2); + // copy out + WaitFlag(EVENT_ID2); + DataCopy(outputGm[outputOffset], outputLocal, count); + } +} + +/** + * @brief CastPerTokenQc 用于对Qc做类型转换;按行做cast流程,给oriRow * col的数据做类型转换 + * @param outputGm 输出tensor + * @param inputGm 输入tensor + * @param shareTmpUb 临时buffer + * @param castRowColStrideParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + * @param oriRow 一共有多少行 +*/ +template +__aicore__ inline void CastPerTokenQc(const GlobalTensor &outputGm, const GlobalTensor &inputGm, + const LocalTensor &shareTmpUb, Rectangle castRowColStrideParams, + uint32_t oriRow) +{ + int64_t count = castRowColStrideParams.row * castRowColStrideParams.col; + + LocalTensor inputLocal = shareTmpUb.ReinterpretCast(); // count * sizeof(T) + LocalTensor outputLocal = inputLocal[count + 16].template ReinterpretCast(); // count * sizeof(O) + + DataCopyParams copyParams{ + static_cast(castRowColStrideParams.row), + static_cast(castRowColStrideParams.col * sizeof(T) / 32U), + static_cast((castRowColStrideParams.stride - castRowColStrideParams.col) * sizeof(T) / 32U), 0}; + + for (int64_t rowOffset = 0; rowOffset < oriRow; rowOffset += castRowColStrideParams.row) { + int64_t inputOffset = rowOffset * castRowColStrideParams.stride; + int64_t outputOffset = rowOffset * castRowColStrideParams.col; + // copy in + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + DataCopy(inputLocal, inputGm[inputOffset], copyParams); + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + // cast + Cast(outputLocal, inputLocal, RoundMode::CAST_RINT, count); + SetFlag(EVENT_ID2); + // copy out + WaitFlag(EVENT_ID2); + DataCopy(outputGm[outputOffset], outputLocal, count); + } +} + +/** + DequantSplitNQc 用于enableGroupComputeOpt场景 + 场景特征:半量化,BS = 1, headsize = 8 + * @brief 用于对Qc做反量化;按N方向切分的dequant,理解为做一个head的 + * @param outputGm 输出位置 + * @param inputGm 输入tensor + * @param deqScaleQcQrWGm deqScaleQcQr反量化系数,原shape[1,ND] + * @param deQuantScaleQcQrLocal deQuantScaleQcQr反量化系数,原shape[BS,1] + * @param shareTmpUb 临时buffer + * @param dequantRowColStrideParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + * @param oriCol 一列真实的长度 + * @param dstStride 目的数据行间的偏移 + * @param subBlockIdx_ 这是奇数核还是偶数核 + */ +// 用于enableGroupComputeOpt场景 +template +__aicore__ inline void +DequantSplitNQc(const GlobalTensor &outputGm, const GlobalTensor &inputGm, const GlobalTensor &deqScaleQcQrWGm, + const LocalTensor &deQuantScaleQcQrLocal, const LocalTensor &shareTmpUb, + Rectangle dequantRowColStrideParams, uint32_t oriCol, uint32_t dstStride, uint32_t subBlockIdx_) +{ + int64_t count = dequantRowColStrideParams.col * 1; + LocalTensor inputLocal = shareTmpUb.ReinterpretCast(); // count * sizeof(T) + LocalTensor scaleLocal = inputLocal[count + 16].template ReinterpretCast(); // count * sizeof(C) + LocalTensor computeLocal = scaleLocal[count + 16].template ReinterpretCast(); // count * sizeof(C) + LocalTensor outputLocal = computeLocal[count + 16].template ReinterpretCast(); // count * sizeof(O) + + DataCopyParams inputCopyParams{ + static_cast(1), static_cast(count * sizeof(T) / 32U), + static_cast((dequantRowColStrideParams.stride - dequantRowColStrideParams.col) * sizeof(T) / 32U), 0}; + + DataCopyParams outputCopyParams{static_cast(1), static_cast(count * sizeof(O) / 32U), 0, + static_cast(dstStride * sizeof(O) / 32U)}; + + Rectangle rectangleParams{ + static_cast(1), // row + static_cast(count), // col + static_cast(count) // columnStride + }; + + SetFlag(EVENT_ID0); + int64_t scaleOffset = subBlockIdx_ * count; + DataCopy(scaleLocal, deqScaleQcQrWGm[scaleOffset], dequantRowColStrideParams.col); + for (int64_t rowOffset = 0; rowOffset < dequantRowColStrideParams.row; rowOffset++) { + int64_t inputOffset = rowOffset * oriCol + subBlockIdx_ * count; + int64_t outputOffset = rowOffset * oriCol + subBlockIdx_ * count; + WaitFlag(EVENT_ID0); + DataCopy(inputLocal, inputGm[inputOffset], inputCopyParams); + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + // compute + Dequant(computeLocal, inputLocal, scaleLocal, deQuantScaleQcQrLocal, rectangleParams); + AscendC::PipeBarrier(); + // cast + Cast(outputLocal, computeLocal, RoundMode::CAST_RINT, count); + SetFlag(EVENT_ID2); + // copy out + WaitFlag(EVENT_ID2); + DataCopy(outputGm[outputOffset], outputLocal, count); + SetFlag(EVENT_ID0); + } + WaitFlag(EVENT_ID0); +} + +} // namespace MlaProlog +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_dynamic_quant_qn_mul_qr.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_dynamic_quant_qn_mul_qr.h new file mode 100644 index 0000000000000000000000000000000000000000..42a4fa89eb28f5e555f337c72092b03b5f73336e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_dynamic_quant_qn_mul_qr.h @@ -0,0 +1,236 @@ +/** + * 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 service_dynamic_quant_qn_mul_qr.h + * \brief + */ + +#ifndef SERVICE_DYNAMIC_QUANT_H +#define SERVICE_DYNAMIC_QUANT_H + +#include "mla_prolog_comm.h" +#include "mla_prolog_vector_comm.h" +#include "vf/vf_mul_qr.h" +#include "vf/vf_dynamic_quant.h" + +namespace MlaProlog { + +template +__aicore__ inline void DynamicQuantMultiRow(const GlobalTensor &outputGm, const LocalTensor &scaleOutputLocal, + const GlobalTensor &inputGm, const LocalTensor outputLocal, + const LocalTensor &inputHalf, const LocalTensor &inputLocal, + const LocalTensor &maxInt8Tensor, const LocalTensor &shareTmpUb, + uint64_t row, uint64_t col, uint64_t subRow, uint64_t queryOutStride, + uint32_t DYNAMIC_QUANT_INPUT_READY, uint32_t DYNAMIC_QUANT_OUTPUT_READY) +{ + constexpr uint64_t inputBlockAlign = (ALIGN_BLOCK_SIZE / sizeof(T)); + constexpr uint64_t outputBlockAlign = (ALIGN_BLOCK_SIZE / sizeof(O)); + // DataCopyParams : count len srcStrideIn dstStrideIn + DataCopyParams outParams{static_cast(subRow), static_cast(col / outputBlockAlign), 0, + static_cast((queryOutStride - col) / outputBlockAlign)}; + DataCopyParams inputParams{static_cast(subRow), static_cast(col / inputBlockAlign), + static_cast((queryOutStride - col) / inputBlockAlign), 0}; + + uint32_t computeSize = subRow * col; + uint64_t loopCnt = CeilDivT(row, subRow); + uint64_t lastSubRow = row - (loopCnt - 1) * subRow; + uint64_t inputGmOffset = 0; + uint64_t scaleOffset = 0; + + for (uint64_t loopIdx = 0; loopIdx < loopCnt; loopIdx++) { + if ((loopIdx == loopCnt - 1) && (lastSubRow != subRow)) { + subRow = lastSubRow; + computeSize = subRow * col; + outParams.blockCount = subRow; + inputParams.blockCount = subRow; + } + + WaitFlag(DYNAMIC_QUANT_INPUT_READY); // 计算是否已经完成可以搬运 + DataCopy(inputHalf, inputGm[inputGmOffset], inputParams); + SetFlag(DYNAMIC_QUANT_INPUT_READY); + WaitFlag(DYNAMIC_QUANT_INPUT_READY); // 搬运是否已经完成可以计算 + + LocalTensor output = outputLocal.template ReinterpretCast(); + WaitFlag(DYNAMIC_QUANT_OUTPUT_READY); + PipeBarrier(); + DynamicQuantPerTokenVf(output, scaleOutputLocal[scaleOffset], inputHalf, subRow, col); + PipeBarrier(); + SetFlag(DYNAMIC_QUANT_INPUT_READY); + SetFlag(DYNAMIC_QUANT_OUTPUT_READY); + WaitFlag(DYNAMIC_QUANT_OUTPUT_READY); // 计算是否已经完成可以搬运 + DataCopy(outputGm[inputGmOffset], output, outParams); + SetFlag(DYNAMIC_QUANT_OUTPUT_READY); + inputGmOffset += subRow * queryOutStride; + scaleOffset += subRow; + } +} + +template +__aicore__ inline void +MulQr(const GlobalTensor &outputGmRope, const GlobalTensor &inputGmRope, LocalTensor outputLocalRope, + const LocalTensor &qrInputLocal, const LocalTensor &qrFp32Local, const LocalTensor &reciprocalLocal, + const LocalTensor &dequantScaleBrcbLocal, uint64_t row, uint64_t colRope, uint64_t subRowRope, + uint64_t qrOutputStrideRope, float quantScaleCkvRope, uint32_t MUL_QR_INPUT_COPY_READY, uint32_t MUL_QR) +{ + constexpr uint64_t inputBlockAlign = (ALIGN_BLOCK_SIZE / sizeof(T)); + constexpr uint64_t computeBlockAlign = (ALIGN_BLOCK_SIZE / sizeof(C)); + + uint64_t loopCntRope = CeilDivT(row, subRowRope); + uint64_t lastSubRowRope = row - (loopCntRope - 1) * subRowRope; + uint32_t computeSizeRope = subRowRope * colRope; + + // DataCopyParams : count len srcStrideIn dstStrideIn + DataCopyParams inputParamsRope{static_cast(row), static_cast(colRope / inputBlockAlign), + static_cast((qrOutputStrideRope - colRope) / inputBlockAlign), 0}; + DataCopyParams outputParamsRope{static_cast(subRowRope), static_cast(colRope / inputBlockAlign), + 0, static_cast((qrOutputStrideRope - colRope) / inputBlockAlign)}; + + uint64_t inputGmRopeOffset = 0; + uint64_t dequantScaleOffset = 0; + uint64_t inputLocalRopeOffset = 0; + + + WaitFlag(MUL_QR_INPUT_COPY_READY); + DataCopy(qrInputLocal, inputGmRope, inputParamsRope); + for (uint64_t loopIdx = 0; loopIdx < loopCntRope; loopIdx++) { + if (loopIdx == (loopCntRope - 1) && subRowRope != lastSubRowRope) { + subRowRope = lastSubRowRope; + computeSizeRope = subRowRope * colRope; + outputParamsRope.blockCount = subRowRope; + } + SetFlag(MUL_QR); + WaitFlag(MUL_QR); + + SetFlag(MUL_QR); + WaitFlag(MUL_QR); + + Cast(qrFp32Local, qrInputLocal[inputLocalRopeOffset], RoundMode::CAST_NONE, computeSizeRope); + PipeBarrier(); + MulQrVF(qrFp32Local, qrFp32Local, dequantScaleBrcbLocal, quantScaleCkvRope, computeSizeRope, computeBlockAlign); + Cast(outputLocalRope, qrFp32Local, RoundMode::CAST_RINT, computeSizeRope); + PipeBarrier(); + + SetFlag(MUL_QR); + WaitFlag(MUL_QR); + + DataCopy(outputGmRope[inputGmRopeOffset], outputLocalRope, outputParamsRope); + inputLocalRopeOffset += subRowRope * colRope; + inputGmRopeOffset += subRowRope * qrOutputStrideRope; + dequantScaleOffset += subRowRope * computeBlockAlign; + } + SetFlag(MUL_QR_INPUT_COPY_READY); +} +/** + * @brief DynamicQuantQnWithMulQr 流程中dynamicquant和ropeMul融合流程 + UB,流水,中间产物统筹规划 + * @tparam T mmQnOutputType -> bf16 + * @tparam C dequantScaleQNopeType -> float + * @tparam O queryOutputType -> int8 + * @param scaleOutputGm 动态量化参数输出GM位置 + * @param outputGm 动态量化结果输出GM位置 + * @param outputGmRope rope处理后的输出位置 + * @param inputGm dynamicQuant部分的输入 + * @param shareTmpUb 临时buffer空间 + * @param row + * @param col + * @param scaleOutStride 描述动态量化参数输出GM位置的偏移关系 + * @param queryOutStride 描述动态量化结果输出GM位置 + * @param inputGmRope + * @param quantScaleCkvRope + * @param colRope + * @param qrOutputStrideRope 描述rope处理后的输出位置 + */ +template +__aicore__ inline void DynamicQuantQnWithMulQr( + // Dynamic Quant With MulQr 输出 + const GlobalTensor &scaleOutputGm, const GlobalTensor &outputGm, const GlobalTensor &outputGmRope, + // Dynamic Quant 入参 + const GlobalTensor &inputGm, LocalTensor &shareTmpUb, uint64_t row, uint64_t col, + uint64_t scaleOutStride, uint64_t queryOutStride, + // Mul Qr 入参 + const GlobalTensor &inputGmRope, float quantScaleCkvRope, uint64_t colRope, uint64_t qrOutputStrideRope, + uint32_t cvRatio) +{ + if (row == 0 || col == 0) { + return; + } + // 常量 + constexpr uint32_t MUL_QR = EVENT_ID1; // 用于控制Mul_Qr的同步 + // dynamicquant输入的计算/搬运 是否已经完成可以开始下一轮的 搬运/计算 + constexpr uint32_t DYNAMIC_QUANT_INPUT_READY = EVENT_ID0; + constexpr uint32_t MUL_QR_INPUT_COPY_READY = EVENT_ID3; // 是否可以开始下一轮的MUL_QR_INPUT_COPY + constexpr uint32_t CALC_SCALE_FINISH = EVENT_ID0; // dynamicquant的scale是否计算完成可以开始搬运 + // dynamicquant输出的计算/搬运 是否已经完成可以开始下一轮的 搬运/计算 + constexpr uint32_t DYNAMIC_QUANT_OUTPUT_READY = EVENT_ID3; + + constexpr uint64_t computeBlockAlign = (ALIGN_BLOCK_SIZE / sizeof(C)); + constexpr uint64_t inputBlockAlign = (ALIGN_BLOCK_SIZE / sizeof(T)); + constexpr float maxInt8 = 127.0; + // Dynamic Quant 局部变量 + uint64_t rowStepSize = 8 * cvRatio; // 单次处理最大行数, cv1:1场景,改为8行进行计算,降低UB使用 + + uint64_t subRow = row < rowStepSize ? row : rowStepSize; + uint32_t computeSize = subRow * col; + uint32_t brcbCnt = Align(subRow, computeBlockAlign); + + // Rope Post Process 局部变量 + uint64_t rowStepSizeRope = 64; // 单次处理最大行数 + uint64_t subRowRope = row < rowStepSizeRope ? row : rowStepSizeRope; + uint32_t computeSizeRope = subRowRope * colRope; + uint32_t loadRopeGmSize = row * colRope; + + // Dynamic Quant & Rope Post Process UB Buffer分配 + LocalTensor inputHalf = shareTmpUb.ReinterpretCast(); + LocalTensor qrInputLocal = inputHalf[computeSize]; + LocalTensor outputLocalRope = qrInputLocal[loadRopeGmSize + inputBlockAlign]; + + LocalTensor inputLocal = outputLocalRope[computeSizeRope + inputBlockAlign].template ReinterpretCast(); + LocalTensor outputLocal = inputLocal[computeSize]; + LocalTensor maxInt8Tensor = outputLocal[computeSize]; + LocalTensor dynamicQuantUb = maxInt8Tensor[brcbCnt]; + LocalTensor scaleOutputLocal = dynamicQuantUb[computeSize + brcbCnt * computeBlockAlign]; + LocalTensor scaleBrcb = scaleOutputLocal[Align(row, computeBlockAlign)]; + + // Rope Post Process流程在Dynamic Quant流程结束,两者UB Buffer不会同时使用,故可以从起始位置开始重新计算,减少UB + // Buffer使用 + LocalTensor qrFp32Local = inputLocal; + LocalTensor reciprocalLocal = qrFp32Local[computeSizeRope + computeBlockAlign]; + + // Dynamic Quant + Duplicate(maxInt8Tensor, static_cast(maxInt8), brcbCnt); + PipeBarrier(); + + DynamicQuantMultiRow(outputGm, scaleOutputLocal, inputGm, outputLocal, inputHalf, inputLocal, maxInt8Tensor, + dynamicQuantUb.template ReinterpretCast(), row, col, subRow, queryOutStride, + DYNAMIC_QUANT_INPUT_READY, DYNAMIC_QUANT_OUTPUT_READY); + + Brcb(scaleBrcb, scaleOutputLocal, CeilDivT(row, computeBlockAlign), {1, computeBlockAlign}); + PipeBarrier(); + + // DataCopyParams : count len srcStrideIn dstStrideIn + DataCopyParams scaleOutCopyParams{(uint16_t)row, (uint16_t)sizeof(C), 0, + (uint16_t)((scaleOutStride - 1) * sizeof(C))}; + + SetFlag(CALC_SCALE_FINISH); + WaitFlag(CALC_SCALE_FINISH); + DataCopyPad(scaleOutputGm, scaleBrcb, scaleOutCopyParams); + + // qr rope 后的乘法 + MulQr(outputGmRope, inputGmRope, outputLocalRope, qrInputLocal, qrFp32Local, reciprocalLocal, scaleBrcb, row, + colRope, subRowRope, qrOutputStrideRope, quantScaleCkvRope, MUL_QR_INPUT_COPY_READY, MUL_QR); + + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); +} + +} // namespace MlaProlog + +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_gather_sin_cos.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_gather_sin_cos.h new file mode 100644 index 0000000000000000000000000000000000000000..aca6647a0755411886b1a1a2090439802e9b66f1 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_gather_sin_cos.h @@ -0,0 +1,66 @@ +/** + * 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 service_gather_sin_cos.h + * \brief + */ + +#ifndef SERVICE_GATHER_SIN_COS_H +#define SERVICE_GATHER_SIN_COS_H + +#include "mla_prolog_comm.h" + +namespace MlaProlog { + +/** + * @brief GatherSinCos 读取rope所需的sin和cos系数,并进行预处理,rope中sin的-1系数会在此处融合进sin中; + * @param cosLocal cos搬运的位置; + * @param sinLocal sin搬运的位置;rope中sin的-1系数会在此处融合进sin中; + * @param cosGm cos在GM的位置,可以认为一个token有col个系数;整体连续排布 + * @param sinGm sin在GM的位置,同上 + * @param tokenIndex 从哪个token开始读取 + * @param curVecToken 读取多少个token的系数 + * @param shareTmpUb 临时buffer 内部需要的空间为 [2 * curVecToken * col * sizeof(bfloat16_t)] + * @param row 行数;预留参数 + * @param col 列数 + */ +template +__aicore__ inline void GatherSinCos(LocalTensor &cosLocal, LocalTensor &sinLocal, const GlobalTensor &cosGm, + const GlobalTensor &sinGm, int64_t tokenIndex, int64_t curVecToken, + LocalTensor &shareTmpUb, int64_t row, int64_t col) +{ + int64_t offset = col * tokenIndex; + int64_t curDataSize = col * curVecToken; + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + if constexpr (IsSameType::value) { + auto tmpUbBf16 = shareTmpUb.ReinterpretCast(); + DataCopy(tmpUbBf16, cosGm[offset], curDataSize); + DataCopy(tmpUbBf16[curDataSize], sinGm[offset], curDataSize); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + Cast(cosLocal, tmpUbBf16, RoundMode::CAST_NONE, curDataSize); + Cast(sinLocal, tmpUbBf16[curDataSize], RoundMode::CAST_NONE, curDataSize); + PipeBarrier(); + } else { + DataCopy(cosLocal, cosGm[offset], curDataSize); + DataCopy(sinLocal, sinGm[offset], curDataSize); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + } + uint8_t blockNumPerRow = col / (ALIGN_BLOCK_SIZE / sizeof(O)); + Muls(sinLocal, sinLocal, -1.0f, col >> 1, curVecToken, {1, 1, blockNumPerRow, blockNumPerRow}); + PipeBarrier(); +} + +} // namespace MlaProlog + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_matmul.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_matmul.h new file mode 100644 index 0000000000000000000000000000000000000000..7a5d35efd87b03719851d819495b5bcf9729ece3 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_matmul.h @@ -0,0 +1,987 @@ +/** + * 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 service_matmul.h + * \brief + */ + +#ifndef SERVICE_MATMUL_H +#define SERVICE_MATMUL_H + +#include "mla_prolog_comm.h" + +namespace MlaProlog { + +constexpr uint8_t UNIT_FLAG_DISABLE = 0; // 0: disable: 不配置unitFlag +constexpr uint8_t UNIT_FLAG_CHECK = 0b10; // 2: enable: 将mmadParams.unitFlag设置为 0b10 +constexpr uint8_t UNIT_FLAG_SET = 0b11; // 3: enable: 在k的最后一轮循环,会将mmadParams.unitFlag设置为 0b11 + + +/** + * @brief Struct to encapsulate all local tensor objects for matrix multiplication + * @tparam T Data type for A, B, and L0 tensors + * @tparam O_L0C Data type for C L0 tensor + */ +template +struct mmLocalTensors { + LocalTensor aL1Tensor; + LocalTensor bL1Tensor; + LocalTensor aL0Tensor; + LocalTensor bL0Tensor; + LocalTensor cL0Tensor; + + /** + * @brief Initialize all local tensors with buffer addresses from bufParam + * @param bufParam Buffer parameter object containing all buffer addresses + */ + __aicore__ inline void Init(const MMBufParams &bufParam) + { + aL1Tensor.SetAddr(bufParam.aL1BufAddr); + bL1Tensor.SetAddr(bufParam.bL1BufAddr); + aL0Tensor.SetAddr(bufParam.aL0BufAddr); + bL0Tensor.SetAddr(bufParam.bL0BufAddr); + cL0Tensor.SetAddr(bufParam.cL0BufAddr); + } +}; + +template +__aicore__ inline constexpr uint32_t GetC0Num() +{ + if (sizeof(SrcT) == sizeof(float)) { + return 8; + } else if (sizeof(SrcT) == sizeof(int8_t)) { + return 32; + } + return 16; +} + +template +__aicore__ inline void CopyNDGmToL1(LocalTensor &l1Tensor, const 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 = CeilDivT(srcN, BLOCK_CUBE_SIZE) * BLOCK_CUBE_SIZE; // 对齐到16 单位 block + nd2nzPara.dstNzNStride = 1; + nd2nzPara.srcNdMatrixStride = 0; + nd2nzPara.dstNzMatrixStride = 0; + DataCopy(l1Tensor, gmSrcTensor, nd2nzPara); +} + +template +__aicore__ inline void CopyNZGmToL1(LocalTensor &l1Tensor, const GlobalTensor &gmSrcTensor, uint32_t srcN, + uint32_t srcD, uint32_t srcNstride) +{ + DataCopyParams param; + param.blockCount = CeilDivT(srcD, GetC0Num()); + param.blockLen = srcN; // 单位为32B srcN*16/16 + param.srcStride = (srcNstride - srcN); // 单位为32B (srcNstride - srcN)*16/16 + param.dstStride = 0; + DataCopy(l1Tensor, gmSrcTensor, param); +} + +template +__aicore__ inline void LoadL1A(const GlobalTensor &tensorAGm, const uint32_t mInput, const uint32_t kL1StepSize, + const uint32_t kInput, MMBufParams &bufParam) +{ + uint32_t bufIter = bufParam.aL1BufIter; + if constexpr (preload) { + bufIter++; + } + LocalTensor aL1Tensor; + aL1Tensor.SetAddr(bufParam.aL1BufAddr); + uint32_t aL1Offset = L1_A_SIZE / sizeof(T); + + WaitFlag(A_EVENT0 + (bufIter & 1u)); + LocalTensor aL1 = aL1Tensor[(bufIter & 1u) * aL1Offset]; + CopyNDGmToL1(aL1, tensorAGm, mInput, kL1StepSize, kInput); + SetFlag(A_EVENT0 + (bufIter & 1u)); +} + +template +__aicore__ inline void LoadL1B(const GlobalTensor &tensorBGm, const uint32_t nL1Size, const uint32_t nInput, + const uint32_t kL1StepSize, const uint32_t kInput, MMBufParams &bufParam) +{ + uint32_t bufIter = bufParam.bL1BufIter; + if constexpr (preload) { + bufIter++; + } + LocalTensor bL1Tensor; + bL1Tensor.SetAddr(bufParam.bL1BufAddr); + uint32_t bL1Offset = L1_B_SIZE / sizeof(T); + + WaitFlag(B_EVENT0 + (bufIter & 1u)); + LocalTensor bL1 = bL1Tensor[(bufIter & 1u) * bL1Offset]; + if constexpr (loadFormat == DataFormat::NZ) { + CopyNZGmToL1(bL1, tensorBGm, kL1StepSize, nL1Size, kInput); + } else { + CopyNDGmToL1(bL1, tensorBGm, kInput, nL1Size, nInput); + } + SetFlag(B_EVENT0 + (bufIter & 1u)); +} + +template +__aicore__ inline void LoadL1AAndScale(const GlobalTensor &tensorAGm, const GlobalTensor &tensorAScaleGm, + const uint32_t mInput, const uint32_t kL1StepSize, const uint32_t kInput, + const uint32_t nInput, const uint64_t scaleAInL1BOffset, MMBufParams &bufParam) +{ + uint32_t bufIter = bufParam.aL1BufIter; + if constexpr (preload) { + bufIter++; + } + LocalTensor aL1Tensor; + aL1Tensor.SetAddr(bufParam.aL1BufAddr); + uint32_t aL1Offset = L1_A_SIZE / sizeof(T); + + LocalTensor bL1Tensor; + bL1Tensor.SetAddr(bufParam.bL1BufAddr); + uint32_t srcDValue = nInput / FP8_TWO; + if constexpr (scaleSrcPadFlag) { + srcDValue = Align(nInput / FP8_TWO, BLOCK_CUBE_SIZE); + } + GlobalTensor tensorScaleGmCast; + tensorScaleGmCast.SetGlobalBuffer(((__gm__ bfloat16_t *)(tensorAScaleGm.GetPhyAddr()))); + + WaitFlag(A_EVENT0 + (bufIter & 1u)); + LocalTensor aL1 = aL1Tensor[(bufIter & 1u) * aL1Offset]; + CopyNDGmToL1(aL1, tensorAGm, mInput, kL1StepSize, kInput); + + Dn2NzParams dn2Nzparam; + dn2Nzparam.dnNum = 1; + dn2Nzparam.nValue = nInput / FP8_TWO; // 单个DN矩阵的列数N, 单位为元素个数 + dn2Nzparam.dValue = mInput; // 单个DN矩阵的实际行数D, 单位为元素个数 + dn2Nzparam.srcDnMatrixStride = 0; // 相邻DN矩阵起始地址之间的偏移, 单位为元素个数 + dn2Nzparam.srcDValue = srcDValue; // 同一个DN矩阵中相邻行起始地址之间的偏移, 单位为元素个数 + dn2Nzparam.dstNzC0Stride = + nInput / FP8_TWO; // 来自DN矩阵中同一列的相邻两个block在NZ矩阵中起始地址间的偏移,单位为block(32B)个数 + dn2Nzparam.dstNzNStride = 1; // 转换为NZ矩阵后,DN中相邻两行在NZ矩阵中起始地址之间的偏移,单位为元素个数 + dn2Nzparam.dstNzMatrixStride = dn2Nzparam.nValue; // 两个NZ矩阵,起始地址之间的偏移,单位为block个数 + DataCopy(bL1Tensor[scaleAInL1BOffset / FP8_TWO], tensorScaleGmCast, dn2Nzparam); + + SetFlag(A_EVENT0 + (bufIter & 1u)); +} + +template +__aicore__ inline void LoadL1BAndScale(const GlobalTensor &tensorBGm, const GlobalTensor &tensorBScaleGm, + const uint32_t nL1Size, const uint32_t kL1StepSize, const uint32_t kInput, + const uint32_t nInput, const uint64_t scaleBInL1BOffset, MMBufParams &bufParam) +{ + uint32_t bufIter = bufParam.bL1BufIter; + if constexpr (preload) { + bufIter++; + } + LocalTensor bL1Tensor; + bL1Tensor.SetAddr(bufParam.bL1BufAddr); + uint32_t bL1Offset = L1_B_SIZE / sizeof(T); + + LocalTensor bL1ScaleTensor; + bL1ScaleTensor.SetAddr(bufParam.bL1BufAddr); + GlobalTensor tensorScaleGmCast; + tensorScaleGmCast.SetGlobalBuffer(((__gm__ bfloat16_t *)(tensorBScaleGm.GetPhyAddr()))); + + WaitFlag(B_EVENT0 + (bufIter & 1u)); + + LocalTensor bL1 = bL1Tensor[(bufIter & 1u) * bL1Offset]; + if constexpr (loadFormat == DataFormat::NZ) { + CopyNZGmToL1(bL1, tensorBGm, kL1StepSize, nL1Size, kInput); + } else { + CopyNDGmToL1(bL1, tensorBGm, kInput, nL1Size, nL1Size); + } + + Dn2NzParams dn2Nzparam; + dn2Nzparam.dnNum = 1; + dn2Nzparam.nValue = nInput / FP8_TWO; // 单个DN矩阵的列数N, 单位为元素个数 + dn2Nzparam.dValue = nL1Size; // 单个DN矩阵的实际行数D, 单位为元素个数 + dn2Nzparam.srcDnMatrixStride = 0; // 相邻DN矩阵起始地址之间的偏移, 单位为元素个数 + dn2Nzparam.srcDValue = nInput / FP8_TWO; // 同一个DN矩阵中相邻行起始地址之间的偏移, 单位为元素个数 + dn2Nzparam.dstNzC0Stride = + dn2Nzparam.srcDValue; // 来自DN矩阵中同一列的相邻两个block在NZ矩阵中起始地址间的偏移,单位为block(32B)个数 + dn2Nzparam.dstNzNStride = 1; // 转换为NZ矩阵后,DN中相邻两行在NZ矩阵中起始地址之间的偏移,单位为元素个数 + dn2Nzparam.dstNzMatrixStride = dn2Nzparam.dstNzC0Stride; // 两个NZ矩阵,起始地址之间的偏移,单位为block个数 + DataCopy(bL1ScaleTensor[scaleBInL1BOffset / FP8_TWO], tensorScaleGmCast, dn2Nzparam); + + SetFlag(B_EVENT0 + (bufIter & 1u)); +} + +/** + * @brief 使用3D Pro模式将数据从L1加载到L0,可选择是否进行转置操作 + * @tparam T 张量的数据类型 + * @tparam enTranspose 是否启用转置操作(用于B矩阵) + * @param l0Tensor L0缓冲区中的目标张量 + * @param l1Tensor L1缓冲区中的源张量 + * @param mSize 行维度(对应A矩阵的m,B矩阵的k) + * @param kSize 列维度(对应A矩阵的k,B矩阵的n) + * @param l1StepSize L1缓冲区中的步长大小,用于B矩阵转置 + * @param kl1Size L1缓冲区中的大小,用于B矩阵转置 + */ +template +__aicore__ inline void LoadDataL1ToL0(const LocalTensor &l0Tensor, const LocalTensor &l1Tensor, + const uint32_t mSize, const uint32_t kSize, const uint32_t l1StepSize = 0) +{ + if constexpr (enTranspose) { // B + LoadData2DParamsV2 loadData2DV2; + loadData2DV2.mStartPosition = 0; + loadData2DV2.kStartPosition = 0; + loadData2DV2.mStep = ((mSize + ROUND_UP_UNIT) >> SHIFTS_UNIT << SHIFTS_UNIT) / BLOCK_CUBE_SIZE; + loadData2DV2.kStep = ((kSize + ROUND_UP_UNIT) >> SHIFTS_UNIT << SHIFTS_UNIT) / BLOCK_CUBE_SIZE; + loadData2DV2.srcStride = ((l1StepSize + ROUND_UP_UNIT) >> SHIFTS_UNIT << SHIFTS_UNIT) / BLOCK_CUBE_SIZE; + loadData2DV2.dstStride = ((kSize + ROUND_UP_UNIT) >> SHIFTS_UNIT << SHIFTS_UNIT) / BLOCK_CUBE_SIZE; + loadData2DV2.ifTranspose = true; + LoadData(l0Tensor, l1Tensor, loadData2DV2); + } else { // A + LoadData3DParamsV2 loadDataAParams; + loadDataAParams.l1W = 1; + loadDataAParams.l1H = mSize; + loadDataAParams.channelSize = kSize; + loadDataAParams.kExtension = kSize; + loadDataAParams.mExtension = mSize; + loadDataAParams.kStartPt = 0; + loadDataAParams.mStartPt = 0; + loadDataAParams.strideW = 1; + loadDataAParams.strideH = 1; + loadDataAParams.filterW = 1; + loadDataAParams.filterH = 1; + loadDataAParams.dilationFilterW = 1; + loadDataAParams.dilationFilterH = 1; + loadDataAParams.enTranspose = false; + loadDataAParams.enSmallK = false; + loadDataAParams.padValue = 0; + loadDataAParams.filterSizeW = 0; + loadDataAParams.filterSizeH = 0; + loadDataAParams.fMatrixCtrl = false; + uint16_t dstStride = CeilDivT(mSize, BLOCK_CUBE_SIZE); +#if defined(ASC_DEVKIT_VERSION_NUM) && (ASC_DEVKIT_VERSION_NUM >= 90000000) + SetLoadDataRepeatWithStride({0, 1, 0, dstStride}); // >= 9.0.0 release 新 API + LoadDataWithStride(l0Tensor, l1Tensor, loadDataAParams); +#else + SetLoadDataRepeat({0, 1, 0, dstStride}); // < 9.0.0 (beta.2) 旧 API + LoadData(l0Tensor, l1Tensor, loadDataAParams); +#endif + } +} + +template +__aicore__ inline void LoadDataL1ToL0Mxfp8(const LocalTensor &l0Tensor, const LocalTensor &l1Tensor, + const LocalTensor &l1AMxTensor, const uint32_t mSize, + const uint32_t kSize, const uint32_t kL1Size = 0) +{ + // LoadData and A Scale + LocalTensor dstTensor = l0Tensor.template ReinterpretCast(); + LocalTensor l1MxTensor = l1AMxTensor.template ReinterpretCast(); + + LoadData2DParamsV2 loadDataA2DParams; + loadDataA2DParams.mStartPosition = 0; + loadDataA2DParams.kStartPosition = 0; + loadDataA2DParams.ifTranspose = false; + loadDataA2DParams.mStep = CeilDivT(mSize, BLOCK_CUBE_SIZE); // m轴分型大小为16 + loadDataA2DParams.kStep = CeilDivT(kSize, K_STEP_SIZE_32); // k轴分型大小为32B + // 配合ub->L1使用256 * 32 / 256 + // 64搬运 + loadDataA2DParams.srcStride = loadDataA2DParams.mStep; // m轴全搬,无pad + loadDataA2DParams.dstStride = loadDataA2DParams.mStep; // 搬运前后不转置,m轴不变 + + LoadData2DMxParams loadAScaleParam; + loadAScaleParam.xStartPosition = 0; + loadAScaleParam.yStartPosition = 0; + loadAScaleParam.xStep = CeilDivT(mSize, BLOCK_CUBE_SIZE); + loadAScaleParam.yStep = CeilDivT(kSize, K_STEP_SIZE_32 * FP8_TWO); // ksize对应baseK + loadAScaleParam.srcStride = CeilDivT(kL1Size, K_STEP_SIZE_32 * FP8_TWO); // kL1Size对应baseK*stepK + loadAScaleParam.dstStride = loadAScaleParam.yStep; + LoadData(dstTensor, l1Tensor, l1MxTensor, loadDataA2DParams, loadAScaleParam); +} + +template +__aicore__ inline void LoadDataL1ToL0B(const LocalTensor &bL0Tensor, const LocalTensor &bL1Tensor, + const LocalTensor &bscaleL1, const uint32_t kSize, const uint32_t nSize, + const uint32_t kL1StepSize = 0, const uint32_t kL1Size = 0) +{ + LoadData2DParamsV2 loadData2DV2; + loadData2DV2.mStartPosition = 0; + loadData2DV2.kStartPosition = 0; + loadData2DV2.mStep = CeilDivT(kSize, BLOCK_CUBE_SIZE); + loadData2DV2.kStep = CeilDivT(nSize, K_STEP_SIZE_32); + loadData2DV2.srcStride = CeilDivT(kL1StepSize, BLOCK_CUBE_SIZE); // k轴切分,stride为完整k的长度 + loadData2DV2.dstStride = + CeilDivT(nSize, UNIT_SIZE / K_STEP_SIZE_32); // n轴切分,B矩阵搬运后转置,dst中M轴变成src中的K轴 + loadData2DV2.ifTranspose = true; // 搬运后转置 + + if (std::is_same::value) { + LocalTensor dstTensor = bL0Tensor.template ReinterpretCast(); + LocalTensor srcTensor = bL1Tensor.template ReinterpretCast(); + LocalTensor l1MxTensor = bscaleL1.template ReinterpretCast(); + LoadData2DMxParams loadDataMxParams; + loadDataMxParams.xStartPosition = 0; + loadDataMxParams.yStartPosition = 0; + loadDataMxParams.xStep = CeilDivT(nSize, BLOCK_CUBE_SIZE); + loadDataMxParams.yStep = CeilDivT(kSize, K_STEP_SIZE_32 * FP8_TWO); // ksize对应baseK + loadDataMxParams.srcStride = CeilDivT(kL1Size, K_STEP_SIZE_32 * FP8_TWO); // kL1Size对应baseK*stepK + loadDataMxParams.dstStride = loadDataMxParams.yStep; + LoadData(dstTensor, srcTensor, l1MxTensor, loadData2DV2, loadDataMxParams); + } else { + LoadData(bL0Tensor, bL1Tensor, loadData2DV2); + } +} + +template +__aicore__ inline void MatmulL0(MMBufParams &bufParam, const LocalTensor &aL1, const LocalTensor &bL1, + const LocalTensor &aL0Tensor, const LocalTensor &bL0Tensor, + const LocalTensor &cL0Tensor, const MmadParams &mmadParams, + const uint32_t kL1StepSize, const uint32_t kL1Size = 0, + const LocalTensor &aScaleL1 = {}, const LocalTensor &bscaleL1 = {}) +{ + WaitFlag(L0A_EVENT0 + (bufParam.aL0BufIter & 1u)); + LocalTensor aL0 = aL0Tensor[(bufParam.aL0BufIter & 1u) * (L0A_PP_SIZE / sizeof(T))]; + if constexpr (std::is_same::value && std::is_same::value) { + LoadDataL1ToL0Mxfp8(aL0, aL1, aScaleL1, mmadParams.m, mmadParams.k, kL1Size); + } else { + LoadDataL1ToL0(aL0, aL1, mmadParams.m, mmadParams.k); + } + SetFlag(L0A_EVENT0 + (bufParam.aL0BufIter & 1u)); + WaitFlag(L0A_EVENT0 + (bufParam.aL0BufIter & 1u)); + WaitFlag(L0B_EVENT0 + (bufParam.bL0BufIter & 1u)); + + LocalTensor bL0 = bL0Tensor[(bufParam.bL0BufIter & 1u) * (L0B_PP_SIZE / sizeof(T))]; + if constexpr (std::is_same::value || std::is_same::value || + (std::is_same::value && std::is_same::value)) { + LoadDataL1ToL0B(bL0, bL1, bscaleL1, mmadParams.k, mmadParams.n, kL1StepSize); + } else if constexpr (std::is_same::value && std::is_same::value) { + LoadDataL1ToL0B(bL0, bL1, bscaleL1, mmadParams.k, mmadParams.n, kL1StepSize, kL1Size); + } else { + LoadDataL1ToL0(bL0, bL1, mmadParams.k, mmadParams.n, kL1StepSize); + } + + SetFlag(L0B_EVENT0 + (bufParam.bL0BufIter & 1u)); + WaitFlag(L0B_EVENT0 + (bufParam.bL0BufIter & 1u)); + if constexpr (std::is_same::value && std::is_same::value) { + LocalTensor aL0Tmp = aL0.template ReinterpretCast(); + LocalTensor bL0Tmp = bL0.template ReinterpretCast(); + Mmad(cL0Tensor, aL0Tmp, bL0Tmp, mmadParams); + } else { + Mmad(cL0Tensor, aL0, bL0, mmadParams); + } + PipeBarrier(); + SetFlag(L0B_EVENT0 + (bufParam.bL0BufIter & 1u)); + bufParam.bL0BufIter++; + SetFlag(L0A_EVENT0 + (bufParam.aL0BufIter & 1u)); + bufParam.aL0BufIter++; +} + +template +__aicore__ inline void GetTensorC(const GlobalTensor &tensorCGm, const LocalTensor &cL0, const uint32_t mSize, + const uint32_t nSize, const uint32_t srcStride, const uint32_t dstStride, + MMBufParams &bufParam) +{ + FixpipeParamsV220 fixParams; + fixParams.nSize = nSize; // 实现切片大小 + fixParams.mSize = mSize; // msdIterNum * gSize; // 有效数据不足16行,只需要输出部分行即可 + fixParams.srcStride = srcStride; // ((fixParams.mSize + 15) / 16) * 16 + fixParams.dstStride = dstStride; + fixParams.ndNum = 1; + if constexpr (enUnitFlag) { + fixParams.unitFlag = UNIT_FLAG_SET; + } else { + fixParams.unitFlag = UNIT_FLAG_DISABLE; + } + if constexpr (std::is_same::value && std::is_same::value) { + fixParams.quantPre = QuantMode_t::F322BF16; + } + if constexpr (!enUnitFlag) { + SetFlag(L0C_EVENT0 + (bufParam.cL0BufIter & 1u)); + WaitFlag(L0C_EVENT0 + (bufParam.cL0BufIter & 1u)); + } + Fixpipe(tensorCGm, cL0, fixParams); +} + +/** + * @brief 将AB矩阵从GM加载到L1缓存以进行矩阵乘法运算 + * @tparam T 张量的数据类型 + * @tparam hasL1ALoaded A矩阵是否已经加载到L1中 + * @param tensorAGm GM中的A矩阵 + * @param tensorBGm GM中的B矩阵 + * @param kL1 当前K L1循环迭代次数 + * @param kL1Loops K L1循环的总次数 + * @param para 包含维度和步长信息的矩阵乘法参数 + * @param nL1Offset L1缓冲区中的N维度偏移 + * @param nL1Size L1缓冲区中的N维度大小 + * @param kOffesetUnit K维度寻址的偏移单位 + * @param bufParam L1缓冲区管理的参数对象 + */ +template +__aicore__ inline void LoadL1AB(const GlobalTensor &tensorAGm, const GlobalTensor &tensorBGm, uint32_t kL1, + uint32_t kL1Loops, const MMParams ¶, uint32_t nL1Offset, uint32_t nL1Size, + uint32_t kOffesetUnit, MMBufParams &bufParam) +{ + if (kL1 == 0) { + if constexpr (!hasL1ALoaded) { + LoadL1A(tensorAGm[kL1 * para.kL1StepSize], para.m, para.kL1StepSize, para.orgKa, bufParam); + } + if constexpr (bLoadFormat == DataFormat::NZ) { + LoadL1B(tensorBGm[para.k * nL1Offset + kL1 * kOffesetUnit], nL1Size, para.n, para.kL1StepSize, para.k, + bufParam); + } else { + LoadL1B(tensorBGm[kL1 * para.kL1StepSize * para.n + nL1Offset], nL1Size, para.n, + para.kL1StepSize, para.kL1StepSize, bufParam); + } + } + + if (kL1 + 1 < kL1Loops) { + if constexpr (!hasL1ALoaded) { + LoadL1A(tensorAGm[(kL1 + 1) * para.kL1StepSize], para.m, para.kL1StepSize, para.orgKa, bufParam); + } + if constexpr (bLoadFormat == DataFormat::NZ) { + LoadL1B(tensorBGm[para.k * nL1Offset + (kL1 + 1) * kOffesetUnit], nL1Size, para.n, + para.kL1StepSize, para.k, bufParam); + } else { + LoadL1B(tensorBGm[(kL1 + 1) * para.kL1StepSize * para.n + nL1Offset], nL1Size, + para.n, para.kL1StepSize, para.kL1StepSize, bufParam); + } + } +} + +/** + * @brief 将AB矩阵和用于伪量化的Scale矩阵从GM加载到L1缓存以进行矩阵乘法运算 + * @tparam T 张量的数据类型 + * @tparam S Scale矩阵的数据类型 + * @tparam hasL1ALoaded A矩阵是否已经加载到L1中 + * @tparam scaleSrcPadFlag Scale矩阵是否需要对齐搬运,在mm3中AScale为True + * @param tensorAGm GM中的A矩阵 + * @param tensorBGm GM中的B矩阵 + * @param tensorAScaleGm GM中的AScale矩阵 + * @param tensorBScaleGm GM中的BScale矩阵 + * @param kL1 当前K L1循环迭代次数 + * @param kL1Loops K L1循环的总次数 + * @param para 包含维度和步长信息的矩阵乘法参数 + * @param nL1Offset L1缓冲区中的N维度偏移 + * @param nL1Size L1缓冲区中的N维度大小 + * @param kOffesetUnit K维度寻址的偏移单位 + * @param bufParam L1缓冲区管理的参数对象 + */ +template +__aicore__ inline void LoadL1ABAndScale(const GlobalTensor &tensorAGm, const GlobalTensor &tensorBGm, + const GlobalTensor &tensorAScaleGm, const GlobalTensor &tensorBScaleGm, + uint32_t kL1, uint32_t kL1Loops, const MMParams ¶, uint32_t nL1Offset, + uint32_t nL1Size, uint32_t kOffesetUnit, MMBufParams &bufParam) +{ + uint64_t offsetL1B = L1_B_SIZE / 2 / sizeof(T); // // 2表示scale起始地址固定从L1B上ping的64k开始 + if (kL1 == 0) { + if constexpr (!hasL1ALoaded) { + LoadL1AAndScale(tensorAGm, tensorAScaleGm, para.m, para.kL1StepSize, + para.k, para.kScale, offsetL1B, bufParam); + } + uint64_t scaleOffsetL1B = offsetL1B + para.kScale * Align(para.m, BLOCK_CUBE_SIZE); + LoadL1BAndScale(tensorBGm[para.k * nL1Offset], tensorBScaleGm[para.kScale * nL1Offset], nL1Size, + para.kL1StepSize, para.k, para.kScale, scaleOffsetL1B, bufParam); + } + + if (kL1 + 1 < kL1Loops) { + if constexpr (!hasL1ALoaded) { + LoadL1A(tensorAGm[(kL1 + 1) * para.kL1StepSize], para.m, para.kL1StepSize, para.k, bufParam); + } + LoadL1B(tensorBGm[para.k * nL1Offset + (kL1 + 1) * kOffesetUnit], nL1Size, para.n, + para.kL1StepSize, para.k, bufParam); + } +} + +/** + * @brief B矩阵数据加载到L1缓冲区的辅助函数 + * @tparam T B张量的数据类型 + * @tparam isContinuousCopy 是否使用连续复制模式 + * @param bL1 B矩阵L1张量 + * @param tensorBGm B矩阵GM张量 + * @param kL1StepSize L1中K维度的步长大小 + * @param subNL1SplitSize L1中N维度的分割大小 + * @param para MMParams参数 + * @param bufParam 缓冲区管理参数 + * @param nL1 当前N L1迭代 + * @param kL1 当前K L1迭代 + * @param kOffesetUnit K维度偏移单位 + */ +template +__aicore__ inline void LoadL1BGroupCompute(LocalTensor &bL1, const GlobalTensor &tensorBGm, + uint32_t subNL1SplitSize, const MMParams ¶, int64_t nL1, uint32_t kL1, + uint32_t kOffesetUnit) +{ + int64_t tensorBGmOffset = para.k * nL1 * para.baseN + kL1 * kOffesetUnit; + auto tensorBGmForL1 = tensorBGm[tensorBGmOffset]; + if constexpr (isContinuousCopy) { + CopyNZGmToL1(bL1, tensorBGmForL1, para.kL1StepSize, subNL1SplitSize, para.k); + } else { + // 每次搬运两块K*64拼接成K*128 + CopyNZGmToL1(bL1, tensorBGmForL1, para.kL1StepSize, subNL1SplitSize >> 1, para.k); + LocalTensor b2L1 = bL1[(para.kL1StepSize * subNL1SplitSize) >> 1]; + auto tensorB2GmForL1 = tensorBGmForL1[para.k * DIM_HEAD_SIZE_QCQR]; + CopyNZGmToL1(b2L1, tensorB2GmForL1, para.kL1StepSize, subNL1SplitSize >> 1, para.k); + } +} + +/** + * @brief 执行矩阵乘法的K L0循环计算 + * @tparam T A和B矩阵的数据类型 + * @tparam O_L0C L0C缓存中的数据类型 + * @tparam enUnitFlag 是否启用unitFlag功能 + * @param cL0 L0缓存中的C矩阵张量 + * @param aL1 L1缓存中的A矩阵张量 + * @param bL1 L1缓存中的B矩阵张量 + * @param localTensors 矩阵乘法所需的本地张量对象 + * @param bufParam L1缓存管理的缓冲区参数对象 + * @param kL1 当前K L1循环迭代次数 + * @param kL1Loops K L1循环的总次数 + * @param stepK K L0步数 + * @param aOffsetUnit A矩阵L0寻址的偏移单位 + * @param bOffsetUnit B矩阵L0寻址的偏移单位 + * @param mmadParams 矩阵乘法参数 + * @param aOffset A矩阵计算的起始偏移 + * @param bOffset B矩阵计算的起始偏移 + */ +template +__aicore__ inline void MatmulL1(const LocalTensor &cL0, const LocalTensor &aL1, const LocalTensor &bL1, + const mmLocalTensors &localTensors, MMBufParams &bufParam, + const MMParams ¶, uint32_t kL1, uint32_t kL1Loops, MmadParams &mmadParams, + int64_t &aOffset) +{ + uint32_t mSize = Align(para.m, BLOCK_CUBE_SIZE); + uint64_t weightSizeL1B = L1_B_SIZE / 2 / sizeof(T); // 2表示scale起始地址固定从L1B上ping的64k开始 + uint64_t scaleASize = mSize * para.kScale; // BS*224 + uint32_t bOffset = 0; + uint32_t aOffsetUnit = mSize * para.baseK; + uint32_t bOffsetUnit = GetC0Num() * para.baseK; + + uint32_t aScaleOffset = kL1 * para.kScale / kL1Loops * BLOCK_CUBE_SIZE; + uint32_t bScaleOffset = kL1 * para.kScale / kL1Loops * BLOCK_CUBE_SIZE; + uint32_t aScaleOffsetUnit = para.baseK / BYTE_BLOCK * BLOCK_CUBE_SIZE; + uint32_t bScaleOffsetUnit = para.baseK / BYTE_BLOCK * BLOCK_CUBE_SIZE; + const LocalTensor scaleALocalTensor = localTensors.bL1Tensor[weightSizeL1B]; + const LocalTensor scaleBLocalTensor = scaleALocalTensor[scaleASize]; + + for (int64_t kL0Loops = 0; kL0Loops < para.stepK; kL0Loops++) { + mmadParams.cmatrixInitVal = ((kL1 == 0) && (kL0Loops == 0)); + if constexpr (enUnitFlag) { + mmadParams.unitFlag = + (kL1 == kL1Loops - 1) && (kL0Loops == para.stepK - 1) ? UNIT_FLAG_SET : UNIT_FLAG_CHECK; + } + MatmulL0(bufParam, aL1[aOffset], bL1[bOffset], localTensors.aL0Tensor, localTensors.bL0Tensor, cL0, + mmadParams, para.kL1StepSize, para.k, scaleALocalTensor[aScaleOffset], + scaleBLocalTensor[bScaleOffset]); + aOffset += aOffsetUnit; // 16(BS)*256=4096 + bOffset += bOffsetUnit; // 32(Get)*256=8192 + if constexpr (std::is_same::value && std::is_same::value) { + aScaleOffset += aScaleOffsetUnit; // 16(BS)*baseK/32=16(BS)*8=128 + bScaleOffset += bScaleOffsetUnit; // baseK/32*baseN=8*64 + } + } +} + +/** + * @brief MatmulSplitK 通过切分K轴,进行L1的数据管理和矩阵乘运算; 用于mmCq, mmCKvKr和mmQcQr。 + * @param tensorAGm A矩阵在GM的位置 + * @param tensorBGm B矩阵在GM的位置 + * @param tensorCGm C矩阵在GM的位置 + * @param para 表示matmul形状信息的结构体参数 + * @param bufParam 管理L1 buffer地址和同步计数的结构体参数 + * @param nL1Offset 本次计算中,L1 buffer内B矩阵在n轴上的偏移 + * @param nL1Size 本次计算中,L1 buffer内B矩阵在n轴上的计算量 + * @param tensorAScaleGm AScale矩阵在GM的位置 + * @param tensorBScaleGm BScale矩阵在GM的位置 + */ +template +__aicore__ inline void +MatmulSplitK(const GlobalTensor &tensorCGm, const GlobalTensor &tensorAGm, const GlobalTensor &tensorBGm, + const MMParams ¶, MMBufParams &bufParam, const uint32_t nL1Offset, const uint32_t nL1Size, + const GlobalTensor &tensorAScaleGm = {}, const GlobalTensor &tensorBScaleGm = {}) +{ + using O_L0C = typename std::conditional::value, int32_t, float>::type; + + // 全局L1管理 + uint32_t kOffesetUnit = para.kL1StepSize * GetC0Num(); + uint32_t mSize = Align(para.m, BLOCK_CUBE_SIZE); + uint32_t kL1Loops = CeilDivT(para.k, para.kL1StepSize); + + mmLocalTensors localTensors; + localTensors.Init(bufParam); + + LocalTensor aL1, bL1; + + if constexpr (hasL1ALoaded) { + aL1 = localTensors.aL1Tensor[(bufParam.aL1BufIter & 1u) * L1_A_SIZE / sizeof(T)]; + } + + WaitFlag(L0C_EVENT0 + (bufParam.cL0BufIter & 1u)); + LocalTensor cL0 = localTensors.cL0Tensor[(bufParam.cL0BufIter & 1u) * (L0C_PP_SIZE / sizeof(O_L0C))]; + + MmadParams mmadParams = MmadParams(mSize, nL1Size, para.baseK, UNIT_FLAG_DISABLE, false, true); + + int64_t aOffset = 0; + if constexpr (std::is_same::value && std::is_same::value) { + WaitFlag(SCALE_EVENT); + } + + for (uint32_t kL1 = 0; kL1 < kL1Loops; kL1++) { + // Load data from global memory to L1 cache + if constexpr (std::is_same::value && std::is_same::value) { + LoadL1ABAndScale(tensorAGm, tensorBGm, tensorAScaleGm, tensorBScaleGm, + kL1, kL1Loops, para, nL1Offset, nL1Size, kOffesetUnit, + bufParam); + } else { + LoadL1AB(tensorAGm, tensorBGm, kL1, kL1Loops, para, nL1Offset, nL1Size, + kOffesetUnit, bufParam); + } + + WaitFlag(B_EVENT0 + (bufParam.bL1BufIter & 1u)); + bL1 = localTensors.bL1Tensor[(bufParam.bL1BufIter & 1u) * L1_B_SIZE / sizeof(T)]; + if constexpr (!hasL1ALoaded) { + WaitFlag(A_EVENT0 + (bufParam.aL1BufIter & 1u)); + aL1 = localTensors.aL1Tensor[(bufParam.aL1BufIter & 1u) * L1_A_SIZE / sizeof(T)]; + aOffset = 0; + } + + // Perform core K L0 loops computation + MatmulL1(cL0, aL1, bL1, localTensors, bufParam, para, kL1, kL1Loops, mmadParams, + aOffset); + + SetFlag(B_EVENT0 + (bufParam.bL1BufIter & 1u)); + bufParam.bL1BufIter++; + if constexpr (!hasL1ALoaded) { + SetFlag(A_EVENT0 + (bufParam.aL1BufIter & 1u)); + bufParam.aL1BufIter++; + } + } + if constexpr (std::is_same::value && std::is_same::value) { + SetFlag(SCALE_EVENT); + } + GetTensorC(tensorCGm[nL1Offset], cL0, para.m, nL1Size, mSize, para.orgKc, bufParam); + SetFlag(L0C_EVENT0 + (bufParam.cL0BufIter & 1u)); + bufParam.cL0BufIter++; +} + +/** + * @brief MatmulFullLoad A,B矩阵能够全载L1时的矩阵运算,用于mmQn; + * @param tensorAGm A矩阵在GM的位置 + * @param tensorBGm B矩阵在GM的位置 + * @param tensorCGm C矩阵在GM的位置 + * @param para 表示matmul形状信息的结构体参数 + * @param bufParam 管理L1 buffer地址和同步计数的结构体参数 + */ +template +__aicore__ inline void MatmulFullLoad(const GlobalTensor &tensorCGm, const GlobalTensor &tensorAGm, + const GlobalTensor &tensorBGm, const MMParams ¶, MMBufParams &bufParam) +{ + using O_L0C = typename std::conditional::value, int32_t, float>::type; + uint32_t mSize = Align(para.m, BLOCK_CUBE_SIZE); + constexpr uint32_t aL1Offset = L1_A_SIZE / sizeof(T); + constexpr uint32_t bL1Offset = L1_B_SIZE / sizeof(T); + + mmLocalTensors localTensors; + localTensors.Init(bufParam); + + LoadL1A(tensorAGm, para.m, para.k, para.orgKa, bufParam); + WaitFlag(A_EVENT0 + (bufParam.aL1BufIter & 1u)); + LocalTensor aL1 = localTensors.aL1Tensor[(bufParam.aL1BufIter & 1u) * aL1Offset]; + + if constexpr (!hasL1BLoaded) { + LoadL1B(tensorBGm, para.n, para.n, para.k, para.k, bufParam); + WaitFlag(B_EVENT0 + (bufParam.bL1BufIter & 1u)); + } + LocalTensor bL1 = localTensors.bL1Tensor[(bufParam.bL1BufIter & 1u) * bL1Offset]; + + uint32_t nSplitSize = 128; + uint32_t nSplitSizeAct = nSplitSize; + uint32_t nloops = CeilDivT(para.n, nSplitSize); + + MmadParams mmadParams = MmadParams(mSize, nSplitSizeAct, para.k, UNIT_FLAG_DISABLE, false, true); + + for (uint32_t n = 0; n < nloops; n++) { + if (n == nloops - 1) { + nSplitSizeAct = para.n - (nloops - 1) * nSplitSize; + mmadParams.n = nSplitSizeAct; + } + // Perform matrix multiplication computation for current N-dimension split + if constexpr (enUnitFlag) { + mmadParams.unitFlag = UNIT_FLAG_SET; + } + WaitFlag(L0C_EVENT0 + (bufParam.cL0BufIter & 1u)); + LocalTensor cL0 = localTensors.cL0Tensor[(bufParam.cL0BufIter & 1u) * (L0C_PP_SIZE / sizeof(O_L0C))]; + MatmulL0(bufParam, aL1, bL1[para.k * nSplitSize * n], localTensors.aL0Tensor, + localTensors.bL0Tensor, cL0, mmadParams, para.kL1StepSize); + GetTensorC(tensorCGm[n * nSplitSize], cL0, para.m, nSplitSizeAct, mSize, para.orgKc, + bufParam); + SetFlag(L0C_EVENT0 + (bufParam.cL0BufIter & 1u)); + bufParam.cL0BufIter++; + } + + SetFlag(B_EVENT0 + (bufParam.bL1BufIter & 1u)); + bufParam.bL1BufIter++; + SetFlag(A_EVENT0 + (bufParam.aL1BufIter & 1u)); + bufParam.aL1BufIter++; +} + +/** + * @brief MatmulGroupComputeAFullLoad + * A矩阵能够全载,通过切分K轴,进行L1的数据管理和矩阵乘运算,仅适用于算力分组场景下的mmQc和mmQr; + * @param tensorAGm A矩阵在GM的位置 + * @param tensorBGm B矩阵在GM的位置 + * @param tensorCGm C矩阵在GM的位置 + * @param para 表示matmul形状信息的结构体参数 + * @param bufParam 管理L1 buffer地址和同步计数的结构体参数 + */ +template +__aicore__ inline void MatmulGroupComputeAFullLoad(const GlobalTensor &tensorCGm, const GlobalTensor &tensorAGm, + const GlobalTensor &tensorBGm, const MMParams ¶, + MMBufParams &bufParam) +{ + using O_L0C = typename std::conditional::value, int32_t, float>::type; + // 全局L1管理 + uint32_t kOffesetUnit = para.kL1StepSize * GetC0Num(); + uint32_t mSize = Align(para.m, BLOCK_CUBE_SIZE); + uint32_t kL1Loops = CeilDivT(para.k, para.kL1StepSize); + uint32_t nL1loops = CeilDivT(para.n, para.baseN); + + mmLocalTensors localTensors; + localTensors.Init(bufParam); + + WaitFlag(A_EVENT0 + (bufParam.aL1BufIter & 1u)); + LocalTensor aL1 = localTensors.aL1Tensor[(bufParam.aL1BufIter & 1u) * (L1_A_SIZE / sizeof(T))]; + CopyNDGmToL1(aL1, tensorAGm, para.m, para.k, para.k); + SetFlag(A_EVENT0 + (bufParam.aL1BufIter & 1u)); + WaitFlag(A_EVENT0 + (bufParam.aL1BufIter & 1u)); + + uint32_t subNL1SplitSize = para.baseN; + + MmadParams mmadParams = MmadParams(mSize, subNL1SplitSize, para.baseK, UNIT_FLAG_DISABLE, false, true); + + for (int64_t nL1 = 0; nL1 < nL1loops; nL1++) { + if (nL1 == nL1loops - 1) { + subNL1SplitSize = para.n - (nL1loops - 1) * para.baseN; + mmadParams.n = subNL1SplitSize; + } + + WaitFlag(L0C_EVENT0 + (bufParam.cL0BufIter & 1u)); + LocalTensor cL0 = localTensors.cL0Tensor[(bufParam.cL0BufIter & 1u) * (L0C_PP_SIZE / sizeof(O_L0C))]; + + int64_t aOffset = 0; + for (uint32_t kL1 = 0; kL1 < kL1Loops; kL1++) { + WaitFlag(B_EVENT0 + (bufParam.bL1BufIter & 1u)); + LocalTensor bL1 = localTensors.bL1Tensor[(bufParam.bL1BufIter & 1u) * (L1_B_SIZE / sizeof(T))]; + LoadL1BGroupCompute(bL1, tensorBGm, subNL1SplitSize, para, nL1, kL1, kOffesetUnit); + SetFlag(B_EVENT0 + (bufParam.bL1BufIter & 1u)); + WaitFlag(B_EVENT0 + (bufParam.bL1BufIter & 1u)); + + // Perform core K L0 loops computation using shared function + MatmulL1(cL0, aL1, bL1, localTensors, bufParam, para, kL1, kL1Loops, mmadParams, + aOffset); + SetFlag(B_EVENT0 + (bufParam.bL1BufIter & 1u)); + bufParam.bL1BufIter++; + } + GetTensorC(tensorCGm[nL1 * para.baseN], cL0, para.m, subNL1SplitSize, mSize, + para.orgKc, bufParam); + SetFlag(L0C_EVENT0 + (bufParam.cL0BufIter & 1u)); + bufParam.cL0BufIter++; + } + SetFlag(A_EVENT0 + (bufParam.aL1BufIter & 1u)); + bufParam.aL1BufIter++; +} + +/** + * @brief K-outer: 加载B矩阵到L1B(支持双缓冲slot选择) + * bScaleL1Offset: B-scale在slot内的bf16偏移 (需放在A-scale之后避免冲突) + */ +template +__aicore__ inline void LoadL1BOuter(const GlobalTensor &tensorBGm, const GlobalTensor &tensorBScaleGm, + uint32_t nL1Size, uint32_t kL1StepSize, uint32_t kInput, uint32_t kScale, + uint32_t bEventIdx, uint32_t bScaleL1Offset, MMBufParams &bufParam) +{ + LocalTensor bL1Tensor; + bL1Tensor.SetAddr(bufParam.bL1BufAddr); + uint32_t bL1SlotSize = L1_B_SIZE / sizeof(T); + + WaitFlag(B_EVENT0 + bEventIdx); + LocalTensor bL1 = bL1Tensor[bEventIdx * bL1SlotSize]; + + if constexpr (std::is_same::value && std::is_same::value) { + CopyNZGmToL1(bL1, tensorBGm, kL1StepSize, nL1Size, kInput); + + LocalTensor bL1ScaleTensor = bL1.template ReinterpretCast(); + GlobalTensor tensorScaleGmCast; + tensorScaleGmCast.SetGlobalBuffer(((__gm__ bfloat16_t *)(tensorBScaleGm.GetPhyAddr()))); + Dn2NzParams dn2Nzparam; + dn2Nzparam.dnNum = 1; + uint32_t nValueB = CeilDivT(kScale, static_cast(FP8_TWO)); + dn2Nzparam.nValue = nValueB; + dn2Nzparam.dValue = nL1Size; + dn2Nzparam.srcDnMatrixStride = 0; + dn2Nzparam.srcDValue = nValueB; // B-scale无padding, 保持原值 + dn2Nzparam.dstNzC0Stride = nValueB; // = nValue, NZ输出布局不变 + dn2Nzparam.dstNzNStride = 1; + dn2Nzparam.dstNzMatrixStride = nValueB; + DataCopy(bL1ScaleTensor[bScaleL1Offset], tensorScaleGmCast, dn2Nzparam); + } else if constexpr (loadFormat == DataFormat::NZ) { + CopyNZGmToL1(bL1, tensorBGm, kL1StepSize, nL1Size, kInput); + } else { + CopyNDGmToL1(bL1, tensorBGm, kInput, nL1Size, nL1Size); + } + SetFlag(B_EVENT0 + bEventIdx); +} + + +/** + * @brief K-outer: 主Matmul函数。A数据每kL1加载到L1A,A-scale复用原LoadL1AAndScale放L1B一次加载全量。 + * B每nb双缓冲加载,B-scale紧随B数据之后。FixPipe使用AtomicAdd累加到GM。 + */ +template +__aicore__ inline void MatmulSplitMKOuter(const GlobalTensor &tensorCGm, const GlobalTensor &tensorAGm, + const GlobalTensor &tensorBGm, const MMParams ¶, MMBufParams &bufParam, + const GlobalTensor &tensorAScaleGm, const GlobalTensor &tensorBScaleGm) +{ + using O_L0C = typename std::conditional::value, int32_t, float>::type; + + uint32_t nBlocks = CeilDivT(para.n, para.baseN); + uint32_t kL1Loops = CeilDivT(para.k, para.kL1StepSize); + uint32_t kOffesetUnit = para.kL1StepSize * GetC0Num(); + uint32_t mSizeAligned = Align(para.m, BLOCK_CUBE_SIZE); + uint32_t aOffsetUnit = mSizeAligned * para.baseK; + uint32_t bOffsetUnit = GetC0Num() * para.baseK; + uint32_t bL1SlotSize = L1_B_SIZE / sizeof(T); + uint32_t scaleOffUnit = para.baseK / static_cast(BYTE_BLOCK) * BLOCK_CUBE_SIZE; + + mmLocalTensors localTensors; + localTensors.Init(bufParam); + + // ──── 一次加载全量A-scale到L1B, 复用原LoadL1AAndScale的DN2NZ参数 ──── + LocalTensor aScaleL1Base; + uint32_t bScaleBf16Off = 0; + uint32_t bScaleL1BaseOff = 0; + if constexpr (std::is_same::value && std::is_same::value) { + uint64_t scaleAOff = L1_B_SIZE / 2 / sizeof(T); + LocalTensor bL1Bf16; + bL1Bf16.SetAddr(bufParam.bL1BufAddr); + GlobalTensor scaleGmCast; + scaleGmCast.SetGlobalBuffer(((__gm__ bfloat16_t *)(tensorAScaleGm.GetPhyAddr()))); + Dn2NzParams dn2nz; + dn2nz.dnNum = 1; + uint32_t nValue = CeilDivT(para.kScale, static_cast(FP8_TWO)); + dn2nz.nValue = nValue; + dn2nz.dValue = para.m; + dn2nz.srcDnMatrixStride = 0; + dn2nz.srcDValue = nValue; + dn2nz.dstNzC0Stride = nValue; + dn2nz.dstNzNStride = 1; + dn2nz.dstNzMatrixStride = nValue; + DataCopy(bL1Bf16[scaleAOff / FP8_TWO], scaleGmCast, dn2nz); + aScaleL1Base = localTensors.bL1Tensor[scaleAOff]; + + uint32_t aScaleTotalSize = mSizeAligned * para.kScale; + bScaleL1BaseOff = static_cast(scaleAOff) + aScaleTotalSize; + bScaleBf16Off = bScaleL1BaseOff / FP8_TWO; + } + + for (uint32_t kL1 = 0; kL1 < kL1Loops; ++kL1) { + // ── 加载A数据到L1A slot0 ── + LocalTensor aL1; + WaitFlag(A_EVENT0); + aL1 = localTensors.aL1Tensor; + CopyNDGmToL1(aL1, tensorAGm[kL1 * para.kL1StepSize], para.m, para.kL1StepSize, para.k); + SetFlag(A_EVENT0); + WaitFlag(A_EVENT0); + + // A-scale起始偏移: 原MatmulL1公式 + uint32_t kL1ScaleOff = kL1 * para.kScale / kL1Loops * BLOCK_CUBE_SIZE; + + // ── 预加载 B[0] ── + uint32_t subN0 = (nBlocks == 1) ? para.n : para.baseN; + int64_t bGmOff0 = static_cast(kL1) * kOffesetUnit; + if constexpr (std::is_same::value && std::is_same::value) { + int64_t bScaleOff0 = static_cast(0); // 全量K-step从0开始 + LoadL1BOuter(tensorBGm[bGmOff0], tensorBScaleGm[bScaleOff0], subN0, para.kL1StepSize, para.k, + para.kScale, 0, bScaleBf16Off, bufParam); + } else { + LoadL1BOuter(tensorBGm[bGmOff0], tensorBScaleGm, subN0, para.kL1StepSize, para.k, 0, 0, bScaleBf16Off, + bufParam); + } + + // ── N分块: B双缓冲ping-pong ── + for (uint32_t nb = 0; nb < nBlocks; ++nb) { + uint32_t subN = (nb == nBlocks - 1) ? (para.n - nb * para.baseN) : para.baseN; + uint32_t curSlot = nb & 1u; + + WaitFlag(B_EVENT0 + curSlot); + LocalTensor bL1 = localTensors.bL1Tensor[curSlot * bL1SlotSize]; + LocalTensor bScaleL1; + if constexpr (std::is_same::value && std::is_same::value) { + bScaleL1 = localTensors.bL1Tensor[curSlot * bL1SlotSize + bScaleL1BaseOff]; + } + + // 预取 B[nb+1] + if (nb + 1 < nBlocks) { + uint32_t nextSlot = (nb + 1) & 1u; + uint32_t subNx = ((nb + 1) == nBlocks - 1) ? (para.n - (nb + 1) * para.baseN) : para.baseN; + int64_t bOffNext = + static_cast(para.k) * (nb + 1) * para.baseN + static_cast(kL1) * kOffesetUnit; + if constexpr (std::is_same::value && std::is_same::value) { + int64_t bScOffNext = static_cast((nb + 1) * para.baseN * para.kScale); + LoadL1BOuter(tensorBGm[bOffNext], tensorBScaleGm[bScOffNext], subNx, para.kL1StepSize, para.k, + para.kScale, nextSlot, bScaleBf16Off, bufParam); + } else { + LoadL1BOuter(tensorBGm[bOffNext], tensorBScaleGm, subNx, para.kL1StepSize, para.k, 0, + nextSlot, bScaleBf16Off, bufParam); + } + } + + // ── L0C ── + WaitFlag(L0C_EVENT0 + (bufParam.cL0BufIter & 1u)); + LocalTensor cL0 = localTensors.cL0Tensor[(bufParam.cL0BufIter & 1u) * (L0C_PP_SIZE / sizeof(O_L0C))]; + + // ── stepK L0循环 ── + MmadParams mmadParams = MmadParams(mSizeAligned, subN, para.baseK, UNIT_FLAG_DISABLE, false, true); + int64_t aOffset = 0; + uint32_t bOffset = 0; + uint32_t aScaleOff = kL1ScaleOff; + uint32_t bScaleOff = kL1ScaleOff; + for (int64_t sk = 0; sk < para.stepK; sk++) { + mmadParams.cmatrixInitVal = (sk == 0); + MatmulL0(bufParam, aL1[aOffset], bL1[bOffset], localTensors.aL0Tensor, + localTensors.bL0Tensor, cL0, mmadParams, para.kL1StepSize, para.k, + aScaleL1Base[aScaleOff], bScaleL1[bScaleOff]); + aOffset += aOffsetUnit; + bOffset += bOffsetUnit; + aScaleOff += scaleOffUnit; + bScaleOff += scaleOffUnit; + } + + // ── FixPipe AtomicAdd ── + SetFlag(L0C_EVENT0 + (bufParam.cL0BufIter & 1u)); + WaitFlag(L0C_EVENT0 + (bufParam.cL0BufIter & 1u)); + FixpipeParamsV220 fixParams; + fixParams.nSize = subN; + fixParams.mSize = para.m; + fixParams.srcStride = mSizeAligned; + fixParams.dstStride = para.orgKc; + fixParams.ndNum = 1; + fixParams.unitFlag = UNIT_FLAG_DISABLE; + SetAtomicAdd(); + Fixpipe(tensorCGm[nb * para.baseN], cL0, fixParams); + SetAtomicNone(); + + SetFlag(L0C_EVENT0 + (bufParam.cL0BufIter & 1u)); + bufParam.cL0BufIter++; + + SetFlag(B_EVENT0 + curSlot); + } + SetFlag(A_EVENT0); + } +} + +} // namespace MlaProlog + + +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_rms_norm.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_rms_norm.h new file mode 100644 index 0000000000000000000000000000000000000000..aaeab1838cb79e37ed16b6bcebaf997f9a682555 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_rms_norm.h @@ -0,0 +1,159 @@ +/** + * 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 service_rms_norm.h + * \brief + */ + +#ifndef SERVICE_RMS_NORM_H +#define SERVICE_RMS_NORM_H + +#include "mla_prolog_comm.h" +#include "mla_prolog_vector_comm.h" + +#include "vf/vf_rms_norm.h" +#include "vf/vf_dynamic_quant.h" + +namespace MlaProlog { + +/** + * @brief RmsNormNormal rmsNorm流程 + * @param outputLocal 输出tensor,[B, S1, H] + * @param inputGm 输入tensor,[B, S1, H],dtype支持bf16,fp32,int32 + * @param gammaLocal 系数gamma [H],dtype只支持bf16 + * @param dequantScaleWDqLocal 权重w反量化系数 + * @param dequantScaleXLocal x反量化系数 + * @param shareTmpUb 临时buffer 所需空间[2 * cnt * sizeof(float) + ALIGN_BLOCK_SIZE] + ALIGN_BLOCK_SIZE = 32Bytes, cnt = row * col + * @param rmsNormParams rms所需系数,包括 + reciprocal rmsnorm系数reciprocal + epsilon rmsnorm系数epsilon + row 处理的行数;预留参数,当前仅支持单个batch的处理,row为1,对应S1 + col 列数,对应H + */ +template +__aicore__ inline void RmsNormNormal(const LocalTensor &outputLocal, const GlobalTensor &inputGm, + const LocalTensor &gammaLocal, + const LocalTensor &dequantScaleWDqLocal, + const LocalTensor &dequantScaleXLocal, + const LocalTensor &shareTmpUb, RmsNormParam &rmsNormParams) +{ + int64_t cnt = rmsNormParams.row * rmsNormParams.col; + LocalTensor xFp32Local = shareTmpUb.ReinterpretCast(); + + // load input [1, col] + DataCopyExtParams copyParams{1, static_cast(rmsNormParams.col * sizeof(T)), 0, 0, 0}; + DataCopyPadExtParams padParams{false, 0, 0, 0}; + + if constexpr (std::is_same::value && std::is_same::value) { + DataCopyPad(xFp32Local, inputGm, copyParams, padParams); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + } else if constexpr (std::is_same::value && std::is_same::value) { + DataCopyPad(xFp32Local, inputGm, copyParams, padParams); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + Rectangle rectangleParams{ + static_cast(rmsNormParams.row), static_cast(rmsNormParams.col), + static_cast(rmsNormParams.col) // columnStride + }; + Dequant(xFp32Local, xFp32Local, dequantScaleWDqLocal, dequantScaleXLocal, rectangleParams); + PipeBarrier(); + } else if constexpr (std::is_same::value) { + LocalTensor xInt32Local = shareTmpUb.ReinterpretCast(); + DataCopyPad(xInt32Local, inputGm, copyParams, padParams); + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + Rectangle rectangleParams{ + static_cast(rmsNormParams.row), static_cast(rmsNormParams.col), + static_cast(rmsNormParams.col) // columnStride + }; + Dequant(xFp32Local, xInt32Local, dequantScaleWDqLocal, dequantScaleXLocal, rectangleParams); + PipeBarrier(); + } else { + LocalTensor inputLocal = xFp32Local[rmsNormParams.col].template ReinterpretCast(); + DataCopyPad(inputLocal, inputGm, copyParams, padParams); + + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + // Cast input to fp32 [1, col] + Cast(xFp32Local, inputLocal, RoundMode::CAST_NONE, cnt); + PipeBarrier(); + } + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + + if constexpr (std::is_same::value) { + RmsNormVF(outputLocal, xFp32Local, gammaLocal, rmsNormParams); + PipeBarrier(); + } else { + RmsNormVF(xFp32Local, xFp32Local, gammaLocal, rmsNormParams); + // Cast xFp32 to outputLocal + PipeBarrier(); + Cast(outputLocal, xFp32Local, RoundMode::CAST_RINT, cnt); + PipeBarrier(); + } +} + +/** + * @brief RmsNormDynamicQuant rmsNorm + dynamicQuant融合流程 + 目前C均为float + * @param outputLocal 输出tensor,[B, S1, H], 量化完后为int8 + * @param outputScales dynamicQuant计算系数输出 + * @param inputGm 输入tensor,[B, S1, H],dtype支持bf16,fp32,int32 + * @param gammaLocal 输入tensor,[H, ], dtype只支持bf16 + * @param smoothLocal dynamicQuant平滑参数 + * @param dequantScaleWDqLocal 权重w反量化系数 + * @param dequantScaleXLocal x反量化系数 + * @param shareTmpUb 临时buffer 所需空间[(4 * cnt + 8) * sizeof(float)] cnt = row * col + * @param rmsNormParams rms所需系数,包括 + reciprocal rmsnorm系数reciprocal + epsilon rmsnorm系数epsilon + row 处理的行数;预留参数,当前仅支持单个batch的处理,row为1,对应S1 + col 列数,对应H + * @param enableSmoothScalesCq 表示是否有smoothGm的需求 + */ +template +__aicore__ inline void +RmsNormDynamicQuant(const LocalTensor &outputLocal, const LocalTensor &outputScales, + const GlobalTensor &inputGm, const LocalTensor &gammaLocal, + const LocalTensor &smoothLocal, const LocalTensor &dequantScaleWDqLocal, + const LocalTensor &dequantScaleXLocal, const LocalTensor &shareTmpUb, + RmsNormParam &rmsNormParams, bool enableSmoothScalesCq = true) +{ + int64_t cnt = rmsNormParams.row * rmsNormParams.col; + LocalTensor xFp32Local = shareTmpUb.ReinterpretCast(); + RmsNormNormal(xFp32Local, inputGm, gammaLocal, dequantScaleWDqLocal, dequantScaleXLocal, + shareTmpUb[rmsNormParams.col * sizeof(C)], rmsNormParams); + PipeBarrier(); + if constexpr (std::is_same::value && std::is_same::value) { + LocalTensor xBf16Local = xFp32Local[cnt].template ReinterpretCast(); + Cast(xBf16Local, xFp32Local, RoundMode::CAST_ROUND, cnt); + PipeBarrier(); + LocalTensor outputScalesLocal = outputScales.template ReinterpretCast(); + LocalTensor outLocal = outputLocal.template ReinterpretCast(); + LocalTensor tmpLocal = xBf16Local[cnt].template ReinterpretCast(); + DynamicQuantPerBlockMxfp8Vf(outLocal, outputScalesLocal, xBf16Local, tmpLocal, + rmsNormParams.row, rmsNormParams.col); + LocalTensor scale = outputScalesLocal.template ReinterpretCast(); + PipeBarrier(); + } else { + if (enableSmoothScalesCq) { + Mul(xFp32Local, xFp32Local, smoothLocal, cnt); + } + DynamicQuantPerTokenVf(outputLocal, outputScales, xFp32Local, rmsNormParams.row, rmsNormParams.col); + PipeBarrier(); + } +} + +} // namespace MlaProlog + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_rope.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_rope.h new file mode 100644 index 0000000000000000000000000000000000000000..3afe4b333b790e77cf31270906ce36e64d6d942a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_rope.h @@ -0,0 +1,42 @@ +/** + * 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 service_rope.h + * \brief + */ + +#ifndef SERVICE_ROPE_H +#define SERVICE_ROPE_H + +#include "vf/vf_rope.h" + +namespace MlaProlog { +/** + * @brief RotaryPosEmb, 同时做row行的RotaryPosEmb,每一行的元素为col + * @param outputLocal 输出tensor [row * col],支持和inputLocal是同一块空间 + * @param inputLocal 输入tensor [row * col] + * @param cosLocal cos系数tensor [(row - 1) * sinCosRepStride + col] + * @param sinLocal sin系数tensor [(row - 1) * sinCosRepStride + col] - 1 应已在sin中 + * @param row 待处理的行数 + * @param col 待处理的列数 col <= 512 / sizeof(C) + * @param sinCosRepStride 行与行之间sin/cos系数的偏移,单位为元素个数。 + */ +template +__aicore__ inline void RotaryPosEmb(const LocalTensor &outputLocal, const LocalTensor &inputLocal, + const LocalTensor &cosLocal, const LocalTensor &sinLocal, + uint64_t row, uint64_t col, uint8_t sinCosRepStride) +{ + DataSyncBarrier(); + RotaryPosEmbVF(outputLocal, inputLocal, cosLocal, sinLocal, + static_cast(row), col, col, static_cast(sinCosRepStride)); +} +} // namespace MlaProlog +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_rotary_position_embedding.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_rotary_position_embedding.h new file mode 100644 index 0000000000000000000000000000000000000000..d481003f1760c212f361aeefd6541d7f5f7a4f06 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_rotary_position_embedding.h @@ -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 service_rotary_position_embedding.h + * \brief + */ + +#ifndef SERVICE_ROTARY_POSITION_EMBEDDING_H +#define SERVICE_ROTARY_POSITION_EMBEDDING_H + +#include "mla_prolog_comm.h" +#include "mla_prolog_vector_comm.h" +#include "service_rope.h" + +namespace MlaProlog { + +template +__aicore__ inline void PreprocessRopeInput(const GlobalTensor &inputGm, LocalTensor &shareTmpUb, + const Rectangle &ropeParams, LocalTensor &kFp32Local, + LocalTensor &kLocal, int64_t cnt) +{ + int64_t baseOffset; + kLocal = shareTmpUb.ReinterpretCast(); + + if constexpr (std::is_same::value) { + baseOffset = cnt; + } else { + baseOffset = cnt >> 1; + } + kFp32Local = shareTmpUb.ReinterpretCast()[baseOffset]; + + DataCopyExtParams copyParams{static_cast(ropeParams.row), + static_cast(ropeParams.col * sizeof(T)), + static_cast((ropeParams.stride - ropeParams.col) * sizeof(T)), 0, 0}; + DataCopyPadExtParams padParams{false, 0, 0, 0}; + + if constexpr (std::is_same::value) { + DataCopyPad(kFp32Local, inputGm, copyParams, padParams); + } else { + DataCopyPad(kLocal, inputGm, copyParams, padParams); + } +} + +/** + * @brief RotaryPosEmbPerTensor 对一个tensor进行RotartPosEmb,tensor的维度为[row * col] + 行与行之间sin/cos公用; + C:ropeComputType, float + * @param outputLocal 输出tensor + * @param inputGm 输入tensor + * @param cosLocal cos系数 + * @param sinLocal sin系数 + * @param shareTmpUb 临时buffer,需要大小为 cnt * 5 * sizeof(float) + * @param ropeParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + * @param channelDeqScaleGm 量化参数;该tensor的每个元素不同 + * @param scale 量化参数;该tensor共用 + */ +template +__aicore__ inline void RotaryPosEmbPerTensor(LocalTensor &outputLocal, const GlobalTensor &inputGm, + const LocalTensor &cosLocal, const LocalTensor &sinLocal, + LocalTensor &shareTmpUb, Rectangle ropeParams, + LocalTensor channelDeqScaleLocal = LocalTensor(), + LocalTensor scale = LocalTensor()) +{ + int64_t cnt = ropeParams.row * ropeParams.col; + LocalTensor kFp32Local; + LocalTensor kLocal; + PreprocessRopeInput(inputGm, shareTmpUb, ropeParams, kFp32Local, kLocal, cnt); + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + LocalTensor kFp32OutputLocal = kFp32Local[cnt]; + + if constexpr (std::is_same::value || enableDequant) { // 反量化 + Rectangle rectangleParams{ + static_cast(1), // row + static_cast(cnt), // col + static_cast(cnt) // columnStride + }; + if constexpr (std::is_same::value) { + Dequant(kFp32Local, kFp32Local, channelDeqScaleLocal, scale, rectangleParams); + } else { + Dequant(kFp32Local, kLocal, channelDeqScaleLocal, scale, rectangleParams); + } + PipeBarrier(); + } else if constexpr (std::is_same::value) { + Cast(kFp32Local, kLocal, RoundMode::CAST_NONE, cnt); + PipeBarrier(); + } + if constexpr (std::is_same::value) { + RotaryPosEmb(outputLocal, kFp32Local, cosLocal, sinLocal, ropeParams.row, ropeParams.col, 0); + PipeBarrier(); + } else { + RotaryPosEmb(kFp32OutputLocal, kFp32Local, cosLocal, sinLocal, ropeParams.row, ropeParams.col, 0); + PipeBarrier(); + Cast(outputLocal, kFp32OutputLocal, RoundMode::CAST_RINT, cnt); + PipeBarrier(); + } +} + +/** + * @brief RotaryPosEmbPerHead 进行row行col列的RotaryPosEmb + 每行的量化系数,sin/cos均不同 + C:ropeComputType,float + * @param outputLocal 输出tensor + * @param inputGm 输入tensor + * @param cosLocal cos系数 + * @param sinLocal sin系数 + * @param shareTmpUb 临时buffer + * @param ropeParams 描述待处理数据的排布,包括 + row 行数 + col 列数 + stride 一行的真实长度 + * @param strideScale 一段的真实长度,描述channelDeqScaledGm数据排布 + * @param channelDeqScaleGm 量化参数:最终使用shape[1,col] + * @param deQuantScale 量化参数;最终使用shape[row,8] + */ +template +__aicore__ inline void RotaryPosEmbPerHead(LocalTensor &outputLocal, const GlobalTensor &inputGm, + const LocalTensor &cosLocal, const LocalTensor &sinLocal, + LocalTensor &shareTmpUb, Rectangle ropeParams, int64_t strideScale, + GlobalTensor channelDeqScaleGm = GlobalTensor(), + LocalTensor deQuantScale = LocalTensor()) +{ + // 在 BS = 1 场景可能存在有row为零的情况,提前返回减少运算 + if (ropeParams.row == 0) { + return; + } + + int64_t cnt = ropeParams.row * ropeParams.col; + LocalTensor kFp32Local; + LocalTensor kLocal; + PreprocessRopeInput(inputGm, shareTmpUb, ropeParams, kFp32Local, kLocal, cnt); + // scale参数可以和rope使用的空间复用 + LocalTensor scaleLocal = kFp32Local[cnt]; + LocalTensor kFp32OutputLocal = scaleLocal[ropeParams.col]; + SetFlag(EVENT_ID0); + WaitFlag(EVENT_ID0); + if constexpr (std::is_same::value || enableDequant) { // 反量化 + DataCopyExtParams copyParams1{static_cast(1), static_cast(ropeParams.col * sizeof(C)), + static_cast((strideScale - ropeParams.col) * sizeof(C)), 0, 0}; + DataCopyPadExtParams padParams1{false, 0, 0, 0}; + DataCopyPad(scaleLocal, channelDeqScaleGm, copyParams1, padParams1); // 复用内存 + SetFlag(EVENT_ID1); + WaitFlag(EVENT_ID1); + + uint8_t blockNumPerRow = ropeParams.col / (ALIGN_BLOCK_SIZE / sizeof(C)); + // row col stride + Rectangle rectangleParams{static_cast(ropeParams.row), static_cast(ropeParams.col), + static_cast(ropeParams.col)}; + if constexpr (std::is_same::value) { + Dequant(kFp32Local, kFp32Local, scaleLocal, deQuantScale, rectangleParams); + } else { + Dequant(kFp32Local, kLocal, scaleLocal, deQuantScale, rectangleParams); + } + } else if constexpr (std::is_same::value) { + Cast(kFp32Local, kLocal, RoundMode::CAST_NONE, cnt); + } + PipeBarrier(); + RotaryPosEmb(kFp32OutputLocal, kFp32Local, cosLocal, sinLocal, ropeParams.row, ropeParams.col, ropeParams.col); + PipeBarrier(); + + if constexpr (std::is_same::value) { + DataCopy(outputLocal, kFp32OutputLocal, cnt); + } else { + Cast(outputLocal, kFp32OutputLocal, RoundMode::CAST_RINT, cnt); + } + PipeBarrier(); +} + +template +__aicore__ inline void RopePostQuantPerChannel(LocalTensor &outputLocal, LocalTensor &inputLocal, + LocalTensor &quantScaleLocal, LocalTensor &shareTmpUb, + int64_t cnt) +{ + LocalTensor inFp32; + if constexpr (std::is_same::value) { + inFp32 = inputLocal; + } else { + inFp32 = shareTmpUb.ReinterpretCast()[cnt]; + Cast(inFp32, inputLocal, RoundMode::CAST_NONE, cnt); + PipeBarrier(); + } + Mul(inFp32, inFp32, quantScaleLocal, cnt); + PipeBarrier(); + CastFP32ToINT8(outputLocal, inFp32, shareTmpUb, cnt); + PipeBarrier(); +} +} // namespace MlaProlog +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_scatter_cache.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_scatter_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..c79165668223ab9c8cce91f67644f055bf1eb4fa --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/service_scatter_cache.h @@ -0,0 +1,135 @@ +/** + * 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 service_scatter_cache.h + * \brief + */ + +#ifndef SERVICE_SCATTER_CACHE_H +#define SERVICE_SCATTER_CACHE_H + +#include "mla_prolog_comm.h" + +namespace MlaProlog { + +__aicore__ inline int64_t CeilDiv64(int64_t x, int64_t y) +{ + if (y == 0) { + return static_cast(0); + } + return (x + y - 1) / y; +}; + +/** + * @brief PA场景,将inputLocal中的数据scatter到cacheGm,支持ND和Nz cache + * @param cacheGm 输出tensor + * ND [blockNum, blockSize, col] + * Nz [blockNum, ceil(col/col0), blockSize, col0] + * @param inputLocal 输入tensor,[row, col],一行对应一个token,只支持单行数据处理,row为1 + * @param scatterCacheParams 所需相关参数,包括 + blockSize KV blocks的大小 + paTokenIndex 待处理token在cache中的全局index,取值[0, blockNum*blockSize) + row 待处理的行数 + col 待处理的列数,需满足32 bytes对齐 + */ + +struct ScatterCacheParams { + int64_t blockSize; + int64_t paTokenIndex; + int64_t row; + int64_t col; + int64_t stride; + int64_t seqLength; + int64_t tokenIndex; +}; + +template +__aicore__ inline void ScatterCache(const GlobalTensor &cacheGm, const LocalTensor &inputLocal, + const ScatterCacheParams &scatterCacheParams) +{ + if (scatterCacheParams.paTokenIndex < 0) { + return; + } + if constexpr (!IS_NZ) { + DataCopy(cacheGm[scatterCacheParams.paTokenIndex * scatterCacheParams.stride], inputLocal, + scatterCacheParams.col); + } else { + constexpr uint8_t col0 = ALIGN_BLOCK_SIZE / sizeof(T); + int64_t cacheOffset = scatterCacheParams.paTokenIndex / scatterCacheParams.blockSize * + scatterCacheParams.blockSize * scatterCacheParams.stride + + scatterCacheParams.paTokenIndex % scatterCacheParams.blockSize * col0; + DataCopyParams copyParams{static_cast(scatterCacheParams.col / col0), 1, 0, + static_cast(scatterCacheParams.blockSize - 1)}; + DataCopy(cacheGm[cacheOffset], inputLocal, copyParams); + } +} + +template +__aicore__ inline void ScatterCacheUnAligned(const GlobalTensor &cacheGm, const LocalTensor &inputLocal, + const ScatterCacheParams &scatterCacheParams) +{ + if (scatterCacheParams.paTokenIndex < 0) { + return; + } + if constexpr (!IS_NZ) { + // blockCount, blockLen, srcStride, dstStride + DataCopyParams dataCopyParams{1, static_cast(scatterCacheParams.col * sizeof(T)), 0, 0}; + DataCopyPad(cacheGm[scatterCacheParams.paTokenIndex * scatterCacheParams.stride], inputLocal, dataCopyParams); + } +} + +template +__aicore__ inline void ScatterCacheMultiRows(GlobalTensor &cacheGm, const LocalTensor &inputLocal, + const ScatterCacheParams &scatterCacheParams, int64_t rowsInCurBatch, + int64_t cacheOffset, int64_t nextBatchOffset) +{ + if (cacheOffset < 0) { + return; + } + int64_t copyCnt = scatterCacheParams.col * rowsInCurBatch; + + if constexpr (!IS_NZ) { + DataCopy(cacheGm[cacheOffset], inputLocal, copyCnt); + if (rowsInCurBatch != scatterCacheParams.row) { + DataCopy(cacheGm[nextBatchOffset], inputLocal[copyCnt], + (scatterCacheParams.row - rowsInCurBatch) * scatterCacheParams.col); + } + } else { + constexpr uint8_t col0 = ALIGN_BLOCK_SIZE / sizeof(T); + DataCopyParams copyParams{static_cast(scatterCacheParams.col / col0), 1, 0, + static_cast(scatterCacheParams.blockSize - 1)}; + DataCopy(cacheGm[cacheOffset], inputLocal, copyParams); + if (rowsInCurBatch != scatterCacheParams.row) { + for (int row = 0; row < scatterCacheParams.row - rowsInCurBatch; ++row) { + DataCopy(cacheGm[nextBatchOffset + row * col0], inputLocal[copyCnt + row * col0], copyParams); + } + } + } +} + +template +__aicore__ inline void MaterializeOffsetsWithHeadSize(int64_t pageTokenOffset, int64_t tokenOffsetInPage, + int64_t rowsThisStep, bool spill, int64_t nextPageId, + int64_t headSize, CkvkrParams &ckvkrParams) +{ + ckvkrParams.rowsInCurBatch = rowsThisStep; + if constexpr (IS_NZ) { + constexpr uint8_t col0 = ALIGN_BLOCK_SIZE / sizeof(T); + ckvkrParams.cacheOffset = pageTokenOffset * headSize + tokenOffsetInPage * col0; + } else { + ckvkrParams.cacheOffset = (pageTokenOffset + tokenOffsetInPage) * headSize; + } + ckvkrParams.nextBatchOffset = (spill && nextPageId >= 0) ? nextPageId * headSize : 0; +} + +} // namespace MlaProlog + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_comm.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_comm.h new file mode 100644 index 0000000000000000000000000000000000000000..10e38dc09f64a45eddb0f15cdefc3279035e03e0 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_comm.h @@ -0,0 +1,40 @@ +/** + * 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_comm.h + * \brief VF comm + */ + +#ifndef VF_COMM_H +#define VF_COMM_H + +#include "kernel_tensor.h" + +namespace MlaProlog { +constexpr uint32_t ROPE_VF_COL = 64; + +constexpr MicroAPI::CastTrait castTraitB162B32 = { + MicroAPI::RegLayout::ZERO, + MicroAPI::SatMode::UNKNOWN, + MicroAPI::MaskMergeMode::ZEROING, + RoundMode::UNKNOWN, +}; + +constexpr MicroAPI::CastTrait castTraitB322B16 = { + MicroAPI::RegLayout::ZERO, + MicroAPI::SatMode::NO_SAT, + MicroAPI::MaskMergeMode::ZEROING, + RoundMode::CAST_RINT, +}; + +} // namespace MlaProlog + +#endif // VF_COMM_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_dequant.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_dequant.h new file mode 100644 index 0000000000000000000000000000000000000000..61c65f370bac9294e4f76131a9d0983c3ce02766 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_dequant.h @@ -0,0 +1,127 @@ +/** + * 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 vf_dequant.h + * \brief + */ + +#ifndef VF_DEQUANT_H +#define VF_DEQUANT_H +#include "kernel_tensor.h" + +namespace MlaProlog { + +template +__simd_vf__ void DequantVFImpl(__ubuf__ float *yAddr, __ubuf__ T *xAddr, __ubuf__ float *scalePerChannelAddr, + __ubuf__ float *scalePerTokenAddr, uint32_t floatRepSize, uint32_t fp32BlockElementNum, + uint32_t dLoops, uint32_t dTail, uint32_t dTailLoop, uint32_t row, uint32_t col, + uint32_t stride) +{ + constexpr static AscendC::MicroAPI::CastTrait castTraitInt32ToFp32 = { + AscendC::MicroAPI::RegLayout::UNKNOWN, AscendC::MicroAPI::SatMode::NO_SAT, + AscendC::MicroAPI::MaskMergeMode::ZEROING, AscendC::RoundMode::CAST_RINT}; + + AscendC::MicroAPI::RegTensor vregInput; + AscendC::MicroAPI::RegTensor vregScalePerChannel; + AscendC::MicroAPI::RegTensor vregScalePerToken; + AscendC::MicroAPI::RegTensor vregInputFp32; // cast成float之后的vregInput + AscendC::MicroAPI::MaskReg fullMask = AscendC::MicroAPI::CreateMask(); + AscendC::MicroAPI::MaskReg tailMask; + tailMask = AscendC::MicroAPI::UpdateMask(dTail); + + uint32_t colOffset = 0; + uint32_t rowOffset = 0; + uint32_t scaleOffset = 0; + for (uint32_t j = 0; j < dLoops; j++) { + AscendC::MicroAPI::LoadAlign(vregScalePerChannel, + scalePerChannelAddr + colOffset); + rowOffset = 0; + scaleOffset = 0; + for (uint32_t i = 0; i < row; i++) { + AscendC::MicroAPI::LoadAlign( + vregScalePerToken, scalePerTokenAddr + scaleOffset); + if constexpr (!std::is_same::value) { + AscendC::MicroAPI::LoadAlign( + vregInput, xAddr + colOffset + rowOffset); + AscendC::MicroAPI::Cast( + vregInputFp32, vregInput, fullMask); + } else { + AscendC::MicroAPI::LoadAlign(vregInputFp32, + xAddr + colOffset + rowOffset); + } + AscendC::MicroAPI::Mul(vregInputFp32, vregInputFp32, vregScalePerChannel, fullMask); + AscendC::MicroAPI::Mul(vregInputFp32, vregInputFp32, vregScalePerToken, fullMask); + AscendC::MicroAPI::StoreAlign( + yAddr + colOffset + rowOffset, vregInputFp32, fullMask); + rowOffset += stride; + scaleOffset += fp32BlockElementNum; + } + colOffset += floatRepSize; + } + + if (dTailLoop > 0) { + rowOffset = 0; + scaleOffset = 0; + AscendC::MicroAPI::LoadAlign( + vregScalePerChannel, scalePerChannelAddr + dLoops * floatRepSize); + for (uint32_t i = 0; i < row; i++) { + AscendC::MicroAPI::LoadAlign( + vregScalePerToken, scalePerTokenAddr + scaleOffset); + if constexpr (!std::is_same::value) { + AscendC::MicroAPI::LoadAlign( + vregInput, xAddr + dLoops * floatRepSize + rowOffset); + AscendC::MicroAPI::Cast( + vregInputFp32, vregInput, tailMask); + } else { + AscendC::MicroAPI::LoadAlign( + vregInputFp32, xAddr + dLoops * floatRepSize + rowOffset); + } + AscendC::MicroAPI::Mul(vregInputFp32, vregInputFp32, vregScalePerChannel, tailMask); + AscendC::MicroAPI::Mul(vregInputFp32, vregInputFp32, vregScalePerToken, tailMask); + AscendC::MicroAPI::StoreAlign( + yAddr + dLoops * floatRepSize + rowOffset, vregInputFp32, tailMask); + rowOffset += stride; + scaleOffset += fp32BlockElementNum; + } + } +} + +/** + * @brief DequantVf 对输入做per-token叠加per-channel的反量化, INT32 ---> FP32. + * @param outputLocal 输出tensor [row, col] + * @param inputLocal 输入tensor [row, col] + * @param scalePerChannelLocal 输入tensor [1, col] + * @param scalePerTokenLocal 输入tensor [row, 8] + * @param row 待处理的行数 + * @param col 待处理的列数 + * @param stride 待处理数据一行的真实长度 + */ +template +__aicore__ inline void DequantVf(const LocalTensor &outputLocal, const LocalTensor &inputLocal, + const LocalTensor &scalePerChannelLocal, + const LocalTensor &scalePerTokenLocal, + uint32_t row, uint32_t col, uint32_t stride) +{ + __ubuf__ float *outputUb = (__ubuf__ float *)outputLocal.GetPhyAddr(); + __ubuf__ T *inputUb = (__ubuf__ T *)inputLocal.GetPhyAddr(); + __ubuf__ float *scalePerChannelLocalUb = (__ubuf__ float *)scalePerChannelLocal.GetPhyAddr(); + __ubuf__ float *scalePerTokenLocalUb = (__ubuf__ float *)scalePerTokenLocal.GetPhyAddr(); + + const uint32_t floatRepSize = 64; // 一个寄存器能够存放64个FP32 + const uint32_t fp32BlockElementNum = 8; + uint32_t dLoops = col / floatRepSize; + uint32_t dTail = col % floatRepSize; + uint32_t dTailLoop = dTail > 0 ? 1 : 0; + DequantVFImpl(outputUb, inputUb, scalePerChannelLocalUb, scalePerTokenLocalUb, floatRepSize, fp32BlockElementNum, + dLoops, dTail, dTailLoop, row, col, stride); +} +} // namespace MlaProlog +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_dynamic_quant.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_dynamic_quant.h new file mode 100644 index 0000000000000000000000000000000000000000..f6f115f32faeaae894b95d658de79f99e22f6b63 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_dynamic_quant.h @@ -0,0 +1,446 @@ +/** + * 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_dynamic_quant.h + * \brief + */ + +#ifndef VF_DYNAMIC_QUANT_H +#define VF_DYNAMIC_QUANT_H + +#include "kernel_tensor.h" + +namespace MlaProlog { +constexpr float INT8_MAX_VALUE = 127.0f; +constexpr float FP8_E4M3FN_MAX_VALUE = 448.0f; +constexpr float FP8_E4M3FN_MIN_VALUE = -448.0f; +constexpr float HIFLOAT8_MAX_VALUE = 32768.0f; +constexpr uint32_t FP8_E4M3FN_BLOCK_SIZE = 32; +constexpr uint16_t FP8_E4M3_MAX_EXP = 0x0400; +constexpr uint16_t MAX_EXP_FOR_BF16 = 0x7f80; +constexpr uint16_t BF16_EXP_BIAS = 0x7f00; +constexpr uint16_t MAX_EXP_FOR_FP8 = 0x00ff; +constexpr uint16_t NAN_CUSTOMIZATION = 0x7f81; +constexpr uint16_t SPECIAL_EXP_THRESHOLD = 0x0040; +constexpr int64_t OUT_ELE_NUM_ONE_BLK = 64; +constexpr int64_t DIGIT_TWO = 2; +constexpr int16_t SHR_NUM_FOR_BF16 = 7; +constexpr uint8_t PER_TILE_QUANT_MODE = 1; +#ifndef INFINITY +#define INFINITY (__builtin_inff()) +#endif +constexpr float NEG_INFINITY = -INFINITY; +constexpr uint16_t REDUCE_SIZE = 8; + +template // M=0为fp8全量化pertoken量化;M=1为fp8全量化pertile量化 +__simd_vf__ void ComputeVFImpl(__ubuf__ T *xAddr, __ubuf__ O *yAddr, __ubuf__ float *scaleAddr, uint32_t rowIndex, + uint32_t rowCount, uint32_t dtypeSize, uint16_t VL, uint16_t vfLoop, + const float alphaValue) +{ + constexpr static AscendC::MicroAPI::CastTrait castTraitB16ToF32 = { + AscendC::MicroAPI::RegLayout::ZERO, AscendC::MicroAPI::SatMode::UNKNOWN, + AscendC::MicroAPI::MaskMergeMode::ZEROING, AscendC::RoundMode::UNKNOWN}; + constexpr static AscendC::MicroAPI::CastTrait castTraitPack2 = { + AscendC::MicroAPI::RegLayout::ZERO, AscendC::MicroAPI::SatMode::SAT, AscendC::MicroAPI::MaskMergeMode::ZEROING, + RoundMode::CAST_RINT}; + constexpr static AscendC::MicroAPI::CastTrait castTraitF32ToHalf = { + AscendC::MicroAPI::RegLayout::ZERO, AscendC::MicroAPI::SatMode::NO_SAT, + AscendC::MicroAPI::MaskMergeMode::ZEROING, RoundMode::CAST_ODD}; + constexpr static AscendC::MicroAPI::CastTrait castTraitF32ToHif8 = { + AscendC::MicroAPI::RegLayout::ZERO, AscendC::MicroAPI::SatMode::SAT, AscendC::MicroAPI::MaskMergeMode::ZEROING, + RoundMode::CAST_ROUND}; + static constexpr AscendC::MicroAPI::DivSpecificMode mode = {AscendC::MicroAPI::MaskMergeMode::ZEROING, true}; + AscendC::MicroAPI::RegTensor xInput; // 搬入的x + AscendC::MicroAPI::RegTensor xFp32; // cast成float之后的x + AscendC::MicroAPI::RegTensor xFp32Abs; // x的绝对值absvalue + AscendC::MicroAPI::RegTensor xMaxAbs; // x的abs与-inf比较的结果,可以认为是x的absvalue的一些最大值 + AscendC::MicroAPI::RegTensor xReduceMax; // reduceMax + AscendC::MicroAPI::RegTensor xScale; // scale + AscendC::MicroAPI::RegTensor xScaleDup; // Duplicate之后的scale,为了和input一起得到y + AscendC::MicroAPI::RegTensor xNorm; // input/scale + AscendC::MicroAPI::RegTensor yHalf; // float-->half-->int8 + AscendC::MicroAPI::RegTensor yOutput; // 最终y + + AscendC::MicroAPI::MaskReg validMask0; // 有效掩码 + AscendC::MicroAPI::MaskReg fullMask1 = + AscendC::MicroAPI::CreateMask(); // 启用所有通道,全掩码 + AscendC::MicroAPI::MaskReg validMask2; + + AscendC::MicroAPI::UnalignRegForStore ureg0; + AscendC::MicroAPI::Duplicate(xMaxAbs, NEG_INFINITY, fullMask1); + uint32_t sreg0 = rowCount; + + // 计算量化参数 + for (uint16_t j = 0; j < vfLoop; j++) { + validMask0 = AscendC::MicroAPI::UpdateMask(sreg0); // 有效元素 + if constexpr (!std::is_same::value) { + AscendC::MicroAPI::LoadAlign( + xInput, xAddr + rowIndex * rowCount + j * VL); + AscendC::MicroAPI::Cast(xFp32, xInput, validMask0); + } else { + AscendC::MicroAPI::LoadAlign(xFp32, xAddr + rowIndex * rowCount + + j * VL); + } + AscendC::MicroAPI::Abs(xFp32Abs, xFp32, validMask0); + AscendC::MicroAPI::Max(xMaxAbs, xFp32Abs, xMaxAbs, fullMask1); + } + AscendC::MicroAPI::Reduce( + xReduceMax, xMaxAbs, fullMask1); + if constexpr (M == PER_TILE_QUANT_MODE) { + constexpr float epsilonValue = 1e-4f; + AscendC::MicroAPI::RegTensor epsilonReg; + AscendC::MicroAPI::Duplicate(epsilonReg, epsilonValue, fullMask1); + AscendC::MicroAPI::Max(xReduceMax, xReduceMax, epsilonReg, fullMask1); // regtensor类型 + } + AscendC::MicroAPI::Muls(xScale, xReduceMax, alphaValue, fullMask1); + AscendC::MicroAPI::Duplicate(xScaleDup, xScale, fullMask1); + AscendC::MicroAPI::StoreUnAlign(scaleAddr, xScale, ureg0, + 1); + + uint32_t sreg1 = rowCount; + for (uint16_t j = 0; j < vfLoop; j++) { + auto addr = yAddr + rowIndex * rowCount + j * VL; + validMask2 = AscendC::MicroAPI::UpdateMask(sreg1); + if constexpr (!std::is_same::value) { + AscendC::MicroAPI::LoadAlign( + xInput, xAddr + rowIndex * rowCount + j * VL); + AscendC::MicroAPI::Cast(xFp32, xInput, validMask2); + } else { + AscendC::MicroAPI::LoadAlign(xFp32, xAddr + rowIndex * rowCount + + j * VL); + } + AscendC::MicroAPI::Div(xNorm, xFp32, xScaleDup, validMask2); + if constexpr (std::is_same::value) { + AscendC::MicroAPI::Cast(yOutput, xNorm, validMask2); + } else if constexpr (std::is_same::value) { + AscendC::MicroAPI::Cast(yOutput, xNorm, validMask2); + } else { + AscendC::MicroAPI::Cast(yHalf, xNorm, validMask2); + AscendC::MicroAPI::Cast(yOutput, yHalf, validMask2); + } + AscendC::MicroAPI::StoreAlign(addr, yOutput, validMask2); + } + AscendC::MicroAPI::StoreUnAlignPost(scaleAddr, ureg0, 0); +} + +/** + * @brief DynamicQuantPerTokenVf 对row行进行dynamicquant, BF16 ---> int8/FP8E4M3, 每一行出一个系数。 + * @param outputLocal 输出tensor [row , col] + * @param scale 输出每行的反量化系数 [row] + * @param inputLocal 输入tensor [row , col] + * @param row 待处理的行数 + * @param col 待处理的列数 + */ +template +__aicore__ inline void DynamicQuantPerTokenVf(const LocalTensor &outputLocal, const LocalTensor &scale, + const LocalTensor &inputLocal, uint64_t row, uint64_t col) +{ + auto xAddr = (__local_mem__ T *)inputLocal.GetPhyAddr(); + auto yAddr = (__local_mem__ O *)outputLocal.GetPhyAddr(); + auto scaleAddr = (__local_mem__ C *)scale.GetPhyAddr(); + uint32_t dtypeSize = sizeof(float); + uint16_t VL = AscendC::VECTOR_REG_WIDTH / dtypeSize; + uint32_t rowCount = col; + uint16_t vfLoop = (rowCount + VL - 1) / VL; + + constexpr float maxValue = std::is_same::value ? FP8_E4M3FN_MAX_VALUE : + std::is_same::value ? HIFLOAT8_MAX_VALUE : + INT8_MAX_VALUE; + const float alphaValue = static_cast(1.0) / maxValue; + for (int32_t i = 0; i < row; i++) { + ComputeVFImpl(xAddr, yAddr, scaleAddr + i, i, rowCount, dtypeSize, VL, vfLoop, alphaValue); + } +} + +template +__simd_vf__ void ComputeMaxExpVF(__ubuf__ T *srcAddr, __ubuf__ uint16_t *maxExpAddr, uint32_t totalCountInUB, + uint16_t loopNum, uint16_t vecLen) +{ + AscendC::MicroAPI::RegTensor vdExp0; + AscendC::MicroAPI::RegTensor vdExp1; + AscendC::MicroAPI::RegTensor vdExpExtract0; + AscendC::MicroAPI::RegTensor vdExpExtract1; + + AscendC::MicroAPI::RegTensor expMaskBF16; + AscendC::MicroAPI::Duplicate(expMaskBF16, MAX_EXP_FOR_BF16); + + AscendC::MicroAPI::RegTensor vdMaxExp; + AscendC::MicroAPI::MaskReg scaleMask1; + AscendC::MicroAPI::MaskReg scaleMask2; + AscendC::MicroAPI::UnalignRegForStore u1; + + for (uint16_t i = 0; i < loopNum; i++) { + scaleMask1 = AscendC::MicroAPI::UpdateMask(totalCountInUB); + scaleMask2 = AscendC::MicroAPI::UpdateMask(totalCountInUB); + AscendC::MicroAPI::LoadAlign(vdExp0, vdExp1, srcAddr, + vecLen * DIGIT_TWO); + // 通过位与运算得到bf16的指数位保留,尾数位置0所对应的值, 0x7f80是bf16 8个指数位为1,7个尾数位为0对应的值 + AscendC::MicroAPI::And(vdExpExtract0, (AscendC::MicroAPI::RegTensor &)vdExp0, expMaskBF16, + scaleMask1); + + AscendC::MicroAPI::And(vdExpExtract1, (AscendC::MicroAPI::RegTensor &)vdExp1, expMaskBF16, + scaleMask1); + // 得到指数位最大的值 + AscendC::MicroAPI::Max(vdMaxExp, vdExpExtract0, vdExpExtract1, scaleMask1); + // 得到每个block(32个元素)中的指数位最大的值 + AscendC::MicroAPI::ReduceDataBlock( + vdMaxExp, vdMaxExp, scaleMask1); + AscendC::MicroAPI::StoreUnAlign( + maxExpAddr, vdMaxExp, u1, REDUCE_SIZE); + } + AscendC::MicroAPI::StoreUnAlignPost(maxExpAddr, u1, 0); +} + + +template +__simd_vf__ void ComputeScaleVF(__ubuf__ uint16_t *maxExpAddr, __ubuf__ uint16_t *mxScaleLocalAddr, + __ubuf__ uint16_t *halfScaleLocalAddr, uint32_t totalScaleInUB, uint16_t loopNumScale, + uint16_t vecLen) +{ + AscendC::MicroAPI::RegTensor expMask; + AscendC::MicroAPI::Duplicate(expMask, MAX_EXP_FOR_BF16); + AscendC::MicroAPI::RegTensor vdMaxExp; + + AscendC::MicroAPI::MaskReg cmpResult; + AscendC::MicroAPI::MaskReg zeroMask; + AscendC::MicroAPI::MaskReg preMaskScale; + AscendC::MicroAPI::MaskReg invalidDataMask; + AscendC::MicroAPI::MaskReg specialDataMask; + + AscendC::MicroAPI::RegTensor maxExpValue; + AscendC::MicroAPI::Duplicate(maxExpValue, FP8_E4M3_MAX_EXP); + AscendC::MicroAPI::RegTensor sharedExp; + AscendC::MicroAPI::RegTensor scaleValue; + AscendC::MicroAPI::RegTensor scaleBias; + AscendC::MicroAPI::Duplicate(scaleBias, BF16_EXP_BIAS); + AscendC::MicroAPI::RegTensor halfScale; + AscendC::MicroAPI::RegTensor fp8NanRegTensor; + AscendC::MicroAPI::Duplicate(fp8NanRegTensor, MAX_EXP_FOR_FP8); + AscendC::MicroAPI::RegTensor zeroRegTensor; + AscendC::MicroAPI::Duplicate(zeroRegTensor, 0); + AscendC::MicroAPI::RegTensor nanRegTensor; + AscendC::MicroAPI::Duplicate(nanRegTensor, NAN_CUSTOMIZATION); + AscendC::MicroAPI::RegTensor specialExpRegTensor; + AscendC::MicroAPI::Duplicate(specialExpRegTensor, SPECIAL_EXP_THRESHOLD); + + for (uint16_t i = 0; i < loopNumScale; i++) { + preMaskScale = AscendC::MicroAPI::UpdateMask(totalScaleInUB); + AscendC::MicroAPI::LoadAlign(vdMaxExp, maxExpAddr, + vecLen); + AscendC::MicroAPI::Compare(cmpResult, vdMaxExp, expMask, preMaskScale); // INF/NAN + AscendC::MicroAPI::Compare(zeroMask, vdMaxExp, zeroRegTensor, preMaskScale); + // 如果vdMaxExp小于等于maxExpValue, 则置为maxExpValue, maxExpValue为FP8E4M3最大正整数的指数位8左移7位是0x400 + AscendC::MicroAPI::Compare(invalidDataMask, vdMaxExp, maxExpValue, preMaskScale); + AscendC::MicroAPI::Select(vdMaxExp, maxExpValue, vdMaxExp, invalidDataMask); + // vdMaxExp - maxExpValue后右移7位得到FP8E8M0的值,右移7位是因为bf16的指数位从第7位开始 + AscendC::MicroAPI::Sub(sharedExp, vdMaxExp, maxExpValue, preMaskScale); + AscendC::MicroAPI::ShiftRights(scaleValue, sharedExp, SHR_NUM_FOR_BF16, preMaskScale); + + AscendC::MicroAPI::Select(scaleValue, scaleValue, fp8NanRegTensor, cmpResult); + AscendC::MicroAPI::Select(scaleValue, scaleValue, zeroRegTensor, zeroMask); + + AscendC::MicroAPI::StoreAlign(mxScaleLocalAddr, scaleValue, + vecLen / DIGIT_TWO, preMaskScale); + + AscendC::MicroAPI::Compare(specialDataMask, sharedExp, scaleBias, preMaskScale); + // 0x7f00 - sharedExp得到1/sharedExp + AscendC::MicroAPI::Sub(halfScale, scaleBias, sharedExp, preMaskScale); + AscendC::MicroAPI::Select(halfScale, halfScale, nanRegTensor, cmpResult); + AscendC::MicroAPI::Select(halfScale, halfScale, zeroRegTensor, zeroMask); + AscendC::MicroAPI::Select(halfScale, specialExpRegTensor, halfScale, specialDataMask); + + AscendC::MicroAPI::StoreAlign( + halfScaleLocalAddr, halfScale, vecLen, preMaskScale); + } +} + +template +__simd_vf__ void ComputeDataVF(__ubuf__ T *srcAddr, __ubuf__ uint16_t *halfScaleLocalAddr, + __ubuf__ int8_t *outLocalAddr, uint32_t totalCountInUB, uint32_t totalCountInUB2, + uint16_t loopNum, uint16_t vecLen) +{ + AscendC::MicroAPI::MaskReg dataMask1; + AscendC::MicroAPI::MaskReg dataMask2; + AscendC::MicroAPI::MaskReg dataMask3; + AscendC::MicroAPI::MaskReg dataMask4; + AscendC::MicroAPI::MaskReg nanResult; + + AscendC::MicroAPI::RegTensor halfScaleForMul; + AscendC::MicroAPI::RegTensor floatScaleForMul; + AscendC::MicroAPI::RegTensor vdExp0; + AscendC::MicroAPI::RegTensor vdExp1; + AscendC::MicroAPI::RegTensor vdExp0Convert; + AscendC::MicroAPI::RegTensor vdExp1Convert; + AscendC::MicroAPI::RegTensor vdExp0FP32Zero; + AscendC::MicroAPI::RegTensor vdExp0FP32One; + AscendC::MicroAPI::RegTensor vdExp1FP32Zero; + AscendC::MicroAPI::RegTensor vdExp1FP32One; + AscendC::MicroAPI::RegTensor maxFp8Value; + AscendC::MicroAPI::Duplicate(maxFp8Value, FP8_E4M3FN_MAX_VALUE); + AscendC::MicroAPI::RegTensor minFp8Value; + AscendC::MicroAPI::Duplicate(minFp8Value, FP8_E4M3FN_MIN_VALUE); + AscendC::MicroAPI::RegTensor vdExp0FP8Zero; + AscendC::MicroAPI::RegTensor vdExp0FP8One; + AscendC::MicroAPI::RegTensor vdExp1FP8Zero; + AscendC::MicroAPI::RegTensor vdExp1FP8One; + + static constexpr AscendC::MicroAPI::CastTrait castTraitZero = { + AscendC::MicroAPI::RegLayout::ZERO, AscendC::MicroAPI::SatMode::UNKNOWN, + AscendC::MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + static constexpr AscendC::MicroAPI::CastTrait castTraitOne = { + AscendC::MicroAPI::RegLayout::ONE, AscendC::MicroAPI::SatMode::UNKNOWN, + AscendC::MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + static constexpr AscendC::MicroAPI::CastTrait castTrait32to8 = { + AscendC::MicroAPI::RegLayout::ZERO, AscendC::MicroAPI::SatMode::SAT, AscendC::MicroAPI::MaskMergeMode::ZEROING, + RoundMode::CAST_RINT}; + for (uint16_t i = 0; i < loopNum; i++) { + dataMask1 = AscendC::MicroAPI::UpdateMask(totalCountInUB); + dataMask2 = AscendC::MicroAPI::UpdateMask(totalCountInUB); + dataMask3 = AscendC::MicroAPI::UpdateMask(totalCountInUB2); + dataMask4 = AscendC::MicroAPI::UpdateMask(totalCountInUB2); + AscendC::MicroAPI::LoadAlign(vdExp0, vdExp1, srcAddr, + vecLen * DIGIT_TWO); + AscendC::MicroAPI::LoadAlign(halfScaleForMul, halfScaleLocalAddr, + REDUCE_SIZE); + + // X / mxscale + AscendC::MicroAPI::Mul(vdExp0, vdExp0, (AscendC::MicroAPI::RegTensor &)halfScaleForMul, dataMask1); + AscendC::MicroAPI::Mul(vdExp1, vdExp1, (AscendC::MicroAPI::RegTensor &)halfScaleForMul, dataMask1); + AscendC::MicroAPI::Interleave(vdExp0, vdExp1, vdExp0, vdExp1); + AscendC::MicroAPI::Cast(vdExp0FP32Zero, vdExp0, dataMask1); + AscendC::MicroAPI::Cast(vdExp0FP32One, vdExp0, dataMask1); + AscendC::MicroAPI::Interleave(vdExp0FP32Zero, vdExp0FP32One, vdExp0FP32Zero, vdExp0FP32One); + // 大于448.0的值设为448.0 + AscendC::MicroAPI::Compare(nanResult, vdExp0FP32Zero, maxFp8Value, dataMask1); + AscendC::MicroAPI::Select(vdExp0FP32Zero, maxFp8Value, vdExp0FP32Zero, nanResult); + AscendC::MicroAPI::Compare(nanResult, vdExp0FP32One, maxFp8Value, dataMask1); + AscendC::MicroAPI::Select(vdExp0FP32One, maxFp8Value, vdExp0FP32One, nanResult); + // 小于-448.0的值设为-448。0 + AscendC::MicroAPI::Compare(nanResult, vdExp0FP32Zero, minFp8Value, dataMask1); + AscendC::MicroAPI::Select(vdExp0FP32Zero, minFp8Value, vdExp0FP32Zero, nanResult); + AscendC::MicroAPI::Compare(nanResult, vdExp0FP32One, minFp8Value, dataMask1); + AscendC::MicroAPI::Select(vdExp0FP32One, minFp8Value, vdExp0FP32One, nanResult); + // 将结果转为FP8E4M3 + AscendC::MicroAPI::Cast(vdExp0FP8Zero, vdExp0FP32Zero, dataMask3); + AscendC::MicroAPI::Cast(vdExp0FP8One, vdExp0FP32One, dataMask3); + + AscendC::MicroAPI::Cast(vdExp1FP32Zero, vdExp1, dataMask2); + AscendC::MicroAPI::Cast(vdExp1FP32One, vdExp1, dataMask2); + AscendC::MicroAPI::Interleave(vdExp1FP32Zero, vdExp1FP32One, vdExp1FP32Zero, vdExp1FP32One); + // 大于448.0的值设为448.0 + AscendC::MicroAPI::Compare(nanResult, vdExp1FP32Zero, maxFp8Value, dataMask2); + AscendC::MicroAPI::Select(vdExp1FP32Zero, maxFp8Value, vdExp1FP32Zero, nanResult); + AscendC::MicroAPI::Compare(nanResult, vdExp1FP32One, maxFp8Value, dataMask2); + AscendC::MicroAPI::Select(vdExp1FP32One, maxFp8Value, vdExp1FP32One, nanResult); + // 小于-448.0的值设为-448。0 + AscendC::MicroAPI::Compare(nanResult, vdExp1FP32Zero, minFp8Value, dataMask2); + AscendC::MicroAPI::Select(vdExp1FP32Zero, minFp8Value, vdExp1FP32Zero, nanResult); + AscendC::MicroAPI::Compare(nanResult, vdExp1FP32One, minFp8Value, dataMask2); + AscendC::MicroAPI::Select(vdExp1FP32One, minFp8Value, vdExp1FP32One, nanResult); + // 将结果转为FP8E4M3 + AscendC::MicroAPI::Cast(vdExp1FP8Zero, vdExp1FP32Zero, dataMask4); + AscendC::MicroAPI::Cast(vdExp1FP8One, vdExp1FP32One, dataMask4); + AscendC::MicroAPI::StoreAlign( + outLocalAddr, (AscendC::MicroAPI::RegTensor &)vdExp0FP8Zero, OUT_ELE_NUM_ONE_BLK, dataMask3); + AscendC::MicroAPI::StoreAlign( + outLocalAddr, (AscendC::MicroAPI::RegTensor &)vdExp0FP8One, OUT_ELE_NUM_ONE_BLK, dataMask3); + AscendC::MicroAPI::StoreAlign( + outLocalAddr, (AscendC::MicroAPI::RegTensor &)vdExp1FP8Zero, OUT_ELE_NUM_ONE_BLK, dataMask4); + AscendC::MicroAPI::StoreAlign( + outLocalAddr, (AscendC::MicroAPI::RegTensor &)vdExp1FP8One, OUT_ELE_NUM_ONE_BLK, dataMask4); + } +} + +/** + * @brief DynamicQuantPerBlockMxfp8Vf 对row进行dynamicquant, BF16 ---> FP8E4M3, 每个BLOCK出一个系数。 + * @param outputLocal 输出tensor [row, col] + * @param outputScale 输出每行的反量化系数 [row, col/32] + * @param inputLocal 输入tensor [row, col] + * @param tmpLocal 临时buffer,所需空间大小row * col * 2 + * @param row 待处理的行数 + * @param col 待处理的列数 + */ +/** + shared_exp = floor(log2(max(|Vi|))) - emax + mxscale = 2^shared_exp + Pi = cast_to_dst_type(Vi/mxscale, round_mode) +**/ +template +__aicore__ inline void DynamicQuantPerBlockMxfp8Vf(const LocalTensor &outputLocal, + const LocalTensor &outputScale, + const LocalTensor &inputLocal, + const LocalTensor &tmpLocal, uint32_t row, uint32_t col) +{ + LocalTensor maxExpLocal = tmpLocal.ReinterpretCast(); + uint32_t totalScaleInUB = row * col / FP8_E4M3FN_BLOCK_SIZE; + uint32_t totalCountInUB = row * col; + uint16_t vecLen = AscendC::VECTOR_REG_WIDTH / sizeof(T); + uint16_t loopNum = (totalCountInUB + vecLen * DIGIT_TWO - 1) / (vecLen * DIGIT_TWO); + uint16_t loopNumScale = (totalScaleInUB + vecLen - 1) / vecLen; + + auto srcAddr = reinterpret_cast<__ubuf__ T *>(inputLocal.GetPhyAddr()); + auto maxExpAddr = reinterpret_cast<__ubuf__ uint16_t *>(maxExpLocal.GetPhyAddr()); + auto mxScaleLocalAddr = reinterpret_cast<__ubuf__ uint16_t *>(outputScale.GetPhyAddr()); + LocalTensor halfScaleLocal = maxExpLocal[totalCountInUB].template ReinterpretCast(); + auto halfScaleLocalAddr = reinterpret_cast<__ubuf__ uint16_t *>(halfScaleLocal.GetPhyAddr()); + auto outLocalAddr = reinterpret_cast<__ubuf__ int8_t *>(outputLocal.GetPhyAddr()); + ComputeMaxExpVF(srcAddr, maxExpAddr, totalCountInUB, loopNum, vecLen); + ComputeScaleVF(maxExpAddr, mxScaleLocalAddr, halfScaleLocalAddr, totalScaleInUB, loopNumScale, vecLen); + + srcAddr = reinterpret_cast<__ubuf__ T *>(inputLocal.GetPhyAddr()); + halfScaleLocalAddr = reinterpret_cast<__ubuf__ uint16_t *>(halfScaleLocal.GetPhyAddr()); + + uint32_t totalCountInUB2 = totalCountInUB * DIGIT_TWO; + ComputeDataVF(srcAddr, halfScaleLocalAddr, outLocalAddr, totalCountInUB, totalCountInUB2, loopNum, vecLen); +} + +/** + * @brief QuantPerTileVF 计算一行中每个tile的最大值,并计算量化参数和量化后的激活 + * @param outputLocal 输出tensor [row * col],row为rmsnorm输出的结果,均为1 + * @param inputLocal 输入tensor [row * col] + * @param quantScaleLocal 量化参数tensor [row, col / tileSize] + * @param row 处理数据的行数,默认为1 后续可拓展 + * @param col 处理数据的列数 + * @param tileSize tile的大小 当前只支持128,且col可被tileSize整除 + */ +template +__aicore__ inline void QuantPerTileVF(const LocalTensor &outputLocal, const LocalTensor &inputLocal, + const LocalTensor &quantScaleLocal, const uint32_t row, const uint32_t col, + const uint32_t tileSize) +{ + uint32_t cnt = row * col; + __ubuf__ T *inputBuf = (__ubuf__ T *)inputLocal.GetPhyAddr(); + __ubuf__ T *quantScaleBuf = (__ubuf__ T *)quantScaleLocal.GetPhyAddr(); + __ubuf__ O *outputBuf = (__ubuf__ O *)outputLocal.GetPhyAddr(); + uint32_t dtypeSize = sizeof(float); + uint16_t VL = AscendC::VECTOR_REG_WIDTH / dtypeSize; + uint16_t vfLoop = (tileSize + VL - 1) / VL; + constexpr float maxValue = std::is_same::value ? FP8_E4M3FN_MAX_VALUE : + std::is_same::value ? HIFLOAT8_MAX_VALUE : + INT8_MAX_VALUE; + const float alphaValue = static_cast(1.0) / maxValue; + uint32_t loopCount = cnt / tileSize; + for (uint32_t rowIndex = 0; rowIndex < loopCount; rowIndex++) { + ComputeVFImpl(inputBuf, outputBuf, quantScaleBuf + rowIndex, rowIndex, tileSize, + dtypeSize, VL, vfLoop, alphaValue); + } +} + +} // namespace MlaProlog +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_mul_qr.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_mul_qr.h new file mode 100644 index 0000000000000000000000000000000000000000..b2375018e5dce7ac70db0c153c06eb37326ef71a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_mul_qr.h @@ -0,0 +1,74 @@ +/** + * 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_mul_qr.h + * \brief + */ + +#ifndef VF_MUL_QR_H +#define VF_MUL_QR_H + +namespace MlaProlog { +template +__simd_vf__ void MulQrVFImpl(__ubuf__ T *inputBuf, __ubuf__ T *outputBuf, __ubuf__ T *dequantScaleBrcbBuf, + const uint16_t floatRepSize, uint16_t repeatTimes, float quantScaleCkvRope, + uint64_t computeBlockAlign) +{ + MicroAPI::MaskReg pregAll = MicroAPI::CreateMask(); + + for (uint16_t i = 0; i < repeatTimes; i++) { + MicroAPI::RegTensor vregSrc; + MicroAPI::RegTensor vregQuantScale; + MicroAPI::RegTensor vregDequantScaleVrcb; + MicroAPI::RegTensor vregMulScale; + MicroAPI::RegTensor vregRes; + uint16_t loopOffset = i * floatRepSize; // 计算数据偏移 + uint16_t dequantLoopOffset = i * computeBlockAlign; // 动态量化参数偏移 + + MicroAPI::LoadAlign(vregSrc, inputBuf + loopOffset); + // broadcast量化系数 + MicroAPI::LoadAlign(vregDequantScaleVrcb, + dequantScaleBrcbBuf + dequantLoopOffset); + MicroAPI::Duplicate(vregQuantScale, quantScaleCkvRope); + + MicroAPI::Div(vregMulScale, vregQuantScale, vregDequantScaleVrcb, pregAll); + + MicroAPI::Mul(vregRes, vregSrc, vregMulScale, pregAll); + + MicroAPI::StoreAlign(outputBuf + loopOffset, vregRes, pregAll); + } +} + +/** + * @brief MulQrVF 对于RopeQr输出的结果进行mul系数计算 + * @param outputLocal 输出tensor [subRow, colRope],row目前均为1 + * @param inputLocal 输入tensor [subRow, colRope] + * @param dequantScaleBrcbLocal 动态量化参数tensor [row, computeBlockAlign] + * @param quantScaleCkvRope 量化系数 + * @param computeSizeRope 输入参数的大小 subRow * colRope + * @param computeBlockAlign 输入动态量化参数的单个数据块存放多少个动态量化参数 + */ +template +__aicore__ inline void MulQrVF(const LocalTensor &outputLocal, const LocalTensor &inputLocal, + const LocalTensor &dequantScaleBrcbLocal, float quantScaleCkvRope, + uint64_t computeSizeRope, uint64_t computeBlockAlign) +{ + const uint16_t floatRepSize = 64; // 一个寄存器能够存放64个FP32 + uint16_t repeatTimes = (computeSizeRope + floatRepSize - 1) / floatRepSize; // 对尾块处理的扩展,循环处理的次数 + + __ubuf__ T *inputBuf = (__ubuf__ T *)inputLocal.GetPhyAddr(); + __ubuf__ T *outputBuf = (__ubuf__ T *)outputLocal.GetPhyAddr(); + __ubuf__ T *dequantScaleBrcbBuf = (__ubuf__ T *)dequantScaleBrcbLocal.GetPhyAddr(); + MulQrVFImpl(inputBuf, outputBuf, dequantScaleBrcbBuf, floatRepSize, repeatTimes, quantScaleCkvRope, + computeBlockAlign); +} +} // namespace MlaProlog +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_quant_perchannel.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_quant_perchannel.h new file mode 100644 index 0000000000000000000000000000000000000000..2b9a5a97306390d3304241f61c95123033515eab --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_quant_perchannel.h @@ -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 vf_quant_perchannel.h + * \brief + */ + +#ifndef VF_QUANT_PERCHANNEL_H +#define VF_QUANT_PERCHANNEL_H +#include "kernel_tensor.h" + +namespace MlaProlog { + +template +__simd_vf__ void QuantChannelVFImpl(__ubuf__ O *yAddr, __ubuf__ T *xAddr, __ubuf__ C *quantScaleAddr, + const uint32_t floatRepSize, uint32_t dLoops, uint32_t dTail, uint32_t dTailLoop, + uint32_t row, uint32_t col, uint32_t stride) +{ + AscendC::MicroAPI::RegTensor vregInput; + AscendC::MicroAPI::RegTensor vregQuantScale; + AscendC::MicroAPI::RegTensor vregOutput; + AscendC::MicroAPI::RegTensor vregOutputHalf; // float-->half-->int8 + AscendC::MicroAPI::MaskReg fullMask = AscendC::MicroAPI::CreateMask(); + AscendC::MicroAPI::MaskReg tailMask; + tailMask = AscendC::MicroAPI::UpdateMask(dTail); + constexpr static AscendC::MicroAPI::CastTrait castTraitPack2 = { + AscendC::MicroAPI::RegLayout::ZERO, AscendC::MicroAPI::SatMode::SAT, AscendC::MicroAPI::MaskMergeMode::ZEROING, + AscendC::RoundMode::CAST_RINT}; + constexpr static AscendC::MicroAPI::CastTrait castTraitF32ToHalf = { + AscendC::MicroAPI::RegLayout::ZERO, AscendC::MicroAPI::SatMode::NO_SAT, + AscendC::MicroAPI::MaskMergeMode::ZEROING, RoundMode::CAST_ODD}; + + uint32_t colOffset = 0; + uint32_t rowOffset = 0; + for (uint32_t j = 0; j < dLoops; j++) { + AscendC::MicroAPI::LoadAlign(vregQuantScale, + quantScaleAddr + colOffset); + rowOffset = 0; + for (uint32_t i = 0; i < row; i++) { + AscendC::MicroAPI::LoadAlign(vregInput, + xAddr + colOffset + rowOffset); + AscendC::MicroAPI::Mul(vregInput, vregInput, vregQuantScale, fullMask); + AscendC::MicroAPI::Cast(vregOutputHalf, vregInput, fullMask); + AscendC::MicroAPI::Cast(vregOutput, vregOutputHalf, fullMask); + AscendC::MicroAPI::StoreAlign( + yAddr + colOffset + rowOffset, vregOutput, fullMask); + rowOffset += stride; + } + colOffset += floatRepSize; + } + + if (dTailLoop > 0) { + rowOffset = 0; + AscendC::MicroAPI::LoadAlign(vregQuantScale, + quantScaleAddr + dLoops * floatRepSize); + for (uint32_t i = 0; i < row; i++) { + AscendC::MicroAPI::LoadAlign( + vregInput, xAddr + dLoops * floatRepSize + rowOffset); + AscendC::MicroAPI::Mul(vregInput, vregInput, vregQuantScale, tailMask); + AscendC::MicroAPI::Cast(vregOutputHalf, vregInput, tailMask); + AscendC::MicroAPI::Cast(vregOutput, vregOutputHalf, tailMask); + AscendC::MicroAPI::StoreAlign( + yAddr + dLoops * floatRepSize + rowOffset, vregOutput, tailMask); + rowOffset += stride; + } + } +} + +/** + * @brief QuantPerChannelVF 同时对row进行FP32到int8的per-channel量化操作。一行中的每一列用不同的量化参数。 + outLocal[i , j] = inputLocal[i , j] * quantScaleLocal[j] + * @param outputLocal 输出tensor [row, col] + * @param inputLocal 输入tensor [row, col] + * @param quantScaleLocal 量化参数tensor [1, col] + * @param row 处理数据的行数 默认为1 后续可扩展 + * @param col 处理数据的列数 + * @param stride 待处理数据一行的真实长度 + */ +template +__aicore__ inline void QuantPerChannelVf(const LocalTensor &outputLocal, const LocalTensor &inputLocal, + const LocalTensor &quantScaleLocal, const uint32_t row, const uint32_t col, + const uint32_t stride) +{ + __ubuf__ O *outputUb = (__ubuf__ O *)outputLocal.GetPhyAddr(); + __ubuf__ T *inputUb = (__ubuf__ T *)inputLocal.GetPhyAddr(); + __ubuf__ C *quantScaleUb = (__ubuf__ C *)quantScaleLocal.GetPhyAddr(); + + const uint32_t floatRepSize = 64; // 一个寄存器能够存放64个FP32 + uint32_t dLoops = col / floatRepSize; + uint32_t dTail = col % floatRepSize; + uint32_t dTailLoop = dTail > 0 ? 1 : 0; + + QuantChannelVFImpl(outputUb, inputUb, quantScaleUb, floatRepSize, dLoops, dTail, dTailLoop, row, col, stride); +} +} // namespace MlaProlog +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_quant_pertensor.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_quant_pertensor.h new file mode 100644 index 0000000000000000000000000000000000000000..9339b00712b604a1d87ac76969f23083a9ec4216 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_quant_pertensor.h @@ -0,0 +1,89 @@ +/** + * 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_quant_pertensor.h + * \brief + */ + +#ifndef VF_QUANT_PERTENSOR_H +#define VF_QUANT_PERTENSOR_H +#include "kernel_tensor.h" + +namespace MlaProlog { +template +__simd_vf__ void QuantPerTensorVFImpl(__ubuf__ T *inputBuf, __ubuf__ T *quantScaleBuf, __ubuf__ U *outputBuf, + uint32_t cnt, const uint16_t floatRepSize, uint16_t repeatTimes) +{ + MicroAPI::MaskReg pregAll = MicroAPI::CreateMask(); + + // float -> fp8e4m3 类型转换模式结构体 + static constexpr MicroAPI::CastTrait CAST_TRAITF322FP8E4M3 = { + MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::SAT, MicroAPI::MaskMergeMode::ZEROING, RoundMode::CAST_RINT}; + static constexpr MicroAPI::CastTrait CAST_TRAIT = {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::SAT, + MicroAPI::MaskMergeMode::ZEROING, RoundMode::CAST_RINT}; + static constexpr MicroAPI::CastTrait CAST_TRAITB162F32 = {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::UNKNOWN, + MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + static constexpr MicroAPI::CastTrait CAST_TRAITF322HIF8 = {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::SAT, + MicroAPI::MaskMergeMode::ZEROING, RoundMode::CAST_ROUND}; + static constexpr MicroAPI::CastTrait castTraitF32ToHalf = {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::NO_SAT, + MicroAPI::MaskMergeMode::ZEROING, RoundMode::CAST_ODD}; + MicroAPI::RegTensor vregSrc; + MicroAPI::RegTensor vregQuantScale; + MicroAPI::RegTensor vregFloat; + MicroAPI::RegTensor vregRes; + MicroAPI::RegTensor yHalf; + // 量化系数broadcast到寄存器所有位置 + MicroAPI::LoadAlign(vregQuantScale, quantScaleBuf); + for (uint16_t i = 0; i < uint16_t(repeatTimes); i++) { + uint16_t loopOffset = i * floatRepSize; + if constexpr (std::is_same::value) { + MicroAPI::LoadAlign(vregFloat, inputBuf + loopOffset); + } else if constexpr (std::is_same::value) { + MicroAPI::LoadAlign(vregSrc, inputBuf + loopOffset); + MicroAPI::Cast(vregFloat, vregSrc, pregAll); + } + MicroAPI::Mul(vregFloat, vregFloat, vregQuantScale, pregAll); + if constexpr (std::is_same::value) { + MicroAPI::Cast(vregRes, vregFloat, pregAll); + } else if constexpr (std::is_same::value) { + MicroAPI::Cast(yHalf, vregFloat, pregAll); + MicroAPI::Cast(vregRes, yHalf, pregAll); + } else { + MicroAPI::Cast(vregRes, vregFloat, pregAll); + } + MicroAPI::StoreAlign(outputBuf + loopOffset, vregRes, pregAll); + } +} + +/** + * @brief QuantPerTensorVF 对一行进行mul,并量化到fp8e4m3 T float U fp8e4m3 可根据不同量化结果扩展 + * @param outputLocal 输出tensor [row, col],row为rmsnorm输出的结果,均为1 + * @param inputLocal 输入tensor [row, col] + * @param quantScaleLocal 量化参数tensor [row, 1] + * @param row 处理数据的行数 默认为1 后续可扩展 + * @param col 处理数据的列数 + */ +template +__aicore__ inline void QuantPerTensorVF(const LocalTensor &outputLocal, const LocalTensor &inputLocal, + const LocalTensor &quantScaleLocal, const uint32_t row, const uint32_t col) +{ + uint32_t cnt = row * col; + const uint16_t floatRepSize = 64; // 一个寄存器能够存放64个FP32 + uint16_t repeatTimes = (cnt + floatRepSize - 1) / floatRepSize; // 对尾块处理的扩展,循环处理的次数 + + __ubuf__ T *inputBuf = (__ubuf__ T *)inputLocal.GetPhyAddr(); + __ubuf__ T *quantScaleBuf = (__ubuf__ T *)quantScaleLocal.GetPhyAddr(); + __ubuf__ U *outputBuf = (__ubuf__ U *)outputLocal.GetPhyAddr(); + + QuantPerTensorVFImpl(inputBuf, quantScaleBuf, outputBuf, cnt, floatRepSize, repeatTimes); +} +} // namespace MlaProlog +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_rms_norm.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_rms_norm.h new file mode 100644 index 0000000000000000000000000000000000000000..171cd9d5eb0e62fca8c3b6045167e33682fabfa7 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_rms_norm.h @@ -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 vf_rms_norm.h + * \brief + */ + +#ifndef VF_RMS_NORM_H +#define VF_RMS_NORM_H +#include "kernel_tensor.h" + +namespace MlaProlog { +constexpr uint64_t FLOAT_REP_SIZE = 64; + +template +__simd_vf__ void RmsNormVFImpl(__ubuf__ InType *inputBuf, __ubuf__ GammaType *gammaBuf, __ubuf__ OutType *outputBuf, + uint32_t cnt, uint32_t repeatTimes, const RmsNormParam rmsNormParams) +{ + MicroAPI::RegTensor vregSum; + MicroAPI::RegTensor vregSumReduce; + MicroAPI::RegTensor vregDiv; + MicroAPI::RegTensor vregSquareRoot; + + MicroAPI::MaskReg pregAll = MicroAPI::CreateMask(); + MicroAPI::MaskReg pregFirst = MicroAPI::CreateMask(); + + static constexpr MicroAPI::CastTrait castTraitB162B32 = {MicroAPI::RegLayout::ZERO, MicroAPI::SatMode::UNKNOWN, + MicroAPI::MaskMergeMode::ZEROING, RoundMode::UNKNOWN}; + + MicroAPI::Duplicate(vregSum, 0.0); + + for (uint16_t i = 0; i < uint16_t(repeatTimes); ++i) { + MicroAPI::RegTensor vregXCast; + MicroAPI::RegTensor vregXSquare; + uint64_t loopOffset = i * FLOAT_REP_SIZE; + + MicroAPI::LoadAlign(vregXCast, inputBuf + loopOffset); + MicroAPI::Mul(vregXSquare, vregXCast, vregXCast, pregAll); + MicroAPI::Add(vregSum, vregXSquare, vregSum, pregAll); + } + + MicroAPI::Reduce(vregSumReduce, vregSum, + pregAll); + MicroAPI::Muls(vregSumReduce, vregSumReduce, rmsNormParams.reciprocal, + pregFirst); + MicroAPI::Adds(vregSumReduce, vregSumReduce, rmsNormParams.epsilon, + pregFirst); + MicroAPI::Sqrt(vregSquareRoot, vregSumReduce, pregFirst); + MicroAPI::Duplicate(vregDiv, vregSquareRoot, + pregAll); + + for (uint16_t i = 0; i < uint16_t(repeatTimes); ++i) { + MicroAPI::RegTensor vregXCast; + MicroAPI::RegTensor vregGamma; + MicroAPI::RegTensor vregGammaCast; + uint16_t loopOffset = i * FLOAT_REP_SIZE; + + MicroAPI::LoadAlign(vregXCast, inputBuf + loopOffset); + MicroAPI::LoadAlign(vregGamma, gammaBuf + loopOffset); + MicroAPI::Cast(vregGammaCast, vregGamma, pregAll); + + MicroAPI::Div(vregXCast, vregXCast, vregDiv, pregAll); + MicroAPI::Mul(vregXCast, vregXCast, vregGammaCast, pregAll); + + MicroAPI::StoreAlign(outputBuf + loopOffset, vregXCast, pregAll); + } +} + +/** + * @brief RmsNormVF 对一行进行rmsnorm + * @param outputLocal 输出tensor [row, col],row目前均为1 + * @param inputLocal 输入tensor [row, col] + * @param gammaLocal gamma参数tensor [row, col] + * @param rmsNormParams rmsNrom计算所需系数,包括 + row 行数 + col 列数,对应headSizeCq或headSizeCkv + reciprocal ,1/N + epsilon,防止除零极小数 + */ +template +__aicore__ inline void RmsNormVF(const LocalTensor &outputLocal, const LocalTensor &inputLocal, + const LocalTensor &gammaLocal, const RmsNormParam rmsNormParams) +{ + uint32_t cnt = rmsNormParams.row * rmsNormParams.col; + uint32_t repeatTimes = (cnt + FLOAT_REP_SIZE - 1) / FLOAT_REP_SIZE; + + __ubuf__ InType *inputBuf = (__ubuf__ InType *)inputLocal.GetPhyAddr(); + __ubuf__ GammaType *gammaBuf = (__ubuf__ GammaType *)gammaLocal.GetPhyAddr(); + __ubuf__ OutType *outputBuf = (__ubuf__ OutType *)outputLocal.GetPhyAddr(); + + RmsNormVFImpl(inputBuf, gammaBuf, outputBuf, cnt, repeatTimes, rmsNormParams); + + if (unlikely(rmsNormParams.isScaleEnable)) { + AscendC::PipeBarrier(); + Muls(outputLocal, outputLocal, rmsNormParams.scale, cnt); + } +} +} // namespace MlaProlog +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_rope.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_rope.h new file mode 100644 index 0000000000000000000000000000000000000000..c1c4481f75c0ad29fd20f0ce775b3814169e0db3 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/arch35/vf/vf_rope.h @@ -0,0 +1,91 @@ +/** + * 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_rope.h + * \brief VF implementation for mla_prolog rope path (interleave-half mode). + */ + +#ifndef VF_ROPE_H +#define VF_ROPE_H + +#include "kernel_tensor.h" +#include "vf_comm.h" + +namespace MlaProlog { + +template +__simd_vf__ inline void RopeVFImpl(__ubuf__ C *outputUb, __ubuf__ C *inputUb, __ubuf__ C *sinUb, __ubuf__ C *cosUb, + uint32_t row, uint64_t srcStride, uint64_t dstStride, uint64_t sinCosStride) +{ + MicroAPI::RegTensor vregX; + MicroAPI::RegTensor vregSin; + MicroAPI::RegTensor vregCos; + MicroAPI::RegTensor vregEven; + MicroAPI::RegTensor vregOdd; + MicroAPI::RegTensor vregHigh; + MicroAPI::RegTensor vregLow; + MicroAPI::RegTensor vregTemp; + MicroAPI::RegTensor vregRes; + + MicroAPI::MaskReg maskAll = MicroAPI::CreateMask(); + MicroAPI::MaskReg maskLowHalf = MicroAPI::CreateMask(); + MicroAPI::MaskReg maskHighHalf; + MicroAPI::Not(maskHighHalf, maskLowHalf, maskAll); + + for (uint16_t i = 0; i < row; ++i) { + __ubuf__ C *curXUb = inputUb + i * srcStride; + __ubuf__ C *curResUb = outputUb + i * dstStride; + __ubuf__ C *curSinUb = sinUb + i * sinCosStride; + __ubuf__ C *curCosUb = cosUb + i * sinCosStride; + + MicroAPI::LoadAlign(vregX, curXUb); + MicroAPI::LoadAlign(vregSin, curSinUb); + MicroAPI::LoadAlign(vregCos, curCosUb); + + // vregEven = [evens(0..31), evens(32..63)] + // vregOdd = [odds(0..31), odds(32..63)] + MicroAPI::DeInterleave(vregEven, vregOdd, vregX, vregX); + + // Part1 low = cos * evens, Part1 high preserved + MicroAPI::Mul(vregRes, vregCos, vregEven, maskLowHalf); + // Part1 high = sin * evens, Part1 low preserved + MicroAPI::Mul(vregTemp, vregSin, vregEven, maskHighHalf); + // Part2 low = sin(-) * odds, Part2 high preserved + MicroAPI::Mul(vregLow, vregSin, vregOdd, maskLowHalf); + // Part2 high = cos * odds, Part2 low preserved + MicroAPI::Mul(vregHigh, vregCos, vregOdd, maskHighHalf); + + // Part1 = [cos_l*even + sin_l*odd, cos_u*odd + sin_u*even] = [y_lower, y_upper] + MicroAPI::Add(vregRes, vregRes, vregLow, maskLowHalf); + MicroAPI::Add(vregTemp, vregTemp, vregHigh, maskHighHalf); + MicroAPI::Move(vregRes, vregTemp, maskHighHalf); + + MicroAPI::StoreAlign(curResUb, vregRes, maskAll); + } +} + + +// col == 64 +template +__aicore__ inline void RotaryPosEmbVF(const LocalTensor &outputLocal, const LocalTensor &inputLocal, + const LocalTensor &cosLocal, const LocalTensor &sinLocal, uint32_t row, + uint64_t srcStride, uint64_t dstStride, uint64_t sinCosStride) +{ + __ubuf__ C *inputUb = (__ubuf__ C *)inputLocal.GetPhyAddr(); + __ubuf__ C *sinUb = (__ubuf__ C *)sinLocal.GetPhyAddr(); + __ubuf__ C *cosUb = (__ubuf__ C *)cosLocal.GetPhyAddr(); + __ubuf__ C *outputUb = (__ubuf__ C *)outputLocal.GetPhyAddr(); + + RopeVFImpl(outputUb, inputUb, sinUb, cosUb, row, srcStride, dstStride, sinCosStride); +} +} // namespace MlaProlog + +#endif // VF_ROPE_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/mla_prolog.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/mla_prolog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b803eec8db3b961f248ce4b77cf6999224bc2607 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/mla_prolog.cpp @@ -0,0 +1,87 @@ +/** + * 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 mla_prolog.cpp + * \brief + */ + +#define MLA_PROLOG_VERSION 1 +#if __CCE_AICORE__ == 310 +#include "arch35/kernel_mla_prolog_split_n.h" +#else +#include "arch22/kernel_mla_prolog_split_n.h" +#endif +using namespace MlaProlog; + +template +__global__ __aicore__ void +mla_prolog(__gm__ uint8_t *tokenX, __gm__ uint8_t *weightDq, __gm__ uint8_t *weightUqQr, __gm__ uint8_t *weightUk, + __gm__ uint8_t *weightDkvKr, __gm__ uint8_t *rmsnormGammaCq, __gm__ uint8_t *rmsnormGammaCkv, + __gm__ uint8_t *ropeSin, __gm__ uint8_t *ropeCos, __gm__ uint8_t *cacheIndex, __gm__ uint8_t *kvCache, + __gm__ uint8_t *krCache, __gm__ uint8_t *dequantScaleX, __gm__ uint8_t *dequantScaleWDq, + __gm__ uint8_t *dequantScaleWUqQr, __gm__ uint8_t *dequantScaleWDkvKr, __gm__ uint8_t *quantScaleCkv, + __gm__ uint8_t *quantScaleCkr, __gm__ uint8_t *smoothScalesCq, __gm__ uint8_t *queryOut, + __gm__ uint8_t *queryRopeOut, __gm__ uint8_t *kvCacheOut, __gm__ uint8_t *krCacheOut, + __gm__ uint8_t *workspace, __gm__ uint8_t *tiling) +{ + REGISTER_TILING_DEFAULT(optiling::MlaPrologTilingData); + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); + + constexpr auto emptyMode = static_cast(EmptyTensorMode); + if constexpr (emptyMode == EMPTY_TENSOR_MODE::EMPTY_QUERY) { + return; + } + constexpr auto cacheMode = static_cast(CacheMode); + constexpr auto actualSeqLenMode = static_cast(ActualSeqLenMode); + constexpr auto splitMMode = static_cast(SplitMMode); + constexpr uint32_t cvRatio = CvMode == ASCENDC_TPL_MIX_AIC_1_1 ? 1 : 2; + + + GET_TILING_DATA_WITH_STRUCT(optiling::MlaPrologTilingData, tilingDataIn, tiling); + const optiling::MlaPrologTilingData *__restrict tilingData = nullptr; + const optiling::MlaPrologBaseParams *__restrict tilingDataBaseParams = &tilingDataIn.baseParams; + + TPipe pipe; + + if constexpr (static_cast(Scenario) == SCENARIO::NO_QUANT) { + MlaPrologVecS1CubS2> + op(&pipe, tilingData, tilingDataBaseParams); + op.Init(tokenX, weightDq, weightUqQr, weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv, ropeSin, ropeCos, + cacheIndex, kvCacheOut, krCacheOut, dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, + dequantScaleWDkvKr, quantScaleCkv, quantScaleCkr, smoothScalesCq, nullptr, nullptr, queryOut, + queryRopeOut, nullptr, nullptr, nullptr, workspace); + op.Process(); + + } else if constexpr (static_cast(Scenario) == SCENARIO::QUANT && + static_cast(QuantMode) == QUANT_MODE::PARTIAL_QUANT_KV_NO_QUANT) { + MlaPrologVecS1CubS2> + op(&pipe, tilingData, tilingDataBaseParams); + op.Init(tokenX, weightDq, weightUqQr, weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv, ropeSin, ropeCos, + cacheIndex, kvCacheOut, krCacheOut, dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, + dequantScaleWDkvKr, quantScaleCkv, quantScaleCkr, smoothScalesCq, nullptr, nullptr, queryOut, + queryRopeOut, nullptr, nullptr, nullptr, workspace); + op.Process(); + + } else if constexpr (static_cast(Scenario) == SCENARIO::QUANT && + static_cast(QuantMode) == QUANT_MODE::PARTIAL_QUANT_KV_QUANT_PER_CHANNEL) { + MlaPrologVecS1CubS2> + op(&pipe, tilingData, tilingDataBaseParams); + op.Init(tokenX, weightDq, weightUqQr, weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv, ropeSin, ropeCos, + cacheIndex, kvCacheOut, krCacheOut, dequantScaleX, dequantScaleWDq, dequantScaleWUqQr, + dequantScaleWDkvKr, quantScaleCkv, quantScaleCkr, smoothScalesCq, nullptr, nullptr, queryOut, + queryRopeOut, nullptr, nullptr, nullptr, workspace); + op.Process(); + } +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/mla_prolog_template_tiling_key.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/mla_prolog_template_tiling_key.h new file mode 100644 index 0000000000000000000000000000000000000000..bf5a3326f92667a471586fbc462197c8ac5cf658 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/mla_prolog_template_tiling_key.h @@ -0,0 +1,664 @@ +/** + * 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 mla_prolog_template_tiling_key.h + * \brief + */ + +#ifndef MLA_PROLOG_TEMPLATE_TILING_KEY_H +#define MLA_PROLOG_TEMPLATE_TILING_KEY_H + +#ifndef ORIG_DTYPE_TOKEN_X +#define ORIG_DTYPE_TOKEN_X (-1) +#endif + +#ifndef ORIG_DTYPE_WEIGHT_UQ_QR +#define ORIG_DTYPE_WEIGHT_UQ_QR (-1) +#endif + +#ifndef ORIG_DTYPE_KV_CACHE +#define ORIG_DTYPE_KV_CACHE (-1) +#endif + +#ifndef ORIG_DTYPE_KR_CACHE +#define ORIG_DTYPE_KR_CACHE (-1) +#endif + +#ifndef ORIG_DTYPE_QUERY +#define ORIG_DTYPE_QUERY (-1) +#endif + +#ifndef ORIG_DTYPE_DEQUANT_SCALE_X +#define ORIG_DTYPE_DEQUANT_SCALE_X (-1) +#endif + +#ifndef MLA_PROLOG_VERSION +#define MLA_PROLOG_VERSION (-1) +#endif + +#include "ascendc/host_api/tiling/template_argument.h" + +#define ASCENDC_TPL_2_BW 2 // 每个参数占用2个bit位 +#define ASCENDC_TPL_4_BW 4 // 每个参数占用4个bit位 +#define ASCENDC_TPL_6_BW 6 // 每个参数占用6个bit位 + +// 可表示的tilingkey范围为64bit,注意不可超过限制 +ASCENDC_TPL_ARGS_DECL( + mla_prolog, // 算子唯一标识,与opType保持一致 + // bit:0-3 CACHE_MODE:0-ND 1-PA_BSND 2-PA_NZ 3-PA_BLK_BSND 4-PA_BLK_NZ + ASCENDC_TPL_UINT_DECL(CACHE_MODE, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, 0, 1, 2, 3, 4), + // bit:4-5 场景标识:0-FP16(预留) 1-BF16 2-量化场景 + ASCENDC_TPL_UINT_DECL(SCENARIO, ASCENDC_TPL_2_BW, ASCENDC_TPL_UI_LIST, 0, 1, 2), + // bit:6-11 量化场景:0-非量化 1-MMQcQr量化 2-MMQcQr量化+KVcache量化 3-MMcqCkvKr量化+MMQcQr量化 + // 4-MMCqCkvkr量化+MMQcQr量化+KVcache量化 5-MMQcQr量化+KVcache pertoken-pergroup量化 + // 6-MMCqCkvkr量化+MMQcQr量化+KVcache pertoken-pergroup量化 + // 7-Mxfp8量化+MMCqCkvkr量化+MMQcQr量化 8-Mxfp8量化+MMCqCkvkr量化+MMQcQr量化+KVcache量化 + // 9-Mxfp8量化+MMCqCkvkr量化+MMQcQr量化+KVcache pertoken-pergroup量化 + // 10-fp8量化+MMcqCkvKr量化+MMQcQr量化 11-fp8量化+MMCqCkvkr量化+MMQcQr量化+KVcache量化 + // 12-hif8量化+MMcqCkvKr量化+MMQcQr量化 13-hif8量化+MMCqCkvkr量化+MMQcQr量化+KVcache量化 + // 14-fp8量化+MMcqCkvKr量化+MMQcQr量化+KVcache pertoken-pergroup量化 + // 15-hif8量化+MMCqCkvkr量化+MMQcQr量化+KVcache pertoken-pergroup量化 + ASCENDC_TPL_UINT_DECL(QUANT_MODE, ASCENDC_TPL_4_BW, ASCENDC_TPL_UI_LIST, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15), + // bit:12 反量化使能:0-关闭 1-开启 + ASCENDC_TPL_BOOL_DECL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + // bit:13 量化算力分组:0-关闭 1-开启 + ASCENDC_TPL_BOOL_DECL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0, 1), + // bit:14-15 空tensor场景:0-无空tensor 1-kv_cache/kr_cache为空 2-query为空且不更新cache + ASCENDC_TPL_UINT_DECL(EMPTY_TENSOR_MODE, ASCENDC_TPL_2_BW, ASCENDC_TPL_UI_LIST, 0, 1, 2), + // bit:16-17 actualSeqLen使能场景 0-关闭 1-使能actualSeqLen + ASCENDC_TPL_UINT_DECL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_2_BW, ASCENDC_TPL_UI_LIST, 0, 1), + // bit:18-19 切M模式 0-关闭(切N) 1-使能(切M) + ASCENDC_TPL_UINT_DECL(SPLIT_M_MODE, ASCENDC_TPL_2_BW, ASCENDC_TPL_UI_LIST, 0, 1), + // bit:20-25 cv分核模式 ASCENDC_TPL_MIX_AIC_1_1(6)-1:1 ASCENDC_TPL_MIX_AIC_1_2(7)-1:2 + ASCENDC_TPL_KERNEL_TYPE_DECL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2)); + +ASCENDC_TPL_SEL( + +#if MLA_PROLOG_VERSION == -1 || MLA_PROLOG_VERSION >= 1 +// -------------------------- 非量化场景 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_BF16 && ORIG_DTYPE_WEIGHT_UQ_QR == DT_BF16) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif + +// -------------------------- 半量化kv非量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_BF16 && ORIG_DTYPE_WEIGHT_UQ_QR == DT_INT8 && ORIG_DTYPE_KV_CACHE == DT_BF16) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0, 1), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0, 1), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0, 1), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif + +// -------------------------- 半量化kv perchannel量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + ORIG_DTYPE_KR_CACHE == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_BF16 && ORIG_DTYPE_WEIGHT_UQ_QR == DT_INT8 && ORIG_DTYPE_KV_CACHE == DT_INT8 && \ + ORIG_DTYPE_KR_CACHE == DT_INT8) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0, 1), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0, 1), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0, 1), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif +#endif + +#if MLA_PROLOG_VERSION == -1 || MLA_PROLOG_VERSION >= 2 +// -------------------------- 全量化kv非量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_INT8 && ORIG_DTYPE_WEIGHT_UQ_QR == DT_INT8 && ORIG_DTYPE_KV_CACHE == DT_BF16) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 3), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 3), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 3), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif + +// -------------------------- 全量化kv pertensor量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + ORIG_DTYPE_KR_CACHE == -1 || ORIG_DTYPE_QUERY == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_INT8 && ORIG_DTYPE_WEIGHT_UQ_QR == DT_INT8 && ORIG_DTYPE_KV_CACHE == DT_INT8 && \ + ORIG_DTYPE_KR_CACHE == DT_BF16 && ORIG_DTYPE_QUERY == DT_INT8) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 4), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 4), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 4), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif +#endif + +#if MLA_PROLOG_VERSION == -1 || MLA_PROLOG_VERSION == 3 +// -------------------------- 半量化kv pertoken-pergroup量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_BF16 && ORIG_DTYPE_WEIGHT_UQ_QR == DT_INT8 && ORIG_DTYPE_KV_CACHE == DT_INT8) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 5), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 5), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif + +// -------------------------- 全量化kv pertoken-pergroup量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + ORIG_DTYPE_QUERY == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_INT8 && ORIG_DTYPE_WEIGHT_UQ_QR == DT_INT8 && ORIG_DTYPE_KV_CACHE == DT_INT8 && \ + ORIG_DTYPE_QUERY == DT_BF16) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 6), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif + +// -------------------------- Mxfp8全量化kv非量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + ORIG_DTYPE_DEQUANT_SCALE_X == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_FLOAT8_E4M3FN && ORIG_DTYPE_WEIGHT_UQ_QR == DT_FLOAT8_E4M3FN && \ + ORIG_DTYPE_KV_CACHE == DT_BF16 && ORIG_DTYPE_DEQUANT_SCALE_X == DT_FLOAT8_E8M0) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 7), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif + +// -------------------------- Mxfp8全量化kv量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + ORIG_DTYPE_KR_CACHE == -1 || ORIG_DTYPE_DEQUANT_SCALE_X == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_FLOAT8_E4M3FN && ORIG_DTYPE_WEIGHT_UQ_QR == DT_FLOAT8_E4M3FN && \ + ORIG_DTYPE_KV_CACHE == DT_FLOAT8_E4M3FN && ORIG_DTYPE_KR_CACHE == DT_BF16 && \ + ORIG_DTYPE_DEQUANT_SCALE_X == DT_FLOAT8_E8M0) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 8), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif + +// -------------------------- Mxfp8全量化kv pertoken-pergroup量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + ORIG_DTYPE_DEQUANT_SCALE_X == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_FLOAT8_E4M3FN && ORIG_DTYPE_WEIGHT_UQ_QR == DT_FLOAT8_E4M3FN && \ + ORIG_DTYPE_KV_CACHE == DT_FLOAT8_E4M3FN && ORIG_DTYPE_DEQUANT_SCALE_X == DT_FLOAT8_E8M0) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 9), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif + +// -------------------------- fp8全量化kv非量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + ORIG_DTYPE_DEQUANT_SCALE_X == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_FLOAT8_E4M3FN && ORIG_DTYPE_WEIGHT_UQ_QR == DT_FLOAT8_E4M3FN && \ + ORIG_DTYPE_KV_CACHE == DT_BF16 && ORIG_DTYPE_DEQUANT_SCALE_X == DT_FLOAT) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 10), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 10), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 10), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif + +// -------------------------- fp8全量化kv pertensor量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + ORIG_DTYPE_KR_CACHE == -1 || ORIG_DTYPE_QUERY == -1 || ORIG_DTYPE_DEQUANT_SCALE_X == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_FLOAT8_E4M3FN && ORIG_DTYPE_WEIGHT_UQ_QR == DT_FLOAT8_E4M3FN && \ + ORIG_DTYPE_KV_CACHE == DT_FLOAT8_E4M3FN && ORIG_DTYPE_KR_CACHE == DT_BF16 && \ + ORIG_DTYPE_QUERY == DT_FLOAT8_E4M3FN && ORIG_DTYPE_DEQUANT_SCALE_X == DT_FLOAT) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 11), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 11), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 11), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif +// -------------------------- hif8全量化kv非量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_HIFLOAT8 && ORIG_DTYPE_WEIGHT_UQ_QR == DT_HIFLOAT8 && ORIG_DTYPE_KV_CACHE == DT_BF16) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 12), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 12), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 12), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif + +// -------------------------- hif8全量化kv pertensor量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + ORIG_DTYPE_KR_CACHE == -1 || ORIG_DTYPE_QUERY == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_HIFLOAT8 && ORIG_DTYPE_WEIGHT_UQ_QR == DT_HIFLOAT8 && \ + ORIG_DTYPE_KV_CACHE == DT_HIFLOAT8 && ORIG_DTYPE_KR_CACHE == DT_BF16 && ORIG_DTYPE_QUERY == DT_HIFLOAT8) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1, 2, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 13), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 13), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 3, 4), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 13), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif + +// -------------------------- fp8全量化kv pertoken-pergroup量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + ORIG_DTYPE_QUERY == -1 || ORIG_DTYPE_DEQUANT_SCALE_X == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_FLOAT8_E4M3FN && ORIG_DTYPE_WEIGHT_UQ_QR == DT_FLOAT8_E4M3FN && \ + ORIG_DTYPE_KV_CACHE == DT_FLOAT8_E4M3FN && ORIG_DTYPE_QUERY == DT_BF16 && ORIG_DTYPE_DEQUANT_SCALE_X == DT_FLOAT) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 14), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 14), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif + +// -------------------------- hif8全量化kv pertoken-pergroup量化 -------------------------- +#if ORIG_DTYPE_TOKEN_X == -1 || ORIG_DTYPE_WEIGHT_UQ_QR == -1 || ORIG_DTYPE_KV_CACHE == -1 || \ + ORIG_DTYPE_QUERY == -1 || ORIG_DTYPE_DEQUANT_SCALE_X == -1 || \ + (ORIG_DTYPE_TOKEN_X == DT_HIFLOAT8 && ORIG_DTYPE_WEIGHT_UQ_QR == DT_HIFLOAT8 && \ + ORIG_DTYPE_KV_CACHE == DT_HIFLOAT8 && ORIG_DTYPE_QUERY == DT_BF16 && ORIG_DTYPE_DEQUANT_SCALE_X == DT_FLOAT) + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 1), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 15), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), + + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 15), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0, 1), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0, 1), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData)), +#endif +#endif + + // -------------------------- 空tensor场景 -------------------------- + ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_UINT_SEL(CACHE_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SCENARIO, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(QUANT_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_DEQUANT_OPTIONAL, 0), + ASCENDC_TPL_BOOL_SEL(ENABLE_GROUP_COMPUTE_OPTIONAL, 0), + ASCENDC_TPL_UINT_SEL(EMPTY_TENSOR_MODE, ASCENDC_TPL_UI_LIST, 2), + ASCENDC_TPL_UINT_SEL(ACTUAL_SEQ_LEN_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_UINT_SEL(SPLIT_M_MODE, ASCENDC_TPL_UI_LIST, 0), + ASCENDC_TPL_SHARED_KERNEL_TYPE_SEL(CV_MODE, ASCENDC_TPL_MIX_AIC_1_1, ASCENDC_TPL_MIX_AIC_1_2), + ASCENDC_TPL_TILING_STRUCT_SEL(optiling::MlaPrologTilingData))); + +#endif // MLA_PROLOG_TEMPLATE_TILING_KEY_H \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/mla_prolog_tiling_data.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/mla_prolog_tiling_data.h new file mode 100644 index 0000000000000000000000000000000000000000..5a963232bde39bc82603fe1ae9cd849be09f14b4 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/op_kernel/mla_prolog_tiling_data.h @@ -0,0 +1,76 @@ +/** + * 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 mla_prolog_tiling_datay.h + * \brief + */ + +#ifndef MLA_PROLOG_TILING_DATA_H +#define MLA_PROLOG_TILING_DATA_H +#include +#include "kernel_tiling/kernel_tiling.h" + +namespace optiling { +// 1. 基础参数结构体(对应 MlaPrologBaseParams 宏定义) +struct MlaPrologBaseParams { + uint32_t batchSize; // batch size(批大小) + uint32_t stepBatchSize; // batch size per step 32(每步批大小) + uint32_t mSubSize; + uint32_t mSubCoreNum; + uint32_t stepNumHeadDequant; // head size per step when dequant before mmqn(反量化前每步头大小) + uint32_t tokenSize; // token size = batchSize * seq1Size(token总数:批大小×序列1长度) + uint32_t seq1Size; // seq1(序列1长度,通常为query序列长度) + uint32_t seq2Size; // seq2(序列2长度,通常为key/value序列长度) + uint32_t headSizeX; // head size of Input Hidden 7168(输入隐藏层的头维度) + uint32_t headSizeCq; // head size of Latent Query 1536(潜在Query的头维度) + uint32_t headSizeCkv; // head size of Latent KeyValue 512(潜在KeyValue的头维度) + uint32_t headSizeQc; // head size of Query = dimHeadSizeQc * numHeadSize = 128 * 32(Query总头维度) + uint32_t headSizeQr; // head size of Query Rope = dimHeadRope * numHeadSize = 64 * 32(带RoPE的Query头维度) + uint32_t headSizeKr; // head size of Key Rope 64(带RoPE的Key头维度) + uint32_t numHeadSize; // number of head 32(头数量) + uint32_t numHeadKvSize; // number of headkv(KeyValue的头数量) + uint32_t dimHeadSizeQc; // dim size per query head 128(单个Query头的维度) + uint32_t dimHeadRope; // dim size per rope head 64(单个带RoPE头的维度) + uint32_t blockNum; // pa block num(PA格式的块数量) + uint32_t blockSize; // pa block size 128(PA格式的块大小) + uint32_t mm1BlockNum; // 24 Cq(矩阵乘1的块数量,对应Cq计算) + uint32_t mm2BlockNum; // 9 Ckv(矩阵乘2的块数量,对应Ckv计算) + uint32_t mm3BlockNum; // 24 QcQr(矩阵乘3的块数量,对应QcQr计算) + uint32_t mm4BlockNum; // 24 Qn(矩阵乘4的块数量,对应Qn计算) + uint32_t vectorBlockNum; // 32(向量计算的块数量) + uint32_t mm1SingleCoreN; // single headSizeCq(单核心矩阵乘1的N维度大小,对应单个Cq头维度) + uint32_t mm2SingleCoreN; // single headSizeCkv+headSizeKr(单核心矩阵乘2的N维度大小,Ckv+Kr头维度之和) + uint32_t mm3SingleCoreN; // single headSizeQc+headSizeQr(单核心矩阵乘3的N维度大小,Qc+Qr头维度之和) + uint32_t mm4SingleCoreBatch; // single numHeadSize(单核心矩阵乘4的批大小,对应单个头数量) + uint32_t dtileSize; + uint32_t kvQuantMode; + uint32_t tileSize; + uint32_t ckvkrRepoMode; + uint32_t quantScaleRepoMode; + uint32_t queryNormFlag; + float reciprocalCq; // 1 / headSizeCq(headSizeCq的倒数,用于快速计算) + float epsilonCq; // Cq计算的epsilon(数值稳定性参数) + float reciprocalCkv; // 1 / headSizeCkv(headSizeCkv的倒数,用于快速计算) + float epsilonCkv; // Ckv计算的epsilon(数值稳定性参数) + float kNopeClipAlpha; + float qcQrScale; // query 的尺度矫正因子 + float kcScale; // kv 的尺度矫正因子 + uint16_t isQcQrScaleEnable; // query 的尺度矫正因子是否生效(默认是1.0的时候不生效) + uint16_t isKcScaleEnable; // kv 的尺度矫正因子是否生效(默认是1.0的时候不生效) +}; + +// 2. 完整分块数据结构体(对应 MlaPrologTilingData 宏定义,嵌套基础参数) +struct MlaPrologTilingData { + MlaPrologBaseParams baseParams; // 嵌套基础参数结构体(包含维度、头信息等核心配置) +}; +} // namespace optiling + +#endif // MLA_PROLOG_TILING_DATA_H \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/test_data/cases_manifest.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/test_data/cases_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..0ade98e85fa674d759942bc2a2fc4fb7b5e4d5f9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/test_data/cases_manifest.json @@ -0,0 +1,153 @@ +{ + "op_name": "mla_prolog", + "op_camel": "MlaProlog", + "output_keys": [ + "query", + "query_rope", + "kv_cache", + "kr_cache" + ], + "cases": [ + { + "id": 0, + "shape": [ + 1, + 1, + 4, + 512 + ], + "attrs": { + "N": 4, + "bsz": 16, + "fused": false + } + }, + { + "id": 1, + "shape": [ + 1, + 1, + 2, + 512 + ], + "attrs": { + "T": 2, + "N": 2, + "bsz": 16, + "fused": true + } + }, + { + "id": 2, + "shape": [ + 1, + 4, + 8, + 512 + ], + "attrs": { + "N": 8, + "bsz": 32, + "fused": false + } + }, + { + "id": 3, + "shape": [ + 2, + 1, + 4, + 512 + ], + "attrs": { + "N": 4, + "bsz": 64, + "fused": false + } + }, + { + "id": 4, + "shape": [ + 1, + 8, + 16, + 512 + ], + "attrs": { + "N": 16, + "bsz": 32, + "fused": false + } + }, + { + "id": 5, + "shape": [ + 2, + 4, + 8, + 512 + ], + "attrs": { + "N": 8, + "bsz": 32, + "fused": false + } + }, + { + "id": 6, + "shape": [ + 2, + 2, + 2, + 512 + ], + "attrs": { + "N": 2, + "bsz": 16, + "fused": false + } + }, + { + "id": 7, + "shape": [ + 4, + 4, + 4, + 512 + ], + "attrs": { + "N": 4, + "bsz": 16, + "fused": false + } + }, + { + "id": 8, + "shape": [ + 2, + 16, + 16, + 512 + ], + "attrs": { + "N": 16, + "bsz": 16, + "fused": false + } + }, + { + "id": 9, + "shape": [ + 3, + 3, + 8, + 512 + ], + "attrs": { + "N": 8, + "bsz": 64, + "fused": false + } + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..cb9ce68f58e4add357123563529a1ce8690a5a7d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/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. +# ----------------------------------------------------------------------------------------------------------- + +message(STATUS "=== Debug: start ops.transformer.mla_prolog.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/mla_prolog/tests/ut/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..aa51fc0cb899f41c705141e91211c8a7399359e0 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/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}/*) +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/mla_prolog/tests/ut/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..293f774dc6f299c51af1af7ed2ebe188893e506e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_host/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. +# ====================================================================================================================== + +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/mla_prolog/tests/ut/op_host/test_mla_prolog_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_host/test_mla_prolog_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d1128fe5350da20243a9e85eede22d90273e07d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_host/test_mla_prolog_infershape.cpp @@ -0,0 +1,241 @@ +/** + * 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_datatype_context_faker.h" +#include "infer_shape_case_executor.h" +#include "base/registry/op_impl_space_registry_v2.h" + +class MlaPrologProto : public testing::Test +{ +protected: + static void SetUpTestCase() + { + std::cout << "MlaPrologProto SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "MlaPrologProto TearDown" << std::endl; + } +}; + +TEST_F(MlaPrologProto, mla_prolog_infershape_1) +{ + gert::InfershapeContextPara infershapeContextPara("MlaProlog", + { + {{{48, 10, 7168}, {48, 10, 7168}}, ge::DT_BF16, ge::FORMAT_ND},//token_x + {{{7168, 1536}, {7168, 1536}}, ge::DT_INT8, ge::FORMAT_FRACTAL_NZ},//weight_dq + {{{1536, 768}, {1536, 768}}, ge::DT_INT8, ge::FORMAT_FRACTAL_NZ},//weight_uq_qr + {{{4, 128, 512}, {4, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND},//weight_uk + {{{7168, 576}, {7168, 576}}, ge::DT_INT8, ge::FORMAT_FRACTAL_NZ},//weight_dkv_kr + {{{1536}, {1536}}, ge::DT_BF16, ge::FORMAT_ND},//rmsnorm_gamma_cq + {{{512}, {512}}, ge::DT_BF16, ge::FORMAT_ND},//rmsnorm_gamma_ckv + {{{48, 10, 64}, {48, 10, 64}}, ge::DT_BF16, ge::FORMAT_ND},//rope_sin + {{{48, 10, 64}, {48, 10, 64}}, ge::DT_BF16, ge::FORMAT_ND},//rope_cos + {{{49488, 16, 1, 512}, {49488, 16, 1, 512}}, ge::DT_INT8, ge::FORMAT_ND},//kv_cache + {{{49488, 16, 1, 64}, {49488, 16, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND},//kr_cache + {{{48, 10}, {48, 10}}, ge::DT_INT64, ge::FORMAT_ND},//cache_index + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_x + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_w_dq + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_w_uq_qr + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_w_dkv_kr + {{{1, 512}, {1, 512}}, ge::DT_FLOAT, ge::FORMAT_ND},//quant_scale_ckv + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND},//quant_scale_ckr + {{{1, 1536}, {1, 1536}}, ge::DT_FLOAT, ge::FORMAT_ND},//smooth_scales_cq + }, + { + {{{}, {}}, ge::DT_INT8, ge::FORMAT_ND},//query + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND},//query_rope + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND},//kv_cache + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND},//kr_cache + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_q_nope + }, + { + {"rmsnorm_epsilon_cq", Ops::Transformer::AnyValue::CreateFrom(1e-05f)}, + {"rmsnorm_epsilon_ckv", Ops::Transformer::AnyValue::CreateFrom(1e-05f)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + }); + std::vector> expectOutputShape = {{48, 10, 4, 512}, {48, 10, 4, 64}, {49488, 16, 1, 64}, {48, 10}, {}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +// TEST(用例集名, 用例名) +TEST_F(MlaPrologProto, mla_prolog_infershape_2) +{ + gert::InfershapeContextPara infershapeContextPara("MlaProlog", + { // input info + {{{8, 1, 7168}, {8, 1, 7168}}, ge::DT_BF16, ge::FORMAT_ND}, // token_x 0 + {{{7168, 1536}, {7168, 1536}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_dq 1 + {{{1536, 192}, {1536, 192}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_uq_qr 2 + {{{1, 128, 512}, {1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // weight_uk 3 + {{{7168, 576}, {7168, 576}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_dkv_kr 4 + {{{1536}, {1536}}, ge::DT_BF16, ge::FORMAT_ND}, // rmsnorm_gamma_cq 5 + {{{512}, {512}}, ge::DT_BF16, ge::FORMAT_ND}, // rmsnorm_gamma_ckv 6 + {{{8, 1, 64}, {8, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // rope_sin 7 + {{{8, 1, 64}, {8, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // rope_cos 8 + {{{8, 1}, {8, 1}}, ge::DT_INT64, ge::FORMAT_ND}, // cache_index 9 + {{{16, 128, 1, 512}, {16, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // kv_cache 10 + {{{16, 128, 1, 64}, {16, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // kr_cache 11 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_x 12 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_dq 13 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_uq_qr 14 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_dkv_kr 15 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // quant_scale_ckv 16 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // quant_scale_ckr 17 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // smooth_scales_cq 18 + }, + { // output info + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // 0 + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // 1 + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // 2 + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // 3 + }, + { // attr + {"rmsnorm_epsilon_cq", Ops::Transformer::AnyValue::CreateFrom(0.0005)}, + {"rmsnorm_epsilon_ckv", Ops::Transformer::AnyValue::CreateFrom(0.0005)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")} + }); + std::vector> expectOutputShape = {{8, 1, 1, 512}, {8, 1, 1, 64}, {16, 128, 1, 512}, {16, 128, 1, 64}}; // 预期输出shape + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); // 框架中已提供该接口 +} + +TEST_F(MlaPrologProto, mla_prolog_infershape_3) +{ + gert::InfershapeContextPara infershapeContextPara("MlaProlog", + { // input info + {{{32, 1, 7168}, {32, 1, 7168}}, ge::DT_BF16, ge::FORMAT_ND}, // token_x 0 + {{{7168, 1536}, {7168, 1536}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_dq 1 + {{{1536, 6144}, {1536, 6144}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_uq_qr 2 + {{{32, 128, 512}, {32, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // weight_uk 3 + {{{7168, 576}, {7168, 576}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_dkv_kr 4 + {{{1536}, {1536}}, ge::DT_BF16, ge::FORMAT_ND}, // rmsnorm_gamma_cq 5 + {{{512}, {512}}, ge::DT_BF16, ge::FORMAT_ND}, // rmsnorm_gamma_ckv 6 + {{{32, 1, 64}, {32, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // rope_sin 7 + {{{32, 1, 64}, {32, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // rope_cos 8 + {{{32, 1}, {32, 1}}, ge::DT_INT64, ge::FORMAT_ND}, // cache_index 9 + {{{2048, 16, 1, 512}, {2048, 16, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // kv_cache 10 + {{{2048, 16, 1, 64}, {2048, 16, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // kr_cache 11 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_x 12 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_dq 13 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_uq_qr 14 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_dkv_kr 15 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // quant_scale_ckv 16 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // quant_scale_ckr 17 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // smooth_scales_cq 18 + }, + { // output info + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // 0 + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // 1 + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // 2 + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // 3 + }, + { // attr + {"rmsnorm_epsilon_cq", Ops::Transformer::AnyValue::CreateFrom(0.0005)}, + {"rmsnorm_epsilon_ckv", Ops::Transformer::AnyValue::CreateFrom(0.0005)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")} + }); + std::vector> expectOutputShape = {{32, 1, 32, 512}, {32, 1, 32, 64}, {2048, 16, 1, 512}, {2048, 16, 1, 64}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(MlaPrologProto, mla_prolog_infershape_4) +{ + gert::InfershapeContextPara infershapeContextPara("MlaProlog", + { // input info + {{{2,1,7680}, {2,1,7680}}, ge::DT_BF16, ge::FORMAT_ND}, // token_x 0 + {{{7680,1536}, {7680,1536}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_dq 1 + {{{1536,384}, {1536,384}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_uq_qr 2 + {{{2,128,512}, {2,128,512}}, ge::DT_BF16, ge::FORMAT_ND}, // weight_uk 3 + {{{7680,576}, {7680,576}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_dkv_kr 4 + {{{1536}, {1536}}, ge::DT_BF16, ge::FORMAT_ND}, // rmsnorm_gamma_cq 5 + {{{512}, {512}}, ge::DT_BF16, ge::FORMAT_ND}, // rmsnorm_gamma_ckv 6 + {{{2,1,64}, {2,1,64}}, ge::DT_BF16, ge::FORMAT_ND}, // rope_sin 7 + {{{2,1,64}, {2,1,64}}, ge::DT_BF16, ge::FORMAT_ND}, // rope_cos 8 + {{{2,1}, {2,1}}, ge::DT_INT64, ge::FORMAT_ND}, // cache_index 9 + {{{0,16,1,512}, {0,16,1,512}}, ge::DT_BF16, ge::FORMAT_ND}, // kv_cache 10 + {{{0,16,1,64}, {0,16,1,64}}, ge::DT_BF16, ge::FORMAT_ND}, // kr_cache 11 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_x 12 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_dq 13 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_uq_qr 14 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_dkv_kr 15 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // quant_scale_ckv 16 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // quant_scale_ckr 17 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // smooth_scales_cq 18 + }, + { // output info + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // 0 + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // 1 + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // 2 + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, // 3 + }, + { // attr + {"rmsnorm_epsilon_cq", Ops::Transformer::AnyValue::CreateFrom(0.0005)}, + {"rmsnorm_epsilon_ckv", Ops::Transformer::AnyValue::CreateFrom(0.0005)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")} + }); + std::vector> expectOutputShape = {{2,1,2,512}, {2,1,2,64}, {0,16,1,512}, {0,16,1,64}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +// infer dataType +TEST_F(MlaPrologProto, dtype_infer_1) +{ + auto spaceRegistry = gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry(); + ASSERT_NE(spaceRegistry, nullptr); + auto data_type_func = spaceRegistry->GetOpImpl("MlaProlog")->infer_datatype; + if (data_type_func != nullptr) { + ge::DataType input_ref = ge::DT_BF16; + ge::DataType input_ref1 = ge::DT_INT64; + ge::DataType input_ref2 = ge::DT_FLOAT; + ge::DataType output_ref = ge::DT_BF16; + auto context_holder = + gert::InferDataTypeContextFaker() + .NodeIoNum(19, 4) + .IrInstanceNum({1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}) + .NodeInputTd(0, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(1, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_FRACTAL_NZ) + .NodeInputTd(2, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_FRACTAL_NZ) + .NodeInputTd(3, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(4, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_FRACTAL_NZ) + .NodeInputTd(5, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(6, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(7, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(8, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(9, ge::DT_INT64, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(10, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(11, ge::DT_BF16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(12, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(13, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(14, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(15, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(16, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(17, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(18, 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) + .NodeOutputTd(2, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeOutputTd(3, ge::FORMAT_ND, ge::FORMAT_ND) + .InputDataTypes({&input_ref, &input_ref, &input_ref, &input_ref, &input_ref, &input_ref, &input_ref, &input_ref, &input_ref, + &input_ref1, &input_ref, &input_ref, &input_ref, &input_ref, &input_ref, &input_ref, &input_ref, &input_ref, &input_ref}) + .OutputDataTypes({&output_ref, &output_ref, &output_ref, &output_ref}) + .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_ref); + EXPECT_EQ(context->GetOutputDataType(1), output_ref); + EXPECT_EQ(context->GetOutputDataType(2), output_ref); + EXPECT_EQ(context->GetOutputDataType(3), output_ref); + } +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_host/test_mla_prolog_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_host/test_mla_prolog_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cffdbb445427de49cf29ee76698c61644844b145 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_host/test_mla_prolog_tiling.cpp @@ -0,0 +1,217 @@ +/** + * 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 "../../../op_host/mla_prolog_tiling.h" +#include "tiling_context_faker.h" +#include "tiling_case_executor.h" + +using namespace std; + +// 构造版本 +std::string MlaProlog_A2SocInfo = + "{\n" + " \"hardware_info\": {\n" + " \"BT_SIZE\": 0,\n" + " \"load3d_constraints\": \"1\",\n" + " \"Intrinsic_fix_pipe_l0c2out\": false,\n" + " \"Intrinsic_data_move_l12ub\": true,\n" + " \"Intrinsic_data_move_l0c2ub\": true,\n" + " \"Intrinsic_data_move_out2l1_nd2nz\": false,\n" + " \"UB_SIZE\": 196608,\n" + " \"L2_SIZE\": 201326592,\n" + " \"L1_SIZE\": 524288,\n" + " \"L0A_SIZE\": 65536,\n" + " \"L0B_SIZE\": 65536,\n" + " \"L0C_SIZE\": 131072,\n" + " \"vector_core_cnt\": 40,\n" + " \"cube_core_cnt\": 20,\n" + " \"socVersion\": \"Ascend910_B3\"\n" + " }\n" + "}"; + +class MlaProlog : public testing::Test +{ +protected: + static void SetUpTestCase() + { + std::cout << "MlaProlog SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "MlaProlog TearDown" << std::endl; + } +}; + +//全量化kvcache pertensor量化 +TEST_F(MlaProlog, MlaProlog_tiling_test0) { + optiling::MlaPrologCompileInfo compileInfo = {48}; + gert::TilingContextPara tilingContextPara("MlaProlog", + { + {{{8, 1, 7168}, {8, 1, 7168}}, ge::DT_INT8, ge::FORMAT_ND},//token_x + {{{7168, 1536}, {7168, 1536}}, ge::DT_INT8, ge::FORMAT_FRACTAL_NZ},//weight_dq + {{{1536, 32 * (128 + 64)}, {1536, 32 * (128 + 64)}}, ge::DT_INT8, ge::FORMAT_FRACTAL_NZ},//weight_uq_qr + {{{32, 128, 512}, {32, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND},//weight_uk + {{{7168, 512 + 64}, {7168, 512 + 64}}, ge::DT_INT8, ge::FORMAT_FRACTAL_NZ},//weight_dkv_kr + {{{1536}, {1536}}, ge::DT_BF16, ge::FORMAT_ND},//rmsnorm_gamma_cq + {{{512}, {512}}, ge::DT_BF16, ge::FORMAT_ND},//rmsnorm_gamma_ckv + {{{8, 1, 64}, {8, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND},//rope_sin + {{{8, 1, 64}, {8, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND},//rope_cos + {{{8, 1}, {8, 1}}, ge::DT_INT64, ge::FORMAT_ND},//cache_index + {{{16, 128, 1, 512}, {16, 128, 1, 512}}, ge::DT_INT8, ge::FORMAT_ND},//kv_cache + {{{16, 128, 1, 64}, {16, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND},//kr_cache + {{{8 * 1, 1}, {8 * 1, 1}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_x + {{{1, 1536}, {1, 1536}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_w_dq + {{{1, 32 * (128 + 64)}, {1, 32 * (128 + 64)}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_w_uq_qr + {{{1, 512 + 64}, {1, 512 + 64}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_w_dkv_kr + {{{1, 512}, {1, 512}}, ge::DT_FLOAT, ge::FORMAT_ND},//quant_scale_ckv + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND},//quant_scale_ckr + {{{1, 1536}, {1, 1536}}, ge::DT_FLOAT, ge::FORMAT_ND},//smooth_scales_cq + }, + { + {{{8, 1, 32, 64}, {8, 1, 32, 512}}, ge::DT_INT8, ge::FORMAT_ND},//query + {{{8, 1, 32, 64}, {8, 1, 32, 64}}, ge::DT_BF16, ge::FORMAT_ND},//query_rope + {{{16, 128, 1, 512}, {16, 128, 1, 512}}, ge::DT_INT8, ge::FORMAT_ND},//kv_cache + {{{16, 128, 1, 64}, {16, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND},//kr_cache + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_q_nope + }, + { + {"rmsnorm_epsilon_cq", Ops::Transformer::AnyValue::CreateFrom(1e-05f)}, + {"rmsnorm_epsilon_ckv", Ops::Transformer::AnyValue::CreateFrom(1e-05f)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + }, + &compileInfo,"Ascend910_B3", MlaProlog_A2SocInfo, 4096); + int64_t expectTilingKey = 1836321; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey); +} + +TEST_F(MlaProlog, MlaProlog_tiling_0001) { + optiling::MlaPrologCompileInfo compileInfo = {64}; // 根据tiling头文件中的compileInfo填入对应值,一般原先的用例里能找到 + gert::TilingContextPara tilingContextPara("MlaProlog", // op_name + { // input info + {{{8, 1, 7168}, {8, 1, 7168}}, ge::DT_BF16, ge::FORMAT_ND}, // token_x 0 + {{{7168, 1536}, {7168, 1536}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_dq 1 + {{{1536, 192}, {1536, 192}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_uq_qr 2 + {{{1, 128, 512}, {1, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // weight_uk 3 + {{{7168, 576}, {7168, 576}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_dkv_kr 4 + {{{1536}, {1536}}, ge::DT_BF16, ge::FORMAT_ND}, // rmsnorm_gamma_cq 5 + {{{512}, {512}}, ge::DT_BF16, ge::FORMAT_ND}, // rmsnorm_gamma_ckv 6 + {{{8, 1, 64}, {8, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // rope_sin 7 + {{{8, 1, 64}, {8, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // rope_cos 8 + {{{8, 1}, {8, 1}}, ge::DT_INT64, ge::FORMAT_ND}, // cache_index 9 + {{{16, 128, 1, 512}, {16, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // kv_cache 10 + {{{16, 128, 1, 64}, {16, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // kr_cache 11 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_x 12 [全量化] + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_dq 13 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_uq_qr 14 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_dkv_kr 15 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // quant_scale_ckv 16 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // quant_scale_ckr 17 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // smooth_scales_cq 18 + }, + { // output info + {{{8, 1, 1, 512}, {8, 1, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // 0 query + {{{8, 1, 1, 64}, {8, 1, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // 1 query_rope + {{{16, 128, 1, 512}, {16, 128, 1, 512}}, ge::DT_BF16, ge::FORMAT_ND}, // 2 kv_cache + {{{16, 128, 1, 64}, {16, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND}, // 3 kr_cache + }, + { // attr + {"rmsnorm_epsilon_cq", Ops::Transformer::AnyValue::CreateFrom(0.0005)}, + {"rmsnorm_epsilon_ckv", Ops::Transformer::AnyValue::CreateFrom(0.0005)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + }, + &compileInfo,"Ascend910_B3", MlaProlog_A2SocInfo, 4096); + int64_t expectTilingKey = 1835025; // tilngkey + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey); +} + +TEST_F(MlaProlog, MlaProlog_tiling_0002) { + optiling::MlaPrologCompileInfo compileInfo = {28}; // 根据tiling头文件中的compileInfo填入对应值,一般原先的用例里能找到 + gert::TilingContextPara tilingContextPara("MlaProlog", // op_name + { // input info + {{{0,1,7168}, {0,1,7168}}, ge::DT_BF16, ge::FORMAT_ND}, // token_x 0 + {{{7168,1536}, {7168,1536}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_dq 1 + {{{1536,384}, {1536,384}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_uq_qr 2 + {{{2,128,512}, {2,128,512}}, ge::DT_BF16, ge::FORMAT_ND}, // weight_uk 3 + {{{7168,576}, {7168,576}}, ge::DT_BF16, ge::FORMAT_FRACTAL_NZ}, // weight_dkv_kr 4 + {{{1536}, {1536}}, ge::DT_BF16, ge::FORMAT_ND}, // rmsnorm_gamma_cq 5 + {{{512}, {512}}, ge::DT_BF16, ge::FORMAT_ND}, // rmsnorm_gamma_ckv 6 + {{{0,1,64}, {0,1,64}}, ge::DT_BF16, ge::FORMAT_ND}, // rope_sin 7 + {{{0,1,64}, {0,1,64}}, ge::DT_BF16, ge::FORMAT_ND}, // rope_cos 8 + {{{0,1}, {0,1}}, ge::DT_INT64, ge::FORMAT_ND}, // cache_index 9 + {{{0,16,1,512}, {0,16,1,512}}, ge::DT_BF16, ge::FORMAT_ND}, // kv_cache 10 + {{{0,16,1,64}, {0,16,1,64}}, ge::DT_BF16, ge::FORMAT_ND}, // kr_cache 11 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_x 12 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_dq 13 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_uq_qr 14 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // dequant_scale_w_dkv_kr 15 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // quant_scale_ckv 16 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // quant_scale_ckr 17 + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, // smooth_scales_cq 18 + }, + { // output info + {{{0,1,2,512}, {0,1,2,512}}, ge::DT_BF16, ge::FORMAT_ND}, // 0 query + {{{0,1,2,64}, {0,1,2,64}}, ge::DT_BF16, ge::FORMAT_ND}, // 1 query_rope + {{{0,16,1,512}, {0,16,1,512}}, ge::DT_BF16, ge::FORMAT_ND}, // 2 kv_cache + {{{0,16,1,64}, {0,16,1,64}}, ge::DT_BF16, ge::FORMAT_ND}, // 3 kr_cache + }, + { // attr + {"rmsnorm_epsilon_cq", Ops::Transformer::AnyValue::CreateFrom(0.0005)}, + {"rmsnorm_epsilon_ckv", Ops::Transformer::AnyValue::CreateFrom(0.0005)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom("PA_BSND")}, + }, + &compileInfo,"Ascend910_B3", MlaProlog_A2SocInfo, 4096); + int64_t expectTilingKey = 1843200; // tilngkey + string expectTilingData = ""; // tilingData(不确定的话跑下对应用例打印看看) + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData); +} + +// 全量化kvcache异常case:MlaProlog only support cacheMode {BSND, TND,PA_BSND,PA_NZ,PA_BLK_BSND,PA_BLK_NZ}, actually is ABCD. +TEST_F(MlaProlog, MlaProlog_tiling_0003) { + optiling::MlaPrologCompileInfo compileInfo = {48}; + gert::TilingContextPara tilingContextPara("MlaProlog", + { + {{{8, 1, 7168}, {8, 1, 7168}}, ge::DT_INT8, ge::FORMAT_ND},//token_x + {{{7168, 1536}, {7168, 1536}}, ge::DT_INT8, ge::FORMAT_FRACTAL_NZ},//weight_dq + {{{1536, 32 * (128 + 64)}, {1536, 32 * (128 + 64)}}, ge::DT_INT8, ge::FORMAT_FRACTAL_NZ},//weight_uq_qr + {{{32, 128, 512}, {32, 128, 512}}, ge::DT_BF16, ge::FORMAT_ND},//weight_uk + {{{7168, 512 + 64}, {7168, 512 + 64}}, ge::DT_INT8, ge::FORMAT_FRACTAL_NZ},//weight_dkv_kr + {{{1536}, {1536}}, ge::DT_BF16, ge::FORMAT_ND},//rmsnorm_gamma_cq + {{{512}, {512}}, ge::DT_BF16, ge::FORMAT_ND},//rmsnorm_gamma_ckv + {{{8, 1, 64}, {8, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND},//rope_sin + {{{8, 1, 64}, {8, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND},//rope_cos + {{{8, 1}, {8, 1}}, ge::DT_INT64, ge::FORMAT_ND},//cache_index + {{{16, 128, 1, 512}, {16, 128, 1, 512}}, ge::DT_INT8, ge::FORMAT_ND},//kv_cache + {{{16, 128, 1, 64}, {16, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND},//kr_cache + {{{8 * 1, 1}, {8 * 1, 1}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_x + {{{1, 1536}, {1, 1536}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_w_dq + {{{1, 32 * (128 + 64)}, {1, 32 * (128 + 64)}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_w_uq_qr + {{{1, 512 + 64}, {1, 512 + 64}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_w_dkv_kr + {{{1, 512}, {1, 512}}, ge::DT_FLOAT, ge::FORMAT_ND},//quant_scale_ckv + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND},//quant_scale_ckr + {{{1, 1536}, {1, 1536}}, ge::DT_FLOAT, ge::FORMAT_ND},//smooth_scales_cq + }, + { + {{{8, 1, 32, 64}, {8, 1, 32, 512}}, ge::DT_INT8, ge::FORMAT_ND},//query + {{{8, 1, 32, 64}, {8, 1, 32, 64}}, ge::DT_BF16, ge::FORMAT_ND},//query_rope + {{{16, 128, 1, 512}, {16, 128, 1, 512}}, ge::DT_INT8, ge::FORMAT_ND},//kv_cache + {{{16, 128, 1, 64}, {16, 128, 1, 64}}, ge::DT_BF16, ge::FORMAT_ND},//kr_cache + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND},//dequant_scale_q_nope + }, + { + {"rmsnorm_epsilon_cq", Ops::Transformer::AnyValue::CreateFrom(1e-05f)}, + {"rmsnorm_epsilon_ckv", Ops::Transformer::AnyValue::CreateFrom(1e-05f)}, + {"cache_mode", Ops::Transformer::AnyValue::CreateFrom("ABCD")}, + }, + &compileInfo,"Ascend910_B3", MlaProlog_A2SocInfo, 4096); + int64_t expectTilingKey = 1836321; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey); +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_kernel/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_kernel/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7807692943ce67024c970fcf416d8f21c40c4fb9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/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(mla_prolog_tiling_files) + # 使用AddOpTestCase + # param1:算子名称,以kernel方式命名 + # param2:soc版本,多个以分号分隔,例如:"Ascend950PR_9599;AscendB1" + # param3:自定义编译选项,一般填写测试的一种典型数据类型组合,不需要则传入空字符串,例如:"-DDTYPE_X=float",多个使用空格分隔,例如:"-DDTYPE_X=float -DDTYPE_Y=float" + # param4:该算子依赖的所有tiling源码文件 + AddOpTestCase(mla_prolog "ascend910B1" "-DDTYPE_X=float" "${mla_prolog_tiling_files}") +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_kernel/mla_prolog_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_kernel/mla_prolog_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ae69a81bcdee03fc9527487c7662f4585a35bfa --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_kernel/mla_prolog_tiling.cpp @@ -0,0 +1,39 @@ +/** + * 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 mla_prolog_tiling.cpp +* \brief +*/ + + +namespace optiling { + +template +inline auto CeilDiv(T a, T b) -> T +{ + if (b == 0) { + return b; + } + return (a + b - 1) / b; +} + +template +inline auto Align(T num, T rnd) -> T +{ + return (((rnd) == 0) ? 0 : (((num) + (rnd) - 1) / (rnd) * (rnd))); +} + +uint32_t CalcSingleCoreN(uint32_t n, uint32_t coreNum, uint32_t alignNum) +{ + return CeilDiv(n, alignNum * coreNum) * alignNum; +} + +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_kernel/mla_prolog_tiling_data.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_kernel/mla_prolog_tiling_data.h new file mode 100644 index 0000000000000000000000000000000000000000..2f9755928606a7efd10eeee2da7ba0f3d580b1ca --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_kernel/mla_prolog_tiling_data.h @@ -0,0 +1,76 @@ +/** + * 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 mla_prolog_tiling_datay.h + * \brief + */ + +#ifndef MLA_PROLOG_TILING_DATA_H +#define MLA_PROLOG_TILING_DATA_H +#include +#include "kernel_tiling/kernel_tiling.h" + +namespace optiling { + // 1. 基础参数结构体(对应 MlaPrologBaseParams 宏定义) + struct MlaPrologBaseParams { + uint32_t batchSize; // batch size(批大小) + uint32_t stepBatchSize; // batch size per step 32(每步批大小) + uint32_t mSubSize; + uint32_t mSubCoreNum; + uint32_t stepNumHeadDequant; // head size per step when dequant before mmqn(反量化前每步头大小) + uint32_t tokenSize; // token size = batchSize * seq1Size(token总数:批大小×序列1长度) + uint32_t seq1Size; // seq1(序列1长度,通常为query序列长度) + uint32_t seq2Size; // seq2(序列2长度,通常为key/value序列长度) + uint32_t headSizeX; // head size of Input Hidden 7168(输入隐藏层的头维度) + uint32_t headSizeCq; // head size of Latent Query 1536(潜在Query的头维度) + uint32_t headSizeCkv; // head size of Latent KeyValue 512(潜在KeyValue的头维度) + uint32_t headSizeQc; // head size of Query = dimHeadSizeQc * numHeadSize = 128 * 32(Query总头维度) + uint32_t headSizeQr; // head size of Query Rope = dimHeadRope * numHeadSize = 64 * 32(带RoPE的Query头维度) + uint32_t headSizeKr; // head size of Key Rope 64(带RoPE的Key头维度) + uint32_t numHeadSize; // number of head 32(头数量) + uint32_t numHeadKvSize; // number of headkv(KeyValue的头数量) + uint32_t dimHeadSizeQc; // dim size per query head 128(单个Query头的维度) + uint32_t dimHeadRope; // dim size per rope head 64(单个带RoPE头的维度) + uint32_t blockNum; // pa block num(PA格式的块数量) + uint32_t blockSize; // pa block size 128(PA格式的块大小) + uint32_t mm1BlockNum; // 24 Cq(矩阵乘1的块数量,对应Cq计算) + uint32_t mm2BlockNum; // 9 Ckv(矩阵乘2的块数量,对应Ckv计算) + uint32_t mm3BlockNum; // 24 QcQr(矩阵乘3的块数量,对应QcQr计算) + uint32_t mm4BlockNum; // 24 Qn(矩阵乘4的块数量,对应Qn计算) + uint32_t vectorBlockNum; // 32(向量计算的块数量) + uint32_t mm1SingleCoreN; // single headSizeCq(单核心矩阵乘1的N维度大小,对应单个Cq头维度) + uint32_t mm2SingleCoreN; // single headSizeCkv+headSizeKr(单核心矩阵乘2的N维度大小,Ckv+Kr头维度之和) + uint32_t mm3SingleCoreN; // single headSizeQc+headSizeQr(单核心矩阵乘3的N维度大小,Qc+Qr头维度之和) + uint32_t mm4SingleCoreBatch; // single numHeadSize(单核心矩阵乘4的批大小,对应单个头数量) + uint32_t dtileSize; + uint32_t kvQuantMode; + uint32_t tileSize; + uint32_t ckvkrRepoMode; + uint32_t quantScaleRepoMode; + uint32_t queryNormFlag; + float reciprocalCq; // 1 / headSizeCq(headSizeCq的倒数,用于快速计算) + float epsilonCq; // Cq计算的epsilon(数值稳定性参数) + float reciprocalCkv; // 1 / headSizeCkv(headSizeCkv的倒数,用于快速计算) + float epsilonCkv; // Ckv计算的epsilon(数值稳定性参数) + float kNopeClipAlpha; + float qcQrScale; // query 的尺度矫正因子 + float kcScale; // kv 的尺度矫正因子 + uint16_t isQcQrScaleEnable; // query 的尺度矫正因子是否生效(默认是1.0的时候不生效) + uint16_t isKcScaleEnable; // kv 的尺度矫正因子是否生效(默认是1.0的时候不生效) + }; + + // 2. 完整分块数据结构体(对应 MlaPrologTilingData 宏定义,嵌套基础参数) + struct MlaPrologTilingData { + MlaPrologBaseParams baseParams; // 嵌套基础参数结构体(包含维度、头信息等核心配置) + }; +} // optiling + +#endif // MLA_PROLOG_TILING_DATA_H \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_kernel/test_mla_prolog.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_kernel/test_mla_prolog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0b5e855884a7db4828878ed3c893af11783bdd05 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/mla_prolog/tests/ut/op_kernel/test_mla_prolog.cpp @@ -0,0 +1,267 @@ +/** + * Copyright (c) 2025 Huawei Technologies Co., Ltd. + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of + * CANN Open Software License Agreement Version 2.0 (the "License"). + * Please refer to the License for details. You may not use this file except in compliance with the License. + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. + * See LICENSE in the root of the software repository for the full text of the License. + */ +#include "gtest/gtest.h" +#include "tikicpulib.h" +#include "mla_prolog_tiling_data.h" +#include "data_utils.h" +#include "../../../op_kernel/mla_prolog.cpp" +#include "mla_prolog_tiling.cpp" + +using namespace std; + + +#define PARAM_LIST_DEF __gm__ uint8_t *tokenX,\ + __gm__ uint8_t *weightDq,\ + __gm__ uint8_t *weightUqQr,\ + __gm__ uint8_t *weightUk,\ + __gm__ uint8_t *weightDkvKr,\ + __gm__ uint8_t *rmsnormGammaCq,\ + __gm__ uint8_t *rmsnormGammaCkv,\ + __gm__ uint8_t *ropeSin,\ + __gm__ uint8_t *ropeCos,\ + __gm__ uint8_t *cacheIndex,\ + __gm__ uint8_t *kvCache,\ + __gm__ uint8_t *krCache,\ + __gm__ uint8_t *dequantScaleX,\ + __gm__ uint8_t *dequantScaleWDq,\ + __gm__ uint8_t *dequantScaleWUqQr,\ + __gm__ uint8_t *dequantScaleWDkvKr,\ + __gm__ uint8_t *quantScaleCkv,\ + __gm__ uint8_t *quantScaleCkr,\ + __gm__ uint8_t *smoothScalesCq,\ + __gm__ uint8_t *queryOut,\ + __gm__ uint8_t *queryRopeOut,\ + __gm__ uint8_t *kvCacheOut,\ + __gm__ uint8_t *krCacheOut,\ + __gm__ uint8_t *workspace,\ + __gm__ uint8_t *tiling + + +#define PARAM_LIST tokenX,\ + weightDq,\ + weightUqQr,\ + weightUk,\ + weightDkvKr,\ + rmsnormGammaCq,\ + rmsnormGammaCkv,\ + ropeSin,\ + ropeCos,\ + cacheIndex,\ + kvCache,\ + krCache,\ + dequantScaleX,\ + dequantScaleWDq,\ + dequantScaleWUqQr,\ + dequantScaleWDkvKr,\ + quantScaleCkv,\ + quantScaleCkr,\ + smoothScalesCq,\ + queryOut,\ + queryRopeOut,\ + kvCacheOut,\ + krCacheOut,\ + workspace,\ + tiling + + + +class MlaPrologKernel : public testing::Test +{ +protected: + static void FreeAllGmMemory( + uint8_t* tokenX, + uint8_t* weightDq, + uint8_t* weightUqQr, + uint8_t* weightUk, + uint8_t* weightDkvKr, + uint8_t* rmsnormGammaCq, + uint8_t* rmsnormGammaCkv, + uint8_t* ropeSin, + uint8_t* ropeCos, + uint8_t* cacheIndex, + uint8_t* kvCache, + uint8_t* krCache, + uint8_t* dequantScaleX, + uint8_t* dequantScaleWDq, + uint8_t* dequantScaleWUqQr, + uint8_t* dequantScaleWDkvKr, + uint8_t* quantScaleCkv, + uint8_t* quantScaleCkr, + uint8_t* smoothScalesCq, + uint8_t* queryOut, + uint8_t* queryRopeOut, + uint8_t* kvCacheOut, + uint8_t* krCacheOut, + uint8_t* workspace, + uint8_t* tiling ) { + // 逐个释放非空指针,避免空指针访问 + if (tokenX != nullptr) AscendC::GmFree(tokenX); + if (weightDq != nullptr) AscendC::GmFree(weightDq); + if (weightUqQr != nullptr) AscendC::GmFree(weightUqQr); + if (weightUk != nullptr) AscendC::GmFree(weightUk); + if (weightDkvKr != nullptr) AscendC::GmFree(weightDkvKr); + if (rmsnormGammaCq != nullptr) AscendC::GmFree(rmsnormGammaCq); + if (rmsnormGammaCkv != nullptr) AscendC::GmFree(rmsnormGammaCkv); + if (ropeSin != nullptr) AscendC::GmFree(ropeSin); + if (ropeCos != nullptr) AscendC::GmFree(ropeCos); + if (cacheIndex != nullptr) AscendC::GmFree(cacheIndex); + if (kvCache != nullptr) AscendC::GmFree(kvCache); + if (krCache != nullptr) AscendC::GmFree(krCache); + if (dequantScaleX != nullptr) AscendC::GmFree(dequantScaleX); + if (dequantScaleWDq != nullptr) AscendC::GmFree(dequantScaleWDq); + if (dequantScaleWUqQr != nullptr) AscendC::GmFree(dequantScaleWUqQr); + if (dequantScaleWDkvKr != nullptr) AscendC::GmFree(dequantScaleWDkvKr); + if (quantScaleCkv != nullptr) AscendC::GmFree(quantScaleCkv); + if (quantScaleCkr != nullptr) AscendC::GmFree(quantScaleCkr); + if (smoothScalesCq != nullptr) AscendC::GmFree(smoothScalesCq); + if (queryOut != nullptr) AscendC::GmFree(queryOut); + if (queryRopeOut != nullptr) AscendC::GmFree(queryRopeOut); + if (kvCacheOut != nullptr) AscendC::GmFree(kvCacheOut); + if (krCacheOut != nullptr) AscendC::GmFree(krCacheOut); + if (workspace != nullptr) AscendC::GmFree(workspace); + if (tiling != nullptr) AscendC::GmFree(tiling); + } + static void SetUpTestCase() + { + std::cout << "MlaPrologKernel SetUp\n" << std::endl; + } + static void TearDownTestCase() + { + std::cout << "MlaPrologKernel TearDown\n" << std::endl; + } +}; + + +// 非量化场景 +TEST_F(MlaPrologKernel, test_case_v1_noQuant) +{ + uint32_t B = 1; + uint32_t N = 8; + uint32_t N2 = 1; + uint32_t D = 128; + uint32_t Dr = 63; + uint32_t S1 = 1; + uint32_t S2 = 0; + uint32_t He = 7168; + uint32_t Hckv = 512; + uint32_t T = 0; + uint32_t Block_Number = 3; + uint32_t Block_Size = 64; + uint32_t Nkv = 1; + uint32_t Dtile = 656; + uint32_t blockDim = 12; + uint32_t Hcq= 1536; + + AscendC::SetKernelMode(KernelMode::MIX_MODE); + std::function func = [](PARAM_LIST_DEF){return mla_prolog< 1, // CACHE_MODE + 1, // SCENARIO + 0, // QUANT_MODE + 0, // ENABLE_DEQUANT_OPTIONAL + 0, // ENABLE_GROUP_COMPUTE_OPTIONAL + 0, // EMPTY_TENSOR_MODE + 0, // ACTUAL_SEQ_LEN_MODE + 0, // SPLIT_M_MODE + 7 // CV_MODE + >(PARAM_LIST);}; + // 输入变量 + uint8_t* tokenX = (uint8_t*)AscendC::GmAlloc(B * S1 * He * sizeof(half)); + uint8_t* weightDq = (uint8_t*)AscendC::GmAlloc(He * Hcq * sizeof(half)); + uint8_t* weightUqQr = (uint8_t*)AscendC::GmAlloc(Hcq * N*(D + Dr) * sizeof(half)); + uint8_t* weightUk = (uint8_t*)AscendC::GmAlloc(N * D * Hckv *sizeof(half)); + uint8_t* weightDkvKr = (uint8_t*)AscendC::GmAlloc(He * (Hckv + Dr) * sizeof(half)); + uint8_t* rmsnormGammaCq = (uint8_t*)AscendC::GmAlloc(Hcq * sizeof(half)); + uint8_t* rmsnormGammaCkv = (uint8_t*)AscendC::GmAlloc(Hckv * sizeof(half)); + uint8_t* ropeSin = (uint8_t*)AscendC::GmAlloc(B * S1 * Dr * sizeof(half)); + uint8_t* ropeCos = (uint8_t*)AscendC::GmAlloc(B * S1 * Dr * sizeof(half)); + uint8_t* cacheIndex = (uint8_t*)AscendC::GmAlloc(B * S1 * sizeof(half)); + uint8_t* kvCache = (uint8_t*)AscendC::GmAlloc(Block_Number * Block_Size * Nkv * Dtile * sizeof(half)); + uint8_t* krCache = (uint8_t*)AscendC::GmAlloc(Block_Number * Block_Size * Nkv * Dr * sizeof(half)); + uint8_t* dequantScaleX = (uint8_t*)AscendC::GmAlloc(1); + uint8_t* dequantScaleWDq = (uint8_t*)AscendC::GmAlloc(1); + uint8_t* dequantScaleWUqQr = (uint8_t*)AscendC::GmAlloc(1 * N * (D + Dr) * sizeof(float)); + uint8_t* dequantScaleWDkvKr = (uint8_t*)AscendC::GmAlloc(1); + uint8_t* quantScaleCkv = (uint8_t*)AscendC::GmAlloc(1); + uint8_t* quantScaleCkr = (uint8_t*)AscendC::GmAlloc(1); + uint8_t* smoothScalesCq = (uint8_t*)AscendC::GmAlloc(1 * Hcq * sizeof(float)); + // 输出类变量 + uint8_t* queryOut = (uint8_t*)AscendC::GmAlloc(B * S1 * N * Hckv * sizeof(half)); + uint8_t* queryRopeOut = (uint8_t*)AscendC::GmAlloc(B * S1 * N * Dr * sizeof(half)); + uint8_t* dequantScaleQNopeOut = (uint8_t*)AscendC::GmAlloc(1); + uint8_t* kvCacheOut = (uint8_t*)AscendC::GmAlloc(Block_Number * Block_Size * Nkv * Dr * sizeof(half)); + uint8_t* krCacheOut = (uint8_t*)AscendC::GmAlloc(Block_Number * Block_Size * Nkv * Dr * sizeof(half)); + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(2048 * 2048 * 2048); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(sizeof(optiling::MlaPrologBaseParams)); + + // ===================tiligndata赋值==================== + optiling::MlaPrologBaseParams* baseParams_ = reinterpret_cast(tiling); + uint32_t aicNum_ = 12; + uint32_t aivNum_ = 12; + baseParams_->batchSize = B; + baseParams_->seq1Size = S1; + baseParams_->headSizeKr = Dr; + baseParams_->numHeadSize = N; + baseParams_->numHeadKvSize = Nkv; + baseParams_->dimHeadSizeQc = D; + baseParams_->dimHeadRope = Dr; + baseParams_->headSizeX = He; + baseParams_->headSizeCq = Hcq; + baseParams_->headSizeCkv = Hckv; + baseParams_->dtileSize = Dtile; + baseParams_->blockNum = Block_Number; + baseParams_->blockSize = Block_Size; + baseParams_->tokenSize = baseParams_->batchSize * baseParams_->seq1Size; + baseParams_->stepBatchSize = std::min(128U, baseParams_->tokenSize); + baseParams_->stepNumHeadDequant = std::min(64U, N); + baseParams_->mSubSize =(baseParams_->tokenSize + aicNum_ - 1U) / aicNum_; + baseParams_->mSubCoreNum = baseParams_->tokenSize - (baseParams_->mSubSize - 1U) * aicNum_; + baseParams_->seq2Size = baseParams_->numHeadKvSize; + baseParams_->headSizeQc = baseParams_->dimHeadSizeQc * baseParams_->numHeadSize; + baseParams_->headSizeQr = baseParams_->headSizeKr * baseParams_->numHeadSize; + baseParams_->mm1SingleCoreN =optiling::CalcSingleCoreN(baseParams_->headSizeCq, aicNum_, Block_Size / 1); + baseParams_->mm2SingleCoreN = 64U; + baseParams_->mm3SingleCoreN = optiling::CalcSingleCoreN(baseParams_->numHeadSize * (baseParams_->headSizeKr + baseParams_->dimHeadSizeQc), aicNum_, D + Dr); + baseParams_->mm4SingleCoreBatch = CeilDiv(baseParams_->numHeadSize, aicNum_); + baseParams_->mm1BlockNum = CeilDiv(baseParams_->headSizeCq, baseParams_->mm1SingleCoreN); + baseParams_->mm2BlockNum =(baseParams_->headSizeCkv + baseParams_->dimHeadRope) / baseParams_->mm2SingleCoreN; + baseParams_->mm3BlockNum = CeilDiv(baseParams_->numHeadSize * (baseParams_->headSizeKr + baseParams_->dimHeadSizeQc), baseParams_ ->mm3SingleCoreN); + baseParams_->mm4BlockNum = CeilDiv(baseParams_->numHeadSize, baseParams_->mm4SingleCoreBatch); + baseParams_->vectorBlockNum = std::min(std::min(128U, baseParams_->tokenSize), aivNum_); + baseParams_->reciprocalCq =1.0f / baseParams_->headSizeCq; + baseParams_->epsilonCq = 0.00461f; + baseParams_->reciprocalCkv = 1.0f / baseParams_->headSizeCkv; + baseParams_->epsilonCkv = 0.001166f; + // v3 + baseParams_->queryNormFlag = 0U; + baseParams_->kvQuantMode = static_cast(0); + baseParams_->ckvkrRepoMode = static_cast(0); + baseParams_->quantScaleRepoMode = static_cast(0); + baseParams_->tileSize = 128U; + baseParams_->qcQrScale = 1.0f; + baseParams_->kcScale = 1.0f; + baseParams_->isQcQrScaleEnable = static_cast(std::abs(baseParams_->qcQrScale - 1.0f) >= std::numeric_limits::epsilon()); + baseParams_->isKcScaleEnable = static_cast(std::abs(baseParams_->kcScale - 1.0f) >= std::numeric_limits::epsilon()); + + ICPU_RUN_KF(func, blockDim, tokenX, weightDq, weightUqQr, + weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv,ropeSin, + ropeCos, cacheIndex, kvCache, krCache, dequantScaleX, + dequantScaleWDq, dequantScaleWUqQr, dequantScaleWDkvKr, quantScaleCkv, quantScaleCkr, + smoothScalesCq, queryOut, queryRopeOut, + kvCacheOut, krCacheOut, + workspace, tiling); + + MlaPrologKernel::FreeAllGmMemory( + tokenX, weightDq, weightUqQr, + weightUk, weightDkvKr, rmsnormGammaCq, rmsnormGammaCkv,ropeSin, + ropeCos, cacheIndex, kvCache, krCache, dequantScaleX, + dequantScaleWDq, dequantScaleWUqQr, dequantScaleWDkvKr, quantScaleCkv, quantScaleCkr, + smoothScalesCq, queryOut, queryRopeOut, + kvCacheOut, krCacheOut, + workspace, tiling); +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..1c6b948e06bb632c1aeca4d1fce36c2d9c4fbb7e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/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.moe.moe_gating_top_k.CMakeLists.txt") +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) +if(NOT ENABLE_TEST) + 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/moe_gating_top_k/README.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4e2fbb05acd11b8279ff5db59184f8e5e91aaa81 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/README.md @@ -0,0 +1,324 @@ +# MoeGatingTopK + +## 产品支持情况 + +|产品 | 是否支持 | +|:-------------------------|:----------:| +| Ascend 950PR/Ascend 950DT | √ | +| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | √ | +| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | √ | +| Atlas 200I/500 A2 推理产品 | × | +| Atlas 推理系列产品 | × | +| Atlas 训练系列产品 | × | + +## 功能说明 + +- 算子功能:MoE计算中,对输入x做Sigmoid、SoftMax或者SqrtSoftplus计算,对计算结果分组进行排序,最后根据分组排序的结果选取前k个专家。支持两种模式: + - **TopK模式**:对normValue进行TopK排序选择专家 + - **Hash模式**:根据inputIds从tid2eid映射表中获取预计算的专家索引,跳过排序步骤直接输出 +- 计算公式: + + **TopK模式:** + + **Step 1: 归一化** + + 根据normType对输入x做归一化: + +$$ +normOut = +\begin{cases} + \text{SoftMax}(x), & normType = 0 \\ + \text{Sigmoid}(x), & normType = 1 \\ + \sqrt{\text{Softplus}(x)}, & normType = 2\quad \text{(仅Ascend 950PR/Ascend 950DT支持)} +\end{cases} +$$ + + **Step 2: 加偏置** + + 若bias不为空,加偏置得到用于选择的值: + + $$ + normValue = normOut + bias + $$ + + 否则 $normValue = normOut$。 + + **Step 3: 分组筛选**(仅groupCount > 1 时执行) + + 将normValue按groupCount分组,根据groupSelectMode计算每组得分: + + $$ + groupedValue = Reshape(normValue,\ [batch,\ groupCount,\ -1]) + $$ + + $$ + groupScore = \begin{cases} + ReduceMax(groupedValue,\ dim=-1), & groupSelectMode = 0 \\ + ReduceSum(TopK(groupedValue,\ k=2,\ dim=-1),\ dim=-1), & groupSelectMode = 1 + \end{cases} + $$ + + 选取得分最高的kGroup个组,将未选中组的对应位置置为 $-\infty$: + + $$ + groupIdx = TopK(groupScore,\ k=kGroup).indices + $$ + + $$ + normValue = Mask(groupedValue,\ groupIdx,\ fillValue=-\infty) + $$ + + **Step 4: Top-K专家选择** + + 对normValue取Top-K得到专家索引,这里只需要expertIdxOut: + + $$ + y, expertIdxOut = TopK(normValue[groupIdx, :],\ k=k) + $$ + + **Step 5: Renorm与缩放** + + 根据expertIdxOut从normOut中取出对应的k个专家得分: + + $$ + gathered = normOut[\text{expertIdxOut}] + $$ + + normType=1 or normType=2 时做归一化;normType=0 时,renorm参数生效,renorm=1 时做renorm: + + $$ + if\ (normType = 1\ or\ normType = 2)\ or\ (normType = 0\ and\ renorm = 1): + $$ + + $$ + \quad yOut = \frac{gathered}{ReduceSum(normOut,\ dim=-1) + eps} + $$ + + 否则 $yOut = gathered$ + + 最终输出: + + $$ + yOut = yOut \times routedScalingFactor + $$ + + **Step 6: 可选输出** + + 若outFlag为True,第三个输出为normOut;否则为空。 + + **Hash模式:** + + 当提供inputIds和tid2eid时,启用Hash模式: + + **Step 1: 归一化** + + 根据normType对输入x做归一化(与TopK模式相同): + +$$ +normOut = +\begin{cases} + SoftMax(x), & normType = 0 \\ + Sigmoid(x), & normType = 1 \\ + \sqrt{Softplus(x)}, & normType = 2\ (仅Ascend 950PR/Ascend 950DT支持) +\end{cases} +$$ + + **Step 2: Hash索引查找** + + 根据inputIds从tid2eid映射表获取专家索引: + + $$ + expertIdxOut = tid2eid[inputIds, :] + $$ + + 其中tid2eid的shape为[numKeys, k],inputIds的shape为[batch],每个inputIds值对应一行k个专家索引。 + + **Step 3: Gather与缩放** + + 根据expertIdxOut从normOut中取出对应的k个专家得分: + + $$ + gathered = normOut[expertIdxOut] + $$ + + normType=1 or normType=2 时做归一化;normType=0 时,renorm参数生效,renorm=1 时做renorm: + + $$ + if\ (normType = 1\ or\ normType = 2)\ or\ (normType = 0\ and\ renorm = 1): + $$ + + $$ + \quad yOut = \frac{gathered}{ReduceSum(gathered) + eps} + $$ + + 否则 $yOut = gathered$ + + 最终输出: + + $$ + yOut = yOut \times routedScalingFactor + $$ + +## 参数说明 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出/属性描述数据类型数据格式
x输入待计算输入,对应公式中的`x`。FLOAT16、BFLOAT16、FLOAT32ND
biasOptional输入与输入x进行计算的bias值,对应公式中的`bias`。FLOAT16、BFLOAT16、FLOAT32ND
inputIdsOptional输入Hash模式的输入索引,用于从tid2eid中查找专家索引。对应公式中的`inputIds`。shape为[batch],与x的第一维相等。仅在Hash模式时需要。INT32、INT64ND
tid2eidOptional输入Hash映射表,存储预计算的专家索引。对应公式中的`tid2eid`。shape为[numKeys, k],其中numKeys为映射表行数,k与参数k相等。仅在Hash模式时需要。INT32、INT64ND
k输入topk的k值,对应公式中的`k`。INT64-
kGroup输入分组排序后取的group个数,对应公式中的`kGroup`。INT64-
groupCount输入分组的总个数,对应公式中的`groupCount`。INT64-
routedScalingFactor输入计算yOut使用的routedScalingFactor系数,对应公式中的`routedScalingFactor`。DOUBLE-
eps输入用于计算yOut使用的eps系数,对应公式中的`eps`。DOUBLE-
yOut输出对x做norm、分组排序topk后计算的结果,对应公式中的`yOut`。FLOAT16、BFLOAT16、FLOAT32ND
expertIdxOut输出对x做norm、分组排序topk后的索引,对应公式中的`expertIdxOut`。INT32ND
normOut输出norm计算的输出结果,对应公式中的`normOut`。FLOAT32ND
groupSelectMode输入分组排序方式。INT64-
renorm输入renorm标记。INT64-
normType输入norm函数类型。INT64-
outFlag输入表示是否输出norm操作结果。BOOL-
+ +## 约束说明 + + * 输入shape限制: + * x最后一维(即专家数)要求不大于2048。 + * 输入值域限制: + * 要求1 <= k <= x_shape[-1] / groupCount * kGroup。 + * 要求1 <= kGroup <= groupCount,并且kGroup * x_shape[-1] / groupCount的值要大于等于k。 + * 要求groupCount > 0,x_shape[-1]能够被groupCount整除且整除后的结果大于groupSelectMode,并且整除的结果按照32个数对齐后乘groupCount的结果不大于2048。 + * renorm支持0和1。normType=1或者normType=2时做归一化;normType=0 时,renorm参数生效,renorm=1 时做renorm。 + * 其他限制: + * groupSelectMode取值0和1,0表示使用最大值对group进行排序,1表示使用topk2的sum值对group进行排序。 + * normType取值0、1和2(仅Ascend 950PR/Ascend 950DT支持),0表示使用Softmax函数,1表示使用Sigmoid函数,2表示使用SqrtSoftplus函数。 + * normType取值为1或2时,renorm参数无效;normType取值为0时,renorm参数生效,renorm取值为0和1,0表示不做renorm,1表示做renorm。 + * outFlag取值true和false,true表示输出,false表示不输出。 + * **Hash模式限制**: + * Hash模式需同时提供inputIdsOptional和tid2eidOptional,否则为TopK模式。 + * Hash模式仅支持简化路径(kGroup == groupCount或groupCount == expertCount)。 + * Hash模式下k要求不大于64。 + * tid2eid的shape必须为[numKeys, k],其中numKeys为映射表总行数,k与参数k相等。 + * inputIds的shape必须为[batch],与x的第一维相等。 + * inputIds中的每个值应在[0, numKeys-1]范围内。 + * inputIdsOptional和tid2eidOptional的数据类型支持INT32和INT64的组合。 + +## 调用说明 + +| 调用方式 | 样例代码 | 说明 | +| ---------------- | --------------------------- | --------------------------------------------------- | +| aclnn接口 | [test_aclnn_moe_gating_top_k](examples/test_aclnn_moe_gating_top_k.cpp) | 通过[aclnnMoeGatingTopK](docs/aclnnMoeGatingTopK.md)接口方式调用MoeGatingTopK算子。 | +| aclnn接口 | [test_aclnn_moe_gating_top_k_v2](examples/test_aclnn_moe_gating_top_k_v2.cpp) | 通过[aclnnMoeGatingTopKV2](docs/aclnnMoeGatingTopKV2.md)接口方式调用MoeGatingTopKV2算子(支持Hash模式)。 | +| 图模式 | [test_geir_moe_gating_top_k](examples/test_geir_moe_gating_top_k.cpp) | 通过[算子IR](op_graph/moe_gating_top_k_proto.h)构图方式调用MoeGatingTopK算子。 | diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/docs/aclnnMoeGatingTopK.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/docs/aclnnMoeGatingTopK.md new file mode 100644 index 0000000000000000000000000000000000000000..1d1d4b2723224707f02430f8deb273dfeb0cac89 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/docs/aclnnMoeGatingTopK.md @@ -0,0 +1,608 @@ +# aclnnMoeGatingTopK + +[📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/moe/moe_gating_top_k) + +## 产品支持情况 + +|产品 | 是否支持 | +|:-------------------------|:----------:| +| Ascend 950PR/Ascend 950DT | √ | +| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | √ | +| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | √ | +| Atlas 200I/500 A2 推理产品 | × | +| Atlas 推理系列产品 | × | +| Atlas 训练系列产品 | × | + +## 功能说明 + +- 算子功能:MoE计算中,对输入x做Sigmoid、SoftMax或者SqrtSoftplus计算,对计算结果分组进行排序,最后根据分组排序的结果选取前k个专家。 +- 计算公式: + + **Step 1: 归一化** + + 根据normType对输入x做归一化: + +$$ +normOut = +\begin{cases} + \text{SoftMax}(x), & normType = 0 \\ + \text{Sigmoid}(x), & normType = 1 \\ + \sqrt{\text{Softplus}(x)}, & normType = 2\quad \text{(仅Ascend 950PR/Ascend 950DT支持)} +\end{cases} +$$ + + **Step 2: 加偏置** + + 若bias不为空,加偏置得到用于选择的值: + + $$ + normValue = normOut + bias + $$ + + 否则 $normValue = normOut$。 + + **Step 3: 分组筛选**(仅groupCount > 1 时执行) + + 将normValue按groupCount分组,根据groupSelectMode计算每组得分: + + $$ + groupedValue = Reshape(normValue,\ [batch,\ groupCount,\ -1]) + $$ + + $$ + groupScore = \begin{cases} + ReduceMax(groupedValue,\ dim=-1), & groupSelectMode = 0 \\ + ReduceSum(TopK(groupedValue,\ k=2,\ dim=-1),\ dim=-1), & groupSelectMode = 1 + \end{cases} + $$ + + 选取得分最高的kGroup个组,将未选中组的对应位置置为 $-\infty$: + + $$ + groupIdx = TopK(groupScore,\ k=kGroup).indices + $$ + + $$ + normValue = Mask(groupedValue,\ groupIdx,\ fillValue=-\infty) + $$ + + **Step 4: Top-K专家选择** + + 对normValue取Top-K得到专家索引,这里只需要expertIdxOut: + + $$ + y, expertIdxOut = TopK(normValue[groupIdx, :],\ k=k) + $$ + + **Step 5: Renorm与缩放** + + 根据expertIdxOut从normOut中取出对应的k个专家得分: + + $$ + gathered = normOut[\text{expertIdxOut}] + $$ + + normType=1 or normType=2 时做归一化;normType=0 时,renorm参数生效,renorm=1 时做renorm: + + $$ + if\ (normType = 1\ or\ normType = 2)\ or\ (normType = 0\ and\ renorm = 1): + $$ + + $$ + \quad yOut = \frac{gathered}{ReduceSum(normOut,\ dim=-1) + eps} + $$ + + 否则 $yOut = gathered$ + + 最终输出: + + $$ + yOut = yOut \times routedScalingFactor + $$ + + **Step 6: 可选输出** + + 若outFlag为True,第三个输出为normOut;否则为空。 + +## 函数原型 + +该算子采用两段式接口,必须先调用“aclnnMoeGatingTopKGetWorkspaceSize”接口获取计算所需workspace大小以及包含了算子计算流程的执行器,再调用“aclnnMoeGatingTopK”接口执行计算。 + +```Cpp +aclnnStatus aclnnMoeGatingTopKGetWorkspaceSize( + const aclTensor *x, + const aclTensor *biasOptional, + int64_t k, + int64_t kGroup, + int64_t groupCount, + int64_t groupSelectMode, + int64_t renorm, + int64_t normType, + bool outFlag, + double routedScalingFactor, + double eps, + const aclTensor *yOut, + const aclTensor *expertIdxOut, + const aclTensor *outOut, + uint64_t *workspaceSize, + aclOpExecutor **executor) +``` + +```Cpp +aclnnStatus aclnnMoeGatingTopK( + void *workspace, + uint64_t workspaceSize, + aclOpExecutor *executor, + aclrtStream stream) +``` + +## aclnnMoeGatingTopKGetWorkspaceSize + +- **参数说明:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述使用说明数据类型数据格式维度(shape)非连续Tensor
x输入待计算入参,对应公式中的x。无FLOAT16、BFLOAT16、FLOAT32ND2√
biasOptional输入与输入x进行计算的bias值,对应公式中的`bias`。shape值与x最后一维相等。FLOAT16、BFLOAT16、FLOAT32ND1√
k输入topk的k值,对应公式中的`k`。无INT64---
kGroup输入分组排序后取的group个数,对应公式中的`kGroup`。无INT64---
groupCount输入分组的总个数,对应公式中的`groupCount`无INT64---
groupSelectMode输入分组排序方式。无INT64---
renorm输入renorm标记。无INT64---
normType输入norm函数类型。无INT64---
outFlag输入表示是否输出norm操作结果。无BOOL---
routedScalingFactor输入计算yOut使用的routedScalingFactor系数,对应公式中的`routedScalingFactor`。无DOUBLE---
eps输入用于计算yOut使用的eps系数,对应公式中的`eps`。无DOUBLE---
yOut输出对x做norm、分组排序topk后计算的结果,对应公式中的`yOut`。数据类型与x需要保持一致。FLOAT16、BFLOAT16、FLOAT32ND2-
expertIdxOut输出对x做norm、分组排序topk后的索引,对应公式中的`expertIdxOut`。shape要求与yOut一致。INT32ND2-
outOut输出norm计算的输出结果,对应公式中的`normOut`。shape要求与x保持一致。FLOAT32ND2-
workspaceSize输出返回需要在Device侧申请的workspace大小。-----
executor输出返回op执行器,包含了算子计算流程。-----
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + + 第一段接口完成入参校验,出现以下场景时报错: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
返回值错误码描述
ACLNN_ERR_PARAM_NULLPTR161001计算输入和计算输出是空指针。
ACLNN_ERR_PARAM_NULLPTR161002输入和输出的数据类型不在支持的范围内。
ACLNN_ERR_INNER_TILING_ERROR561002 + x的shape不满足要求。
+ x和biasOptional的shape不匹配。
+ k的大小不在1到x_shape[-1] / groupCount * kGroup之间。
+ kGroup的大小不在1到groupCount之间。
+ 每个group的专家数按32对齐之后
+ 计算输入参数的值不满足要求。
+
+ +## aclnnMoeGatingTopK + +- **参数说明:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述
workspace输入在Device侧申请的workspace内存地址。
workspaceSize输入在Device侧申请的workspace大小,由第一段接口aclnnMoeGatingTopKGetWorkspaceSize获取。
executor输入op执行器,包含了算子计算流程。
stream输入指定执行任务的Stream。
+ +- **返回值:** + + 返回 aclnnStatus 状态码。 + +## 约束说明 + +- 确定性计算: + - aclnnMoeGatingTopK默认确定性实现。 + +* 输入shape限制: + * x最后一维(即专家数)要求不大于2048。 +* 输入值域限制: + * 要求1 <= k <= x_shape[-1] / groupCount * kGroup。 + * 要求1 <= kGroup <= groupCount,并且kGroup * x_shape[-1] / groupCount的值要大于等于k。 + * 要求groupCount > 0,x_shape[-1]能够被groupCount整除且整除后的结果大于groupSelectMode,并且整除的结果按照32个数对齐后乘groupCount的结果不大于2048。 +* 其他限制: + * groupSelectMode取值0和1,0表示使用最大值对group进行排序, 1表示使用topk2的sum值对group进行排序。 + * normType取值0、1和2(仅Ascend 950PR/Ascend 950DT 支持),0表示使用Softmax函数,1表示使用Sigmoid函数,2表示使用SqrtSoftplus函数。 + * normType取值为1时,renorm参数无效;normType取值为0时,renorm参数生效,renorm取值为0和1,0表示不做renorm,1表示做renorm。 + * outFlag取值true和false,true表示输出,false表示不输出。 + * 输入不支持空Tensor,不支持标量Tensor。 + +## 调用示例 + +以下示例代码展示接口调用流程,可供编译和运行时参考。 + +```Cpp +#include "acl/acl.h" +#include "aclnnop/aclnn_moe_gating_top_k.h" +#include +#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 GenerateRandomFloats(int64_t count) { + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_real_distribution dist(0.0f, 10.0f); + + std::vector result(count); + for (auto& num : result) { + num = dist(gen); + } + return result; +} +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的接口自定义构造 + std::vector inputShape = {3, 256}; + std::vector biasShape = {256}; + std::vector outShape = {3, 8}; + std::vector expertIdOutShape = {3, 8}; + std::vector normOutShape = {3, 256}; + + void* inputAddr = nullptr; + void* biasAddr = nullptr; + void* outAddr = nullptr; + void* expertIdOutAddr = nullptr; + void* normOutAddr = nullptr; + + aclTensor* input = nullptr; + aclTensor* bias = nullptr; + aclTensor* out = nullptr; + aclTensor* expertIdOut = nullptr; + aclTensor* normOut = nullptr; + + std::vector inputHostData = GenerateRandomFloats(GetShapeSize(inputShape)); + std::vector biasHostData = GenerateRandomFloats(GetShapeSize(biasShape)); + std::vector outHostData(GetShapeSize(outShape)); + std::vector expertIdOutHostData(GetShapeSize(expertIdOutShape)); + std::vector normOutHostData(GetShapeSize(normOutShape)); + + // 创建expandedPermutedRows aclTensor + ret = CreateAclTensor(inputHostData, inputShape, &inputAddr, aclDataType::ACL_FLOAT, &input); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建expandedPermutedRows aclTensor + ret = CreateAclTensor(biasHostData, biasShape, &biasAddr, aclDataType::ACL_FLOAT, &bias); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建expertForSourceRow aclTensor + ret = CreateAclTensor(outHostData, outShape, &outAddr, aclDataType::ACL_FLOAT, &out); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建expandedSrcToDstRow aclTensor + ret = CreateAclTensor(expertIdOutHostData, expertIdOutShape, &expertIdOutAddr, aclDataType::ACL_INT32, &expertIdOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建expandedSrcToDstRow aclTensor + ret = CreateAclTensor(normOutHostData, normOutShape, &normOutAddr, aclDataType::ACL_FLOAT, &normOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3.调用CANN算子库API,需要修改为具体的算子接口 + uint64_t workspaceSize = 0; + aclOpExecutor* executor; + + // 调用aclnnMoeGatingTopK第一段接口 + ret = aclnnMoeGatingTopKGetWorkspaceSize(input, bias, 8, 4, 8, 1, 0, 1, false, 1, 1, out, expertIdOut, normOut, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeGatingTopKGetWorkspaceSize 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;); + } + // 调用aclnnMoeGatingTopK第二段接口 + ret = aclnnMoeGatingTopK(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeGatingTopK 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, 0.0f); + ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), + outAddr, size * sizeof(float), 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, resultData[i]); + } + + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(input); + aclDestroyTensor(bias); + aclDestroyTensor(out); + aclDestroyTensor(expertIdOut); + aclDestroyTensor(normOut); + + // 7. 释放device资源,需要根据具体API的接口定义修改 + aclrtFree(inputAddr); + aclrtFree(biasAddr); + aclrtFree(outAddr); + aclrtFree(normOutAddr); + aclrtFree(expertIdOutAddr); + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtResetDevice(deviceId); + aclFinalize(); + return 0; +} +``` diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/docs/aclnnMoeGatingTopKV2.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/docs/aclnnMoeGatingTopKV2.md new file mode 100644 index 0000000000000000000000000000000000000000..9381971a06b3ab13099d084b52f94401abc725fb --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/docs/aclnnMoeGatingTopKV2.md @@ -0,0 +1,721 @@ +# aclnnMoeGatingTopKV2 + +[📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/moe/moe_gating_top_k) + +## 产品支持情况 + +|产品 | 是否支持 | +|:-------------------------|:----------:| +| Ascend 950PR/Ascend 950DT | √ | +| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | √ | +| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | √ | +| Atlas 200I/500 A2 推理产品 | × | +| Atlas 推理系列产品 | × | +| Atlas 训练系列产品 | × | + +## 功能说明 + +- 接口功能:MoE计算中,对输入x做Sigmoid、SoftMax或者SqrtSoftplus计算,对计算结果分组进行排序,最后根据分组排序的结果选取前k个专家。支持两种模式: + - **TopK模式**:对normValue进行TopK排序选择专家 + - **Hash模式**:根据inputIds从tid2eid映射表中获取预计算的专家索引,跳过排序步骤直接输出(aclnnMoeGatingTopKV2新增支持) + +- 计算公式: + + **TopK模式:** + + **Step 1: 归一化** + + 根据normType对输入x做归一化: + + $$ + normOut = + \begin{cases} + \text{SoftMax}(x), & normType = 0 \\ + \text{Sigmoid}(x), & normType = 1 \\ + \sqrt{\text{Softplus}(x)}, & normType = 2\quad \text{(仅Ascend 950PR/Ascend 950DT支持)} + \end{cases} + $$ + + **Step 2: 加偏置** + + 若bias不为空,加偏置得到用于选择的值: + + $$ + normValue = normOut + bias + $$ + + 否则 $normValue = normOut$。 + + **Step 3: 分组筛选**(仅groupCount > 1 时执行) + + 将normValue按groupCount分组,根据groupSelectMode计算每组得分: + + $$ + groupedValue = Reshape(normValue,\ [batch,\ groupCount,\ -1]) + $$ + + $$ + groupScore = \begin{cases} + ReduceMax(groupedValue,\ dim=-1), & groupSelectMode = 0 \\ + ReduceSum(TopK(groupedValue,\ k=2,\ dim=-1),\ dim=-1), & groupSelectMode = 1 + \end{cases} + $$ + + 选取得分最高的kGroup个组,将未选中组的对应位置置为 $-\infty$: + + $$ + groupIdx = TopK(groupScore,\ k=kGroup).indices + $$ + + $$ + normValue = Mask(groupedValue,\ groupIdx,\ fillValue=-\infty) + $$ + + **Step 4: Top-K专家选择** + + 对normValue取Top-K得到专家索引,这里只需要expertIdxOut: + + $$ + y, expertIdxOut = TopK(normValue[groupIdx, :],\ k=k) + $$ + + **Step 5: Renorm与缩放** + + 根据expertIdxOut从normOut中取出对应的k个专家得分: + + $$ + gathered = normOut[\text{expertIdxOut}] + $$ + + normType=1 or normType=2 时做归一化;normType=0 时,renorm参数生效,renorm=1 时做renorm: + + $$ + if\ (normType = 1\ or\ normType = 2)\ or\ (normType = 0\ and\ renorm = 1): + $$ + + $$ + \quad yOut = \frac{gathered}{ReduceSum(normOut,\ dim=-1) + eps} + $$ + + 否则 $yOut = gathered$ + + 最终输出: + + $$ + yOut = yOut \times routedScalingFactor + $$ + + **Step 6: 可选输出** + + 若outFlag为True,第三个输出为normOut;否则为空。 + + **Hash模式:** + + 当提供inputIds和tid2eid时,启用Hash模式: + + **Step 1: 归一化** + + 根据normType对输入x做归一化(与TopK模式相同): + + $$ + normOut = + \begin{cases} + SoftMax(x), & normType = 0 \\ + Sigmoid(x), & normType = 1 \\ + \sqrt{Softplus(x)}, & normType = 2\ (仅Ascend 950PR/Ascend 950DT支持) + \end{cases} + $$ + + **Step 2: Hash索引查找** + + 根据inputIds从tid2eid映射表获取专家索引: + + $$ + expertIdxOut = tid2eid[inputIds, :] + $$ + + 其中tid2eid的shape为[numKeys, k],inputIds的shape为[batch],每个inputIds值对应一行k个专家索引。 + + **Step 3: Gather与缩放** + + 根据expertIdxOut从normOut中取出对应的k个专家得分: + + $$ + gathered = normOut[expertIdxOut] + $$ + + normType=1 or normType=2 时做归一化;normType=0 时,renorm参数生效,renorm=1 时做renorm: + + $$ + if\ (normType = 1\ or\ normType = 2)\ or\ (normType = 0\ and\ renorm = 1): + $$ + + $$ + \quad yOut = \frac{gathered}{ReduceSum(gathered) + eps} + $$ + + 否则 $yOut = gathered$ + + 最终输出: + + $$ + yOut = yOut \times routedScalingFactor + $$ + +## 函数原型 + +该算子采用两段式接口,必须先调用"aclnnMoeGatingTopKV2GetWorkspaceSizeV2"接口获取计算所需workspace大小以及包含了算子计算流程的执行器,再调用"aclnnMoeGatingTopKV2"接口执行计算。 + +```Cpp +aclnnStatus aclnnMoeGatingTopKV2GetWorkspaceSize( + const aclTensor *x, + const aclTensor *biasOptional, + const aclTensor *inputIdsOptional, + const aclTensor *tid2eidOptional, + int64_t k, + int64_t kGroup, + int64_t groupCount, + int64_t groupSelectMode, + int64_t renorm, + int64_t normType, + bool outFlag, + double routedScalingFactor, + double eps, + const aclTensor *yOut, + const aclTensor *expertIdxOut, + const aclTensor *outOut, + uint64_t *workspaceSize, + aclOpExecutor **executor) +``` + +```Cpp +aclnnStatus aclnnMoeGatingTopKV2( + void *workspace, + uint64_t workspaceSize, + aclOpExecutor *executor, + aclrtStream stream) +``` + +## aclnnMoeGatingTopKV2GetWorkspaceSize + +- **参数说明:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述使用说明数据类型数据格式维度(shape)非连续Tensor
x输入待计算入参,对应公式中的x。无FLOAT16、BFLOAT16、FLOAT32ND2√
biasOptional输入与输入x进行计算的bias值,对应公式中的bias。shape值与x最后一维相等。FLOAT16、BFLOAT16、FLOAT32ND1√
inputIdsOptional输入Hash模式的输入索引,用于从tid2eid中查找专家索引。对应公式中的inputIds。shape为[batch],与x的第一维相等。仅在Hash模式时需要。INT32、INT64ND1√
tid2eidOptional输入Hash映射表,存储预计算的专家索引。对应公式中的tid2eid。shape为[numKeys, k],其中numKeys为映射表行数,k与参数k相等。仅在Hash模式时需要。INT32、INT64ND2√
k输入topk的k值,对应公式中的k。无INT64---
kGroup输入分组排序后取的group个数,对应公式中的kGroup。无INT64---
groupCount输入分组的总个数,对应公式中的groupCount无INT64---
groupSelectMode输入分组排序方式。无INT64---
renorm输入renorm标记。无INT64---
normType输入norm函数类型。无INT64---
outFlag输入表示是否输出norm操作结果。无BOOL---
routedScalingFactor输入计算yOut使用的routedScalingFactor系数,对应公式中的routedScalingFactor。无DOUBLE---
eps输入用于计算yOut使用的eps系数,对应公式中的eps。无DOUBLE---
yOut输出对x做norm、分组排序topk后计算的结果,对应公式中的yOut。数据类型与x需要保持一致。FLOAT16、BFLOAT16、FLOAT32ND2-
expertIdxOut输出对x做norm、分组排序topk后的索引,对应公式中的expertIdxOut。shape要求与yOut一致。INT32ND2-
outOut输出norm计算的输出结果,对应公式中的normOut。shape要求与x保持一致。FLOAT32ND2-
workspaceSize输出返回需要在Device侧申请的workspace大小。-----
executor输出返回op执行器,包含了算子计算流程。-----
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + + 第一段接口完成入参校验,出现以下场景时报错: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
返回值错误码描述
ACLNN_ERR_PARAM_NULLPTR161001计算输入和计算输出是空指针。
ACLNN_ERR_PARAM_NULLPTR161002输入和输出的数据类型不在支持的范围内。
ACLNN_ERR_INNER_TILING_ERROR561002 + x的shape不满足要求。
+ x和biasOptional的shape不匹配。
+ k的大小不在1到x_shape[-1] / groupCount * kGroup之间。
+ kGroup的大小不在1到groupCount之间。
+ 每个group的专家数按32对齐之后
+ 计算输入参数的值不满足要求。
+ Hash模式下k超过64。
+ Hash模式下tid2eid的shape不匹配。
+ Hash模式下inputIds的shape不匹配。
+ Hash模式下不支持非简化路径。
+
+ +## aclnnMoeGatingTopKV2 + +- **参数说明:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述
workspace输入在Device侧申请的workspace内存地址。
workspaceSize输入在Device侧申请的workspace大小,由第一段接口aclnnMoeGatingTopKV2GetWorkspaceSizeV2获取。
executor输入op执行器,包含了算子计算流程。
stream输入指定执行任务的Stream。
+ +- **返回值:** + + 返回 aclnnStatus 状态码。 + +## 约束说明 + +- 确定性计算: + - aclnnMoeGatingTopKV2默认确定性实现。 + +* 输入shape限制: + * x最后一维(即专家数)要求不大于2048。 +* 输入值域限制: + * 要求1 <= k <= x_shape[-1] / groupCount * kGroup。 + * 要求1 <= kGroup <= groupCount,并且kGroup * x_shape[-1] / groupCount的值要大于等于k。 + * 要求groupCount > 0,x_shape[-1]能够被groupCount整除且整除后的结果大于groupSelectMode,并且整除的结果按照32个数对齐后乘groupCount的结果不大于2048。 +* 其他限制: + * groupSelectMode取值0和1,0表示使用最大值对group进行排序, 1表示使用topk2的sum值对group进行排序。 + * normType取值0、1和2(仅Ascend 950PR/Ascend 950DT支持),0表示使用Softmax函数,1表示使用Sigmoid函数,2表示使用SqrtSoftplus函数。 + * normType取值为1或2时,renorm参数无效;normType取值为0时,renorm参数生效,renorm取值为0和1,0表示不做renorm,1表示做renorm。 + * outFlag取值true和false,true表示输出,false表示不输出。 +* **Hash模式限制**: + * Hash模式需同时提供inputIdsOptional和tid2eidOptional,否则为TopK模式。 + * Hash模式仅支持简化路径(kGroup == groupCount或groupCount == expertCount)。 + * Hash模式下k要求不大于64。 + * tid2eid的shape必须为[numKeys, k],其中numKeys为映射表总行数,k与参数k相等。 + * inputIds的shape必须为[batch],与x的第一维相等。 + * inputIds中的每个值应在[0, numKeys-1]范围内。 + * inputIdsOptional和tid2eidOptional的数据类型支持INT32和INT64的组合。 + +## 调用示例 + +以下示例代码展示接口调用流程,可供编译和运行时参考。 + +```Cpp +#include "acl/acl.h" +#include "aclnnop/aclnn_moe_gating_top_k_v2.h" +#include +#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 GenerateRandomFloats(int64_t count) { + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_real_distribution dist(0.0f, 10.0f); + + std::vector result(count); + for (auto& num : result) { + num = dist(gen); + } + return result; +} +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的接口自定义构造 + std::vector inputShape = {3, 256}; + std::vector biasShape = {256}; + std::vector inputIdsShape = {3}; + std::vector tid2eidShape = {3, 2}; + std::vector outShape = {3, 2}; + std::vector expertIdOutShape = {3, 2}; + std::vector normOutShape = {3, 256}; + + void* inputAddr = nullptr; + void* biasAddr = nullptr; + void* inputIdsAddr = nullptr; + void* tid2eidAddr = nullptr; + void* outAddr = nullptr; + void* expertIdOutAddr = nullptr; + void* normOutAddr = nullptr; + + aclTensor* input = nullptr; + aclTensor* bias = nullptr; + aclTensor* inputIds = nullptr; + aclTensor* tid2eid = nullptr; + aclTensor* out = nullptr; + aclTensor* expertIdOut = nullptr; + aclTensor* normOut = nullptr; + + std::vector inputHostData = GenerateRandomFloats(GetShapeSize(inputShape)); + std::vector biasHostData = GenerateRandomFloats(GetShapeSize(biasShape)); + std::vector inputIdsHostData = {0, 2, 1}; + std::vector tid2eidHostData = { + 10, 42, + 33, 127, + 5, 88 + }; + std::vector outHostData(GetShapeSize(outShape)); + std::vector expertIdOutHostData(GetShapeSize(expertIdOutShape)); + std::vector normOutHostData(GetShapeSize(normOutShape)); + + // 创建input aclTensor + ret = CreateAclTensor(inputHostData, inputShape, &inputAddr, aclDataType::ACL_FLOAT, &input); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建bias aclTensor + ret = CreateAclTensor(biasHostData, biasShape, &biasAddr, aclDataType::ACL_FLOAT, &bias); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建inputIds aclTensor + ret = CreateAclTensor(inputIdsHostData, inputIdsShape, &inputIdsAddr, aclDataType::ACL_INT32, &inputIds); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建tid2eid aclTensor + ret = CreateAclTensor(tid2eidHostData, tid2eidShape, &tid2eidAddr, aclDataType::ACL_INT32, &tid2eid); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建out aclTensor + ret = CreateAclTensor(outHostData, outShape, &outAddr, aclDataType::ACL_FLOAT, &out); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建expertIdOut aclTensor + ret = CreateAclTensor(expertIdOutHostData, expertIdOutShape, &expertIdOutAddr, aclDataType::ACL_INT32, &expertIdOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建normOut aclTensor + ret = CreateAclTensor(normOutHostData, normOutShape, &normOutAddr, aclDataType::ACL_FLOAT, &normOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3.调用CANN算子库API,需要修改为具体的算子接口 + uint64_t workspaceSize = 0; + aclOpExecutor* executor; + + // 调用aclnnMoeGatingTopKV2第一段接口 + ret = aclnnMoeGatingTopKV2GetWorkspaceSize(input, bias, inputIds, tid2eid, 2, 1, 1, 1, 0, 1, false, 1.0, 1e-20, out, expertIdOut, normOut, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeGatingTopKV2GetWorkspaceSize 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;); + } + // 调用aclnnMoeGatingTopKV2第二段接口 + ret = aclnnMoeGatingTopKV2(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeGatingTopKV2 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, 0.0f); + ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), + outAddr, size * sizeof(float), 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, resultData[i]); + } + + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(input); + aclDestroyTensor(bias); + aclDestroyTensor(inputIds); + aclDestroyTensor(tid2eid); + aclDestroyTensor(out); + aclDestroyTensor(expertIdOut); + aclDestroyTensor(normOut); + + // 7. 释放device资源,需要根据具体API的接口定义修改 + aclrtFree(inputAddr); + aclrtFree(biasAddr); + aclrtFree(inputIdsAddr); + aclrtFree(tid2eidAddr); + aclrtFree(outAddr); + aclrtFree(normOutAddr); + aclrtFree(expertIdOutAddr); + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtResetDevice(deviceId); + aclFinalize(); + return 0; +} +``` diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/examples/test_aclnn_moe_gating_top_k.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/examples/test_aclnn_moe_gating_top_k.cpp new file mode 100644 index 0000000000000000000000000000000000000000..794514c06d36b4b0648874b9cabe5be148dd6a7c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/examples/test_aclnn_moe_gating_top_k.cpp @@ -0,0 +1,258 @@ +/** + * 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 "acl/acl.h" +#include "aclnnop/aclnn_moe_gating_top_k.h" +#include +#include +#include + +#define CHECK_RET(cond) ((cond) ? true : (false)) + +#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 GenerateRandomFloats(int64_t count) { + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_real_distribution dist(0.0f, 10.0f); + + std::vector result(count); + for (auto& num : result) { + num = dist(gen); + } + return result; +} +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); + // 调用aclrtMalloc申请device侧内存 + 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; + } + // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上 + 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; + } + // 计算连续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; +} + +struct TensorResources { + void* inputDeviceAddr = nullptr; + void* biasDeviceAddr = nullptr; + void* outDeviceAddr = nullptr; + void* expertIdOutDeviceAddr = nullptr; + void* normOutDeviceAddr = nullptr; + aclTensor* inputTensor = nullptr; + aclTensor* biasTensor = nullptr; + aclTensor* outTensor = nullptr; + aclTensor* expertIdOutTensor = nullptr; + aclTensor* normOutTensor = nullptr; +}; + +void CleanupResources(TensorResources& resources, void* workspaceAddr, + aclrtStream stream, int32_t deviceId) { + if (resources.inputTensor) { + aclDestroyTensor(resources.inputTensor); + } + if (resources.biasTensor) { + aclDestroyTensor(resources.biasTensor); + } + if (resources.outTensor) { + aclDestroyTensor(resources.outTensor); + } + if (resources.expertIdOutTensor) { + aclDestroyTensor(resources.expertIdOutTensor); + } + if (resources.normOutTensor) { + aclDestroyTensor(resources.normOutTensor); + } + if (resources.inputDeviceAddr) { + aclrtFree(resources.inputDeviceAddr); + } + if (resources.biasDeviceAddr) { + aclrtFree(resources.biasDeviceAddr); + } + if (resources.outDeviceAddr) { + aclrtFree(resources.outDeviceAddr); + } + if (resources.expertIdOutDeviceAddr) { + aclrtFree(resources.expertIdOutDeviceAddr); + } + if (resources.normOutDeviceAddr) { + aclrtFree(resources.normOutDeviceAddr); + } + if (workspaceAddr) { + aclrtFree(workspaceAddr); + } + if (stream) { + aclrtDestroyStream(stream); + } + aclrtResetDevice(deviceId); + aclFinalize(); +} + +int main() { + // 1. (固定写法)device/stream初始化, 参考AscendCL对外接口列表 + // 根据自己的实际device填写deviceId + int32_t deviceId = 0; + aclrtStream stream = nullptr; + auto ret = Init(deviceId, &stream); + if (!CHECK_RET(ret == 0)) { + LOG_PRINT("Init acl failed. ERROR: %d\n", ret); + return ret; + } + + // 2. 构造输入与输出,需要根据API的接口自定义构造 + std::vector inputShape = {3, 256}; + std::vector biasShape = {256}; + std::vector outShape = {3, 8}; + std::vector expertIdOutShape = {3, 8}; + std::vector normOutShape = {3, 256}; + + TensorResources resources = {}; + void* workspaceAddr = nullptr; + uint64_t workspaceSize = 0; + + std::vector inputHostData = GenerateRandomFloats(GetShapeSize(inputShape)); + std::vector biasHostData = GenerateRandomFloats(GetShapeSize(biasShape)); + std::vector outHostData(GetShapeSize(outShape)); + std::vector expertIdOutHostData(GetShapeSize(expertIdOutShape)); + std::vector normOutHostData(GetShapeSize(normOutShape)); + + // 创建expandedPermutedRows aclTensor + ret = CreateAclTensor(inputHostData, inputShape, &resources.inputDeviceAddr, aclDataType::ACL_FLOAT, &resources.inputTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + CleanupResources(resources, workspaceAddr, stream, deviceId); + return ret; + } + // 创建expandedPermutedRows aclTensor + ret = CreateAclTensor(biasHostData, biasShape, &resources.biasDeviceAddr, aclDataType::ACL_FLOAT, &resources.biasTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + CleanupResources(resources, workspaceAddr, stream, deviceId); + return ret; + } + // 创建expertForSourceRow aclTensor + ret = CreateAclTensor(outHostData, outShape, &resources.outDeviceAddr, aclDataType::ACL_FLOAT, &resources.outTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + CleanupResources(resources, workspaceAddr, stream, deviceId); + return ret; + } + // 创建expandedSrcToDstRow aclTensor + ret = CreateAclTensor(expertIdOutHostData, expertIdOutShape, &resources.expertIdOutDeviceAddr, aclDataType::ACL_INT32, &resources.expertIdOutTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + CleanupResources(resources, workspaceAddr, stream, deviceId); + return ret; + } + // 创建expandedSrcToDstRow aclTensor + ret = CreateAclTensor(normOutHostData, normOutShape, &resources.normOutDeviceAddr, aclDataType::ACL_FLOAT, &resources.normOutTensor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + CleanupResources(resources, workspaceAddr, stream, deviceId); + return ret; + } + + // 3.调用CANN算子库API,需要修改为具体的算子接口 + aclOpExecutor* executor; + + // 调用aclnnMoeGatingTopK第一段接口 + ret = aclnnMoeGatingTopKGetWorkspaceSize(resources.inputTensor, resources.biasTensor, 8, 4, 8, 1, 0, 1, false, 1, 1, + resources.outTensor, resources.expertIdOutTensor, resources.normOutTensor, + &workspaceSize, &executor); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclnnMoeGatingTopKGetWorkspaceSize failed. ERROR: %d\n", ret); + CleanupResources(resources, workspaceAddr, stream, deviceId); + return ret; + } + // 根据第一段接口计算出的workspaceSize申请device内存 + if (workspaceSize > 0) { + ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); + CleanupResources(resources, workspaceAddr, stream, deviceId); + return ret; + } + } + // 调用aclnnMoeGatingTopK第二段接口 + ret = aclnnMoeGatingTopK(workspaceAddr, workspaceSize, executor, stream); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("aclnnMoeGatingTopK failed. ERROR: %d\n", ret); + CleanupResources(resources, workspaceAddr, stream, deviceId); + return ret; + } + + // 4.( 固定写法)同步等待任务执行结束 + 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. 获取输出的值,将device侧内存上的结果拷贝至Host侧,需要根据具体API的接口定义修改 + auto size = GetShapeSize(outShape); + std::vector resultData(size, 0.0f); + ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), + resources.outDeviceAddr, size * sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST); + if (!CHECK_RET(ret == ACL_SUCCESS)) { + LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); + CleanupResources(resources, workspaceAddr, stream, deviceId); + return ret; + } + for (int64_t i = 0; i < size; i++) { + LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]); + } + + // 6. 清理资源 + CleanupResources(resources, workspaceAddr, stream, deviceId); + return 0; +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/examples/test_aclnn_moe_gating_top_k_v2.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/examples/test_aclnn_moe_gating_top_k_v2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..046941d45ba37d1362ab71500a88952db03348e5 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/examples/test_aclnn_moe_gating_top_k_v2.cpp @@ -0,0 +1,207 @@ +/** + * 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_moe_gating_top_k_v2.h" +#include +#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 GenerateRandomFloats(int64_t count) +{ + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_real_distribution dist(0.0f, 10.0f); + + std::vector result(count); + for (auto &num : result) { + num = dist(gen); + } + return result; +} +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的接口自定义构造 + std::vector inputShape = {3, 256}; + std::vector biasShape = {256}; + std::vector inputIdsShape = {3}; + std::vector tid2eidShape = {3, 2}; + std::vector outShape = {3, 2}; + std::vector expertIdOutShape = {3, 2}; + std::vector normOutShape = {3, 256}; + + void *inputAddr = nullptr; + void *biasAddr = nullptr; + void *inputIdsAddr = nullptr; + void *tid2eidAddr = nullptr; + void *outAddr = nullptr; + void *expertIdOutAddr = nullptr; + void *normOutAddr = nullptr; + + aclTensor *input = nullptr; + aclTensor *bias = nullptr; + aclTensor *inputIds = nullptr; + aclTensor *tid2eid = nullptr; + aclTensor *out = nullptr; + aclTensor *expertIdOut = nullptr; + aclTensor *normOut = nullptr; + + std::vector inputHostData = GenerateRandomFloats(GetShapeSize(inputShape)); + std::vector biasHostData = GenerateRandomFloats(GetShapeSize(biasShape)); + std::vector inputIdsHostData = {0, 2, 1}; + std::vector tid2eidHostData = {10, 42, 33, 127, 5, 88}; + std::vector outHostData(GetShapeSize(outShape)); + std::vector expertIdOutHostData(GetShapeSize(expertIdOutShape)); + std::vector normOutHostData(GetShapeSize(normOutShape)); + + // 创建input aclTensor + ret = CreateAclTensor(inputHostData, inputShape, &inputAddr, aclDataType::ACL_FLOAT, &input); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建bias aclTensor + ret = CreateAclTensor(biasHostData, biasShape, &biasAddr, aclDataType::ACL_FLOAT, &bias); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建inputIds aclTensor + ret = CreateAclTensor(inputIdsHostData, inputIdsShape, &inputIdsAddr, aclDataType::ACL_INT32, &inputIds); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建tid2eid aclTensor + ret = CreateAclTensor(tid2eidHostData, tid2eidShape, &tid2eidAddr, aclDataType::ACL_INT32, &tid2eid); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建out aclTensor + ret = CreateAclTensor(outHostData, outShape, &outAddr, aclDataType::ACL_FLOAT, &out); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建expertIdOut aclTensor + ret = + CreateAclTensor(expertIdOutHostData, expertIdOutShape, &expertIdOutAddr, aclDataType::ACL_INT32, &expertIdOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + // 创建normOut aclTensor + ret = CreateAclTensor(normOutHostData, normOutShape, &normOutAddr, aclDataType::ACL_FLOAT, &normOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3.调用CANN算子库API,需要修改为具体的算子接口 + uint64_t workspaceSize = 0; + aclOpExecutor *executor; + + // 调用aclnnMoeGatingTopKV2第一段接口 + ret = aclnnMoeGatingTopKV2GetWorkspaceSize(input, bias, inputIds, tid2eid, 2, 1, 1, 1, 0, 1, false, 1.0, 1e-20, out, + expertIdOut, normOut, &workspaceSize, &executor); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeGatingTopKV2GetWorkspaceSize 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;); + } + // 调用aclnnMoeGatingTopKV2第二段接口 + ret = aclnnMoeGatingTopKV2(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeGatingTopKV2 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, 0.0f); + ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outAddr, size * sizeof(float), + 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, resultData[i]); + } + + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(input); + aclDestroyTensor(bias); + aclDestroyTensor(inputIds); + aclDestroyTensor(tid2eid); + aclDestroyTensor(out); + aclDestroyTensor(expertIdOut); + aclDestroyTensor(normOut); + + // 7. 释放device资源,需要根据具体API的接口定义修改 + aclrtFree(inputAddr); + aclrtFree(biasAddr); + aclrtFree(inputIdsAddr); + aclrtFree(tid2eidAddr); + aclrtFree(outAddr); + aclrtFree(normOutAddr); + aclrtFree(expertIdOutAddr); + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtResetDevice(deviceId); + aclFinalize(); + return 0; +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/examples/test_geir_moe_gating_top_k.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/examples/test_geir_moe_gating_top_k.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e71f6ddf6d89c0303bb886323d3caf079fa51dc8 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/examples/test_geir_moe_gating_top_k.cpp @@ -0,0 +1,324 @@ +/** + * 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 +#include +#include "assert.h" + +#include "graph/graph.h" +#include "types.h" +#include "tensor.h" +#include "ge_error_codes.h" +#include "ge_api_types.h" +#include "ge_api.h" +#include "array_ops.h" +#include "ge_ir_build.h" + +#include "fusion_ops.h" +#include "nn_other.h" + +#define FAILED -1 +#define SUCCESS 0 + +using namespace ge; +using std::map; +using std::string; +using std::vector; + +#define ADD_INPUT(intputIndex, intputName, intputDtype, inputShape) \ + vector placeholder##intputIndex##_shape = inputShape; \ + auto placeholder##intputIndex = op::Data("placeholder" + intputIndex).set_attr_index(0); \ + TensorDesc placeholder##intputIndex##_desc = \ + TensorDesc(ge::Shape(placeholder##intputIndex##_shape), FORMAT_ND, intputDtype); \ + placeholder##intputIndex##_desc.SetPlacement(ge::kPlacementHost); \ + placeholder##intputIndex##_desc.SetFormat(FORMAT_ND); \ + Tensor tensor_placeholder##intputIndex; \ + ret = GenOnesData(placeholder##intputIndex##_shape, \ + tensor_placeholder##intputIndex, \ + placeholder##intputIndex##_desc, \ + intputDtype, \ + 2); \ + if (ret != SUCCESS) { \ + printf("%s - ERROR - [XIR]: Generate input data failed\n", GetTime().c_str()); \ + return FAILED; \ + } \ + placeholder##intputIndex.update_input_desc_x(placeholder##intputIndex##_desc); \ + input.push_back(tensor_placeholder##intputIndex); \ + graph.AddOp(placeholder##intputIndex); \ + moe_gating_top_k_op.set_input_##intputName(placeholder##intputIndex); \ + inputs.push_back(placeholder##intputIndex); + +#define ADD_INPUT_ATTR(attrName, attrValue) \ + moe_gating_top_k_op.set_attr_##attrName(attrValue); + +#define ADD_CONST_INPUT(intputIndex, intputName, intputDtype, inputShape) \ + vector placeholder##intputIndex##_shape = inputShape; \ + auto placeholder##intputIndex = op::Const("placeholder" + intputIndex); \ + TensorDesc placeholder##intputIndex##_desc = \ + TensorDesc(ge::Shape(placeholder##intputIndex##_shape), FORMAT_ND, intputDtype); \ + placeholder##intputIndex##_desc.SetPlacement(ge::kPlacementHost); \ + placeholder##intputIndex##_desc.SetFormat(FORMAT_ND); \ + Tensor tensor_placeholder##intputIndex; \ + ret = GenOnesData(placeholder##intputIndex##_shape, \ + tensor_placeholder##intputIndex, \ + placeholder##intputIndex##_desc, \ + intputDtype, \ + 2); \ + if (ret != SUCCESS) { \ + printf("%s - ERROR - [XIR]: Generate input data failed\n", GetTime().c_str()); \ + return FAILED; \ + } \ + placeholder##intputIndex.SetAttr("value", tensor_placeholder##intputIndex); \ + placeholder##intputIndex.update_output_desc_y(placeholder##intputIndex##_desc); \ + graph.AddOp(placeholder##intputIndex); \ + moe_gating_top_k_op.set_input_##intputName(placeholder##intputIndex); \ + moe_gating_top_k_op.update_input_desc_##intputName(placeholder##intputIndex##_desc); \ + inputs.push_back(placeholder##intputIndex); + +#define ADD_OUTPUT(outputIndex, outputName, outputDtype, outputShape) \ + TensorDesc outputName##outputIndex##_desc = \ + TensorDesc(ge::Shape(outputShape), FORMAT_ND, outputDtype); \ + moe_gating_top_k_op.update_output_desc_##outputName(outputName##outputIndex##_desc); + +#define LOG_PRINT(message, ...) \ + do { \ + printf(message, ##__VA_ARGS__); \ + } while (0) + +string GetTime() +{ + time_t timep; + time(&timep); + char tmp[64]; + strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S,000", localtime(&timep)); + return tmp; +} + +uint32_t GetDataTypeSize(DataType dt) +{ + uint32_t dilation = 1; + uint32_t oneByte = 1; + uint32_t twoByte = 2; + uint32_t fourByte = 4; + uint32_t eightByte = 8; + + if (dt == ge::DT_FLOAT) { + dilation = fourByte; + } else if (dt == ge::DT_FLOAT16) { + dilation = twoByte; + } else if (dt == ge::DT_BF16) { + dilation = twoByte; + } else if (dt == ge::DT_INT16) { + dilation = twoByte; + } else if (dt == ge::DT_UINT16) { + dilation = twoByte; + } else if (dt == ge::DT_INT32) { + dilation = fourByte; + } else if (dt == ge::DT_UINT32) { + dilation = fourByte; + } else if (dt == ge::DT_INT64) { + dilation = eightByte; + } else if (dt == ge::DT_UINT64) { + dilation = eightByte; + } else if (dt == ge::DT_INT8) { + dilation = oneByte; + } + return dilation; +} + +int32_t GenOnesDataFloat32(vector shapes, Tensor &input_tensor, TensorDesc &input_tensor_desc, float value) +{ + input_tensor_desc.SetRealDimCnt(shapes.size()); + size_t size = 1; + for (uint32_t i = 0; i < shapes.size(); i++) { + size *= shapes[i]; + } + uint32_t byteSizeFloat32 = 4; + uint32_t data_len = size * byteSizeFloat32; + float *pData = new (std::nothrow) float[size]; + + for (size_t i = 0; i < size; ++i) { + *(pData + i) = value; + } + input_tensor = Tensor(input_tensor_desc, (uint8_t *)pData, data_len); + return SUCCESS; +} + +int32_t GenOnesData( + vector shapes, Tensor &input_tensor, TensorDesc &input_tensor_desc, DataType data_type, int value) +{ + input_tensor_desc.SetRealDimCnt(shapes.size()); + size_t size = 1; + for (uint32_t i = 0; i < shapes.size(); i++) { + size *= shapes[i]; + } + uint32_t data_len = size * GetDataTypeSize(data_type); + int32_t *pData = new (std::nothrow) int32_t[data_len]; + for (uint32_t i = 0; i < size; ++i) { + *(pData + i) = value; + } + input_tensor = Tensor(input_tensor_desc, reinterpret_cast(pData), data_len); + return SUCCESS; +} + +int32_t WriteDataToFile(string bin_file, uint64_t data_size, uint8_t *inputData) +{ + FILE *fp; + fp = fopen(bin_file.c_str(), "w"); + fwrite(inputData, sizeof(uint8_t), data_size, fp); + fclose(fp); + return SUCCESS; +} + +int CreateOppInGraph(DataType inDtype, std::vector &input, std::vector &inputs, + std::vector &outputs, Graph &graph) +{ + Status ret = SUCCESS; + // 自定义代码:添加单算子定义到图中 + auto moe_gating_top_k_op = op::MoeGatingTopK("test_geir_moe_gating_top_k"); + + // shape定义 + std::vector inputShape = {3, 256}; + std::vector biasShape = {256}; + std::vector outShape = {3, 8}; + std::vector expertIdOutShape = {3, 8}; + std::vector normOutShape = {3, 256}; + + // 添加输入(顺序严格匹配 proto.h) + ADD_INPUT(1, x, inDtype, inputShape); + ADD_INPUT(2, bias, inDtype, biasShape); + + // 添加输出(顺序严格匹配 proto.h) + ADD_OUTPUT(1, y, inDtype, outShape); + ADD_OUTPUT(2, expert_idx, DT_INT32, expertIdOutShape); + ADD_OUTPUT(3, out, inDtype, normOutShape); + + // 添加属性 + ADD_INPUT_ATTR(k, 8); + + outputs.push_back(moe_gating_top_k_op); + // 添加完毕 + return SUCCESS; +} + +int main(int argc, char *argv[]) +{ + const char *graph_name = "tc_ge_irrun_test"; + Graph graph(graph_name); + std::vector input; + + printf("%s - INFO - [XIR]: Start to initialize ge using ge global options\n", GetTime().c_str()); + std::map global_options = {{"ge.exec.deviceId", "0"}, {"ge.graphRunMode", "1"}}; + Status ret = ge::GEInitialize(global_options); + if (ret != SUCCESS) { + printf("%s - INFO - [XIR]: Initialize ge using ge global options failed\n", GetTime().c_str()); + return FAILED; + } + printf("%s - INFO - [XIR]: Initialize ge using ge global options success\n", GetTime().c_str()); + + std::vector inputs{}; + std::vector outputs{}; + + std::cout << argv[1] << std::endl; + char *endptr; + + DataType inDtype = DT_FLOAT16; + std::cout << inDtype << std::endl; + + ret = CreateOppInGraph(inDtype, input, inputs, outputs, graph); + if (ret != SUCCESS) { + printf("%s - ERROR - [XIR]: Create ir session using build options failed\n", GetTime().c_str()); + return FAILED; + } + + if (!inputs.empty() && !outputs.empty()) { + graph.SetInputs(inputs).SetOutputs(outputs); + } + + std::map build_options = { + + }; + printf("%s - INFO - [XIR]: Start to create ir session using build options\n", GetTime().c_str()); + ge::Session *session = new Session(build_options); + + if (session == nullptr) { + printf("%s - ERROR - [XIR]: Create ir session using build options failed\n", GetTime().c_str()); + return FAILED; + } + printf("%s - INFO - [XIR]: Create ir session using build options success\n", GetTime().c_str()); + printf("%s - INFO - [XIR]: Start to add compute graph to ir session\n", GetTime().c_str()); + + std::map graph_options = { + + }; + uint32_t graph_id = 0; + ret = session->AddGraph(graph_id, graph, graph_options); + + printf("%s - INFO - [XIR]: Session add ir compute graph to ir session success\n", GetTime().c_str()); + printf("%s - INFO - [XIR]: dump graph to txt\n", GetTime().c_str()); + std::string file_path = "./dump"; + aclgrphDumpGraph(graph, file_path.c_str(), file_path.length()); + printf("%s - INFO - [XIR]: Start to run ir compute graph\n", GetTime().c_str()); + std::vector output; + ret = session->RunGraph(graph_id, input, output); + if (ret != SUCCESS) { + printf("%s - INFO - [XIR]: Run graph failed\n", GetTime().c_str()); + delete session; + GEFinalize(); + return FAILED; + } + printf("%s - INFO - [XIR]: Session run ir compute graph success\n", GetTime().c_str()); + + int input_num = input.size(); + for (int i = 0; i < input_num; i++) { + std::cout << "input " << i << " dtype : " << input[i].GetTensorDesc().GetDataType() << std::endl; + string input_file = "./tc_ge_irrun_test_0008_npu_input_" + std::to_string(i) + ".bin"; + uint8_t *input_data_i = input[i].GetData(); + int64_t input_shape = input[i].GetTensorDesc().GetShape().GetShapeSize(); + std::cout << "this is " << i << "th input, input shape size =" << input_shape << std::endl; + uint32_t data_size = input_shape * GetDataTypeSize(input[i].GetTensorDesc().GetDataType()); + WriteDataToFile((const char *)input_file.c_str(), data_size, input_data_i); + } + + int output_num = output.size(); + for (int i = 0; i < output_num; i++) { + std::cout << "output " << i << " dtype : " << output[i].GetTensorDesc().GetDataType() << std::endl; + string output_file = "./tc_ge_irrun_test_0008_npu_output_" + std::to_string(i) + ".bin"; + uint8_t *output_data_i = output[i].GetData(); + int64_t output_shape = output[i].GetTensorDesc().GetShape().GetShapeSize(); + std::cout << "this is " << i << "th output, output shape size =" << output_shape << std::endl; + uint32_t data_size = output_shape * GetDataTypeSize(output[i].GetTensorDesc().GetDataType()); + WriteDataToFile((const char *)output_file.c_str(), data_size, output_data_i); + int32_t *result = (int32_t*)output_data_i; + for (int64_t j = 0; j < output_shape; j++) { + LOG_PRINT("result[%ld] is: %d\n", j, result[j]); + } + } + + ge::AscendString error_msg = ge::GEGetErrorMsgV2(); + std::string error_str(error_msg.GetString()); + std::cout << "Error message: " << error_str << std::endl; + ge::AscendString warning_msg = ge::GEGetWarningMsgV2(); + std::string warning_str(warning_msg.GetString()); + std::cout << "Warning message: " << warning_str << std::endl; + printf("%s - INFO - [XIR]: Start to finalize ir graph session\n", GetTime().c_str()); + ret = ge::GEFinalize(); + if (ret != SUCCESS) { + printf("%s - INFO - [XIR]: Finalize ir graph session failed\n", GetTime().c_str()); + return FAILED; + } + printf("%s - INFO - [XIR]: Finalize ir graph session success\n", GetTime().c_str()); + return SUCCESS; +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/moe_gating_top_k_collect.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/moe_gating_top_k_collect.py new file mode 100644 index 0000000000000000000000000000000000000000..4849681b44212993e464dcad65121c574a9ec1c4 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/moe_gating_top_k_collect.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Collect golden data for moe_gating_top_k by running the NPU operator on every case. + +Re-run ONLY after an intentional kernel change — this overwrites the regression baseline. + +COMPUTE (from docs/aclnnMoeGatingTopK.md) — per row of x: + 1. normOut = SoftMax(x) if normType=0 + Sigmoid(x) if normType=1 + sqrt(Softplus(x)) if normType=2 (950 only) + 2. normValue = normOut + bias (if bias given), else normOut + 3. if groupCount > 1: reshape to [rows, groupCount, per_group]; per-group score is + ReduceMax(.) if groupSelectMode=0, + ReduceSum(TopK(., k=2),.) if groupSelectMode=1; + pick top-kGroup groups, mask the rest with -inf. + 4. y, expertIdx = TopK(normValue, k=k) (expertIdx is INT32, the selected indices) + 5. y = gathered(normOut[expertIdx]) / (ReduceSum(normOut) + eps) if renorm (nt=0) or nt in (1,2); + else gathered; then y *= routedScalingFactor. + 6. out (3rd output) = normOut when outFlag=True. + +SHAPES / OUTPUTS (from infershape): + x (rows, expert_num) fp16/bf16/fp32 expert_num <= 2048 + bias (expert_num,) optional same dtype as x + y (rows, k) same dtype as x (top-k values) + expert_idx (rows, k) INT32 (selected expert indices) + out (rows, expert_num) FLOAT32 always (normOut) + +CONSTRAINTS (validated by the aclnn layer): + 1 <= k <= expert_num/groupCount * kGroup + 1 <= kGroup <= groupCount + groupCount > 0, expert_num % groupCount == 0, + align32(expert_num/groupCount) * groupCount <= 2048 + groupSelectMode in {0,1}; normType in {0,1}; renorm in {0,1} + +BINDING NOTE: the aclnn header (aclnn_moe_gating_top_k.h) declares ONLY +(x, bias, k, kGroup, groupCount, groupSelectMode, renorm, normType, outFlag, +routedScalingFactor, eps, y, expertIdx, out). The op_def also declares optional +input_ids and tid2eid (used only by the group-select-by-token-ids path), which the +aclnn call drops. The autobind reflects that via aclnn_call_order, so the Python +signature keeps input_ids/tid2eid but they are not passed to the aclnn call (None). +""" +import inspect +import json +import os +import sys + +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "moe_gating_top_k" +OP_CAMEL = "MoeGatingTopK" +DEVICE = "npu:0" +SEED = 2027 + +# Positional order of the generated wrapper (binding.py), excluding 'out'. +# input_ids / tid2eid are kept in the wrapper signature but not passed to the aclnn. +PARAM_NAMES = [ + "x", "bias", "input_ids", "tid2eid", + "k", "k_group", "group_count", "group_select_mode", + "renorm", "norm_type", "out_flag", "routed_scaling_factor", "eps", +] +OUTPUT_KEYS = ["y", "expert_idx", "out"] + +DT = {"fp16": torch.float16, "bf16": torch.bfloat16, "fp32": torch.float32} + +CASES = [ + # id: dtype rows expert k kg gc gsm ren nt of rsf eps bias + # 0: fp32, no grouping (gc=1), softmax + renorm, no bias + {"id": 0, "dt": "fp32", "rows": 4, "expert": 64, "k": 8, "kg": 1, "gc": 1, + "gsm": 0, "ren": 1, "nt": 0, "of": True, "rsf": 1.5, "eps": 1e-12}, + # 1: fp16, gc=8, gsm=1 (sum-top2), kg=4, sigmoid, bias (docs example config) + {"id": 1, "dt": "fp16", "rows": 3, "expert": 256, "k": 8, "kg": 4, "gc": 8, + "gsm": 1, "ren": 0, "nt": 1, "of": True, "rsf": 1.0, "eps": 1e-20, "bias": True}, + # 2: bf16, gc=4, gsm=0 (max), kg=2, sigmoid, bias + {"id": 2, "dt": "bf16", "rows": 5, "expert": 128, "k": 2, "kg": 2, "gc": 4, + "gsm": 0, "ren": 0, "nt": 1, "of": True, "rsf": 0.5, "eps": 1e-20, "bias": True}, + # 3: fp16, gc=1, softmax no renorm, tiny experts, bias + {"id": 3, "dt": "fp16", "rows": 6, "expert": 32, "k": 16, "kg": 1, "gc": 1, + "gsm": 0, "ren": 0, "nt": 0, "of": True, "rsf": 2.0, "eps": 1e-6, "bias": True}, + # 4: fp32, gc=16, gsm=0, kg=4, sigmoid, no bias + # NOTE: out_flag is True here — the docs state the 3rd output (out) is only defined when + # outFlag=True ("otherwise empty"), so out_flag=False leaves that buffer uninitialized / + # non-deterministic and the golden could not be compared across sessions. + {"id": 4, "dt": "fp32", "rows": 2, "expert": 512, "k": 4, "kg": 4, "gc": 16, + "gsm": 0, "ren": 0, "nt": 1, "of": True, "rsf": 1.0, "eps": 1e-20}, + # 5: fp16, gc=1, sigmoid, max expert_num 2048, no bias + {"id": 5, "dt": "fp16", "rows": 9, "expert": 2048, "k": 32, "kg": 1, "gc": 1, + "gsm": 0, "ren": 0, "nt": 1, "of": True, "rsf": 1.0, "eps": 1e-20}, + # 6: bf16, gc=8, gsm=1, kg=8, softmax, bias + {"id": 6, "dt": "bf16", "rows": 4, "expert": 64, "k": 8, "kg": 8, "gc": 8, + "gsm": 1, "ren": 0, "nt": 0, "of": True, "rsf": 1.0, "eps": 1e-20, "bias": True}, + # 7: fp32, gc=4, gsm=1, kg=4, sigmoid, single row, no bias + {"id": 7, "dt": "fp32", "rows": 1, "expert": 128, "k": 4, "kg": 4, "gc": 4, + "gsm": 1, "ren": 0, "nt": 1, "of": True, "rsf": 0.1, "eps": 1e-20}, + # 8: fp16, gc=2, gsm=1, kg=2, sigmoid, bias, larger k + {"id": 8, "dt": "fp16", "rows": 7, "expert": 64, "k": 16, "kg": 2, "gc": 2, + "gsm": 1, "ren": 0, "nt": 1, "of": True, "rsf": 1.0, "eps": 1e-20, "bias": True}, + # 9: bf16, gc=1, softmax + renorm, non-power-of-2 experts, no bias + {"id": 9, "dt": "bf16", "rows": 2, "expert": 300, "k": 32, "kg": 1, "gc": 1, + "gsm": 0, "ren": 1, "nt": 0, "of": True, "rsf": 1.0, "eps": 1e-20}, +] + + +def align32(n): + return ((n + 31) // 32) * 32 + + +def check_constraints(case): + expert = case["expert"] + gc, kg, k = case["gc"], case["kg"], case["k"] + assert expert <= 2048, f"case {case['id']}: expert_num {expert} > 2048" + assert expert % gc == 0, f"case {case['id']}: expert {expert} not div by gc {gc}" + assert align32(expert // gc) * gc <= 2048, \ + f"case {case['id']}: align32({expert//gc})*{gc} > 2048" + assert 1 <= kg <= gc, f"case {case['id']}: k_group {kg} not in [1, groupCount {gc}]" + assert 1 <= k <= (expert // gc) * kg, \ + f"case {case['id']}: k {k} > (expert/gc)*kg = {(expert//gc)*kg}" + assert case["gsm"] in (0, 1) + assert case["nt"] in (0, 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) + + +def make_inputs(case): + g = torch.Generator(device=DEVICE) + g.manual_seed(SEED + case["id"]) + dt = DT[case["dt"]] + # well-conditioned ~N(0, 0.5) scores so sigmoid/softmax and top-k are stable + x = (torch.randn((case["rows"], case["expert"]), generator=g, device=DEVICE) * 0.5).to(dt) + bias = None + if case.get("bias"): + bias = (torch.randn((case["expert"],), generator=g, device=DEVICE) * 0.5).to(dt) + return { + "x": x, + "bias": bias, + "input_ids": None, + "tid2eid": None, + "k": int(case["k"]), + "k_group": int(case["kg"]), + "group_count": int(case["gc"]), + "group_select_mode": int(case["gsm"]), + "renorm": int(case["ren"]), + "norm_type": int(case["nt"]), + "out_flag": bool(case["of"]), + "routed_scaling_factor": float(case["rsf"]), + "eps": float(case["eps"]), + } + + +def make_output_bufs(case): + rows, expert, k = case["rows"], case["expert"], case["k"] + dt = DT[case["dt"]] + return [ + torch.empty((rows, k), dtype=dt, device=DEVICE), # y + torch.empty((rows, k), dtype=torch.int32, device=DEVICE), # expert_idx + torch.empty((rows, expert), dtype=torch.float32, device=DEVICE), # out + ] + + +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) + + outputs = ops.npu_moe_gating_top_k(*call_args, out_bufs) + 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 = {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_moe_gating_top_k).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: + check_constraints(case) + 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"], + "x_shape": [case["rows"], case["expert"]], + "attrs": {k: v for k, v in case.items() if k not in ("id", "dt", "rows", "expert")}, + }) + 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/moe_gating_top_k/moe_gating_top_k_test.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/moe_gating_top_k_test.py new file mode 100644 index 0000000000000000000000000000000000000000..8aea230c67d77102928f881bcc2231a952c38e0c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/moe_gating_top_k_test.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Regression test: NPU moe_gating_top_k 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. expert_idx is INT32, so any index +mismatch makes diff >= 1 and rel > atol — an exact match is required there. +""" +import json +import os +import sys + +import numpy as np +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "moe_gating_top_k" +OP_CAMEL = "MoeGatingTopK" +DEVICE = "npu:0" + +# Positional order of the generated wrapper (binding.py), excluding 'out'. +PARAM_NAMES = [ + "x", "bias", "input_ids", "tid2eid", + "k", "k_group", "group_count", "group_select_mode", + "renorm", "norm_type", "out_flag", "routed_scaling_factor", "eps", +] +# Order in which the operator returns its outputs. +OUTPUT_KEYS = ["y", "expert_idx", "out"] + +# No float32-stored intermediate outputs: y is in x's dtype, out is always float32, expert_idx int32. +INTERMEDIATE_OUTPUT_KEYS = set() + +ATOL_DEFAULT = 1e-4 +ERR_RATE_DEFAULT = 0.0 + +# Dtype floor for the fp16/bf16 value outputs, a couple of ulp of headroom. +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. + out_bufs = [torch.empty_like(golden[k]).to(DEVICE) for k in OUTPUT_KEYS] + positional = [call_kwargs[p] for p in PARAM_NAMES] + [out_bufs] + outputs = ops.npu_moe_gating_top_k(*positional) + torch.npu.synchronize() + + outputs = [outputs] if isinstance(outputs, torch.Tensor) else list(outputs) + input_dtype = input_data["x"].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: + 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:<16}{max_diff:<18.10f}{error_rate:<14.6f}{status:<8}") + except Exception as exc: + all_pass = False + print(f"{'case_' + str(case_id):<12}{'-':<16}{'ERR':<18}{'-':<14}FAIL {type(exc).__name__}: {str(exc)[:200]}") + + 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/moe_gating_top_k/op_graph/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_graph/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..daa741ebd043d1aa536e44474a665627c9e4199c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_graph/CMakeLists.txt @@ -0,0 +1,14 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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.moe.moe_gating_top_k.op_graph.CMakeLists.txt") +if (BUILD_OPEN_PROJECT) + add_graph_plugin_sources() +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_graph/fusion_pass/.gitkeep b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_graph/fusion_pass/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_graph/moe_gating_top_k_proto.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_graph/moe_gating_top_k_proto.h new file mode 100644 index 0000000000000000000000000000000000000000..89943a392bcf30c8850385e39537db8f1603e2d0 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_graph/moe_gating_top_k_proto.h @@ -0,0 +1,68 @@ +/** + * 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 moe_gating_top_k_proto.h + * \brief + */ +#ifndef OPS_OP_PROTO_INC_MOEGATINGTOPK_H_ +#define OPS_OP_PROTO_INC_MOEGATINGTOPK_H_ + +#include "graph/operator_reg.h" + +namespace ge { + +/** + * @brief Compute renorm(sigmoid) and topk for moe input. + * + * @par Inputs: + * @li x: A 2D tensor which moe gating topk is applied, The shape is: (B*S, E), format supports ND, and data type must be float16, float or bfloat16. E(Expert num) can not be greater than 2048. E(Expert num) should be divisible by group_count. + * @li bias: A 1D tensor which is "bias" in moe gating topk. The shape is: (E), format supports ND, and data type must be the same as that of x. + * + * @par Outputs: + * @li y: A 2D tensor which is the topk value result of moe gating topk, format supports ND, and data type must be the same as that of x. + The size of the non-1 axis must be the same as that of the corresponding axis of x. + The size of the -1 axis must be the same as that of k. + * @li expert_idx: A 2D tensor which is the topk index result of moe gating topk, format supports ND, and data type must be int. The shape must be the same as that of y. + * @li out: A 2D tensor which is the renorm result of moe gating topk, format supports ND, and data type must be float. The shape must be the same as that of x. + * + * @par Attributes: + * @li k: A required attribute of type int. The value must greater than 0 and less than or equal to expert_num / group_count * k_group, idicating the topk value. + * @li k_group: An optional attribute of type int. It can not be less than 1, and can not be greater than group_count, indicating the topk group value. The default value is 1. + * @li group_count: An optional attribute of type int. It can not be less than 1, indicating the group count. x_shpe[-1] must be divisible by groupCount, and the result after division must be greater than groupSelectMode. The group_count * align_32(expert_num / group_count) can not be greater than 2048. The default value is 1. + * @li group_select_mode: An optional attribute of type int. 0 indicating that sort group by max values, 1 indicating that sort group by sum of top-2 values. The default value is 0. + * @li renorm: An optional attribute of type int. It can only be 0 now, indicating that norm firstly and then topk. The default value is 0. + * @li norm_type: An optional attribute of type int. 0 indicating that the softmax function is used, 1 indicating that the sigmoid function is used. The default value is 0. + * @li out_flag: An optional attribute of type bool. true indicating that has renorm output, false indicating that does not have renorm output. The default value is false. + * @li routed_scaling_factor: An optional attribute of type float, indicating the routed_scaling_factor coefficient in use. The default value is 1.0. + * @li eps: An optional attribute of type float, indicating the eps coefficient in use. The default value is 1e-20. + */ +REG_OP(MoeGatingTopK) + .INPUT(x, TensorType({DT_FLOAT, DT_FLOAT16, DT_BF16})) + .OPTIONAL_INPUT(bias, TensorType({DT_FLOAT, DT_FLOAT16, DT_BF16})) + .OPTIONAL_INPUT(input_ids, TensorType({DT_INT32, DT_INT64})) + .OPTIONAL_INPUT(tid2eid, TensorType({DT_INT32, DT_INT64})) + .OUTPUT(y, TensorType({DT_FLOAT, DT_FLOAT16, DT_BF16})) + .OUTPUT(expert_idx, TensorType({DT_INT32})) + .OUTPUT(out, TensorType({DT_FLOAT})) + .REQUIRED_ATTR(k, Int) + .ATTR(k_group, Int, 1) + .ATTR(group_count, Int, 1) + .ATTR(group_select_mode, Int, 0) + .ATTR(renorm, Int, 0) + .ATTR(norm_type, Int, 0) + .ATTR(out_flag, Bool, false) + .ATTR(routed_scaling_factor, Float, 1.0) + .ATTR(eps, Float, 1e-20f) + .OP_END_FACTORY_REG(MoeGatingTopK) + +} // namespace ge + +#endif // OPS_OP_PROTO_INC_MOEGATINGTOPK_H_ \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..402c20aca337f68a642c1c6071b3047017a7ce15 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/CMakeLists.txt @@ -0,0 +1,41 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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.moe.moe_gating_top_k.op_host.CMakeLists.txt") + +set(CONDITION_UNIT ${ASCEND_COMPUTE_UNIT}) +if (BUILD_OPEN_PROJECT) + message(STATUS "=== Debug: BUILD is BUILD_OPEN_PROJECT") + target_sources(op_host_aclnnExc PRIVATE + moe_gating_top_k_def.cpp + ) + if(CONDITION_UNIT STREQUAL "ascend950") + add_ops_compile_options( + OP_NAME MoeGatingTopK + OPTIONS --cce-auto-sync=off + -Wno-deprecated-declarations + -Werror + -mllvm + -cce-aicore-dcci-before-kernel-end=false + ) + else() + add_ops_compile_options( + OP_NAME MoeGatingTopK + OPTIONS --cce-auto-sync=on + -Wno-deprecated-declarations + -Werror + ) + endif() +endif() + +if(NOT BUILD_OPS_RTY_KERNEL) + message(STATUS "=== Debug: BUILD is NOT BUILD_OPS_RTY_KERNEL") + add_modules_sources(OPTYPE moe_gating_top_k ACLNNTYPE aclnn_exclude) +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend910_93/moe_gating_top_k_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend910_93/moe_gating_top_k_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..b4a06a17f74c6b6265ae4408a97c64ad1da2b36d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend910_93/moe_gating_top_k_binary.json @@ -0,0 +1,335 @@ +{ + "op_type": "MoeGatingTopK", + "op_list": [ + { + "bin_filename": "MoeGatingTopK_1ea4bd0e3cd9df67071f7a7aaec9c732", + "inputs": [ + { + "name": "x", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "bias", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "y", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "expert_idx", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "out", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "k", + "dtype": "int", + "value": 0 + }, + { + "name": "k_group", + "dtype": "int", + "value": 1 + }, + { + "name": "group_count", + "dtype": "int", + "value": 1 + }, + + { + "name": "group_select_mode", + "dtype": "int", + "value": 0 + }, + { + "name": "renorm", + "dtype": "int", + "value": 0 + }, + { + "name": "norm_type", + "dtype": "int", + "value": 0 + }, + { + "name": "out_flag", + "dtype": "bool", + "value": false + }, + { + "name": "routed_scaling_factor", + "dtype": "float", + "value": 1.0 + }, + { + "name": "eps", + "dtype": "float", + "value": 1e-20 + } + ] + }, + { + "bin_filename": "MoeGatingTopK_1ea4bd0e3cd9df67071f7a7aaec9c733", + "inputs": [ + { + "name": "x", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "bias", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "y", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "expert_idx", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "out", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "k", + "dtype": "int", + "value": 0 + }, + { + "name": "k_group", + "dtype": "int", + "value": 1 + }, + { + "name": "group_count", + "dtype": "int", + "value": 1 + }, + + { + "name": "group_select_mode", + "dtype": "int", + "value": 0 + }, + { + "name": "renorm", + "dtype": "int", + "value": 0 + }, + { + "name": "norm_type", + "dtype": "int", + "value": 0 + }, + { + "name": "out_flag", + "dtype": "bool", + "value": false + }, + { + "name": "routed_scaling_factor", + "dtype": "float", + "value": 1.0 + }, + { + "name": "eps", + "dtype": "float", + "value": 1e-20 + } + ] + }, + { + "bin_filename": "MoeGatingTopK_1ea4bd0e3cd9df67071f7a7aaec9c734", + "inputs": [ + { + "name": "x", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "bias", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "y", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "expert_idx", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "out", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "k", + "dtype": "int", + "value": 0 + }, + { + "name": "k_group", + "dtype": "int", + "value": 1 + }, + { + "name": "group_count", + "dtype": "int", + "value": 1 + }, + + { + "name": "group_select_mode", + "dtype": "int", + "value": 0 + }, + { + "name": "renorm", + "dtype": "int", + "value": 0 + }, + { + "name": "norm_type", + "dtype": "int", + "value": 0 + }, + { + "name": "out_flag", + "dtype": "bool", + "value": false + }, + { + "name": "routed_scaling_factor", + "dtype": "float", + "value": 1.0 + }, + { + "name": "eps", + "dtype": "float", + "value": 1e-20 + } + ] + } + ] + } \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend910_93/moe_gating_top_k_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend910_93/moe_gating_top_k_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..2c2521e3328fee9926ef50446408bb36a7256461 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend910_93/moe_gating_top_k_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 中配置的算子名字和对于的平台决定 +[MoeGatingTopK] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend910b/moe_gating_top_k_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend910b/moe_gating_top_k_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..b4a06a17f74c6b6265ae4408a97c64ad1da2b36d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend910b/moe_gating_top_k_binary.json @@ -0,0 +1,335 @@ +{ + "op_type": "MoeGatingTopK", + "op_list": [ + { + "bin_filename": "MoeGatingTopK_1ea4bd0e3cd9df67071f7a7aaec9c732", + "inputs": [ + { + "name": "x", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "bias", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "y", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "expert_idx", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "out", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "k", + "dtype": "int", + "value": 0 + }, + { + "name": "k_group", + "dtype": "int", + "value": 1 + }, + { + "name": "group_count", + "dtype": "int", + "value": 1 + }, + + { + "name": "group_select_mode", + "dtype": "int", + "value": 0 + }, + { + "name": "renorm", + "dtype": "int", + "value": 0 + }, + { + "name": "norm_type", + "dtype": "int", + "value": 0 + }, + { + "name": "out_flag", + "dtype": "bool", + "value": false + }, + { + "name": "routed_scaling_factor", + "dtype": "float", + "value": 1.0 + }, + { + "name": "eps", + "dtype": "float", + "value": 1e-20 + } + ] + }, + { + "bin_filename": "MoeGatingTopK_1ea4bd0e3cd9df67071f7a7aaec9c733", + "inputs": [ + { + "name": "x", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "bias", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "y", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "expert_idx", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "out", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "k", + "dtype": "int", + "value": 0 + }, + { + "name": "k_group", + "dtype": "int", + "value": 1 + }, + { + "name": "group_count", + "dtype": "int", + "value": 1 + }, + + { + "name": "group_select_mode", + "dtype": "int", + "value": 0 + }, + { + "name": "renorm", + "dtype": "int", + "value": 0 + }, + { + "name": "norm_type", + "dtype": "int", + "value": 0 + }, + { + "name": "out_flag", + "dtype": "bool", + "value": false + }, + { + "name": "routed_scaling_factor", + "dtype": "float", + "value": 1.0 + }, + { + "name": "eps", + "dtype": "float", + "value": 1e-20 + } + ] + }, + { + "bin_filename": "MoeGatingTopK_1ea4bd0e3cd9df67071f7a7aaec9c734", + "inputs": [ + { + "name": "x", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "bias", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "y", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "expert_idx", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "out", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "k", + "dtype": "int", + "value": 0 + }, + { + "name": "k_group", + "dtype": "int", + "value": 1 + }, + { + "name": "group_count", + "dtype": "int", + "value": 1 + }, + + { + "name": "group_select_mode", + "dtype": "int", + "value": 0 + }, + { + "name": "renorm", + "dtype": "int", + "value": 0 + }, + { + "name": "norm_type", + "dtype": "int", + "value": 0 + }, + { + "name": "out_flag", + "dtype": "bool", + "value": false + }, + { + "name": "routed_scaling_factor", + "dtype": "float", + "value": 1.0 + }, + { + "name": "eps", + "dtype": "float", + "value": 1e-20 + } + ] + } + ] + } \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend910b/moe_gating_top_k_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend910b/moe_gating_top_k_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..2c2521e3328fee9926ef50446408bb36a7256461 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend910b/moe_gating_top_k_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 中配置的算子名字和对于的平台决定 +[MoeGatingTopK] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend950/moe_gating_top_k_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend950/moe_gating_top_k_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..264632d239c1261cf70caee6a7a7ddce726ffb20 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend950/moe_gating_top_k_binary.json @@ -0,0 +1,398 @@ +{ + "op_type": "MoeGatingTopK", + "op_list": [ + { + "bin_filename": "MoeGatingTopK_1ea4bd0e3cd9df67071f7a7aaec9c732", + "inputs": [ + { + "name": "x", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "bias", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "input_ids", + "index": 2, + "dtype": "int32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "tid2eid", + "index": 3, + "dtype": "int32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "y", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "expert_idx", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "out", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "k", + "dtype": "int", + "value": 0 + }, + { + "name": "k_group", + "dtype": "int", + "value": 1 + }, + { + "name": "group_count", + "dtype": "int", + "value": 1 + }, + { + "name": "group_select_mode", + "dtype": "int", + "value": 0 + }, + { + "name": "renorm", + "dtype": "int", + "value": 0 + }, + { + "name": "norm_type", + "dtype": "int", + "value": 0 + }, + { + "name": "out_flag", + "dtype": "bool", + "value": false + }, + { + "name": "routed_scaling_factor", + "dtype": "float", + "value": 1.0 + }, + { + "name": "eps", + "dtype": "float", + "value": 1e-20 + } + ] + }, + { + "bin_filename": "MoeGatingTopK_1ea4bd0e3cd9df67071f7a7aaec9c733", + "inputs": [ + { + "name": "x", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "bias", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "input_ids", + "index": 2, + "dtype": "int32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "tid2eid", + "index": 3, + "dtype": "int32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "y", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "expert_idx", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "out", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "k", + "dtype": "int", + "value": 0 + }, + { + "name": "k_group", + "dtype": "int", + "value": 1 + }, + { + "name": "group_count", + "dtype": "int", + "value": 1 + }, + { + "name": "group_select_mode", + "dtype": "int", + "value": 0 + }, + { + "name": "renorm", + "dtype": "int", + "value": 0 + }, + { + "name": "norm_type", + "dtype": "int", + "value": 0 + }, + { + "name": "out_flag", + "dtype": "bool", + "value": false + }, + { + "name": "routed_scaling_factor", + "dtype": "float", + "value": 1.0 + }, + { + "name": "eps", + "dtype": "float", + "value": 1e-20 + } + ] + }, + { + "bin_filename": "MoeGatingTopK_1ea4bd0e3cd9df67071f7a7aaec9c734", + "inputs": [ + { + "name": "x", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "bias", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "input_ids", + "index": 2, + "dtype": "int32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "tid2eid", + "index": 3, + "dtype": "int32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "outputs": [ + { + "name": "y", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "expert_idx", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + }, + { + "name": "out", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ], + "format_match_mode": "FormatAgnostic" + } + ], + "attrs": [ + { + "name": "k", + "dtype": "int", + "value": 0 + }, + { + "name": "k_group", + "dtype": "int", + "value": 1 + }, + { + "name": "group_count", + "dtype": "int", + "value": 1 + }, + { + "name": "group_select_mode", + "dtype": "int", + "value": 0 + }, + { + "name": "renorm", + "dtype": "int", + "value": 0 + }, + { + "name": "norm_type", + "dtype": "int", + "value": 0 + }, + { + "name": "out_flag", + "dtype": "bool", + "value": false + }, + { + "name": "routed_scaling_factor", + "dtype": "float", + "value": 1.0 + }, + { + "name": "eps", + "dtype": "float", + "value": 1e-20 + } + ] + } + ] + } diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend950/moe_gating_top_k_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend950/moe_gating_top_k_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..2c2521e3328fee9926ef50446408bb36a7256461 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/config/ascend950/moe_gating_top_k_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 中配置的算子名字和对于的平台决定 +[MoeGatingTopK] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_def.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_def.cpp new file mode 100644 index 0000000000000000000000000000000000000000..03c0edbc8c07ff81860a35ce8b3c3b0e83a36dc1 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_def.cpp @@ -0,0 +1,146 @@ +/** + * 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 moe_gating_top_k_def.cpp + * \brief + */ +#include "register/op_def_registry.h" + +namespace ops { +class MoeGatingTopK : public OpDef { +public: + explicit MoeGatingTopK(const char *name) : OpDef(name) + { + this->Input("x") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16, + ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16, + ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16, + ge::DT_FLOAT16, ge::DT_FLOAT, 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, 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, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("bias") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16, + ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16, + ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16, + ge::DT_FLOAT16, ge::DT_FLOAT, 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, 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, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("input_ids") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, + ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, + ge::DT_INT64, ge::DT_INT64, ge::DT_INT64, + ge::DT_INT32, ge::DT_INT32, ge::DT_INT32}) + .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, 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, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("tid2eid") + .ParamType(OPTIONAL) + .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, + ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, + 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, 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, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .AutoContiguous(); + this->Output("y") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16, + ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16, + ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16, + ge::DT_FLOAT16, ge::DT_FLOAT, 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, 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, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("expert_idx") + .ParamType(REQUIRED) + .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, + ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, + ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, + ge::DT_INT32, ge::DT_INT32, ge::DT_INT32}) + .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, 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, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("out") + .ParamType(REQUIRED) + .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, 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, 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, ge::FORMAT_ND, + ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Attr("k").Int(); + this->Attr("k_group").AttrType(OPTIONAL).Int(1); + this->Attr("group_count").AttrType(OPTIONAL).Int(1); + this->Attr("group_select_mode").AttrType(OPTIONAL).Int(0); + this->Attr("renorm").AttrType(OPTIONAL).Int(0); + this->Attr("norm_type").AttrType(OPTIONAL).Int(0); + this->Attr("out_flag").AttrType(OPTIONAL).Bool(false); + this->Attr("routed_scaling_factor").AttrType(OPTIONAL).Float(1.0); + this->Attr("eps").AttrType(OPTIONAL).Float(1e-20f); + this->AICore().AddConfig("ascend910b"); + this->AICore().AddConfig("ascend910_93"); + + OpAICoreConfig regbaseCfg; + regbaseCfg.DynamicCompileStaticFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .ExtendCfgInfo("opFile.value", "moe_gating_top_k_apt"); + this->AICore().AddConfig("ascend950", regbaseCfg); + } +}; + +OP_ADD(MoeGatingTopK); +} // namespace ops \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51e973dba8b9e8527774c9594d8cc8bbb2c2800e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_infershape.cpp @@ -0,0 +1,143 @@ +/** + * 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 moe_gating_top_k_infershape.cpp + * \brief + */ + +#include "runtime/infer_shape_context.h" +#include "register/op_impl_registry.h" +#include "log/log.h" + +using namespace ge; +namespace ops { +static constexpr size_t DIM_ONE = 1; +static constexpr size_t DIM_TWO = 2; +static constexpr int64_t NEG_ONE = -1; +static constexpr int64_t X_INDEX = 0; +static constexpr int64_t BIAS_INDEX = 1; +static constexpr int64_t Y_INDEX = 0; +static constexpr int64_t EXPERT_IDX_INDEX = 1; +static constexpr int64_t OUT_INDEX = 2; + +static ge::graphStatus CheckInputShape(gert::InferShapeContext *context, const gert::Shape *xShape) +{ + int64_t XRows = xShape->GetDimNum() == 1U ? NEG_ONE : xShape->GetDim(0); + int64_t expertNum = xShape->GetDimNum() == 1U ? NEG_ONE : xShape->GetDim(1); + if (XRows < NEG_ONE || expertNum < NEG_ONE) { + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(context->GetNodeName(), "x", Ops::Base::ToString(*xShape), + "x rows and expert num must be greater than or equal to -1"); + return ge::GRAPH_FAILED; + } + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus CheckInputDimsAndAttr(gert::InferShapeContext *context, const gert::Shape *xShape, + const int64_t k) +{ + if (xShape->GetDimNum() == 1U) { + if (xShape->GetDim(0) != ge::UNKNOWN_DIM_NUM) { + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(context->GetNodeName(), "x", Ops::Base::ToString(*xShape), + "dynamic dim of x should be -2"); + return ge::GRAPH_FAILED; + } + } else if (xShape->GetDimNum() != DIM_TWO) { + OP_LOGE_FOR_INVALID_SHAPEDIM(context->GetNodeName(), "x", std::to_string(xShape->GetDimNum()), + "2 or dynamic"); + return ge::GRAPH_FAILED; + } + + if (k < 0) { + OP_LOGE_WITH_INVALID_ATTR(context->GetNodeName(), "k", std::to_string(k), "non-negative"); + return ge::GRAPH_FAILED; + } + + return ge::GRAPH_SUCCESS; +} + +static void ShowInputShapeInfo(gert::InferShapeContext *context, const gert::Shape *xShape, const int64_t k) +{ + OP_LOGD(context, "x shape is: %s.", Ops::Base::ToString(*xShape).c_str()); + OP_LOGD(context, "k is: %ld.", k); +} + +static void ShowOutputShapeInfo(gert::InferShapeContext *context, const gert::Shape *yShape, + const gert::Shape *expertIdxShape, const gert::Shape *outShape) +{ + OP_LOGD(context, "y shape is: %s after infershape.", Ops::Base::ToString(*yShape).c_str()); + OP_LOGD(context, "expert_idx shape is: %s after infershape.", Ops::Base::ToString(*expertIdxShape).c_str()); + OP_LOGD(context, "out shape is: %s after infershape.", Ops::Base::ToString(*outShape).c_str()); +} + +static ge::graphStatus InferShape4MoeGatingTopK(gert::InferShapeContext *context) +{ + OP_LOGD(context, "Begin to do MoeGatingTopKInfershape."); + + // 获取输入shape + const gert::Shape *xShape = context->GetInputShape(0); + OP_CHECK_NULL_WITH_CONTEXT(context, xShape); + gert::Shape *yShape = context->GetOutputShape(0); + OP_CHECK_NULL_WITH_CONTEXT(context, yShape); + gert::Shape *expertIdxShape = context->GetOutputShape(1); + OP_CHECK_NULL_WITH_CONTEXT(context, expertIdxShape); + gert::Shape *outShape = context->GetOutputShape(2); + OP_CHECK_NULL_WITH_CONTEXT(context, outShape); + + // 获取attr + auto attrs = context->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context, attrs); + const int64_t *kPtr = attrs->GetAttrPointer(0); + OP_CHECK_NULL_WITH_CONTEXT(context, kPtr); + const int64_t k = *kPtr; + ShowInputShapeInfo(context, xShape, k); + + // 参数校验 + if (CheckInputDimsAndAttr(context, xShape, k) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + if (CheckInputShape(context, xShape) != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + int64_t rows = xShape->GetDimNum() == 1U ? NEG_ONE : xShape->GetDim(0); + int64_t expertNum = xShape->GetDimNum() == 1U ? NEG_ONE : xShape->GetDim(1); + + yShape->SetDimNum(DIM_TWO); + yShape->SetDim(0U, rows); + yShape->SetDim(1U, k); + + expertIdxShape->SetDimNum(DIM_TWO); + expertIdxShape->SetDim(0U, rows); + expertIdxShape->SetDim(1U, k); + + outShape->SetDimNum(DIM_TWO); + outShape->SetDim(0U, rows); + outShape->SetDim(1U, expertNum); + + ShowOutputShapeInfo(context, yShape, expertIdxShape, outShape); + OP_LOGD(context, "End to do MoeGatingTopKInfershape."); + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus InferDataType4MoeGatingTopK(gert::InferDataTypeContext *context) +{ + OP_LOGD(context, "Begin to do MoeGatingTopKInferDataType."); + auto xDtype = context->GetInputDataType(0); + context->SetOutputDataType(Y_INDEX, xDtype); + context->SetOutputDataType(EXPERT_IDX_INDEX, ge::DT_INT32); + context->SetOutputDataType(OUT_INDEX, ge::DT_FLOAT); + OP_LOGD(context, "End to do MoeGatingTopKInferDataType."); + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(MoeGatingTopK).InferShape(InferShape4MoeGatingTopK).InferDataType(InferDataType4MoeGatingTopK); +} // namespace ops diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af3ee9a53f5b131ecf0b5bbbdd661ba50cebedee --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_tiling.cpp @@ -0,0 +1,618 @@ +/** + * 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 moe_gating_top_k_tiling.cpp + * \brief + */ +#include +#include "register/op_def_registry.h" +#include "op_host/tiling_templates_registry.h" +#include "op_host/tiling_base.h" +#include "platform/platform_info.h" +#include "log/log.h" +#include "moe_gating_top_k_tiling.h" + +namespace optiling { +const static int64_t GROUP_SELECT_MODE_MAX = 0; +const static int64_t GROUP_SELECT_MODE_SUM = 1; +const static int64_t RENORM_NO = 0; +const static int64_t RENORM_L1 = 1; +const static int64_t NORM_TYPE_SOFTMAX = 0; +const static int64_t NORM_TYPE_SIGMOID = 1; +const static int64_t OUT_FLAG_FALSE = 0; +const static int64_t OUT_FLAG_TRUE = 1; +const static size_t X_INPUT_DIMS = 2; +const static size_t BIAS_INPUT_DIMS = 1; +const static size_t Y_OUTPUT_DIMS = 2; +const static size_t EXPERT_IDX_OUTPUY_DIMS = 2; +const static size_t OUT_OUTPUT_DIMS = 2; +const static int64_t MAX_EXPERT_COUNT = 2048; + +const static int64_t X_INPUT_INDEX = 0; +const static int64_t BIAS_INPUT_INDEX = 1; +const static int64_t INPUT_IDS_INPUT_INDEX = 2; +const static int64_t TID_TO_EID_INPUT_INDEX = 3; +const static int64_t Y_OUTPUT_INDEX = 0; +const static int64_t EXPERT_IDX_OUTPUT_INDEX = 1; +const static int64_t OUT_OUTPUT_INDEX = 2; +const static int64_t K_ATTR_INDEX = 0; +const static int64_t K_GROUP_ATTR_INDEX = 1; +const static int64_t GROUP_COUNT_ATTR_INDEX = 2; +const static int64_t GROUP_SELECT_MODE_ATTR_INDEX = 3; +const static int64_t RENORM_ATTR_INDEX = 4; +const static int64_t NORM_TYPE_ATTR_INDEX = 5; +const static int64_t OUT_FLAG_ATTR_INDEX = 6; +const static int64_t ROUTED_SCALING_FACTOR_ATTR_INDEX = 7; +const static int64_t EPS_ATTR_INDEX = 8; +const static int64_t DEFAULT_WORKSPACE_SIZE = 16777216; // 预留16M空间 +const static uint32_t DATATYPESIZE_FLOAT = 4; +const static bool IS_LARGEST = true; +const static bool IS_INITINDEX = false; +const static bool IS_REUSESOURCE = false; +const static uint64_t WITH_GROUP_CONDITION = 1; +const static uint64_t WITHOUT_GROUP_CONDITION = 2; +const static uint64_t MAX_IN_GROUP_CONDITION = 3; +constexpr int32_t ROW_COUNT_PER_TASK = 1; + +const static uint64_t TILING_KEY_EXPERTNUM_GROUPNUM_ALIGN_HIGH_PERF = 0; +const static uint64_t TILING_KEY_WITHOUT_GROUP = 1; +const static uint64_t TILING_KEY_GENERALIZED = 2; +const static uint64_t TILING_KEY_HASH_WITHOUT_GROUP_INT32_INT64 = 3; +const static uint64_t TILING_KEY_HASH_WITHOUT_GROUP_INT32_INT32 = 4; +const static uint64_t TILING_KEY_HASH_WITHOUT_GROUP_INT64_INT64 = 5; +const static uint64_t TILING_KEY_HASH_WITHOUT_GROUP_INT64_INT32 = 6; + +inline static int64_t CeilLog4(int64_t x) +{ + return static_cast(std::ceil(std::log(x) / std::log(4))); // 4 for four +} + +class MoeGatingTopKTilingBase : public Ops::Transformer::OpTiling::TilingBaseClass { +public: + explicit MoeGatingTopKTilingBase(gert::TilingContext *context) : Ops::Transformer::OpTiling::TilingBaseClass(context) + { + Reset(); + } + ~MoeGatingTopKTilingBase() override = default; + + void Reset(gert::TilingContext *context) override + { + TilingBaseClass::Reset(context); + Reset(); + } + +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; + void Reset(); + +private: + ge::graphStatus CheckInputShape(); + ge::graphStatus CheckAttr(); + ge::graphStatus CheckOutShape(); + void SplitRows(); + void CalTmpBufUbSize(); + + const gert::Shape *xShape_ = nullptr; + const gert::Shape *biasShape_ = nullptr; + const gert::Shape *inputIdsShape_ = nullptr; + const gert::Shape *tid2eidShape_ = nullptr; + const gert::Shape *yShape_ = nullptr; + const gert::Shape *expertIdxShape_ = nullptr; + const gert::Shape *outShape_ = nullptr; + ge::DataType inputIdsDtype_; + ge::DataType tid2eidDtype_; + + int64_t rows_ = 0; + int64_t expertCount_ = 0; + int64_t addBias_ = 0; + int64_t hashFlag_ = 0; + + int64_t k_ = 0; + int64_t kGroup_ = 0; + int64_t groupCount_ = 0; + int64_t perGroupExpertCount_ = 0; + int64_t groupSelectMode_ = GROUP_SELECT_MODE_MAX; + int64_t renorm_ = RENORM_NO; + int64_t normType_ = NORM_TYPE_SOFTMAX; + int64_t outFlag_ = OUT_FLAG_FALSE; + float routedScalingFactor_ = 1.0; + float eps_ = 1e-20f; + + int64_t inputDtypeSize_; + const char *opName_ = ""; + MoeGatingTopKTilingData moeGatingTopKTilingData_; +}; + +ge::graphStatus MoeGatingTopKTilingBase::CheckInputShape() +{ + size_t xDimNum = xShape_->GetDimNum(); + OP_CHECK_IF(xDimNum != X_INPUT_DIMS, + OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "x", std::to_string(xDimNum), + std::to_string(X_INPUT_DIMS)), + return ge::GRAPH_FAILED); + + // 通过输入获取rows 和 expertCount + rows_ = xShape_->GetDim(0); + expertCount_ = xShape_->GetDim(1); + moeGatingTopKTilingData_.set_rowCount(rows_); + moeGatingTopKTilingData_.set_expertCount(expertCount_); + if (biasShape_ != nullptr) { + addBias_ = 1; + size_t biasDimNum = biasShape_->GetDimNum(); + OP_CHECK_IF(biasDimNum != BIAS_INPUT_DIMS, + OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "bias", std::to_string(biasDimNum), + std::to_string(BIAS_INPUT_DIMS)), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + biasShape_->GetDim(0) != expertCount_, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "bias dim[0]", std::to_string(biasShape_->GetDim(0)), + std::to_string(expertCount_)), + return ge::GRAPH_FAILED); + } + moeGatingTopKTilingData_.set_addBias(addBias_); + + if (inputIdsShape_ != nullptr && tid2eidShape_ != nullptr) { + hashFlag_ = 1; + } + moeGatingTopKTilingData_.set_hashFlag(hashFlag_); + + if (hashFlag_ == 1) { + if (tid2eidShape_->GetDim(1) != k_) { + std::string reasonMsg = + "The 1st axis of input tid2eid must be equal to the value of attribute k, " + "which is " + std::to_string(k_); + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(context_->GetNodeName(), "tid2eid", + Ops::Base::ToString(*tid2eidShape_), reasonMsg.c_str()); + return ge::GRAPH_FAILED; + } + if (inputIdsShape_->GetDim(0) != rows_) { + std::string reasonMsg = + "The 0th axis of input input_ids must be equal to the 0th axis of input x " + + Ops::Base::ToString(*xShape_); + OP_LOGE_FOR_INVALID_SHAPE_WITH_REASON(context_->GetNodeName(), "input_ids", + Ops::Base::ToString(*inputIdsShape_), reasonMsg.c_str()); + return ge::GRAPH_FAILED; + } + } + + OP_CHECK_IF(k_ > expertCount_, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "k", std::to_string(k_), + "less than or equal to expert num"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingBase::CheckAttr() +{ + OP_CHECK_IF( + expertCount_ > MAX_EXPERT_COUNT, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "expert_count", std::to_string(expertCount_), + ("less than or equal to " + std::to_string(MAX_EXPERT_COUNT))), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(k_ <= 0, OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "k", std::to_string(k_), "greater than 0"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(kGroup_ <= 0, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "k_group", std::to_string(kGroup_), + "greater than 0"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(kGroup_ > groupCount_, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "k_group", std::to_string(kGroup_), + "less than or equal to group_count"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(groupCount_ <= 0, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "group_count", std::to_string(groupCount_), + "greater than 0"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(normType_ != NORM_TYPE_SOFTMAX && normType_ != NORM_TYPE_SIGMOID, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "norm_type", std::to_string(normType_), + "0 or 1"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(groupSelectMode_ != GROUP_SELECT_MODE_SUM && groupSelectMode_ != GROUP_SELECT_MODE_MAX, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "group_select_mode", + std::to_string(groupSelectMode_), + "0 or 1"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(renorm_ != RENORM_NO && renorm_ != RENORM_L1, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "renorm", std::to_string(renorm_), "0 or 1"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(expertCount_ % groupCount_ != 0, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_->GetNodeName(), "expert_count", + std::to_string(expertCount_), + "expert_count must be divisible by group_count"), + return ge::GRAPH_FAILED); + perGroupExpertCount_ = expertCount_ / groupCount_; + + OP_CHECK_IF(perGroupExpertCount_ < 1, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "group_expert_count", + std::to_string(perGroupExpertCount_), "greater than 0"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + groupSelectMode_ == GROUP_SELECT_MODE_SUM && perGroupExpertCount_ < 2, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_->GetNodeName(), "group_expert_count", + std::to_string(perGroupExpertCount_), + "group expert count should be greater than 1"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(k_ > kGroup_ * perGroupExpertCount_, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "k", std::to_string(k_), + "less than or equal to k_group * group_expert_count"), + return ge::GRAPH_FAILED); + int64_t groupExpertCountAlign = Ops::Base::CeilAlign(perGroupExpertCount_, 32L); + if (groupCount_ != 1 && groupCount_ != expertCount_ && kGroup_ != groupCount_) { + // 分组场景下才需要校验对齐后的数量 + OP_CHECK_IF(groupCount_ * groupExpertCountAlign > MAX_EXPERT_COUNT, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "group_count * group_expert_count_align", + std::to_string(groupCount_ * groupExpertCountAlign), + ("less than or equal to " + std::to_string(MAX_EXPERT_COUNT))), + return ge::GRAPH_FAILED); + } + + moeGatingTopKTilingData_.set_perGroupExpertCount(perGroupExpertCount_); + moeGatingTopKTilingData_.set_perGroupExpertCountAlign(groupExpertCountAlign); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingBase::GetShapeAttrsInfo() +{ + opName_ = context_->GetNodeName(); + // 获取输入shape信息 + auto xShapePtr = context_->GetInputShape(X_INPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, xShapePtr); + xShape_ = &xShapePtr->GetStorageShape(); + + auto biasShapePtr = context_->GetOptionalInputShape(BIAS_INPUT_INDEX); + biasShape_ = biasShapePtr == nullptr ? nullptr : &biasShapePtr->GetStorageShape(); + + auto inputIdsShapePtr = context_->GetOptionalInputShape(INPUT_IDS_INPUT_INDEX); + inputIdsShape_ = inputIdsShapePtr == nullptr ? nullptr : &inputIdsShapePtr->GetStorageShape(); + auto tid2eidShapePtr = context_->GetOptionalInputShape(TID_TO_EID_INPUT_INDEX); + tid2eidShape_ = tid2eidShapePtr == nullptr ? nullptr : &tid2eidShapePtr->GetStorageShape(); + + // 获取输出shape + auto yShapePtr = context_->GetOutputShape(Y_OUTPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, yShapePtr); + yShape_ = &yShapePtr->GetStorageShape(); + auto expertIdxPtr = context_->GetOutputShape(EXPERT_IDX_OUTPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, expertIdxPtr); + expertIdxShape_ = &expertIdxPtr->GetStorageShape(); + auto outPtr = context_->GetOutputShape(OUT_OUTPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, outPtr); + outShape_ = &outPtr->GetStorageShape(); + + auto x = context_->GetInputDesc(X_INPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, x); + auto xDtype = x->GetDataType(); + OP_CHECK_IF( + (xDtype != ge::DataType::DT_FLOAT && xDtype != ge::DataType::DT_FLOAT16 && xDtype != ge::DataType::DT_BF16), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "x", Ops::Base::ToString(xDtype).c_str(), + "float32, half, bf16"), + return ge::GRAPH_FAILED); + + if (biasShapePtr != nullptr) { + auto biasDtype = context_->GetOptionalInputDesc(BIAS_INPUT_INDEX)->GetDataType(); + OP_CHECK_IF((biasDtype != xDtype), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "bias", + Ops::Base::ToString(biasDtype).c_str(), + Ops::Base::ToString(xDtype).c_str()), + return ge::GRAPH_FAILED); + } + + if (inputIdsShapePtr != nullptr) { + inputIdsDtype_ = context_->GetOptionalInputDesc(INPUT_IDS_INPUT_INDEX)->GetDataType(); + OP_CHECK_IF((inputIdsDtype_ != ge::DataType::DT_INT32 && inputIdsDtype_ != ge::DataType::DT_INT64), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "input_ids", + Ops::Base::ToString(inputIdsDtype_).c_str(), "int32 or int64"), + return ge::GRAPH_FAILED); + } + if (tid2eidShapePtr != nullptr) { + tid2eidDtype_ = context_->GetOptionalInputDesc(TID_TO_EID_INPUT_INDEX)->GetDataType(); + OP_CHECK_IF((tid2eidDtype_ != ge::DataType::DT_INT32 && tid2eidDtype_ != ge::DataType::DT_INT64), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "tid2eid", + Ops::Base::ToString(tid2eidDtype_).c_str(), "int32 or int64"), + return ge::GRAPH_FAILED); + } + + auto yDesc = context_->GetOutputDesc(Y_OUTPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, yDesc); + auto yDtype = yDesc->GetDataType(); + OP_CHECK_IF((yDtype != xDtype), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "y", + Ops::Base::ToString(yDtype).c_str(), + Ops::Base::ToString(xDtype).c_str()), + return ge::GRAPH_FAILED); + + auto expertIdDesc = context_->GetOutputDesc(EXPERT_IDX_OUTPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, expertIdDesc); + auto expertIdDtype = expertIdDesc->GetDataType(); + OP_CHECK_IF((expertIdDtype != ge::DataType::DT_INT32), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "expert_idx", + Ops::Base::ToString(expertIdDtype).c_str(), "int32"), + return ge::GRAPH_FAILED); + + auto normOutDesc = context_->GetOutputDesc(OUT_OUTPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, normOutDesc); + auto normOutDtype = normOutDesc->GetDataType(); + OP_CHECK_IF((normOutDtype != ge::DataType::DT_FLOAT), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "out", + Ops::Base::ToString(normOutDtype).c_str(), "float"), + return ge::GRAPH_FAILED); + + // 获取属性 + auto attrs = context_->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context_, attrs); + + const int64_t *kPtr = attrs->GetAttrPointer(K_ATTR_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, kPtr); + k_ = *kPtr; + moeGatingTopKTilingData_.set_k(k_); + OP_LOGI(context_, "Attr k is: %ld ", k_); + + const int64_t *kGroupPtr = attrs->GetAttrPointer(K_GROUP_ATTR_INDEX); + if (kGroupPtr != nullptr) { + kGroup_ = *kGroupPtr; + moeGatingTopKTilingData_.set_kGroup(kGroup_); + } + OP_LOGI(context_, "Attr k_group is: %ld ", kGroup_); + + const int64_t *groupCountPtr = attrs->GetAttrPointer(GROUP_COUNT_ATTR_INDEX); + if (groupCountPtr != nullptr) { + groupCount_ = *groupCountPtr; + moeGatingTopKTilingData_.set_groupCount(groupCount_); + } + OP_LOGI(context_, "Attr group_count is: %ld ", groupCount_); + + const int64_t *groupSelectModePtr = attrs->GetAttrPointer(GROUP_SELECT_MODE_ATTR_INDEX); + if (groupSelectModePtr != nullptr) { + groupSelectMode_ = *groupSelectModePtr; + moeGatingTopKTilingData_.set_groupSelectMode(groupSelectMode_); + } + OP_LOGI(context_, "Attr group_select_mode is: %ld ", groupSelectMode_); + + const int64_t *renormPtr = attrs->GetAttrPointer(RENORM_ATTR_INDEX); + if (renormPtr != nullptr) { + renorm_ = *renormPtr; + moeGatingTopKTilingData_.set_renorm(renorm_); + } + OP_LOGI(context_, "Attr renorm is: %ld ", renorm_); + + const int64_t *normTypePtr = attrs->GetAttrPointer(NORM_TYPE_ATTR_INDEX); + if (normTypePtr != nullptr) { + normType_ = *normTypePtr; + moeGatingTopKTilingData_.set_normType(normType_); + } + OP_LOGI(context_, "Attr norm_type is: %ld ", normType_); + + const bool *outFlagPtr = attrs->GetAttrPointer(OUT_FLAG_ATTR_INDEX); + if (outFlagPtr != nullptr) { + outFlag_ = (*outFlagPtr) ? 1 : 0; + moeGatingTopKTilingData_.set_outFlag(outFlag_); + } + OP_LOGI(context_, "Attr out_flag is: %ld ", outFlag_); + + const float *routedScalingFactorPtr = attrs->GetAttrPointer(ROUTED_SCALING_FACTOR_ATTR_INDEX); + if (routedScalingFactorPtr != nullptr) { + routedScalingFactor_ = *routedScalingFactorPtr; + moeGatingTopKTilingData_.set_routedScalingFactor(routedScalingFactor_); + } + OP_LOGI(context_, "Attr routed_scaling_factor is: %f ", routedScalingFactor_); + + const float *epsPtr = attrs->GetAttrPointer(EPS_ATTR_INDEX); + if (epsPtr != nullptr) { + eps_ = *epsPtr; + moeGatingTopKTilingData_.set_eps(eps_); + } + OP_LOGI(context_, "Attr eps is: %f ", eps_); + + inputDtypeSize_ = static_cast(ge::GetSizeByDataType(context_->GetInputDesc(0)->GetDataType())); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingBase::GetPlatformInfo() +{ + auto platformInfo = context_->GetPlatformInfo(); + OP_CHECK_IF(platformInfo == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_->GetNodeName(), "platform_info"), + return ge::GRAPH_FAILED); + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); + aicoreParams_.numBlocks = ascendcPlatform.GetCoreNumAiv(); + uint64_t ubSizePlatForm; + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSizePlatForm); + aicoreParams_.ubSize = ubSizePlatForm; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingBase::CheckOutShape() +{ + OP_CHECK_IF((yShape_->GetDimNum() != xShape_->GetDimNum()), + OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "y", std::to_string(yShape_->GetDimNum()), + std::to_string(xShape_->GetDimNum())), + return ge::GRAPH_FAILED); + OP_CHECK_IF((expertIdxShape_->GetDimNum() != xShape_->GetDimNum()), + OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "expert_idx", + std::to_string(expertIdxShape_->GetDimNum()), + std::to_string(xShape_->GetDimNum())), + return ge::GRAPH_FAILED); + if (outShape_ != nullptr) { + OP_CHECK_IF((outShape_->GetDimNum() != xShape_->GetDimNum()), + OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "out", + std::to_string(outShape_->GetDimNum()), + std::to_string(xShape_->GetDimNum())), + return ge::GRAPH_FAILED); + } + + OP_CHECK_IF((yShape_->GetDim(0) != xShape_->GetDim(0)), + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "y dim[0]", std::to_string(yShape_->GetDim(0)), + std::to_string(xShape_->GetDim(0))), + return ge::GRAPH_FAILED); + OP_CHECK_IF((expertIdxShape_->GetDim(0) != xShape_->GetDim(0)), + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "expert_idx dim[0]", + std::to_string(expertIdxShape_->GetDim(0)), + std::to_string(xShape_->GetDim(0))), + return ge::GRAPH_FAILED); + if (outFlag_ && outShape_ != nullptr) { + OP_CHECK_IF((outShape_->GetDim(0) != xShape_->GetDim(0)), + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "out dim[0]", + std::to_string(outShape_->GetDim(0)), + std::to_string(xShape_->GetDim(0))), + return ge::GRAPH_FAILED); + } + + OP_CHECK_IF((yShape_->GetDim(1) != k_), + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "y dim[1]", std::to_string(yShape_->GetDim(1)), + std::to_string(k_)), + return ge::GRAPH_FAILED); + OP_CHECK_IF((expertIdxShape_->GetDim(1) != k_), + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "expert_idx dim[1]", + std::to_string(expertIdxShape_->GetDim(1)), std::to_string(k_)), + return ge::GRAPH_FAILED); + if (outFlag_ && outShape_ != nullptr) { + OP_CHECK_IF((outShape_->GetDim(1) != xShape_->GetDim(1)), + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "out dim[1]", + std::to_string(outShape_->GetDim(1)), + std::to_string(xShape_->GetDim(1))), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +void MoeGatingTopKTilingBase::SplitRows() +{ + int64_t perCoreRows = Ops::Base::CeilDiv(rows_, static_cast(aicoreParams_.numBlocks)); + int64_t needCoreNum = Ops::Base::CeilDiv(rows_, perCoreRows); + // perCoreRows cannot be 0 + int64_t lastCoreRows = rows_ % perCoreRows == 0 ? perCoreRows : rows_ % perCoreRows; + moeGatingTopKTilingData_.set_needCoreNum(needCoreNum); + moeGatingTopKTilingData_.set_perCoreRowCount(perCoreRows); + moeGatingTopKTilingData_.set_lastCoreRowCount(lastCoreRows); + int64_t vmsCount = CeilLog4(Ops::Base::CeilDiv(kGroup_, 4L)); + OP_LOGI(context_, "vms count is: %ld", vmsCount); + moeGatingTopKTilingData_.set_vmsCount(vmsCount); // 需要归并的轮数 +} + +void MoeGatingTopKTilingBase::CalTmpBufUbSize() +{ + std::vector shape_vec = {expertCount_}; + ge::Shape shape(shape_vec); + uint32_t maxValue = 0; + uint32_t minValue = 0; + AscendC::GetSigmoidMaxMinTmpSize(shape, sizeof(float), false, maxValue, minValue); + + int64_t indexTmpBuf = (expertCount_ + 31) / 32 * 32 * static_cast(sizeof(float)); + moeGatingTopKTilingData_.set_calTmpBufUbSize(std::max(indexTmpBuf, static_cast(minValue))); +} + +ge::graphStatus MoeGatingTopKTilingBase::DoOpTiling() +{ + auto ret = CheckInputShape(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + + ret = CheckOutShape(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + + ret = CheckAttr(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + + CalTmpBufUbSize(); + SplitRows(); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingBase::DoLibApiTiling() +{ + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingBase::GetWorkspaceSize() +{ + // 计算workspace大小 + workspaceSize_ = DEFAULT_WORKSPACE_SIZE; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingBase::PostTiling() +{ + context_->SetBlockDim(moeGatingTopKTilingData_.get_needCoreNum()); + size_t *currentWorkspace = context_->GetWorkspaceSizes(1); + currentWorkspace[0] = workspaceSize_; + moeGatingTopKTilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), + context_->GetRawTilingData()->GetCapacity()); + context_->GetRawTilingData()->SetDataSize(moeGatingTopKTilingData_.GetDataSize()); + return ge::GRAPH_SUCCESS; +} + +uint64_t MoeGatingTopKTilingBase::GetTilingKey() const +{ + // DeepSeekV3排序对齐高性能场景 + if (expertCount_ == 256 && groupCount_ == 8 && kGroup_ == 4 && k_ <= 32 && addBias_ && + groupSelectMode_ == GROUP_SELECT_MODE_SUM && renorm_ == RENORM_NO && normType_ == NORM_TYPE_SIGMOID && + !outFlag_) { + // DeepSeekV3排序对齐高性能场景 + return TILING_KEY_EXPERTNUM_GROUPNUM_ALIGN_HIGH_PERF; + } else if (groupCount_ == 1 || groupCount_ == expertCount_ || kGroup_ == groupCount_) { + /** + * 不分组场景: + * 1. 分组数为 1 + * 2. 分组数等于专家数(每个组只有一个专家) + * 3. 选择所有组 + */ + if (hashFlag_ == 0) { + return TILING_KEY_WITHOUT_GROUP; + } else if (inputIdsDtype_ == ge::DataType::DT_INT32 && tid2eidDtype_ == ge::DataType::DT_INT64) { + return TILING_KEY_HASH_WITHOUT_GROUP_INT32_INT64; + } else if (inputIdsDtype_ == ge::DataType::DT_INT32 && tid2eidDtype_ == ge::DataType::DT_INT32) { + return TILING_KEY_HASH_WITHOUT_GROUP_INT32_INT32; + } else if (inputIdsDtype_ == ge::DataType::DT_INT64 && tid2eidDtype_ == ge::DataType::DT_INT64) { + return TILING_KEY_HASH_WITHOUT_GROUP_INT64_INT64; + } else { + return TILING_KEY_HASH_WITHOUT_GROUP_INT64_INT32; + } + } else { + return TILING_KEY_GENERALIZED; + } +} + +void MoeGatingTopKTilingBase::Reset() +{ + opName_ = nullptr; + return; +} + +REGISTER_OPS_TILING_TEMPLATE(MoeGatingTopK, MoeGatingTopKTilingBase, 2000); +} // namespace optiling diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_tiling.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_tiling.h new file mode 100644 index 0000000000000000000000000000000000000000..58e3a923140b5a2eb08e837e4a95a424e2a7d144 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_tiling.h @@ -0,0 +1,83 @@ +/** + * 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 moe_gating_top_k_tiling.h + * \brief + */ + +#ifndef AIR_CXX_RUNTIME_V2_OP_IMPL_MOE_GATING_TOP_K_H +#define AIR_CXX_RUNTIME_V2_OP_IMPL_MOE_GATING_TOP_K_H + +#include +#include +#include +#include + +#include "tiling/tiling_api.h" +#include "op_host/tiling_base.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" + +namespace optiling { +BEGIN_TILING_DATA_DEF(MoeGatingTopKTilingData) +TILING_DATA_FIELD_DEF(int64_t, needCoreNum); +TILING_DATA_FIELD_DEF(int64_t, rowCount); +TILING_DATA_FIELD_DEF(int64_t, perCoreRowCount); +TILING_DATA_FIELD_DEF(int64_t, lastCoreRowCount); +TILING_DATA_FIELD_DEF(int64_t, expertCount); +TILING_DATA_FIELD_DEF(int64_t, addBias); +TILING_DATA_FIELD_DEF(int64_t, k); +TILING_DATA_FIELD_DEF(int64_t, kGroup); +TILING_DATA_FIELD_DEF(int64_t, groupCount); +TILING_DATA_FIELD_DEF(int64_t, perGroupExpertCount); +TILING_DATA_FIELD_DEF(int64_t, perGroupExpertCountAlign); +TILING_DATA_FIELD_DEF(int64_t, groupSelectMode); +TILING_DATA_FIELD_DEF(int64_t, renorm); +TILING_DATA_FIELD_DEF(int64_t, normType); +TILING_DATA_FIELD_DEF(int64_t, outFlag); +TILING_DATA_FIELD_DEF(int64_t, vmsCount); +TILING_DATA_FIELD_DEF(float, routedScalingFactor); +TILING_DATA_FIELD_DEF(float, eps); +TILING_DATA_FIELD_DEF(int64_t, calTmpBufUbSize); +TILING_DATA_FIELD_DEF(bool, hashFlag); +END_TILING_DATA_DEF; +REGISTER_TILING_DATA_CLASS(MoeGatingTopK, MoeGatingTopKTilingData) + +BEGIN_TILING_DATA_DEF(MoeGatingTopKRegbaseTilingData) +TILING_DATA_FIELD_DEF(int64_t, needCoreNum); +TILING_DATA_FIELD_DEF(int64_t, rowCount); +TILING_DATA_FIELD_DEF(int64_t, perCoreRowCount); +TILING_DATA_FIELD_DEF(int64_t, lastCoreRowCount); +TILING_DATA_FIELD_DEF(int64_t, expertCount); +TILING_DATA_FIELD_DEF(int64_t, addBias); +TILING_DATA_FIELD_DEF(int64_t, k); +TILING_DATA_FIELD_DEF(int64_t, kGroup); +TILING_DATA_FIELD_DEF(int64_t, groupCount); +TILING_DATA_FIELD_DEF(int64_t, perGroupExpertCount); +TILING_DATA_FIELD_DEF(int64_t, perGroupExpertCountAlign); +TILING_DATA_FIELD_DEF(int64_t, groupSelectMode); +TILING_DATA_FIELD_DEF(int64_t, renorm); +TILING_DATA_FIELD_DEF(int64_t, normType); +TILING_DATA_FIELD_DEF(int64_t, outFlag); +TILING_DATA_FIELD_DEF(int64_t, vmsCount); +TILING_DATA_FIELD_DEF(float, routedScalingFactor); +TILING_DATA_FIELD_DEF(float, eps); +TILING_DATA_FIELD_DEF(bool, hashFlag); +TILING_DATA_FIELD_DEF_STRUCT(SoftMaxTiling, softmaxTilingData); +END_TILING_DATA_DEF; +REGISTER_TILING_DATA_CLASS(MoeGatingTopK_10000, MoeGatingTopKRegbaseTilingData) +struct MoeGatingTopKCompileInfo {}; +} // namespace optiling +#endif // AIR_CXX_RUNTIME_V2_OP_IMPL_MOE_GATING_TOP_K_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_tiling_arch35.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_tiling_arch35.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f024e6f6ea495bfe536c3bfef5e29bf8cc0ff659 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_tiling_arch35.cpp @@ -0,0 +1,724 @@ +/** + * 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 moe_gating_top_k_tiling_arch35.cpp + * \brief + */ + +#include "log/log.h" +#include "moe_gating_top_k_tiling.h" +#include "register/op_def_registry.h" +#include "platform/platform_info.h" +#include "op_host/tiling_util.h" +#include "op_host/tiling_base.h" +#include "op_host/tiling_templates_registry.h" + +#include + +namespace optiling { +const static uint64_t MOE_GATING_TOP_K_REGBASE_TILING_KEY = 10000; +const static int64_t TILINGKEY_INT32_INT64_SUFFIX = 1; +const static int64_t TILINGKEY_INT32_INT32_SUFFIX = 2; +const static int64_t TILINGKEY_INT64_INT64_SUFFIX = 3; +const static int64_t TILINGKEY_INT64_INT32_SUFFIX = 4; + +const static int64_t GROUP_SELECT_MODE_MAX = 0; +const static int64_t GROUP_SELECT_MODE_SUM = 1; +const static int64_t RENORM_NO = 0; +const static int64_t RENORM_L1 = 1; +const static int64_t NORM_TYPE_SOFTMAX = 0; +const static int64_t NORM_TYPE_SIGMOID = 1; +const static int64_t NORM_TYPE_SOFTPLUS = 2; +const static int64_t OUT_FLAG_FALSE = 0; +const static int64_t OUT_FLAG_TRUE = 1; +const static size_t X_INPUT_DIMS = 2; +const static size_t BIAS_INPUT_DIMS = 1; +const static size_t Y_OUTPUT_DIMS = 2; +const static size_t EXPERT_IDX_OUTPUY_DIMS = 2; +const static size_t OUT_OUTPUT_DIMS = 2; +const static int64_t MAX_EXPERT_COUNT = 2048; +const static int64_t MAX_K_FOR_HASH = 64; + +const static int64_t X_INPUT_INDEX = 0; +const static int64_t BIAS_INPUT_INDEX = 1; +const static int64_t INPUT_IDS_INPUT_INDEX = 2; +const static int64_t TID_TO_EID_INPUT_INDEX = 3; +const static int64_t Y_OUTPUT_INDEX = 0; +const static int64_t EXPERT_IDX_OUTPUT_INDEX = 1; +const static int64_t OUT_OUTPUT_INDEX = 2; +const static int64_t K_ATTR_INDEX = 0; +const static int64_t K_GROUP_ATTR_INDEX = 1; +const static int64_t GROUP_COUNT_ATTR_INDEX = 2; +const static int64_t GROUP_SELECT_MODE_ATTR_INDEX = 3; +const static int64_t RENORM_ATTR_INDEX = 4; +const static int64_t MRGSORT_SIZE = 4; +const static int64_t NORM_TYPE_ATTR_INDEX = 5; +const static int64_t OUT_FLAG_ATTR_INDEX = 6; +const static int64_t ROUTED_SCALING_FACTOR_ATTR_INDEX = 7; +const static int64_t EPS_ATTR_INDEX = 8; +const static int64_t DEFAULT_WORKSPACE_SIZE = static_cast(16 * 1024 * 1024); // 预留16M空间 + + +class MoeGatingTopKTilingRegbase : public Ops::Transformer::OpTiling::TilingBaseClass { +public: + explicit MoeGatingTopKTilingRegbase(gert::TilingContext *context) + : Ops::Transformer::OpTiling::TilingBaseClass(context) + { + Reset(); + } + ~MoeGatingTopKTilingRegbase() override = default; + + void Reset(gert::TilingContext *context) override + { + TilingBaseClass::Reset(context); + Reset(); + } + +protected: + bool IsCapable() override + { + if (!Ops::Transformer::OpTiling::IsRegbaseSocVersion(context_)) { + return false; + } + 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; + void Reset(); + +private: + ge::graphStatus CheckInputShape(); + ge::graphStatus CheckAttr(); + ge::graphStatus CheckAttrBasic(); + ge::graphStatus CheckAttrExpert(); + ge::graphStatus CheckAttrMode(); + ge::graphStatus CheckOutShape(); + ge::graphStatus GetInputOutputShape(); + ge::graphStatus CheckDtypes(); + ge::graphStatus GetAttrs(); + ge::graphStatus GetBasicAttrs(); + ge::graphStatus GetModeAttrs(); + ge::graphStatus GetOtherAttrs(); + ge::graphStatus CheckInputShape4Hash(); + ge::graphStatus CheckDtype4Hash(); + void CalTmpBufUbSize(); + void SplitRows(); + void Tiling4GatherOutComputeSplitK(); + + const gert::Shape *xShape_ = nullptr; + const gert::Shape *biasShape_ = nullptr; + const gert::Shape *inputIdsShape_ = nullptr; + const gert::Shape *tid2eidShape_ = nullptr; + const gert::Shape *yShape_ = nullptr; + const gert::Shape *expertIdxShape_ = nullptr; + const gert::Shape *outShape_ = nullptr; + + ge::DataType inputIdsDtype_; + ge::DataType tid2eidDtype_; + + int64_t rows_; + int64_t expertCount_; + int64_t addBias_ = 0; + bool hashFlag_ = false; + + int64_t k_; + int64_t kGroup_ = 1; + int64_t groupCount_ = 1; + int64_t groupSelectMode_ = GROUP_SELECT_MODE_MAX; + int64_t renorm_ = RENORM_NO; + int64_t normType_ = NORM_TYPE_SOFTMAX; + int64_t outFlag_ = OUT_FLAG_FALSE; + float routedScalingFactor_ = 1.0; + float eps_ = 1e-20f; + + int64_t inputDtypeSize_; + const char *opName_ = ""; + MoeGatingTopKRegbaseTilingData moeGatingTopKTilingData_; + platform_ascendc::SocVersion socVersion; +}; + +ge::graphStatus MoeGatingTopKTilingRegbase::CheckInputShape4Hash() +{ + OP_CHECK_IF(k_ > MAX_K_FOR_HASH, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "k", std::to_string(k_), + "less than or equal to 64 for hash mode"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(tid2eidShape_->GetDim(1) != k_, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "tid2eid dim[1]", + std::to_string(tid2eidShape_->GetDim(1)), std::to_string(k_)), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(inputIdsShape_->GetDim(0) != rows_, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "inputIds dim[0]", + std::to_string(inputIdsShape_->GetDim(0)), std::to_string(rows_)), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::CheckInputShape() +{ + size_t xDimNum = xShape_->GetDimNum(); + OP_CHECK_IF(xDimNum != X_INPUT_DIMS, + OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "x", std::to_string(xDimNum), + std::to_string(X_INPUT_DIMS)), + return ge::GRAPH_FAILED); + + // 通过输入获取rows 和 expertCount + rows_ = xShape_->GetDim(0); + expertCount_ = xShape_->GetDim(1); + moeGatingTopKTilingData_.set_rowCount(rows_); + moeGatingTopKTilingData_.set_expertCount(expertCount_); + OP_CHECK_IF(expertCount_ > MAX_EXPERT_COUNT, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "expert_count", std::to_string(expertCount_), + ("less than or equal to " + std::to_string(MAX_EXPERT_COUNT))), + return ge::GRAPH_FAILED); + + if (biasShape_ != nullptr) { + addBias_ = 1; + size_t biasDimNum = biasShape_->GetDimNum(); + OP_CHECK_IF(biasDimNum != BIAS_INPUT_DIMS, + OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "bias", std::to_string(biasDimNum), + std::to_string(BIAS_INPUT_DIMS)), + return ge::GRAPH_FAILED); + OP_CHECK_IF(biasShape_->GetDim(0) != expertCount_, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "bias dim[0]", + std::to_string(biasShape_->GetDim(0)), std::to_string(expertCount_)), + return ge::GRAPH_FAILED); + } + moeGatingTopKTilingData_.set_addBias(addBias_); + + OP_CHECK_IF( + k_ > expertCount_, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "k", std::to_string(k_), "less than or equal to expert num"), + return ge::GRAPH_FAILED); + + if (hashFlag_ && CheckInputShape4Hash() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + moeGatingTopKTilingData_.set_hashFlag(hashFlag_); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::CheckAttrBasic() +{ + OP_CHECK_IF(k_ <= 0, OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "k", std::to_string(k_), "greater than 0"), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + kGroup_ <= 0, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "k_group", std::to_string(kGroup_), "greater than 0"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(groupCount_ <= 0, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "group_count", std::to_string(groupCount_), + "greater than 0"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(expertCount_ % groupCount_ != 0, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_->GetNodeName(), "expert_count", + std::to_string(expertCount_), + "expert_count must be divisible by group_count"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(kGroup_ > groupCount_, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "k_group", std::to_string(kGroup_), + "less than or equal to group_count"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(groupCount_ == expertCount_ && kGroup_ < k_, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "k_group * group_expert_count", + std::to_string(kGroup_), "greater than or equal to k"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::CheckAttrExpert() +{ + bool isSimplifiedPath = (kGroup_ == groupCount_ || groupCount_ == expertCount_); + OP_CHECK_IF(hashFlag_ && !isSimplifiedPath, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON( + context_->GetNodeName(), "hash mode", "hash mode only supports simplified path", + "k_group must equal group_count or group_count must equal expert_count"), + return ge::GRAPH_FAILED); + + if (isSimplifiedPath) { + kGroup_ = 1; + groupCount_ = 1; + } + moeGatingTopKTilingData_.set_kGroup(kGroup_); + moeGatingTopKTilingData_.set_groupCount(groupCount_); + int64_t groupExpertCount = expertCount_ / groupCount_; + int64_t groupExpertCountAlign = Ops::Base::CeilAlign(groupExpertCount, 32L); + moeGatingTopKTilingData_.set_perGroupExpertCount(expertCount_ / groupCount_); + moeGatingTopKTilingData_.set_perGroupExpertCountAlign(groupExpertCountAlign); + + OP_CHECK_IF(groupCount_ * groupExpertCountAlign > MAX_EXPERT_COUNT, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "group_count * group_expert_count_align", + std::to_string(groupCount_ * groupExpertCountAlign), + ("less than or equal to " + std::to_string(MAX_EXPERT_COUNT))), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(kGroup_ * groupExpertCount < k_, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "k_group * group_expert_count", + std::to_string(kGroup_ * groupExpertCount), "greater than or equal to k"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(groupExpertCount < 1, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "group_expert_count", + std::to_string(groupExpertCount), "greater than 0"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::CheckAttrMode() +{ + OP_CHECK_IF(groupSelectMode_ != GROUP_SELECT_MODE_SUM && groupSelectMode_ != GROUP_SELECT_MODE_MAX, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "group_select_mode", + std::to_string(groupSelectMode_), "0 or 1"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(groupSelectMode_ == GROUP_SELECT_MODE_SUM && (expertCount_ / groupCount_) < 2, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_->GetNodeName(), "group_expert_count", + std::to_string(expertCount_ / groupCount_), + "group expert count should be greater than 1"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(renorm_ != RENORM_NO && renorm_ != RENORM_L1, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "renorm", std::to_string(renorm_), "0 or 1"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF(normType_ != NORM_TYPE_SOFTMAX && normType_ != NORM_TYPE_SIGMOID && normType_ != NORM_TYPE_SOFTPLUS, + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "norm_type", std::to_string(normType_), "0, 1 or 2"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::CheckAttr() +{ + OP_CHECK_IF(CheckAttrBasic() != ge::GRAPH_SUCCESS, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_->GetNodeName(), "CheckAttrBasic", "failed", + "CheckAttrBasic failed"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckAttrExpert() != ge::GRAPH_SUCCESS, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_->GetNodeName(), "CheckAttrExpert", "failed", + "CheckAttrExpert failed"), + return ge::GRAPH_FAILED); + OP_CHECK_IF(CheckAttrMode() != ge::GRAPH_SUCCESS, + OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(context_->GetNodeName(), "CheckAttrMode", "failed", + "CheckAttrMode failed"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::GetInputOutputShape() +{ + auto xShapePtr = context_->GetInputShape(X_INPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, xShapePtr); + xShape_ = &xShapePtr->GetStorageShape(); + auto biasShapePtr = context_->GetOptionalInputShape(BIAS_INPUT_INDEX); + biasShape_ = biasShapePtr == nullptr ? nullptr : &biasShapePtr->GetStorageShape(); + + auto inputIdsShapePtr = context_->GetOptionalInputShape(INPUT_IDS_INPUT_INDEX); + inputIdsShape_ = inputIdsShapePtr == nullptr ? nullptr : &inputIdsShapePtr->GetStorageShape(); + auto tid2eidShapePtr = context_->GetOptionalInputShape(TID_TO_EID_INPUT_INDEX); + tid2eidShape_ = tid2eidShapePtr == nullptr ? nullptr : &tid2eidShapePtr->GetStorageShape(); + if (inputIdsShape_ != nullptr && tid2eidShape_ != nullptr) { + hashFlag_ = true; + } + + auto yShapePtr = context_->GetOutputShape(Y_OUTPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, yShapePtr); + yShape_ = &yShapePtr->GetStorageShape(); + auto expertIdxPtr = context_->GetOutputShape(EXPERT_IDX_OUTPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, expertIdxPtr); + expertIdxShape_ = &expertIdxPtr->GetStorageShape(); + auto outPtr = context_->GetOutputShape(OUT_OUTPUT_INDEX); + if (outPtr != nullptr) { + outShape_ = &outPtr->GetStorageShape(); + } + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::CheckDtype4Hash() +{ + auto inputIdsDesc = context_->GetOptionalInputDesc(INPUT_IDS_INPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, inputIdsDesc); + inputIdsDtype_ = inputIdsDesc->GetDataType(); + OP_CHECK_IF((inputIdsDtype_ != ge::DataType::DT_INT32 && inputIdsDtype_ != ge::DataType::DT_INT64), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "inputIds", + Ops::Base::ToString(inputIdsDtype_).c_str(), "int32, int64"), + return ge::GRAPH_FAILED); + + auto tid2eidDesc = context_->GetOptionalInputDesc(TID_TO_EID_INPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, tid2eidDesc); + tid2eidDtype_ = tid2eidDesc->GetDataType(); + OP_CHECK_IF((tid2eidDtype_ != ge::DataType::DT_INT32 && tid2eidDtype_ != ge::DataType::DT_INT64), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "tid2eid", + Ops::Base::ToString(tid2eidDtype_).c_str(), "int32, int64"), + return ge::GRAPH_FAILED); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::CheckDtypes() +{ + auto x = context_->GetInputDesc(X_INPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, x); + auto xDtype = x->GetDataType(); + OP_CHECK_IF( + (xDtype != ge::DataType::DT_FLOAT && xDtype != ge::DataType::DT_FLOAT16 && xDtype != ge::DataType::DT_BF16), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "x", Ops::Base::ToString(xDtype).c_str(), + "float32, half, bf16"), + return ge::GRAPH_FAILED); + + if (biasShape_ != nullptr) { + auto biasDtype = context_->GetOptionalInputDesc(BIAS_INPUT_INDEX)->GetDataType(); + OP_CHECK_IF((biasDtype != xDtype), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "bias", Ops::Base::ToString(biasDtype).c_str(), + Ops::Base::ToString(xDtype).c_str()), + return ge::GRAPH_FAILED); + } + + auto yDesc = context_->GetOutputDesc(Y_OUTPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, yDesc); + auto yDtype = yDesc->GetDataType(); + OP_CHECK_IF((yDtype != xDtype), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "y", Ops::Base::ToString(yDtype).c_str(), + Ops::Base::ToString(xDtype).c_str()), + return ge::GRAPH_FAILED); + + auto expertIdDesc = context_->GetOutputDesc(EXPERT_IDX_OUTPUT_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, expertIdDesc); + auto expertIdDtype = expertIdDesc->GetDataType(); + OP_CHECK_IF((expertIdDtype != ge::DataType::DT_INT32), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "expert_idx", + Ops::Base::ToString(expertIdDtype).c_str(), "int32"), + return ge::GRAPH_FAILED); + + auto outDesc = context_->GetOutputDesc(OUT_OUTPUT_INDEX); + if (outFlag_ && outDesc != nullptr) { + auto outDtype = outDesc->GetDataType(); + OP_CHECK_IF((outDtype != ge::DataType::DT_FLOAT), + OP_LOGE_FOR_INVALID_DTYPE(context_->GetNodeName(), "outDtype", + Ops::Base::ToString(outDtype).c_str(), "float32"), + return ge::GRAPH_FAILED); + } + + if (hashFlag_ && CheckDtype4Hash() != ge::GRAPH_SUCCESS) { + return ge::GRAPH_FAILED; + } + + inputDtypeSize_ = static_cast(ge::GetSizeByDataType(context_->GetInputDesc(0)->GetDataType())); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::GetBasicAttrs() +{ + auto attrs = context_->GetAttrs(); + OP_CHECK_NULL_WITH_CONTEXT(context_, attrs); + + const int64_t *kPtr = attrs->GetAttrPointer(K_ATTR_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context_, kPtr); + k_ = *kPtr; + moeGatingTopKTilingData_.set_k(k_); + OP_LOGI(context_, "Attr k is: %ld ", k_); + + const int64_t *kGroupPtr = attrs->GetAttrPointer(K_GROUP_ATTR_INDEX); + if (kGroupPtr != nullptr) { + kGroup_ = *kGroupPtr; + } + OP_LOGI(context_, "Attr k_group is: %ld ", kGroup_); + + const int64_t *groupCountPtr = attrs->GetAttrPointer(GROUP_COUNT_ATTR_INDEX); + if (groupCountPtr != nullptr) { + groupCount_ = *groupCountPtr; + } + OP_LOGI(context_, "Attr group_count is: %ld ", groupCount_); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::GetModeAttrs() +{ + auto attrs = context_->GetAttrs(); + + const int64_t *groupSelectModePtr = attrs->GetAttrPointer(GROUP_SELECT_MODE_ATTR_INDEX); + if (groupSelectModePtr != nullptr) { + groupSelectMode_ = *groupSelectModePtr; + } + moeGatingTopKTilingData_.set_groupSelectMode(groupSelectMode_); + OP_LOGI(context_, "Attr group_select_mode is: %ld ", groupSelectMode_); + + const int64_t *renormPtr = attrs->GetAttrPointer(RENORM_ATTR_INDEX); + if (renormPtr != nullptr) { + renorm_ = *renormPtr; + } + moeGatingTopKTilingData_.set_renorm(renorm_); + OP_LOGI(context_, "Attr renorm is: %ld ", renorm_); + + const int64_t *normTypePtr = attrs->GetAttrPointer(NORM_TYPE_ATTR_INDEX); + if (normTypePtr != nullptr) { + normType_ = *normTypePtr; + } + moeGatingTopKTilingData_.set_normType(normType_); + OP_LOGI(context_, "Attr norm_type is: %ld ", normType_); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::GetOtherAttrs() +{ + auto attrs = context_->GetAttrs(); + + const bool *outFlagPtr = attrs->GetAttrPointer(OUT_FLAG_ATTR_INDEX); + if (outFlagPtr != nullptr) { + outFlag_ = (*outFlagPtr) ? 1 : 0; + } + moeGatingTopKTilingData_.set_outFlag(outFlag_); + OP_LOGI(context_, "Attr out_flag is: %ld ", outFlag_); + + const float *routedScalingFactorPtr = attrs->GetAttrPointer(ROUTED_SCALING_FACTOR_ATTR_INDEX); + if (routedScalingFactorPtr != nullptr) { + routedScalingFactor_ = *routedScalingFactorPtr; + } + moeGatingTopKTilingData_.set_routedScalingFactor(routedScalingFactor_); + OP_LOGI(context_, "Attr routed_scaling_factor is: %f ", routedScalingFactor_); + + const float *epsPtr = attrs->GetAttrPointer(EPS_ATTR_INDEX); + if (epsPtr != nullptr) { + eps_ = *epsPtr; + } + moeGatingTopKTilingData_.set_eps(eps_); + OP_LOGI(context_, "Attr eps is: %f ", eps_); + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::GetAttrs() +{ + auto ret = GetBasicAttrs(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + + ret = GetModeAttrs(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + + ret = GetOtherAttrs(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::GetShapeAttrsInfo() +{ + opName_ = context_->GetNodeName(); + + auto ret = GetInputOutputShape(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + + ret = GetAttrs(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + + ret = CheckDtypes(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::GetPlatformInfo() +{ + auto platformInfo = context_->GetPlatformInfo(); + OP_CHECK_IF(platformInfo == nullptr, OP_LOGE_WITH_INVALID_INPUT(context_->GetNodeName(), "platform_info"), + return ge::GRAPH_FAILED); + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); + aicoreParams_.numBlocks = ascendcPlatform.GetCoreNumAiv(); + socVersion = ascendcPlatform.GetSocVersion(); + uint64_t ubSizePlatForm; + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSizePlatForm); + aicoreParams_.ubSize = ubSizePlatForm; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::CheckOutShape() +{ + OP_CHECK_IF((yShape_->GetDimNum() != xShape_->GetDimNum()), + OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "y", std::to_string(yShape_->GetDimNum()), + std::to_string(xShape_->GetDimNum())), + return ge::GRAPH_FAILED); + OP_CHECK_IF((expertIdxShape_->GetDimNum() != xShape_->GetDimNum()), + OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "expert_idx", + std::to_string(expertIdxShape_->GetDimNum()), + std::to_string(xShape_->GetDimNum())), + return ge::GRAPH_FAILED); + if (outShape_ != nullptr) { + OP_CHECK_IF((outShape_->GetDimNum() != xShape_->GetDimNum()), + OP_LOGE_FOR_INVALID_SHAPEDIM(context_->GetNodeName(), "out", std::to_string(outShape_->GetDimNum()), + std::to_string(xShape_->GetDimNum())), + return ge::GRAPH_FAILED); + } + + OP_CHECK_IF((yShape_->GetDim(0) != xShape_->GetDim(0)), + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "y dim[0]", std::to_string(yShape_->GetDim(0)), + std::to_string(xShape_->GetDim(0))), + return ge::GRAPH_FAILED); + OP_CHECK_IF((expertIdxShape_->GetDim(0) != xShape_->GetDim(0)), + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "expert_idx dim[0]", + std::to_string(expertIdxShape_->GetDim(0)), + std::to_string(xShape_->GetDim(0))), + return ge::GRAPH_FAILED); + if (outFlag_ && outShape_ != nullptr) { + OP_CHECK_IF((outShape_->GetDim(0) != xShape_->GetDim(0)), + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "out dim[0]", + std::to_string(outShape_->GetDim(0)), std::to_string(xShape_->GetDim(0))), + return ge::GRAPH_FAILED); + } + + OP_CHECK_IF((yShape_->GetDim(1) != k_), + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "y dim[1]", std::to_string(yShape_->GetDim(1)), + std::to_string(k_)), + return ge::GRAPH_FAILED); + OP_CHECK_IF((expertIdxShape_->GetDim(1) != k_), + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "expert_idx dim[1]", + std::to_string(expertIdxShape_->GetDim(1)), std::to_string(k_)), + return ge::GRAPH_FAILED); + if (outFlag_ && outShape_ != nullptr) { + OP_CHECK_IF((outShape_->GetDim(1) != xShape_->GetDim(1)), + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "out dim[1]", + std::to_string(outShape_->GetDim(1)), std::to_string(xShape_->GetDim(1))), + return ge::GRAPH_FAILED); + } + return ge::GRAPH_SUCCESS; +} + +void MoeGatingTopKTilingRegbase::CalTmpBufUbSize() +{ + std::vector shape_vec = {groupCount_ * moeGatingTopKTilingData_.get_perGroupExpertCountAlign()}; + ge::Shape softmaxShape(shape_vec); + + uint32_t softmaxTmpSize = AscendC::GetSoftMaxMaxTmpSize(softmaxShape, sizeof(float), true); + AscendC::SoftMaxTilingFunc(softmaxShape, sizeof(float), softmaxTmpSize, moeGatingTopKTilingData_.softmaxTilingData); +} + +void MoeGatingTopKTilingRegbase::SplitRows() +{ + int64_t perCoreRows = Ops::Base::CeilDiv(rows_, static_cast(aicoreParams_.numBlocks)); + int64_t needCoreNum = Ops::Base::CeilDiv(rows_, perCoreRows); + if (perCoreRows == 0) { + OP_LOGE_FOR_INVALID_VALUE(context_->GetNodeName(), "perCoreRows", std::to_string(perCoreRows), + "greater than 0"); + return; + } + int64_t lastCoreRows = rows_ % perCoreRows == 0 ? perCoreRows : rows_ % perCoreRows; + moeGatingTopKTilingData_.set_needCoreNum(needCoreNum); + moeGatingTopKTilingData_.set_perCoreRowCount(perCoreRows); + moeGatingTopKTilingData_.set_lastCoreRowCount(lastCoreRows); + + int64_t vmsCount = 0; + if (kGroup_ > MRGSORT_SIZE) { + int64_t index = MRGSORT_SIZE; + while (index < kGroup_) { + index = index * MRGSORT_SIZE; + vmsCount++; + } + } + moeGatingTopKTilingData_.set_vmsCount(vmsCount); +} + +ge::graphStatus MoeGatingTopKTilingRegbase::DoOpTiling() +{ + auto ret = CheckInputShape(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + + ret = CheckAttr(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + + ret = CheckOutShape(); + if (ret != ge::GRAPH_SUCCESS) { + return ret; + } + + CalTmpBufUbSize(); + SplitRows(); + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::DoLibApiTiling() +{ + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::GetWorkspaceSize() +{ + // 计算workspace大小 + workspaceSize_ = DEFAULT_WORKSPACE_SIZE; + return ge::GRAPH_SUCCESS; +} + +ge::graphStatus MoeGatingTopKTilingRegbase::PostTiling() +{ + context_->SetBlockDim(moeGatingTopKTilingData_.get_needCoreNum()); + size_t *currentWorkspace = context_->GetWorkspaceSizes(1); + currentWorkspace[0] = workspaceSize_; + moeGatingTopKTilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), + context_->GetRawTilingData()->GetCapacity()); + context_->GetRawTilingData()->SetDataSize(moeGatingTopKTilingData_.GetDataSize()); + return ge::GRAPH_SUCCESS; +} + +uint64_t MoeGatingTopKTilingRegbase::GetTilingKey() const +{ + if (!hashFlag_) { + return MOE_GATING_TOP_K_REGBASE_TILING_KEY; + } + + bool isInputIdsInt32 = (inputIdsDtype_ == ge::DataType::DT_INT32); + bool isTid2eidInt32 = (tid2eidDtype_ == ge::DataType::DT_INT32); + + if (isInputIdsInt32 && !isTid2eidInt32) { + return MOE_GATING_TOP_K_REGBASE_TILING_KEY + TILINGKEY_INT32_INT64_SUFFIX; + } else if (isInputIdsInt32 && isTid2eidInt32) { + return MOE_GATING_TOP_K_REGBASE_TILING_KEY + TILINGKEY_INT32_INT32_SUFFIX; + } else if (!isInputIdsInt32 && !isTid2eidInt32) { + return MOE_GATING_TOP_K_REGBASE_TILING_KEY + TILINGKEY_INT64_INT64_SUFFIX; + } else { + return MOE_GATING_TOP_K_REGBASE_TILING_KEY + TILINGKEY_INT64_INT32_SUFFIX; + } +} + +void MoeGatingTopKTilingRegbase::Reset() +{ + opName_ = nullptr; + return; +} + +REGISTER_OPS_TILING_TEMPLATE(MoeGatingTopK, MoeGatingTopKTilingRegbase, 1000); +} // namespace optiling diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_tiling_base.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_tiling_base.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9d07eab75478b72a4940d2b44f084b2565dc491 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/moe_gating_top_k_tiling_base.cpp @@ -0,0 +1,38 @@ +/** + * 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 moe_gating_top_k_tiling_base.cpp + * \brief + */ +#include "moe_gating_top_k_tiling.h" +#include "register/op_def_registry.h" +#include "op_host/tiling_base.h" +#include "op_host/tiling_templates_registry.h" +#include "log/log.h" +#include "kernel_tiling/kernel_tiling.h" + +namespace optiling { +static ge::graphStatus TilingForMoeGatingTopK(gert::TilingContext *context) +{ + return Ops::Transformer::OpTiling::TilingRegistry::GetInstance().DoTilingImpl(context); +} + +static ge::graphStatus TilingPrepareForMoeGatingTopK(gert::TilingParseContext *context) +{ + (void)context; + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_OPTILING(MoeGatingTopK) + .Tiling(TilingForMoeGatingTopK) + .TilingParse(TilingPrepareForMoeGatingTopK); + +} // namespace optiling \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/aclnn_moe_gating_top_k.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/aclnn_moe_gating_top_k.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ca053eb338a5a297450a6636782a59a264f74f9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/aclnn_moe_gating_top_k.cpp @@ -0,0 +1,135 @@ +/** + * 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 "aclnn_moe_gating_top_k.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 "aclnn_kernels/contiguous.h" +#include "external/aclnn_kernels/aclnn_platform.h" +#include "opdev/tensor_view_utils.h" +#include "opdev/op_log.h" +#include "moe_gating_top_k.h" + +using namespace op; + +namespace MoeGatingTopKCheck { + +static const std::initializer_list MOE_GATING_TOP_K_DTYPE_SUPPORT_LIST_X = { + DataType::DT_FLOAT16, DataType::DT_BF16, DataType::DT_FLOAT}; +static const std::initializer_list MOE_GATING_TOP_K_DTYPE_SUPPORT_LIST_INT = {DataType::DT_INT32}; + +static inline bool CheckNotNull(const aclTensor *x, const aclTensor *yOut, const aclTensor *expertIdxOut, + const aclTensor *outOut) +{ + OP_CHECK_NULL(x, return false); + OP_CHECK_NULL(yOut, return false); + OP_CHECK_NULL(expertIdxOut, return false); + OP_CHECK_NULL(outOut, return false); + return true; +} + +static inline bool CheckDtypeValid(const aclTensor *x, const aclTensor *biasOptional, const aclTensor *yOut, + const aclTensor *expertIdxOut, const aclTensor *outOut) +{ + if (x != nullptr && x->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(x, MOE_GATING_TOP_K_DTYPE_SUPPORT_LIST_X, return false); + } + if (biasOptional != nullptr && biasOptional->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(biasOptional, MOE_GATING_TOP_K_DTYPE_SUPPORT_LIST_X, return false); + OP_CHECK_DTYPE_NOT_SAME(x, biasOptional, return false); + } + if (yOut != nullptr && yOut->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(yOut, MOE_GATING_TOP_K_DTYPE_SUPPORT_LIST_X, return false); + OP_CHECK_DTYPE_NOT_SAME(x, yOut, return false); + } + if (expertIdxOut != nullptr && expertIdxOut->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(expertIdxOut, MOE_GATING_TOP_K_DTYPE_SUPPORT_LIST_INT, return false); + } + if (outOut != nullptr && outOut->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(outOut, MOE_GATING_TOP_K_DTYPE_SUPPORT_LIST_X, return false); + } + return true; +} + +static aclnnStatus CheckParams(const aclTensor *x, const aclTensor *biasOptional, const aclTensor *yOut, + const aclTensor *expertIdxOut, const aclTensor *outOut) +{ + CHECK_RET(CheckNotNull(x, yOut, expertIdxOut, outOut), ACLNN_ERR_PARAM_NULLPTR); + CHECK_RET(CheckDtypeValid(x, biasOptional, yOut, expertIdxOut, outOut), ACLNN_ERR_PARAM_INVALID); + return ACLNN_SUCCESS; +} + +} // namespace MoeGatingTopKCheck + +#ifdef __cplusplus +extern "C" { +#endif + +ACLNN_API aclnnStatus aclnnMoeGatingTopKGetWorkspaceSize(const aclTensor *x, const aclTensor *biasOptional, int64_t k, + int64_t kGroup, int64_t groupCount, int64_t groupSelectMode, + int64_t renorm, int64_t normType, bool outFlag, + double routedScalingFactor, double eps, const aclTensor *yOut, + const aclTensor *expertIdxOut, const aclTensor *outOut, + uint64_t *workspaceSize, aclOpExecutor **executor) +{ + L2_DFX_PHASE_1(aclnnMoeGatingTopK, + DFX_IN(x, biasOptional, k, kGroup, groupCount, groupSelectMode, renorm, normType, outFlag, + routedScalingFactor, eps), + DFX_OUT(yOut, expertIdxOut, outOut)); + + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + aclnnStatus ret = MoeGatingTopKCheck::CheckParams(x, biasOptional, yOut, expertIdxOut, outOut); + CHECK_RET(ret == ACLNN_SUCCESS, ret); + + auto xContiguous = l0op::Contiguous(x, uniqueExecutor.get()); + CHECK_RET(xContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + + const aclTensor *biasContiguous = nullptr; + if (biasOptional != nullptr) { + biasContiguous = l0op::Contiguous(biasOptional, uniqueExecutor.get()); + CHECK_RET(biasContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + } + + auto result = l0op::MoeGatingTopK(xContiguous, biasContiguous, nullptr, nullptr, k, kGroup, groupCount, + groupSelectMode, renorm, normType, outFlag, routedScalingFactor, eps, yOut, + expertIdxOut, outOut, uniqueExecutor.get()); + CHECK_RET(result.y != nullptr, ACLNN_ERR_INNER_NULLPTR); + CHECK_RET(result.expertIdx != nullptr, ACLNN_ERR_INNER_NULLPTR); + CHECK_RET(result.outOut != nullptr, ACLNN_ERR_INNER_NULLPTR); + + auto viewCopyYOutResult = l0op::ViewCopy(result.y, yOut, uniqueExecutor.get()); + CHECK_RET(viewCopyYOutResult != nullptr, ACLNN_ERR_INNER_NULLPTR); + + auto viewCopyExpertIdxResult = l0op::ViewCopy(result.expertIdx, expertIdxOut, uniqueExecutor.get()); + CHECK_RET(viewCopyExpertIdxResult != nullptr, ACLNN_ERR_INNER_NULLPTR); + + auto viewCopyOutOutResult = l0op::ViewCopy(result.outOut, outOut, uniqueExecutor.get()); + CHECK_RET(viewCopyOutOutResult != nullptr, ACLNN_ERR_INNER_NULLPTR); + + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +ACLNN_API aclnnStatus aclnnMoeGatingTopK(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + aclrtStream stream) +{ + L2_DFX_PHASE_2(aclnnMoeGatingTopK); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +#ifdef __cplusplus +} +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/aclnn_moe_gating_top_k.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/aclnn_moe_gating_top_k.h new file mode 100644 index 0000000000000000000000000000000000000000..b5d09a4aa51df54ea2fb47d8a811a65dbe6f41eb --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/aclnn_moe_gating_top_k.h @@ -0,0 +1,39 @@ +/** + * 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_MOE_GATING_TOP_K_H_ +#define OP_API_INC_MOE_GATING_TOP_K_H_ + +#include "aclnn/aclnn_base.h" +#include "aclnn_util.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief aclnnMoeGatingTopK的第一段接口,根据具体的计算流程,计算workspace大小。 + * @domain aclnn_ops_infer + */ +ACLNN_API aclnnStatus aclnnMoeGatingTopKGetWorkspaceSize(const aclTensor *x, const aclTensor *biasOptional, int64_t k, + int64_t kGroup, int64_t groupCount, int64_t groupSelectMode, + int64_t renorm, int64_t normType, bool outFlag, + double routedScalingFactor, double eps, const aclTensor *yOut, + const aclTensor *expertIdxOut, const aclTensor *outOut, + uint64_t *workspaceSize, aclOpExecutor **executor); + +/* @brief aclnnMoeGatingTopK的第二段接口,用于执行计算。 */ +ACLNN_API aclnnStatus aclnnMoeGatingTopK(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/aclnn_moe_gating_top_k_v2.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/aclnn_moe_gating_top_k_v2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..720093fb96adde57490b011be630e9d1c71bebcc --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/aclnn_moe_gating_top_k_v2.cpp @@ -0,0 +1,157 @@ +/** + * 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 "aclnn_moe_gating_top_k_v2.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 "aclnn_kernels/contiguous.h" +#include "opdev/tensor_view_utils.h" +#include "opdev/op_log.h" +#include "moe_gating_top_k.h" + +using namespace op; + +namespace MoeGatingTopKV2Check { + +static const std::initializer_list MOE_GATING_TOP_K_V2_DTYPE_SUPPORT_LIST_X = { + DataType::DT_FLOAT16, DataType::DT_BF16, DataType::DT_FLOAT}; +static const std::initializer_list MOE_GATING_TOP_K_V2_DTYPE_SUPPORT_LIST_INT = {DataType::DT_INT32, + DataType::DT_INT64}; +static const std::initializer_list MOE_GATING_TOP_K_V2_DTYPE_SUPPORT_LIST_INT32 = {DataType::DT_INT32}; + +static inline bool CheckNotNull(const aclTensor *x, const aclTensor *yOut, const aclTensor *expertIdxOut, + const aclTensor *outOut) +{ + OP_CHECK_NULL(x, return false); + OP_CHECK_NULL(yOut, return false); + OP_CHECK_NULL(expertIdxOut, return false); + OP_CHECK_NULL(outOut, return false); + return true; +} + +static inline bool CheckDtypeValid(const aclTensor *x, const aclTensor *biasOptional, const aclTensor *inputIdsOptional, + const aclTensor *tid2eidOptional, const aclTensor *yOut, + const aclTensor *expertIdxOut, const aclTensor *outOut) +{ + if (x != nullptr && x->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(x, MOE_GATING_TOP_K_V2_DTYPE_SUPPORT_LIST_X, return false); + } + if (biasOptional != nullptr && biasOptional->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(biasOptional, MOE_GATING_TOP_K_V2_DTYPE_SUPPORT_LIST_X, return false); + OP_CHECK_DTYPE_NOT_SAME(x, biasOptional, return false); + } + if (inputIdsOptional != nullptr && inputIdsOptional->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(inputIdsOptional, MOE_GATING_TOP_K_V2_DTYPE_SUPPORT_LIST_INT, return false); + } + if (tid2eidOptional != nullptr && tid2eidOptional->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(tid2eidOptional, MOE_GATING_TOP_K_V2_DTYPE_SUPPORT_LIST_INT, return false); + } + if (yOut != nullptr && yOut->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(yOut, MOE_GATING_TOP_K_V2_DTYPE_SUPPORT_LIST_X, return false); + OP_CHECK_DTYPE_NOT_SAME(x, yOut, return false); + } + if (expertIdxOut != nullptr && expertIdxOut->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(expertIdxOut, MOE_GATING_TOP_K_V2_DTYPE_SUPPORT_LIST_INT32, return false); + } + if (outOut != nullptr && outOut->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(outOut, MOE_GATING_TOP_K_V2_DTYPE_SUPPORT_LIST_X, return false); + } + return true; +} + +static aclnnStatus CheckParams(const aclTensor *x, const aclTensor *biasOptional, const aclTensor *inputIdsOptional, + const aclTensor *tid2eidOptional, const aclTensor *yOut, const aclTensor *expertIdxOut, + const aclTensor *outOut) +{ + CHECK_RET(CheckNotNull(x, yOut, expertIdxOut, outOut), ACLNN_ERR_PARAM_NULLPTR); + CHECK_RET(CheckDtypeValid(x, biasOptional, inputIdsOptional, tid2eidOptional, yOut, expertIdxOut, outOut), + ACLNN_ERR_PARAM_INVALID); + return ACLNN_SUCCESS; +} + +} // namespace MoeGatingTopKV2Check + +#ifdef __cplusplus +extern "C" { +#endif + +ACLNN_API aclnnStatus aclnnMoeGatingTopKV2GetWorkspaceSize( + const aclTensor *x, const aclTensor *biasOptional, const aclTensor *inputIdsOptional, + const aclTensor *tid2eidOptional, int64_t k, int64_t kGroup, int64_t groupCount, int64_t groupSelectMode, + int64_t renorm, int64_t normType, bool outFlag, double routedScalingFactor, double eps, const aclTensor *yOut, + const aclTensor *expertIdxOut, const aclTensor *outOut, uint64_t *workspaceSize, aclOpExecutor **executor) +{ + L2_DFX_PHASE_1(aclnnMoeGatingTopKV2, + DFX_IN(x, biasOptional, inputIdsOptional, tid2eidOptional, k, kGroup, groupCount, groupSelectMode, + renorm, normType, outFlag, routedScalingFactor, eps), + DFX_OUT(yOut, expertIdxOut, outOut)); + + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + aclnnStatus ret = MoeGatingTopKV2Check::CheckParams(x, biasOptional, inputIdsOptional, tid2eidOptional, yOut, + expertIdxOut, outOut); + CHECK_RET(ret == ACLNN_SUCCESS, ret); + + auto xContiguous = l0op::Contiguous(x, uniqueExecutor.get()); + CHECK_RET(xContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + + const aclTensor *biasContiguous = nullptr; + if (biasOptional != nullptr) { + biasContiguous = l0op::Contiguous(biasOptional, uniqueExecutor.get()); + CHECK_RET(biasContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + } + + const aclTensor *inputIdsContiguous = nullptr; + if (inputIdsOptional != nullptr) { + inputIdsContiguous = l0op::Contiguous(inputIdsOptional, uniqueExecutor.get()); + CHECK_RET(inputIdsContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + } + + const aclTensor *tid2eidContiguous = nullptr; + if (tid2eidOptional != nullptr) { + tid2eidContiguous = l0op::Contiguous(tid2eidOptional, uniqueExecutor.get()); + CHECK_RET(tid2eidContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + } + + auto result = l0op::MoeGatingTopK(xContiguous, biasContiguous, inputIdsContiguous, tid2eidContiguous, k, kGroup, + groupCount, groupSelectMode, renorm, normType, outFlag, routedScalingFactor, eps, + yOut, expertIdxOut, outOut, uniqueExecutor.get()); + CHECK_RET(result.y != nullptr, ACLNN_ERR_INNER_NULLPTR); + CHECK_RET(result.expertIdx != nullptr, ACLNN_ERR_INNER_NULLPTR); + CHECK_RET(result.outOut != nullptr, ACLNN_ERR_INNER_NULLPTR); + + auto viewCopyYOutResult = l0op::ViewCopy(result.y, yOut, uniqueExecutor.get()); + CHECK_RET(viewCopyYOutResult != nullptr, ACLNN_ERR_INNER_NULLPTR); + + auto viewCopyExpertIdxResult = l0op::ViewCopy(result.expertIdx, expertIdxOut, uniqueExecutor.get()); + CHECK_RET(viewCopyExpertIdxResult != nullptr, ACLNN_ERR_INNER_NULLPTR); + + auto viewCopyOutOutResult = l0op::ViewCopy(result.outOut, outOut, uniqueExecutor.get()); + CHECK_RET(viewCopyOutOutResult != nullptr, ACLNN_ERR_INNER_NULLPTR); + + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +ACLNN_API aclnnStatus aclnnMoeGatingTopKV2(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + aclrtStream stream) +{ + L2_DFX_PHASE_2(aclnnMoeGatingTopKV2); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +#ifdef __cplusplus +} +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/aclnn_moe_gating_top_k_v2.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/aclnn_moe_gating_top_k_v2.h new file mode 100644 index 0000000000000000000000000000000000000000..fc590b0930be191904690dd87c8de28119c7b651 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/aclnn_moe_gating_top_k_v2.h @@ -0,0 +1,44 @@ +/** + * 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_moe_gating_top_k_v2.h + * \brief + */ + +#ifndef OP_API_INC_MOE_GATING_TOP_K_V2_H_ +#define OP_API_INC_MOE_GATING_TOP_K_V2_H_ + +#include "aclnn/aclnn_base.h" +#include "aclnn_util.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief aclnnMoeGatingTopKV2的第一段接口,根据具体的计算流程,计算workspace大小。 + * @domain aclnn_ops_infer + */ +ACLNN_API aclnnStatus aclnnMoeGatingTopKV2GetWorkspaceSize( + const aclTensor *x, const aclTensor *biasOptional, const aclTensor *inputIdsOptional, + const aclTensor *tid2eidOptional, int64_t k, int64_t kGroup, int64_t groupCount, int64_t groupSelectMode, + int64_t renorm, int64_t normType, bool outFlag, double routedScalingFactor, double eps, const aclTensor *yOut, + const aclTensor *expertIdxOut, const aclTensor *outOut, uint64_t *workspaceSize, aclOpExecutor **executor); + +/* @brief aclnnMoeGatingTopKV2的第二段接口,用于执行计算。 */ +ACLNN_API aclnnStatus aclnnMoeGatingTopKV2(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/moe_gating_top_k.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/moe_gating_top_k.cpp new file mode 100644 index 0000000000000000000000000000000000000000..73786a6c75a629f614fe51310e9420748823bdf6 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/moe_gating_top_k.cpp @@ -0,0 +1,60 @@ +/** + * 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 moe_gating_top_k.cpp + * \brief + */ + +#include "moe_gating_top_k.h" +#include "opdev/op_log.h" +#include "opdev/op_dfx.h" +#include "opdev/shape_utils.h" +#include "opdev/make_op_executor.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "external/aclnn_kernels/aclnn_platform.h" + +using namespace op; + +namespace l0op { +OP_TYPE_REGISTER(MoeGatingTopK); +MoeGatingTopKResult MoeGatingTopK( + const aclTensor* x, const aclTensor* bias, const aclTensor* input_ids, const aclTensor* tid2eid, + int64_t k, int64_t k_group, int64_t group_count, int64_t group_select_mode, + int64_t renorm, int64_t norm_type, bool out_flag, + double routed_scaling_factor, double eps, + const aclTensor* y_out, const aclTensor* expert_idx_out, const aclTensor* out_out, + aclOpExecutor* executor) +{ + L0_DFX(MoeGatingTopK, x, bias, input_ids, tid2eid, k, k_group, group_count, + group_select_mode, renorm, norm_type, out_flag, routed_scaling_factor, eps, + y_out, expert_idx_out, out_out); + + auto y = executor->AllocTensor(y_out->GetViewShape(), y_out->GetDataType(), Format::FORMAT_ND); + auto expert_idx = executor->AllocTensor(expert_idx_out->GetViewShape(), expert_idx_out->GetDataType(), + Format::FORMAT_ND); + auto out_out_alloc = executor->AllocTensor(out_out->GetViewShape(), out_out->GetDataType(), Format::FORMAT_ND); + + MoeGatingTopKResult emptyResult = {nullptr, nullptr, nullptr}; + if (!y->IsEmpty()) { + float routedScalingFactorFloat = static_cast(routed_scaling_factor); + float epsFloat = static_cast(eps); + auto ret = ADD_TO_LAUNCHER_LIST_AICORE(MoeGatingTopK, + OP_INPUT(x, bias, input_ids, tid2eid), + OP_OUTPUT(y, expert_idx, out_out_alloc), + OP_ATTR(k, k_group, group_count, group_select_mode, renorm, norm_type, + out_flag, routedScalingFactorFloat, epsFloat)); + OP_CHECK_ADD_TO_LAUNCHER_LIST_AICORE(ret != ACLNN_SUCCESS, return emptyResult, + "MoeGatingTopK ADD_TO_LAUNCHER_LIST_AICORE failed."); + } + MoeGatingTopKResult result = {y, expert_idx, out_out_alloc}; + return result; +} +} // namespace l0op diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/moe_gating_top_k.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/moe_gating_top_k.h new file mode 100644 index 0000000000000000000000000000000000000000..d3942176d5008b43ef5fb33176f3681e9fe80e7e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_host/op_api/moe_gating_top_k.h @@ -0,0 +1,34 @@ +/** + * 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 moe_gating_top_k.h + * \brief + */ + +#ifndef OP_API_INC_LEVEL0_MOE_GATING_TOP_K_H_ +#define OP_API_INC_LEVEL0_MOE_GATING_TOP_K_H_ + +#include "opdev/op_executor.h" + +namespace l0op { +struct MoeGatingTopKResult { + const aclTensor *y; + const aclTensor *expertIdx; + const aclTensor *outOut; +}; + +MoeGatingTopKResult MoeGatingTopK(const aclTensor *x, const aclTensor *bias, const aclTensor *input_ids, + const aclTensor *tid2eid, int64_t k, int64_t k_group, int64_t group_count, + int64_t group_select_mode, int64_t renorm, int64_t norm_type, bool out_flag, + double routed_scaling_factor, double eps, const aclTensor *y_out, + const aclTensor *expert_idx_out, const aclTensor *out_out, aclOpExecutor *executor); +} // namespace l0op +#endif // OP_API_INC_LEVEL0_MOE_GATING_TOP_K_H_ diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/arch35/common.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/arch35/common.h new file mode 100644 index 0000000000000000000000000000000000000000..6e19a0d48e1716f71641114c31bb4e6400fc6069 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/arch35/common.h @@ -0,0 +1,95 @@ +/** + * 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 common.h + * \brief + */ +#ifndef MOE_GATING_TOP_K_COMMON_H_V35 +#define MOE_GATING_TOP_K_COMMON_H_V35 + +#include "kernel_operator.h" + +namespace MoeGatingTopK { +using namespace AscendC; +constexpr int32_t MIN_FP32 = 0xFF800000; +constexpr int64_t ONE_REPEAT_SORT_NUM = 32; +constexpr int64_t BLOCK_BYTES = 32; + +constexpr int64_t MERGE_LIST_TWO = 2; +constexpr int64_t MERGE_LIST_THREE = 3; +constexpr int64_t MERGE_LIST_FOUR = 4; + +constexpr int64_t MERGE_LIST_IDX_TWO = 2; +constexpr int64_t MERGE_LIST_IDX_THREE = 3; + +__aicore__ inline int64_t Align(int64_t elementNum, int64_t bytes) +{ + if (bytes == 0) { + return 0; + } + return (elementNum * bytes + BLOCK_BYTES - 1) / BLOCK_BYTES * BLOCK_BYTES / bytes; +} + +__aicore__ inline int64_t Ceil(int64_t a, int64_t b) +{ + if (b == 0) { + return 0; + } + return (a + b - 1) / b; +} + +__aicore__ inline int64_t AlignBytes(int64_t elementNum, int64_t bytes) +{ + return (elementNum * bytes + BLOCK_BYTES - 1) / BLOCK_BYTES * BLOCK_BYTES; +} + +template +__aicore__ inline T Max(T a, T b) +{ + return a < b ? b : a; +} + +template +__aicore__ inline T Min(T a, T b) +{ + return a > b ? b : a; +} + +template +__aicore__ inline T1 CeilAlign(T1 a, T2 b) +{ + if (b == 0) { + return 0; + } + return (a + b - 1) / b * b; +} + +template +__aicore__ inline T1 CeilDiv(T1 x, T2 y) +{ + if (y != 0 && x != 0) { + const T1 quotient = x / y; + return (x % y != 0 && ((x ^ y) >= 0)) ? (quotient + 1) : quotient; + } + + return x; +} + +template +__aicore__ inline void SetWaitFlag(HardEvent evt) +{ + event_t eventId = static_cast(GetTPipePtr()->FetchEventID(evt)); + SetFlag(eventId); + WaitFlag(eventId); +} + +} // namespace MoeGatingTopK +#endif // MOE_GATING_TOP_K_COMMON_H_V35 diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/arch35/moe_gating_top_k_regbase.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/arch35/moe_gating_top_k_regbase.h new file mode 100644 index 0000000000000000000000000000000000000000..799ac9bc9c7a78db462a9f5234bc122246213e29 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/arch35/moe_gating_top_k_regbase.h @@ -0,0 +1,1491 @@ +/** + * 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 moe_gating_top_k_regbase.h + * \brief + */ +#ifndef MOE_GATING_TOP_K_REGBASE_H +#define MOE_GATING_TOP_K_REGBASE_H + +#include +#include "common.h" +#include "kernel_operator.h" +#include "op_kernel/math_util.h" +#include "op_kernel/load_store_utils.h" + +namespace MoeGatingTopK { +using namespace AscendC; +using MicroAPI::RegTensor; + +constexpr int32_t CONSTANT_TWO = 2; +constexpr int32_t CONSTANT_THREE = 3; +constexpr int32_t CONSTANT_FOUR = 4; +constexpr int32_t CONSTANT_EIGHT = 8; +constexpr uint32_t VL_FLOAT_SIZE = VECTOR_REG_WIDTH / sizeof(float); +constexpr MicroAPI::DivSpecificMode mode = {MicroAPI::MaskMergeMode::ZEROING, true}; + +template +class MoeGatingTopKRegbase { +public: + __aicore__ inline MoeGatingTopKRegbase(){}; + __aicore__ inline void Init(GM_ADDR x, GM_ADDR bias, GM_ADDR inputIds, GM_ADDR tid2eid, GM_ADDR y, + GM_ADDR expertIdx, GM_ADDR out, GM_ADDR workspace, + const MoeGatingTopKRegbaseTilingData *tilingData, TPipe *tPipe); + __aicore__ inline void Process(); + +private: + __aicore__ inline void CopyInBias(); + __aicore__ inline void CopyInX(int64_t progress); + __aicore__ inline void ComputeX(); + __aicore__ inline void PadWithMinFp32(__local_mem__ float *addBiasOutAddr, uint16_t groupCount0, + uint32_t perGroupExpertCount0, uint32_t perGroupExpertCountAlign0); + __aicore__ inline void GenerateIndexAndCopy(__local_mem__ float *sigmoidOutAddr, + __local_mem__ float *addBiasOutAddr, + __local_mem__ int32_t *indexOutAddr, uint32_t size, uint32_t vfLoopNum); + __aicore__ inline void ComputeWithSoftMax(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor); + __aicore__ inline void ComputeWithSigmoid(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor); + __aicore__ inline void ComputeWithSoftplus(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor); + __aicore__ inline void SoftMaxWithBias(LocalTensor xSigmoidTensor, LocalTensor xBiasTensor, + LocalTensor indexTensor); + __aicore__ inline void SoftMaxWithoutBias(LocalTensor xSigmoidTensor, LocalTensor xBiasTensor, + LocalTensor indexTensor); + __aicore__ inline void SigmoidWithBias(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor); + __aicore__ inline void SigmoidWithoutBias(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor); + __aicore__ inline void SoftplusWithBias(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor); + __aicore__ inline void SoftplusWithoutBias(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor); + __aicore__ inline void CopyOutXNorm(int64_t progress); + __aicore__ inline void SortInGroup(); + __aicore__ inline void SelectTopKGroupIndex(); + __aicore__ inline void SelectTopKInGroup(LocalTensor sortedInGroupTensor, + LocalTensor top2InGroupTensor, uint16_t groupCount0, + uint32_t perGroupExpertCountAlign0, uint32_t padNegInfNum); + __aicore__ inline void SelectTopKAfterSort(LocalTensor sortedGroupTensor, + LocalTensor top2InGroupTensor, uint32_t size, int32_t kGroup0, + LocalTensor tmpLocal); + __aicore__ inline void FinalSortByKGroup(); + __aicore__ inline void FinalSortAfterKGroup(); + __aicore__ inline void ProcessQuartetSort(LocalTensor srcTensor, LocalTensor dstTensor, + int32_t sortedBaseRow, int32_t quotient); + __aicore__ inline void ProcessRemainderSort(LocalTensor srcTensor, LocalTensor dstTensor, + int32_t sortedBaseRow, int32_t quotient, int32_t remainder, + int32_t nextBaseRow); + __aicore__ inline void SelectTopKExpertScore(); + __aicore__ inline void TopKCompute(); + __aicore__ inline void HashCompute(int64_t row); + __aicore__ inline void CopyOut(int64_t progress); + + __aicore__ inline void HashGatherWithSmallKAlignE(LocalTensor xSigmoidTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, + uint32_t k, float eps, float routedScalingFactor); + __aicore__ inline void HashGatherWithSmallKNotAlignE(LocalTensor xSigmoidTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, + uint32_t k, float eps, float routedScalingFactor, + int32_t expertIdxPad, int32_t perGroupExpertCountAlign); + + __aicore__ inline void smallKAlignEVF(LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, uint32_t k, + float eps, float routedScalingFactor); + __aicore__ inline void largeKAlignEVF(LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, uint32_t k, + float eps, float routedScalingFactor); + __aicore__ inline void LargeKAlignEVFNoNorm(LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, + uint32_t k, float routedScalingFactor); + __aicore__ inline void LargeKAlignEVFWithNorm(LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, + uint32_t k, float eps, float routedScalingFactor); + __aicore__ inline void smallKNotAlignEVF(LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, uint32_t k, + float eps, float routedScalingFactor, int32_t expertIdxPad, + int32_t perGroupExpertCountAlign); + __aicore__ inline void largeKNotAlignEVF(LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, uint32_t k, + float eps, float routedScalingFactor, int32_t expertIdxPad, + int32_t perGroupExpertCountAlign); + __aicore__ inline void LargeKNotAlignEVFNoNorm(LocalTensor xSigmoidTensor, + LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, + uint32_t k, float routedScalingFactor, int32_t expertIdxPad, + int32_t perGroupExpertCountAlign); + __aicore__ inline void LargeKNotAlignEVFWithNorm(LocalTensor xSigmoidTensor, + LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, + uint32_t k, float eps, float routedScalingFactor, + int32_t expertIdxPad, int32_t perGroupExpertCountAlign); + __aicore__ inline void LargeKCoreWithNormImpl(LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, + uint32_t k, float eps, float routedScalingFactor, + bool needExpertIdxAdjust, int32_t expertIdxPad, + int32_t perGroupExpertCountAlign); + __aicore__ inline void SmallKCoreImpl(LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, uint32_t k, + float eps, float routedScalingFactor, bool needNorm, bool needExpertIdxAdjust, + int32_t expertIdxPad, int32_t perGroupExpertCountAlign); + +private: + TPipe *pipe_; + TQue xInQueue_; + TQue yOutQueue_; + TQue expertIdxOutQueue_; + TQue outOutQueue_; + + TBuf biasBuf_; + TBuf xBiasBuf_; + TBuf xSigmoidBuf_; + TBuf groupBuf_; + TBuf sortedInGroupBuf_; + TBuf sortedGroupBuf_; + TBuf indexBuffer_; + TBuf finalSortBuffer_; + + GlobalTensor xGm_; + GlobalTensor biasGm_; + GlobalTensor yGm_; + GlobalTensor expertIdxGm_; + GlobalTensor outGm_; + GlobalTensor inputIdsGm_; + GlobalTensor tid2eidGm_; + + LocalTensor indexTensor; + LocalTensor sortedInGroupTensor; + LocalTensor sortedGroupTensor; + LocalTensor mrgSortTensor; + + int64_t blockIdx_; + int64_t curCoreRowCount_; + int64_t expertCount_; + int64_t k_; + int64_t kGroup_; + int64_t groupCount_; + float routedScalingFactor_; + float eps_; + bool hasBias_ = false; + bool hashFlag_ = false; + + int64_t perGroupExpertCount_; + int64_t perGroupExpertCountAlign_; + int64_t expertCountAlign_; + int64_t groupSelectMode_; + const MoeGatingTopKRegbaseTilingData *tilingData_; +}; + +template +__aicore__ inline void MoeGatingTopKRegbase::CopyInBias() +{ + if (!hasBias_) { + return; + } + LocalTensor biasTensor = biasBuf_.Get(); + + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = groupCount_; + dataCopyParams.blockLen = perGroupExpertCount_ * sizeof(T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = (perGroupExpertCountAlign_ - perGroupExpertCount_) * sizeof(T) / BLOCK_BYTES; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, static_cast(0)}; + + DataCopyPad(biasTensor, biasGm_, dataCopyParams, dataCopyPadParams); + event_t eventIdMte2ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventIdMte2ToV); + WaitFlag(eventIdMte2ToV); +} + +template +__aicore__ inline void MoeGatingTopKRegbase::CopyInX(int64_t row) +{ + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = groupCount_; + dataCopyParams.blockLen = perGroupExpertCount_ * sizeof(T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = (perGroupExpertCountAlign_ - perGroupExpertCount_) * sizeof(T) / BLOCK_BYTES; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, static_cast(0)}; + if (tilingData_->normType == 0) { + LocalTensor xInLocalTensor = xInQueue_.AllocTensor(); + if constexpr (IsSameType::value) { + DataCopyPad(xInLocalTensor, xGm_[row * expertCount_], dataCopyParams, dataCopyPadParams); + } else { + DataCopyPad(xInLocalTensor[expertCountAlign_].ReinterpretCast(), xGm_[row * expertCount_], + dataCopyParams, dataCopyPadParams); + } + xInQueue_.EnQue(xInLocalTensor); + } else { + LocalTensor xInLocalTensor = xInQueue_.AllocTensor(); + DataCopyPad(xInLocalTensor, xGm_[row * expertCount_], dataCopyParams, dataCopyPadParams); + xInQueue_.EnQue(xInLocalTensor); + } +} + +template +__aicore__ inline void +MoeGatingTopKRegbase::PadWithMinFp32(__local_mem__ float *addBiasOutAddr, uint16_t groupCount0, + uint32_t perGroupExpertCount0, uint32_t perGroupExpertCountAlign0) +{ + RegTensor vregPad; + MicroAPI::UnalignReg u0; + MicroAPI::Duplicate(vregPad, *((float *)&MIN_FP32)); + for (uint16_t i = 0; i < groupCount0; i++) { + auto padUbAddr = addBiasOutAddr + perGroupExpertCount0 + i * perGroupExpertCountAlign0; + MicroAPI::DataCopyUnAlign(padUbAddr, vregPad, u0, perGroupExpertCountAlign0 - perGroupExpertCount0); + MicroAPI::DataCopyUnAlignPost(padUbAddr, u0, 0); + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::GenerateIndexAndCopy(__local_mem__ float *sigmoidOutAddr, + __local_mem__ float *addBiasOutAddr, + __local_mem__ int32_t *indexOutAddr, + uint32_t size, uint32_t vfLoopNum) +{ + RegTensor vregIndex; + RegTensor vregSoftmaxResult; + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg0 = MicroAPI::UpdateMask(size); + ops::LoadOneTensorForDtypeT(sigmoidOutAddr, vregSoftmaxResult, preg0, i * VL_FLOAT_SIZE); + MicroAPI::Arange(vregIndex, static_cast(i * VL_FLOAT_SIZE)); + MicroAPI::DataCopy(addBiasOutAddr + i * VL_FLOAT_SIZE, vregSoftmaxResult, preg0); + MicroAPI::DataCopy(indexOutAddr + i * VL_FLOAT_SIZE, vregIndex, preg0); + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::SoftMaxWithBias(LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, + LocalTensor indexTensor) +{ + uint32_t size = perGroupExpertCountAlign_ * groupCount_; + uint16_t vfLoopNum = static_cast(CeilDiv(size, VL_FLOAT_SIZE)); + LocalTensor biasTensor = biasBuf_.Get(); + + __local_mem__ float *sigmoidOutAddr = (__local_mem__ float *)xSigmoidTensor.GetPhyAddr(); + __local_mem__ int32_t *indexOutAddr = (__local_mem__ int32_t *)indexTensor.GetPhyAddr(); + __local_mem__ float *addBiasOutAddr = (__local_mem__ float *)xBiasTensor.GetPhyAddr(); + __local_mem__ T *biasAddr = (__local_mem__ T *)biasTensor.GetPhyAddr(); + + __VEC_SCOPE__ + { + RegTensor vregBiasFp32; + RegTensor vregIndex; + RegTensor vregSoftmaxResult; + RegTensor vregBiasResult; + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg0 = MicroAPI::UpdateMask(size); + ops::LoadOneTensorForDtypeT(sigmoidOutAddr, vregSoftmaxResult, preg0, i * VL_FLOAT_SIZE); + ops::LoadOneTensorForDtypeT(biasAddr, vregBiasFp32, preg0, i * VL_FLOAT_SIZE); + MicroAPI::Add(vregBiasResult, vregSoftmaxResult, vregBiasFp32, preg0); + MicroAPI::Arange(vregIndex, static_cast(i * VL_FLOAT_SIZE)); + MicroAPI::DataCopy(indexOutAddr + i * VL_FLOAT_SIZE, vregIndex, preg0); + MicroAPI::DataCopy(addBiasOutAddr + i * VL_FLOAT_SIZE, vregBiasResult, preg0); + } + MicroAPI::LocalMemBar(); + PadWithMinFp32(addBiasOutAddr, groupCount_, perGroupExpertCount_, perGroupExpertCountAlign_); + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::SoftMaxWithoutBias(LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, + LocalTensor indexTensor) +{ + uint32_t size = perGroupExpertCountAlign_ * groupCount_; + + __local_mem__ float *sigmoidOutAddr = (__local_mem__ float *)xSigmoidTensor.GetPhyAddr(); + __local_mem__ int32_t *indexOutAddr = (__local_mem__ int32_t *)indexTensor.GetPhyAddr(); + __local_mem__ float *addBiasOutAddr = (__local_mem__ float *)xBiasTensor.GetPhyAddr(); + + __VEC_SCOPE__ + { + GenerateIndexAndCopy(sigmoidOutAddr, addBiasOutAddr, indexOutAddr, size, CeilDiv(size, VL_FLOAT_SIZE)); + MicroAPI::LocalMemBar(); + PadWithMinFp32(addBiasOutAddr, groupCount_, perGroupExpertCount_, perGroupExpertCountAlign_); + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::ComputeWithSoftMax(LocalTensor xInLocalTensor, + LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, + LocalTensor indexTensor) +{ + if constexpr (!IsSameType::value) { + Cast(xInLocalTensor, xInLocalTensor[expertCountAlign_].template ReinterpretCast(), RoundMode::CAST_NONE, + expertCountAlign_); + } + + int64_t duplicateNum = perGroupExpertCount_ % ONE_REPEAT_SORT_NUM; + int duplicateIndex = perGroupExpertCount_ - duplicateNum; + if (perGroupExpertCount_ != perGroupExpertCountAlign_ && duplicateNum > 0) { + uint64_t mask0 = UINT64_MAX; + mask0 = mask0 << duplicateNum; + mask0 = mask0 & (UINT64_MAX >> ONE_REPEAT_SORT_NUM); + uint64_t mask[2] = {mask0, 0}; + Duplicate(xInLocalTensor.ReinterpretCast()[duplicateIndex], MIN_FP32, mask, groupCount_, 1, + (perGroupExpertCountAlign_ * sizeof(float)) / BLOCK_BYTES); + } + + SoftMaxShapeInfo softmaxShapeInfo; + softmaxShapeInfo.srcM = 1; + softmaxShapeInfo.srcK = groupCount_ * perGroupExpertCountAlign_; + softmaxShapeInfo.oriSrcM = 1; + softmaxShapeInfo.oriSrcK = groupCount_ * perGroupExpertCountAlign_; + SoftMax(xSigmoidTensor, xInLocalTensor, tilingData_->softmaxTilingData, softmaxShapeInfo); + + if (hasBias_) { + SoftMaxWithBias(xSigmoidTensor, xBiasTensor, indexTensor); + } else { + SoftMaxWithoutBias(xSigmoidTensor, xBiasTensor, indexTensor); + } +} + +template +__aicore__ inline void +MoeGatingTopKRegbase::SigmoidWithBias(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor) +{ + uint32_t size = perGroupExpertCountAlign_ * groupCount_; + uint16_t vfLoopNum = static_cast(CeilDiv(size, VL_FLOAT_SIZE)); + LocalTensor biasTensor = biasBuf_.Get(); + + __local_mem__ T *inputAddr = (__local_mem__ T *)xInLocalTensor.GetPhyAddr(); + __local_mem__ float *sigmoidOutAddr = (__local_mem__ float *)xSigmoidTensor.GetPhyAddr(); + __local_mem__ int32_t *indexOutAddr = (__local_mem__ int32_t *)indexTensor.GetPhyAddr(); + __local_mem__ float *addBiasOutAddr = (__local_mem__ float *)xBiasTensor.GetPhyAddr(); + __local_mem__ T *biasAddr = (__local_mem__ T *)biasTensor.GetPhyAddr(); + + __VEC_SCOPE__ + { + RegTensor vregBiasFp32; + RegTensor vregIndex; + RegTensor vregSigmoidResult; + RegTensor vregBiasResult; + RegTensor vregOne; + RegTensor vregInFp32; + RegTensor vreg1; + RegTensor vreg2; + RegTensor vreg3; + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + MicroAPI::Duplicate(vregOne, static_cast(1), preg0); + + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg0 = MicroAPI::UpdateMask(size); + ops::LoadTwoTensorForDtypeT(inputAddr, biasAddr, vregInFp32, vregBiasFp32, preg0, preg0, + i * VL_FLOAT_SIZE, i * VL_FLOAT_SIZE); + MicroAPI::Muls(vreg1, vregInFp32, static_cast(-1), preg0); + MicroAPI::Exp(vreg2, vreg1, preg0); + MicroAPI::Adds(vreg3, vreg2, static_cast(1), preg0); + MicroAPI::Div(vregSigmoidResult, vregOne, vreg3, preg0); + MicroAPI::Add(vregBiasResult, vregSigmoidResult, vregBiasFp32, preg0); + MicroAPI::Arange(vregIndex, static_cast(i * VL_FLOAT_SIZE)); + MicroAPI::DataCopy(sigmoidOutAddr + i * VL_FLOAT_SIZE, vregSigmoidResult, preg0); + MicroAPI::DataCopy(indexOutAddr + i * VL_FLOAT_SIZE, vregIndex, preg0); + MicroAPI::DataCopy(addBiasOutAddr + i * VL_FLOAT_SIZE, vregBiasResult, preg0); + } + MicroAPI::LocalMemBar(); + PadWithMinFp32(addBiasOutAddr, groupCount_, perGroupExpertCount_, perGroupExpertCountAlign_); + } +} + +template +__aicore__ inline void +MoeGatingTopKRegbase::SigmoidWithoutBias(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor) +{ + uint32_t size = perGroupExpertCountAlign_ * groupCount_; + uint16_t vfLoopNum = static_cast(CeilDiv(size, VL_FLOAT_SIZE)); + + __local_mem__ T *inputAddr = (__local_mem__ T *)xInLocalTensor.GetPhyAddr(); + __local_mem__ float *sigmoidOutAddr = (__local_mem__ float *)xSigmoidTensor.GetPhyAddr(); + __local_mem__ int32_t *indexOutAddr = (__local_mem__ int32_t *)indexTensor.GetPhyAddr(); + __local_mem__ float *addBiasOutAddr = (__local_mem__ float *)xBiasTensor.GetPhyAddr(); + + __VEC_SCOPE__ + { + RegTensor vregIndex; + RegTensor vregSigmoidResult; + RegTensor vregOne; + RegTensor vregInFp32; + RegTensor vreg1; + RegTensor vreg2; + RegTensor vreg3; + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + MicroAPI::Duplicate(vregOne, static_cast(1), preg0); + + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg0 = MicroAPI::UpdateMask(size); + ops::LoadOneTensorForDtypeT(inputAddr, vregInFp32, preg0, i * VL_FLOAT_SIZE); + MicroAPI::Muls(vreg1, vregInFp32, static_cast(-1), preg0); + MicroAPI::Exp(vreg2, vreg1, preg0); + MicroAPI::Adds(vreg3, vreg2, static_cast(1), preg0); + MicroAPI::Div(vregSigmoidResult, vregOne, vreg3, preg0); + MicroAPI::Arange(vregIndex, static_cast(i * VL_FLOAT_SIZE)); + MicroAPI::DataCopy(sigmoidOutAddr + i * VL_FLOAT_SIZE, vregSigmoidResult, preg0); + MicroAPI::DataCopy(addBiasOutAddr + i * VL_FLOAT_SIZE, vregSigmoidResult, preg0); + MicroAPI::DataCopy(indexOutAddr + i * VL_FLOAT_SIZE, vregIndex, preg0); + } + MicroAPI::LocalMemBar(); + PadWithMinFp32(addBiasOutAddr, groupCount_, perGroupExpertCount_, perGroupExpertCountAlign_); + } +} + +template +__aicore__ inline void +MoeGatingTopKRegbase::ComputeWithSigmoid(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor) +{ + if (hasBias_) { + SigmoidWithBias(xInLocalTensor, xSigmoidTensor, xBiasTensor, indexTensor); + } else { + SigmoidWithoutBias(xInLocalTensor, xSigmoidTensor, xBiasTensor, indexTensor); + } +} + +template +__aicore__ inline void +MoeGatingTopKRegbase::SoftplusWithBias(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor) +{ + uint32_t size = perGroupExpertCountAlign_ * groupCount_; + uint16_t vfLoopNum = static_cast(CeilDiv(size, VL_FLOAT_SIZE)); + LocalTensor biasTensor = biasBuf_.Get(); + + __local_mem__ T *inputAddr = (__local_mem__ T *)xInLocalTensor.GetPhyAddr(); + __local_mem__ float *softplusOutAddr = (__local_mem__ float *)xSigmoidTensor.GetPhyAddr(); + __local_mem__ int32_t *indexOutAddr = (__local_mem__ int32_t *)indexTensor.GetPhyAddr(); + __local_mem__ float *addBiasOutAddr = (__local_mem__ float *)xBiasTensor.GetPhyAddr(); + __local_mem__ T *biasAddr = (__local_mem__ T *)biasTensor.GetPhyAddr(); + + __VEC_SCOPE__ + { + RegTensor vregBiasFp32; + RegTensor vregIndex; + RegTensor vregSoftplusResult; + RegTensor vregBiasResult; + RegTensor vregOne; + RegTensor vregInFp32; + RegTensor vreg1; + RegTensor vreg2; + RegTensor vreg3; + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + MicroAPI::Duplicate(vregOne, static_cast(1), preg0); + + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg0 = MicroAPI::UpdateMask(size); + ops::LoadTwoTensorForDtypeT(inputAddr, biasAddr, vregInFp32, vregBiasFp32, preg0, preg0, + i * VL_FLOAT_SIZE, i * VL_FLOAT_SIZE); + MicroAPI::Exp(vreg1, vregInFp32, preg0); + MicroAPI::Adds(vreg2, vreg1, static_cast(1), preg0); + MicroAPI::Ln(vreg3, vreg2, preg0); + MicroAPI::Sqrt(vregSoftplusResult, vreg3, preg0); + MicroAPI::Add(vregBiasResult, vregSoftplusResult, vregBiasFp32, preg0); + MicroAPI::Arange(vregIndex, static_cast(i * VL_FLOAT_SIZE)); + MicroAPI::DataCopy(softplusOutAddr + i * VL_FLOAT_SIZE, vregSoftplusResult, preg0); + MicroAPI::DataCopy(indexOutAddr + i * VL_FLOAT_SIZE, vregIndex, preg0); + MicroAPI::DataCopy(addBiasOutAddr + i * VL_FLOAT_SIZE, vregBiasResult, preg0); + } + MicroAPI::LocalMemBar(); + PadWithMinFp32(addBiasOutAddr, groupCount_, perGroupExpertCount_, perGroupExpertCountAlign_); + } +} + +template +__aicore__ inline void +MoeGatingTopKRegbase::SoftplusWithoutBias(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor) +{ + uint32_t size = perGroupExpertCountAlign_ * groupCount_; + uint16_t vfLoopNum = static_cast(CeilDiv(size, VL_FLOAT_SIZE)); + + __local_mem__ T *inputAddr = (__local_mem__ T *)xInLocalTensor.GetPhyAddr(); + __local_mem__ float *softplusOutAddr = (__local_mem__ float *)xSigmoidTensor.GetPhyAddr(); + __local_mem__ int32_t *indexOutAddr = (__local_mem__ int32_t *)indexTensor.GetPhyAddr(); + __local_mem__ float *addBiasOutAddr = (__local_mem__ float *)xBiasTensor.GetPhyAddr(); + + __VEC_SCOPE__ + { + RegTensor vregIndex; + RegTensor vregSoftplusResult; + RegTensor vregOne; + RegTensor vregInFp32; + RegTensor vreg1; + RegTensor vreg2; + RegTensor vreg3; + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + MicroAPI::Duplicate(vregOne, static_cast(1), preg0); + + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg0 = MicroAPI::UpdateMask(size); + ops::LoadOneTensorForDtypeT(inputAddr, vregInFp32, preg0, i * VL_FLOAT_SIZE); + MicroAPI::Exp(vreg1, vregInFp32, preg0); + MicroAPI::Adds(vreg2, vreg1, static_cast(1), preg0); + MicroAPI::Ln(vreg3, vreg2, preg0); + MicroAPI::Sqrt(vregSoftplusResult, vreg3, preg0); + MicroAPI::Arange(vregIndex, static_cast(i * VL_FLOAT_SIZE)); + MicroAPI::DataCopy(softplusOutAddr + i * VL_FLOAT_SIZE, vregSoftplusResult, preg0); + MicroAPI::DataCopy(addBiasOutAddr + i * VL_FLOAT_SIZE, vregSoftplusResult, preg0); + MicroAPI::DataCopy(indexOutAddr + i * VL_FLOAT_SIZE, vregIndex, preg0); + } + MicroAPI::LocalMemBar(); + PadWithMinFp32(addBiasOutAddr, groupCount_, perGroupExpertCount_, perGroupExpertCountAlign_); + } +} + +template +__aicore__ inline void +MoeGatingTopKRegbase::ComputeWithSoftplus(LocalTensor xInLocalTensor, LocalTensor xSigmoidTensor, + LocalTensor xBiasTensor, LocalTensor indexTensor) +{ + if (hasBias_) { + SoftplusWithBias(xInLocalTensor, xSigmoidTensor, xBiasTensor, indexTensor); + } else { + SoftplusWithoutBias(xInLocalTensor, xSigmoidTensor, xBiasTensor, indexTensor); + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::ComputeX() +{ + LocalTensor xSigmoidTensor = xSigmoidBuf_.Get(); + LocalTensor xBiasTensor = xBiasBuf_.Get(); + indexTensor = indexBuffer_.Get(); + + if (tilingData_->normType == 0) { + LocalTensor xInLocalTensor = xInQueue_.DeQue(); + ComputeWithSoftMax(xInLocalTensor, xSigmoidTensor, xBiasTensor, indexTensor); + xInQueue_.FreeTensor(xInLocalTensor); + } else if (tilingData_->normType == 1) { + LocalTensor xInLocalTensor = xInQueue_.DeQue(); + ComputeWithSigmoid(xInLocalTensor, xSigmoidTensor, xBiasTensor, indexTensor); + xInQueue_.FreeTensor(xInLocalTensor); + } else { + LocalTensor xInLocalTensor = xInQueue_.DeQue(); + ComputeWithSoftplus(xInLocalTensor, xSigmoidTensor, xBiasTensor, indexTensor); + xInQueue_.FreeTensor(xInLocalTensor); + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::CopyOutXNorm(int64_t progress) +{ + if (tilingData_->outFlag == 0) { + return; + } + LocalTensor outOutTensor = outOutQueue_.AllocTensor(); + LocalTensor xSigmoidTensor = xSigmoidBuf_.Get(); + DataCopy(outOutTensor, xSigmoidTensor, expertCountAlign_); + outOutQueue_.EnQue(outOutTensor); + outOutTensor = outOutQueue_.DeQue(); + DataCopyExtParams dataCopyParams{ + static_cast(groupCount_), static_cast(perGroupExpertCount_ * sizeof(float)), + static_cast((perGroupExpertCountAlign_ - perGroupExpertCount_) * sizeof(float) / BLOCK_BYTES), 0, 0}; + DataCopyPad(outGm_[progress * expertCount_], outOutTensor, dataCopyParams); + outOutQueue_.FreeTensor(outOutTensor); +} + +template +__aicore__ inline void MoeGatingTopKRegbase::SortInGroup() +{ + LocalTensor xBiasTensor = xBiasBuf_.Get(); + LocalTensor sortedInGroupTensor = sortedInGroupBuf_.Get(); // 组内排序的结果, 后续归并需要 + LocalTensor tmpLocal = finalSortBuffer_.Get(); + + if (perGroupExpertCountAlign_ == ONE_REPEAT_SORT_NUM) { + Sort32(sortedInGroupTensor, xBiasTensor, indexTensor, groupCount_); + } else { + for (uint16_t i = 0; i < groupCount_; i++) { + Sort(sortedInGroupTensor[i * perGroupExpertCountAlign_ * CONSTANT_TWO], + xBiasTensor[i * perGroupExpertCountAlign_], indexTensor[i * perGroupExpertCountAlign_], + tmpLocal, perGroupExpertCountAlign_ / ONE_REPEAT_SORT_NUM); + } + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::HashGatherWithSmallKAlignE(LocalTensor xSigmoidTensor, + LocalTensor expertIdxTensor, + LocalTensor yTensor, uint32_t k, + float eps, float routedScalingFactor) +{ + __local_mem__ float *inputAddr = (__local_mem__ float *)xSigmoidTensor.GetPhyAddr(); + __local_mem__ uint32_t *expertIdxAddr = (__local_mem__ uint32_t *)expertIdxTensor.GetPhyAddr(); + __local_mem__ T *outputAddr = (__local_mem__ T *)yTensor.GetPhyAddr(); + + if (tilingData_->normType == 0 && tilingData_->renorm == 0) { + __VEC_SCOPE__ + { + RegTensor vreg1; + RegTensor vreg2; + + MicroAPI::MaskReg preg0 = MicroAPI::UpdateMask(k); + MicroAPI::DataCopy(vreg1, expertIdxAddr); + MicroAPI::DataCopyGather(vreg2, inputAddr, vreg1, preg0); + MicroAPI::Muls(vreg2, vreg2, routedScalingFactor, preg0); + ops::StoreOneTensorForDtypeT(outputAddr, vreg2, preg0, 0); + } + } else { + __VEC_SCOPE__ + { + RegTensor vreg1; + RegTensor vreg2; + RegTensor vreg3; + RegTensor vreg4; + + MicroAPI::MaskReg preg0 = MicroAPI::UpdateMask(k); + MicroAPI::DataCopy(vreg1, expertIdxAddr); + MicroAPI::DataCopyGather(vreg2, inputAddr, vreg1, preg0); + MicroAPI::ReduceSum(vreg3, vreg2, preg0); + MicroAPI::Adds(vreg3, vreg3, eps, preg0); + MicroAPI::Duplicate(vreg4, vreg3, preg0); + MicroAPI::Div(vreg4, vreg2, vreg4, preg0); + MicroAPI::Muls(vreg4, vreg4, routedScalingFactor, preg0); + ops::StoreOneTensorForDtypeT(outputAddr, vreg4, preg0, 0); + } + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::HashGatherWithSmallKNotAlignE( + LocalTensor xSigmoidTensor, LocalTensor expertIdxTensor, LocalTensor yTensor, uint32_t k, + float eps, float routedScalingFactor, int32_t expertIdxPad, int32_t perGroupExpertCountAlign) +{ + __local_mem__ float *inputAddr = (__local_mem__ float *)xSigmoidTensor.GetPhyAddr(); + __local_mem__ uint32_t *expertIdxAddr = (__local_mem__ uint32_t *)expertIdxTensor.GetPhyAddr(); + __local_mem__ T *outputAddr = (__local_mem__ T *)yTensor.GetPhyAddr(); + + if (tilingData_->normType == 0 && tilingData_->renorm == 0) { + __VEC_SCOPE__ + { + RegTensor vreg1; + RegTensor vreg2; + RegTensor vregAlign; + + MicroAPI::MaskReg preg0 = MicroAPI::UpdateMask(k); + MicroAPI::Duplicate(vregAlign, perGroupExpertCountAlign, preg0); + + MicroAPI::DataCopy(vreg1, expertIdxAddr); + MicroAPI::DataCopyGather(vreg2, inputAddr, vreg1, preg0); + MicroAPI::Muls(vreg2, vreg2, routedScalingFactor, preg0); + + MicroAPI::Div(vregAlign, vreg1, vregAlign, preg0); + MicroAPI::Muls(vregAlign, vregAlign, expertIdxPad, preg0); + MicroAPI::Sub(vreg1, vreg1, vregAlign, preg0); + + ops::StoreOneTensorForDtypeT(outputAddr, vreg2, preg0, 0); + } + } else { + __VEC_SCOPE__ + { + RegTensor vreg1; + RegTensor vreg2; + RegTensor vreg3; + RegTensor vreg4; + RegTensor vregAlign; + + MicroAPI::MaskReg preg0 = MicroAPI::UpdateMask(k); + MicroAPI::Duplicate(vregAlign, perGroupExpertCountAlign, preg0); + + MicroAPI::DataCopy(vreg1, expertIdxAddr); + MicroAPI::DataCopyGather(vreg2, inputAddr, vreg1, preg0); + MicroAPI::ReduceSum(vreg3, vreg2, preg0); + MicroAPI::Adds(vreg3, vreg3, eps, preg0); + MicroAPI::Duplicate(vreg4, vreg3, preg0); + MicroAPI::Div(vreg4, vreg2, vreg4, preg0); + MicroAPI::Muls(vreg4, vreg4, routedScalingFactor, preg0); + + MicroAPI::Div(vregAlign, vreg1, vregAlign, preg0); + MicroAPI::Muls(vregAlign, vregAlign, expertIdxPad, preg0); + MicroAPI::Sub(vreg1, vreg1, vregAlign, preg0); + + ops::StoreOneTensorForDtypeT(outputAddr, vreg4, preg0, 0); + } + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::HashCompute(int64_t row) +{ + LocalTensor expertIdxTensor = expertIdxOutQueue_.AllocTensor(); + LocalTensor hashExpertId = sortedInGroupBuf_.Get(); + LocalTensor hashExpertIdInt32 = hashExpertId.template ReinterpretCast(); + + U1 key = inputIdsGm_.GetValue(row); + SetWaitFlag(HardEvent::MTE3_MTE2); + DataCopyExtParams dataCopyParams{1, static_cast(k_ * sizeof(U2)), 0, 0, 0}; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, static_cast(0)}; + DataCopyPad(hashExpertId, tid2eidGm_[key * k_], dataCopyParams, dataCopyPadParams); + SetWaitFlag(HardEvent::MTE2_V); + if constexpr (IsSameType::value) { + DataCopy(expertIdxTensor, hashExpertId, Align(k_, sizeof(int32_t))); + } else { + Cast(hashExpertIdInt32, hashExpertId, RoundMode::CAST_NONE, Align(k_, sizeof(U2))); + PipeBarrier(); + DataCopy(expertIdxTensor, hashExpertIdInt32, Align(k_, sizeof(int32_t))); + } + PipeBarrier(); + + LocalTensor xSigmoidTensor = xSigmoidBuf_.Get(); + LocalTensor yTensor = yOutQueue_.AllocTensor(); + int32_t expertIdxPad = perGroupExpertCountAlign_ - perGroupExpertCount_; + if (expertIdxPad != 0) { + HashGatherWithSmallKNotAlignE(xSigmoidTensor, expertIdxTensor, yTensor, k_, eps_, routedScalingFactor_, + expertIdxPad, perGroupExpertCountAlign_); + } else { + HashGatherWithSmallKAlignE(xSigmoidTensor, expertIdxTensor, yTensor, k_, eps_, routedScalingFactor_); + } + yOutQueue_.EnQue(yTensor); + expertIdxOutQueue_.EnQue(expertIdxTensor); +} + +template +__aicore__ inline void MoeGatingTopKRegbase::TopKCompute() +{ + LocalTensor xBiasTensor = xBiasBuf_.Get(); + LocalTensor sortedInGroupTensor = sortedInGroupBuf_.Get(); // 组内排序的结果, 后续归并需要 + LocalTensor tmpLocal = finalSortBuffer_.Get(); + + Sort(sortedInGroupTensor, xBiasTensor, indexTensor, tmpLocal, + perGroupExpertCountAlign_ * groupCount_ / ONE_REPEAT_SORT_NUM); + + LocalTensor xSigmoidTensor = xSigmoidBuf_.Get(); + LocalTensor yTensor = yOutQueue_.AllocTensor(); + LocalTensor expertIdxTensor = expertIdxOutQueue_.AllocTensor(); + + LocalTensor sortedInGroupTensorCast = sortedInGroupTensor.template ReinterpretCast(); + + int32_t expertIdxPad = perGroupExpertCountAlign_ - perGroupExpertCount_; + if (k_ <= VL_FLOAT_SIZE) { + if (expertIdxPad != 0) { + smallKNotAlignEVF(xSigmoidTensor, sortedInGroupTensorCast, expertIdxTensor, yTensor, k_, eps_, + routedScalingFactor_, expertIdxPad, perGroupExpertCountAlign_); + } else { + smallKAlignEVF(xSigmoidTensor, sortedInGroupTensorCast, expertIdxTensor, yTensor, k_, eps_, + routedScalingFactor_); + } + } else { + if (expertIdxPad != 0) { + largeKNotAlignEVF(xSigmoidTensor, sortedInGroupTensorCast, expertIdxTensor, yTensor, k_, eps_, + routedScalingFactor_, expertIdxPad, perGroupExpertCountAlign_); + } else { + largeKAlignEVF(xSigmoidTensor, sortedInGroupTensorCast, expertIdxTensor, yTensor, k_, eps_, + routedScalingFactor_); + } + } + + yOutQueue_.EnQue(yTensor); + expertIdxOutQueue_.EnQue(expertIdxTensor); +} + +template +__aicore__ inline void +MoeGatingTopKRegbase::SelectTopKInGroup(LocalTensor sortedInGroupTensor, + LocalTensor top2InGroupTensor, uint16_t groupCount0, + uint32_t perGroupExpertCountAlign0, uint32_t padNegInfNum) +{ + if (groupSelectMode_ == 1) { + __VEC_SCOPE__ + { + RegTensor vreg0; + RegTensor vreg1; + RegTensor vreg2; + RegTensor vregPad; + MicroAPI::UnalignReg u0; + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + __local_mem__ float *inputAddr = (__local_mem__ float *)sortedInGroupTensor.GetPhyAddr(); + __local_mem__ float *outputAddr = (__local_mem__ float *)top2InGroupTensor.GetPhyAddr(); + MicroAPI::Duplicate(vregPad, *((float *)&MIN_FP32)); + for (uint16_t i = 0; i < groupCount0; i++) { + MicroAPI::DataCopy( + vreg0, vreg1, inputAddr + i * perGroupExpertCountAlign0 * 2); + MicroAPI::PairReduceSum(vreg2, vreg0, preg0); + MicroAPI::DataCopyUnAlign(outputAddr, vreg2, u0, 1); + } + MicroAPI::DataCopyUnAlign(outputAddr, vregPad, u0, + padNegInfNum); + MicroAPI::DataCopyUnAlignPost(outputAddr, u0, 0); + } + } else { + __VEC_SCOPE__ + { + RegTensor vreg0; + RegTensor vreg1; + RegTensor vregPad; + MicroAPI::UnalignReg u0; + __local_mem__ float *inputAddr = (__local_mem__ float *)sortedInGroupTensor.GetPhyAddr(); + __local_mem__ float *outputAddr = (__local_mem__ float *)top2InGroupTensor.GetPhyAddr(); + MicroAPI::Duplicate(vregPad, *((float *)&MIN_FP32)); + for (uint16_t i = 0; i < groupCount0; i++) { + MicroAPI::DataCopy( + vreg0, vreg1, inputAddr + i * perGroupExpertCountAlign0 * 2); + MicroAPI::DataCopyUnAlign(outputAddr, vreg0, u0, 1); + } + MicroAPI::DataCopyUnAlign(outputAddr, vregPad, u0, + padNegInfNum); + MicroAPI::DataCopyUnAlignPost(outputAddr, u0, 0); + } + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::SelectTopKAfterSort(LocalTensor sortedGroupTensor, + LocalTensor top2InGroupTensor, + uint32_t size, int32_t kGroup0, + LocalTensor tmpLocal) +{ + int32_t kGroupNumAlign = (kGroup0 + 31) / 32 * 32; + uint32_t padkGroupNum = kGroupNumAlign - kGroup0; + __VEC_SCOPE__ + { + RegTensor vreg0; + RegTensor vreg1; + RegTensor vregPad; + MicroAPI::UnalignReg u0; + + __local_mem__ int32_t *inputAddr = (__local_mem__ int32_t *)sortedGroupTensor.GetPhyAddr(); + __local_mem__ int32_t *outputAddr = (__local_mem__ int32_t *)top2InGroupTensor.GetPhyAddr(); + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + uint16_t vfLoopNum = static_cast(CeilDiv(size, VL_FLOAT_SIZE)); + + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg0 = MicroAPI::UpdateMask(size); + MicroAPI::DataCopy(vreg0, vreg1, + inputAddr + i * 2 * VL_FLOAT_SIZE); + MicroAPI::DataCopy(outputAddr + i * VL_FLOAT_SIZE, vreg1, preg0); + } + AscendC::MicroAPI::LocalMemBar(); + MicroAPI::Duplicate(vregPad, *((float *)&MIN_FP32)); + outputAddr = outputAddr + kGroup0; + MicroAPI::DataCopyUnAlign(outputAddr, (RegTensor &)vregPad, u0, padkGroupNum); + MicroAPI::DataCopyUnAlignPost(outputAddr, u0, 0); + } + Sort(sortedGroupTensor, top2InGroupTensor, indexTensor, tmpLocal, + kGroupNumAlign / ONE_REPEAT_SORT_NUM); +} + +template +__aicore__ inline void MoeGatingTopKRegbase::FinalSortByKGroup() +{ + mrgSortTensor = finalSortBuffer_.Get(); + LocalTensor tmpLocal = sortedGroupTensor.template ReinterpretCast(); + uint32_t offset[MRG_SORT_ELEMENT_LEN] = {0, 0, 0, 0}; + + event_t eventIdVToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(eventIdVToS); + WaitFlag(eventIdVToS); + + uint16_t lenArr[CONSTANT_FOUR] = { + static_cast(perGroupExpertCount_), static_cast(perGroupExpertCount_), + static_cast(perGroupExpertCount_), static_cast(perGroupExpertCount_)}; + MrgSort4Info params{lenArr, false, 0b1111, 1}; + MrgSortSrcList srcList; + + for (int32_t i = kGroup_ - 1; i >= 0; i -= CONSTANT_FOUR) { +#if defined(__CCE_KT_TEST__) + int32_t mrgLen = std::min(i + 1, CONSTANT_FOUR); +#else + int32_t mrgLen = min(i + 1, CONSTANT_FOUR); +#endif + if (mrgLen > 1) { + offset[0] = tmpLocal.GetValue(i * 2) * perGroupExpertCountAlign_ * 2; + offset[1] = tmpLocal.GetValue((i - 1) * 2) * perGroupExpertCountAlign_ * 2; + if (mrgLen == CONSTANT_FOUR) { + offset[CONSTANT_TWO] = tmpLocal.GetValue((i - 2) * 2) * perGroupExpertCountAlign_ * 2; + offset[CONSTANT_THREE] = tmpLocal.GetValue((i - 3) * 2) * perGroupExpertCountAlign_ * 2; + } else if (mrgLen == CONSTANT_THREE) { + offset[CONSTANT_TWO] = tmpLocal.GetValue((i - 2) * 2) * perGroupExpertCountAlign_ * 2; + offset[CONSTANT_THREE] = 0; + params.elementLengths[CONSTANT_THREE] = 0; + params.validBit = 0b111; + } else { + offset[CONSTANT_TWO] = 0; + offset[CONSTANT_THREE] = 0; + params.elementLengths[CONSTANT_TWO] = 0; + params.elementLengths[CONSTANT_THREE] = 0; + params.validBit = 0b11; + } + srcList.src1 = sortedInGroupTensor[offset[0]]; + srcList.src2 = sortedInGroupTensor[offset[1]]; + srcList.src3 = sortedInGroupTensor[offset[CONSTANT_TWO]]; + srcList.src4 = sortedInGroupTensor[offset[CONSTANT_THREE]]; + MrgSort(mrgSortTensor[(kGroup_ - 1 - i) * perGroupExpertCountAlign_ * 2], srcList, params); + } else { + offset[0] = tmpLocal.GetValue(i * 2) * perGroupExpertCountAlign_ * 2; + DataCopy(mrgSortTensor[(kGroup_ - 1 - i) * perGroupExpertCountAlign_ * 2], sortedInGroupTensor[offset[0]], + perGroupExpertCountAlign_ * 2); + } + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::ProcessQuartetSort(LocalTensor srcTensor, + LocalTensor dstTensor, + int32_t sortedBaseRow, int32_t quotient) +{ + if (quotient <= 0) { + return; + } + + MrgSort4Info params; + MrgSortSrcList srcList; + params.ifExhaustedSuspension = false; + params.elementLengths[0] = perGroupExpertCount_ * sortedBaseRow; + params.elementLengths[1] = perGroupExpertCount_ * sortedBaseRow; + params.elementLengths[CONSTANT_TWO] = perGroupExpertCount_ * sortedBaseRow; + params.elementLengths[CONSTANT_THREE] = perGroupExpertCount_ * sortedBaseRow; + params.validBit = 0b1111; + params.repeatTimes = 1; + for (int j = 0; j < quotient; j++) { + srcList.src1 = srcTensor[perGroupExpertCountAlign_ * sortedBaseRow * 8 * j]; + srcList.src2 = srcTensor[perGroupExpertCountAlign_ * sortedBaseRow * (8 * j + 2)]; + srcList.src3 = srcTensor[perGroupExpertCountAlign_ * sortedBaseRow * (8 * j + 4)]; + srcList.src4 = srcTensor[perGroupExpertCountAlign_ * sortedBaseRow * (8 * j + 6)]; + MrgSort(dstTensor[perGroupExpertCountAlign_ * sortedBaseRow * 8 * j], srcList, params); + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::ProcessRemainderSort(LocalTensor srcTensor, + LocalTensor dstTensor, + int32_t sortedBaseRow, int32_t quotient, + int32_t remainder, int32_t nextBaseRow) +{ + if (remainder <= 0) { + return; + } + + int32_t baseOffset = quotient * nextBaseRow * perGroupExpertCountAlign_ * 2; + int32_t mrgLen = CeilDiv(remainder, sortedBaseRow); + int32_t tailRow = remainder - (mrgLen - 1) * sortedBaseRow; + if (mrgLen > 1) { + MrgSort4Info params; + MrgSortSrcList srcList; + params.repeatTimes = 1; + params.ifExhaustedSuspension = false; + params.elementLengths[0] = perGroupExpertCount_ * sortedBaseRow; + params.elementLengths[1] = perGroupExpertCount_ * sortedBaseRow; + params.elementLengths[CONSTANT_TWO] = perGroupExpertCount_ * sortedBaseRow; + params.elementLengths[CONSTANT_THREE] = perGroupExpertCount_ * sortedBaseRow; + srcList.src1 = srcTensor[baseOffset]; + srcList.src2 = srcTensor[baseOffset + perGroupExpertCountAlign_ * sortedBaseRow * 2]; + if (mrgLen == CONSTANT_FOUR) { + srcList.src3 = srcTensor[baseOffset + perGroupExpertCountAlign_ * sortedBaseRow * 2 * 2]; + srcList.src4 = srcTensor[baseOffset + perGroupExpertCountAlign_ * sortedBaseRow * 2 * 3]; + params.elementLengths[CONSTANT_THREE] = perGroupExpertCount_ * tailRow; + params.validBit = 0b1111; + } else if (mrgLen == CONSTANT_THREE) { + srcList.src3 = srcTensor[baseOffset + perGroupExpertCountAlign_ * sortedBaseRow * 2 * 2]; + params.elementLengths[CONSTANT_TWO] = perGroupExpertCount_ * tailRow; + params.elementLengths[CONSTANT_THREE] = 0; + params.validBit = 0b111; + } else { + params.elementLengths[1] = perGroupExpertCount_ * tailRow; + params.elementLengths[CONSTANT_TWO] = 0; + params.elementLengths[CONSTANT_THREE] = 0; + params.validBit = 0b11; + } + MrgSort(dstTensor[baseOffset], srcList, params); + } else { + DataCopy(dstTensor[baseOffset], srcTensor[baseOffset], tailRow * perGroupExpertCountAlign_ * 2); + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::FinalSortAfterKGroup() +{ + LocalTensor srcTensor; + LocalTensor dstTensor; + int32_t sortedBaseRow = CONSTANT_FOUR; + for (int32_t i = 0; i < tilingData_->vmsCount; i++) { + if (i % CONSTANT_TWO == 0) { + srcTensor = mrgSortTensor; + dstTensor = sortedInGroupTensor; + } else { + srcTensor = sortedInGroupTensor; + dstTensor = mrgSortTensor; + } + int32_t nextBaseRow = sortedBaseRow * CONSTANT_FOUR; + int32_t quotient = kGroup_ / nextBaseRow; + int32_t remainder = kGroup_ - quotient * nextBaseRow; + + ProcessQuartetSort(srcTensor, dstTensor, sortedBaseRow, quotient); + ProcessRemainderSort(srcTensor, dstTensor, sortedBaseRow, quotient, remainder, nextBaseRow); + sortedBaseRow = nextBaseRow; + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::SmallKCoreImpl( + LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, LocalTensor expertIdxTensor, + LocalTensor yTensor, uint32_t k, float eps, float routedScalingFactor, bool needNorm, bool needExpertIdxAdjust, + int32_t expertIdxPad, int32_t perGroupExpertCountAlign) +{ + __local_mem__ float *inputAddr = (__local_mem__ float *)xSigmoidTensor.GetPhyAddr(); + __local_mem__ T *outputAddr = (__local_mem__ T *)yTensor.GetPhyAddr(); + __local_mem__ uint32_t *mrgSortAddr = (__local_mem__ uint32_t *)mrgSortTensor.GetPhyAddr(); + __local_mem__ uint32_t *expertIdxAddr = (__local_mem__ uint32_t *)expertIdxTensor.GetPhyAddr(); + + __VEC_SCOPE__ + { + RegTensor vreg2; + RegTensor vreg3; + RegTensor vreg4; + RegTensor vregOutput; + RegTensor vreg0; + RegTensor vreg1; + RegTensor vregExpertIdxTmp; + + MicroAPI::MaskReg preg0 = MicroAPI::UpdateMask(k); + + MicroAPI::DataCopy(vreg0, vreg1, mrgSortAddr); + MicroAPI::DataCopyGather(vreg2, inputAddr, vreg1, preg0); + + if (needNorm) { + MicroAPI::ReduceSum(vreg3, vreg2, preg0); + MicroAPI::Adds(vreg3, vreg3, eps, preg0); + MicroAPI::Duplicate(vreg4, vreg3, preg0); + MicroAPI::Div(vreg4, vreg2, vreg4, preg0); + MicroAPI::Muls(vregOutput, vreg4, routedScalingFactor, preg0); + } else { + MicroAPI::Muls(vregOutput, vreg2, routedScalingFactor, preg0); + } + + if (needExpertIdxAdjust) { + RegTensor vregAlign; + MicroAPI::Duplicate(vregAlign, perGroupExpertCountAlign, preg0); + MicroAPI::Div(vregExpertIdxTmp, vreg1, vregAlign, preg0); + MicroAPI::Muls(vregExpertIdxTmp, vregExpertIdxTmp, expertIdxPad, preg0); + MicroAPI::Sub(vreg1, vreg1, vregExpertIdxTmp, preg0); + } + + ops::StoreOneTensorForDtypeT(outputAddr, vregOutput, preg0, 0); + MicroAPI::DataCopy(expertIdxAddr, vreg1, preg0); + } +} + +template +__aicore__ inline void +MoeGatingTopKRegbase::smallKAlignEVF(LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, + uint32_t k, float eps, float routedScalingFactor) +{ + bool needNorm = !(tilingData_->normType == 0 && tilingData_->renorm == 0); + SmallKCoreImpl(xSigmoidTensor, mrgSortTensor, expertIdxTensor, yTensor, k, eps, routedScalingFactor, needNorm, + false, 0, 0); +} + +template +__aicore__ inline void MoeGatingTopKRegbase::LargeKAlignEVFNoNorm(LocalTensor xSigmoidTensor, + LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, + LocalTensor yTensor, uint32_t k, + float routedScalingFactor) +{ + uint32_t k1 = k_; + __local_mem__ float *inputAddr = (__local_mem__ float *)xSigmoidTensor.GetPhyAddr(); + __local_mem__ uint32_t *mrgSortAddr = (__local_mem__ uint32_t *)mrgSortTensor.GetPhyAddr(); + __local_mem__ T *outputAddr = (__local_mem__ T *)yTensor.GetPhyAddr(); + __local_mem__ uint32_t *expertIdxAddr = (__local_mem__ uint32_t *)expertIdxTensor.GetPhyAddr(); + + __VEC_SCOPE__ + { + RegTensor vregSum; + RegTensor vreg0; + RegTensor vreg1; + RegTensor vreg2; + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + MicroAPI::MaskReg preg1 = MicroAPI::CreateMask(); + MicroAPI::Duplicate(vregSum, static_cast(0), preg0); + uint16_t vfLoopNum = static_cast(CeilDiv(k, VL_FLOAT_SIZE)); + + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg0 = MicroAPI::UpdateMask(k); + MicroAPI::DataCopy(vreg0, vreg1, + mrgSortAddr + i * 2 * VL_FLOAT_SIZE); + MicroAPI::Duplicate(vreg2, static_cast(0), preg1); + MicroAPI::DataCopyGather(vreg2, inputAddr, vreg1, preg0); + MicroAPI::Add(vregSum, vregSum, vreg2, preg1); + } + + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg1 = MicroAPI::UpdateMask(k1); + MicroAPI::DataCopy(vreg0, vreg1, + mrgSortAddr + i * 2 * VL_FLOAT_SIZE); + MicroAPI::DataCopyGather(vreg2, inputAddr, vreg1, preg1); + MicroAPI::Muls(vreg2, vreg2, routedScalingFactor, preg1); + ops::StoreOneTensorForDtypeT(outputAddr, vreg2, preg1, i * VL_FLOAT_SIZE); + MicroAPI::DataCopy(expertIdxAddr + i * VL_FLOAT_SIZE, vreg1, preg1); + } + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::LargeKCoreWithNormImpl( + LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, LocalTensor expertIdxTensor, + LocalTensor yTensor, uint32_t k, float eps, float routedScalingFactor, bool needExpertIdxAdjust, + int32_t expertIdxPad, int32_t perGroupExpertCountAlign) +{ + uint32_t k1 = k_; + __local_mem__ float *inputAddr = (__local_mem__ float *)xSigmoidTensor.GetPhyAddr(); + __local_mem__ uint32_t *mrgSortAddr = (__local_mem__ uint32_t *)mrgSortTensor.GetPhyAddr(); + __local_mem__ T *outputAddr = (__local_mem__ T *)yTensor.GetPhyAddr(); + __local_mem__ uint32_t *expertIdxAddr = (__local_mem__ uint32_t *)expertIdxTensor.GetPhyAddr(); + + __VEC_SCOPE__ + { + RegTensor vreg2; + RegTensor vreg3; + RegTensor vreg4; + RegTensor vregOutput; + RegTensor vregSum; + RegTensor vreg0; + RegTensor vreg1; + RegTensor vregAlign; + RegTensor vregExpertIdxTmp; + + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + MicroAPI::MaskReg preg1 = MicroAPI::CreateMask(); + MicroAPI::Duplicate(vregSum, static_cast(0), preg0); + if (needExpertIdxAdjust) { + MicroAPI::Duplicate(vregAlign, perGroupExpertCountAlign, preg0); + } + uint16_t vfLoopNum = static_cast(CeilDiv(k, VL_FLOAT_SIZE)); + + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg0 = MicroAPI::UpdateMask(k); + MicroAPI::DataCopy(vreg0, vreg1, + 2 * i * VL_FLOAT_SIZE + mrgSortAddr); + MicroAPI::Duplicate(vreg2, static_cast(0), preg1); + MicroAPI::DataCopyGather(vreg2, inputAddr, vreg1, preg0); + MicroAPI::Add(vregSum, vregSum, vreg2, preg1); + } + MicroAPI::ReduceSum(vregSum, vregSum, preg1); + MicroAPI::Adds(vregSum, vregSum, eps, preg1); + MicroAPI::Duplicate(vreg4, vregSum, preg1); + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg1 = MicroAPI::UpdateMask(k1); + MicroAPI::DataCopy(vreg0, vreg1, + mrgSortAddr + i * 2 * VL_FLOAT_SIZE); + MicroAPI::DataCopyGather(vreg2, inputAddr, vreg1, preg1); + MicroAPI::Div(vregOutput, vreg2, vreg4, preg1); + MicroAPI::Muls(vregOutput, vregOutput, routedScalingFactor, preg1); + + if (needExpertIdxAdjust) { + MicroAPI::Div(vregExpertIdxTmp, vreg1, vregAlign, preg1); + MicroAPI::Muls(vregExpertIdxTmp, vregExpertIdxTmp, expertIdxPad, preg1); + MicroAPI::Sub(vreg1, vreg1, vregExpertIdxTmp, preg1); + } + ops::StoreOneTensorForDtypeT(outputAddr, vregOutput, preg1, i * VL_FLOAT_SIZE); + MicroAPI::DataCopy(expertIdxAddr + i * VL_FLOAT_SIZE, vreg1, preg1); + } + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::LargeKAlignEVFWithNorm(LocalTensor xSigmoidTensor, + LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, + LocalTensor yTensor, uint32_t k, + float eps, float routedScalingFactor) +{ + LargeKCoreWithNormImpl(xSigmoidTensor, mrgSortTensor, expertIdxTensor, yTensor, k, eps, routedScalingFactor, false, + 0, 0); +} + +template +__aicore__ inline void +MoeGatingTopKRegbase::largeKAlignEVF(LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, + LocalTensor expertIdxTensor, LocalTensor yTensor, + uint32_t k, float eps, float routedScalingFactor) +{ + if (tilingData_->normType == 0 && tilingData_->renorm == 0) { + LargeKAlignEVFNoNorm(xSigmoidTensor, mrgSortTensor, expertIdxTensor, yTensor, k, routedScalingFactor); + } else { + LargeKAlignEVFWithNorm(xSigmoidTensor, mrgSortTensor, expertIdxTensor, yTensor, k, eps, routedScalingFactor); + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::smallKNotAlignEVF( + LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, LocalTensor expertIdxTensor, + LocalTensor yTensor, uint32_t k, float eps, float routedScalingFactor, int32_t expertIdxPad, + int32_t perGroupExpertCountAlign) +{ + bool needNorm = !(tilingData_->normType == 0 && tilingData_->renorm == 0); + SmallKCoreImpl(xSigmoidTensor, mrgSortTensor, expertIdxTensor, yTensor, k, eps, routedScalingFactor, needNorm, true, + expertIdxPad, perGroupExpertCountAlign); +} + +template +__aicore__ inline void MoeGatingTopKRegbase::LargeKNotAlignEVFNoNorm( + LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, LocalTensor expertIdxTensor, + LocalTensor yTensor, uint32_t k, float routedScalingFactor, int32_t expertIdxPad, + int32_t perGroupExpertCountAlign) +{ + uint32_t k1 = k_; + __local_mem__ T *outputAddr = (__local_mem__ T *)yTensor.GetPhyAddr(); + __local_mem__ float *inputAddr = (__local_mem__ float *)xSigmoidTensor.GetPhyAddr(); + __local_mem__ uint32_t *mrgSortAddr = (__local_mem__ uint32_t *)mrgSortTensor.GetPhyAddr(); + __local_mem__ uint32_t *expertIdxAddr = (__local_mem__ uint32_t *)expertIdxTensor.GetPhyAddr(); + + __VEC_SCOPE__ + { + RegTensor vreg0; + RegTensor vreg1; + RegTensor vreg2; + RegTensor vreg3; + RegTensor vregSum; + RegTensor vregAlign; + + MicroAPI::MaskReg preg0 = MicroAPI::CreateMask(); + MicroAPI::MaskReg preg1 = MicroAPI::CreateMask(); + MicroAPI::Duplicate(vregSum, static_cast(0), preg0); + MicroAPI::Duplicate(vregAlign, perGroupExpertCountAlign, preg0); + uint16_t vfLoopNum = static_cast(CeilDiv(k, VL_FLOAT_SIZE)); + + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg0 = MicroAPI::UpdateMask(k); + MicroAPI::DataCopy(vreg0, vreg1, + mrgSortAddr + 2 * i * VL_FLOAT_SIZE); + MicroAPI::Duplicate(vreg2, static_cast(0), preg1); + MicroAPI::DataCopyGather(vreg2, inputAddr, vreg1, preg0); + MicroAPI::Add(vregSum, vregSum, vreg2, preg1); + } + + for (uint16_t i = 0; i < vfLoopNum; i++) { + preg1 = MicroAPI::UpdateMask(k1); + MicroAPI::DataCopy(vreg0, vreg1, + mrgSortAddr + VL_FLOAT_SIZE * i * 2); + MicroAPI::DataCopyGather(vreg2, inputAddr, vreg1, preg1); + MicroAPI::Muls(vreg2, vreg2, routedScalingFactor, preg1); + + // compute expertIdx: id = id - floor_div(id, perGroupExpertCountAlign) * pad + MicroAPI::Div(vreg3, vreg1, vregAlign, preg1); + MicroAPI::Muls(vreg3, vreg3, expertIdxPad, preg1); + MicroAPI::Sub(vreg1, vreg1, vreg3, preg1); + ops::StoreOneTensorForDtypeT(outputAddr, vreg2, preg1, i * VL_FLOAT_SIZE); + MicroAPI::DataCopy(expertIdxAddr + i * VL_FLOAT_SIZE, vreg1, preg1); + } + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::LargeKNotAlignEVFWithNorm( + LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, LocalTensor expertIdxTensor, + LocalTensor yTensor, uint32_t k, float eps, float routedScalingFactor, int32_t expertIdxPad, + int32_t perGroupExpertCountAlign) +{ + LargeKCoreWithNormImpl(xSigmoidTensor, mrgSortTensor, expertIdxTensor, yTensor, k, eps, routedScalingFactor, true, + expertIdxPad, perGroupExpertCountAlign); +} + +template +__aicore__ inline void MoeGatingTopKRegbase::largeKNotAlignEVF( + LocalTensor xSigmoidTensor, LocalTensor mrgSortTensor, LocalTensor expertIdxTensor, + LocalTensor yTensor, uint32_t k, float eps, float routedScalingFactor, int32_t expertIdxPad, + int32_t perGroupExpertCountAlign) +{ + if (tilingData_->normType == 0 && tilingData_->renorm == 0) { + LargeKNotAlignEVFNoNorm(xSigmoidTensor, mrgSortTensor, expertIdxTensor, yTensor, k, routedScalingFactor, + expertIdxPad, perGroupExpertCountAlign); + } else { + LargeKNotAlignEVFWithNorm(xSigmoidTensor, mrgSortTensor, expertIdxTensor, yTensor, k, eps, routedScalingFactor, + expertIdxPad, perGroupExpertCountAlign); + } +} + +template +__aicore__ inline void MoeGatingTopKRegbase::SelectTopKExpertScore() +{ + LocalTensor expertIdxTensor = expertIdxOutQueue_.AllocTensor(); + LocalTensor mrgSortTensor = finalSortBuffer_.Get(); + + if (tilingData_->vmsCount % CONSTANT_TWO == 1) { + mrgSortTensor = sortedInGroupTensor.ReinterpretCast(); + } + + LocalTensor xSigmoidTensor = xSigmoidBuf_.Get(); + LocalTensor yTensor = yOutQueue_.AllocTensor(); + + int32_t expertIdxPad = perGroupExpertCountAlign_ - perGroupExpertCount_; + if (k_ <= VL_FLOAT_SIZE) { + if (expertIdxPad != 0) { + smallKNotAlignEVF(xSigmoidTensor, mrgSortTensor, expertIdxTensor, yTensor, k_, eps_, routedScalingFactor_, + expertIdxPad, perGroupExpertCountAlign_); + } else { + smallKAlignEVF(xSigmoidTensor, mrgSortTensor, expertIdxTensor, yTensor, k_, eps_, routedScalingFactor_); + } + } else { + if (expertIdxPad != 0) { + largeKNotAlignEVF(xSigmoidTensor, mrgSortTensor, expertIdxTensor, yTensor, k_, eps_, routedScalingFactor_, + expertIdxPad, perGroupExpertCountAlign_); + } else { + largeKAlignEVF(xSigmoidTensor, mrgSortTensor, expertIdxTensor, yTensor, k_, eps_, routedScalingFactor_); + } + } + + yOutQueue_.EnQue(yTensor); + expertIdxOutQueue_.EnQue(expertIdxTensor); +} + +template +__aicore__ inline void MoeGatingTopKRegbase::CopyOut(int64_t row) +{ + LocalTensor yOutTensor = yOutQueue_.DeQue(); + LocalTensor expertIdxTensor = expertIdxOutQueue_.DeQue(); + DataCopyExtParams dataCopyParams{1, static_cast(k_ * sizeof(T)), 0, 0, 0}; + DataCopyPad(yGm_[row * k_], yOutTensor, dataCopyParams); + + dataCopyParams.blockLen = k_ * sizeof(int32_t); + DataCopyPad(expertIdxGm_[row * k_], expertIdxTensor, dataCopyParams); + + expertIdxOutQueue_.FreeTensor(expertIdxTensor); + yOutQueue_.FreeTensor(yOutTensor); +} + +template +__aicore__ inline void MoeGatingTopKRegbase::SelectTopKGroupIndex() +{ + sortedInGroupTensor = sortedInGroupBuf_.Get(); + LocalTensor top2InGroupTensor = groupBuf_.Get(); + LocalTensor tmpLocal = xBiasBuf_.Get(); + sortedGroupTensor = sortedGroupBuf_.Get(); + + uint16_t groupCount0 = groupCount_; + uint32_t perGroupExpertCountAlign0 = perGroupExpertCountAlign_; + int32_t groupCountNumAlign = (groupCount_ + 31) / 32 * 32; + uint32_t padNegInfNum = groupCountNumAlign - groupCount_; + + SelectTopKInGroup(sortedInGroupTensor, top2InGroupTensor, groupCount0, perGroupExpertCountAlign0, padNegInfNum); + + Sort(sortedGroupTensor, top2InGroupTensor, indexTensor, tmpLocal, + groupCountNumAlign / ONE_REPEAT_SORT_NUM); + + uint32_t size = groupCountNumAlign; + int32_t kGroup0 = kGroup_; + SelectTopKAfterSort(sortedGroupTensor, top2InGroupTensor, size, kGroup0, tmpLocal); +} + +template +__aicore__ inline void +MoeGatingTopKRegbase::Init(GM_ADDR x, GM_ADDR bias, GM_ADDR inputIds, GM_ADDR tid2eid, GM_ADDR y, + GM_ADDR expertIdx, GM_ADDR out, GM_ADDR workspace, + const MoeGatingTopKRegbaseTilingData *tilingData, TPipe *tPipe) +{ + tilingData_ = tilingData; + pipe_ = tPipe; + blockIdx_ = GetBlockIdx(); + if (blockIdx_ == GetBlockNum() - 1) { + curCoreRowCount_ = tilingData_->lastCoreRowCount; + } else { + curCoreRowCount_ = tilingData_->perCoreRowCount; + } + expertCount_ = tilingData_->expertCount; + k_ = tilingData_->k; + kGroup_ = tilingData_->kGroup; + groupCount_ = tilingData_->groupCount; + perGroupExpertCount_ = tilingData_->perGroupExpertCount; + perGroupExpertCountAlign_ = tilingData_->perGroupExpertCountAlign; + expertCountAlign_ = Align(perGroupExpertCountAlign_ * groupCount_, sizeof(float)); + routedScalingFactor_ = tilingData_->routedScalingFactor; + groupSelectMode_ = tilingData_->groupSelectMode; + eps_ = tilingData_->eps; + hashFlag_ = tilingData_->hashFlag == 1; + + xGm_.SetGlobalBuffer((__gm__ T *)x + tilingData_->perCoreRowCount * expertCount_ * blockIdx_, expertCount_); + if (bias != nullptr) { + hasBias_ = true; + biasGm_.SetGlobalBuffer((__gm__ T *)bias, expertCount_); + } + yGm_.SetGlobalBuffer((__gm__ T *)y + tilingData_->perCoreRowCount * k_ * blockIdx_, k_); + expertIdxGm_.SetGlobalBuffer((__gm__ int32_t *)expertIdx + tilingData_->perCoreRowCount * k_ * blockIdx_, k_); + outGm_.SetGlobalBuffer((__gm__ float *)out + tilingData_->perCoreRowCount * expertCount_ * blockIdx_, expertCount_); + + if (hashFlag_) { + inputIdsGm_.SetGlobalBuffer((__gm__ U1 *)inputIds); + tid2eidGm_.SetGlobalBuffer((__gm__ U2 *)tid2eid); + } + + int32_t expertGroupAlign = groupCount_ * perGroupExpertCountAlign_; + int32_t groupAlign = static_cast(CeilAlign(groupCount_, ONE_REPEAT_SORT_NUM)); + pipe_->InitBuffer(xInQueue_, CONSTANT_TWO, expertGroupAlign * sizeof(float) * (sizeof(float) / sizeof(T))); + pipe_->InitBuffer(yOutQueue_, CONSTANT_TWO, AlignBytes(k_, sizeof(T))); + pipe_->InitBuffer(expertIdxOutQueue_, CONSTANT_TWO, AlignBytes(k_, sizeof(int32_t))); + pipe_->InitBuffer(outOutQueue_, CONSTANT_TWO, expertGroupAlign * sizeof(float)); + + pipe_->InitBuffer(biasBuf_, expertGroupAlign * sizeof(T)); + pipe_->InitBuffer(xSigmoidBuf_, expertGroupAlign * sizeof(float)); + pipe_->InitBuffer(xBiasBuf_, expertGroupAlign * sizeof(float)); + pipe_->InitBuffer(indexBuffer_, expertGroupAlign * sizeof(int32_t)); + pipe_->InitBuffer(sortedInGroupBuf_, expertGroupAlign * sizeof(float) * 2); + pipe_->InitBuffer(finalSortBuffer_, expertGroupAlign * sizeof(float) * 2); + pipe_->InitBuffer(groupBuf_, groupAlign * sizeof(float)); + pipe_->InitBuffer(sortedGroupBuf_, groupAlign * sizeof(float) * 2); +} + +template +__aicore__ inline void MoeGatingTopKRegbase::Process() +{ + CopyInBias(); + if (kGroup_ == groupCount_ || groupCount_ == expertCount_) { + CopyInX(0); + for (int64_t row = 1; row < curCoreRowCount_; row++) { + ComputeX(); + CopyOutXNorm(row - 1); + CopyInX(row); + if (hashFlag_) { + HashCompute(row - 1 + tilingData_->perCoreRowCount * blockIdx_); + } else { + TopKCompute(); + } + CopyOut(row - 1); + } + ComputeX(); + CopyOutXNorm(curCoreRowCount_ - 1); + if (hashFlag_) { + HashCompute(curCoreRowCount_ - 1 + tilingData_->perCoreRowCount * blockIdx_); + } else { + TopKCompute(); + } + CopyOut(curCoreRowCount_ - 1); + return; + } + + CopyInX(0); + for (int64_t row = 1; row < curCoreRowCount_; row++) { + ComputeX(); + CopyOutXNorm(row - 1); + SortInGroup(); + SelectTopKGroupIndex(); + CopyInX(row); + FinalSortByKGroup(); + FinalSortAfterKGroup(); + SelectTopKExpertScore(); + CopyOut(row - 1); + } + ComputeX(); + CopyOutXNorm(curCoreRowCount_ - 1); + SortInGroup(); + SelectTopKGroupIndex(); + FinalSortByKGroup(); + FinalSortAfterKGroup(); + SelectTopKExpertScore(); + CopyOut(curCoreRowCount_ - 1); +} +} // namespace MoeGatingTopK +#endif // MOE_GATING_TOP_K_REGBASE_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/common.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/common.h new file mode 100644 index 0000000000000000000000000000000000000000..ce26bfa08813aaf6e4a52b8542a5f3649aa653d0 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/common.h @@ -0,0 +1,97 @@ +/** + * 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 common.h + * \brief + */ +#ifndef MOE_GATING_TOP_K_COMMON_H +#define MOE_GATING_TOP_K_COMMON_H + +#include "kernel_operator.h" + +namespace MoeGatingTopK { +using namespace AscendC; +const float MIN_FP32 = *(float *)(&F32_NEG_INF); +constexpr int32_t FLOAT32_NEG_INF = 0xFF800000; // -inf -2139095040 +constexpr int64_t ONE_REPEAT_SORT_NUM = 32; +constexpr int64_t BLOCK_BYTES = 32; +constexpr int64_t REPEAT_BYTES = 256; +constexpr int64_t REPEAT_BLOCKS = 8; + +constexpr int32_t CONSTANT_TWO = 2; +constexpr int32_t CONSTANT_THREE = 3; +constexpr int32_t CONSTANT_FOUR = 4; +constexpr int32_t CONSTANT_EIGHT = 8; + +constexpr int64_t MERGE_LIST_TWO = 2; +constexpr int64_t MERGE_LIST_THREE = 3; +constexpr int64_t MERGE_LIST_FOUR = 4; + +constexpr int64_t MERGE_LIST_IDX_TWO = 2; +constexpr int64_t MERGE_LIST_IDX_THREE = 3; + +constexpr int64_t NORM_TYPE_SOFTMAX = 0; +constexpr int64_t NORM_TYPE_SIGMOID = 1; + +__aicore__ inline int64_t Ceil(int64_t a, int64_t b) +{ + if (b == 0) { + return 0; + } + return (a + b - 1) / b; +} + +__aicore__ inline int64_t Align(int64_t elementNum, int64_t bytes) +{ + if (bytes == 0) { + return 0; + } + return (elementNum * bytes + BLOCK_BYTES - 1) / BLOCK_BYTES * BLOCK_BYTES / bytes; +} + +__aicore__ inline int64_t AlignBytes(int64_t elementNum, int64_t bytes) +{ + return (elementNum * bytes + BLOCK_BYTES - 1) / BLOCK_BYTES * BLOCK_BYTES; +} + +template +__aicore__ inline T Min(T a, T b) +{ + return a > b ? b : a; +} + +template +__aicore__ inline T Max(T a, T b) +{ + return a < b ? b : a; +} + +template +__aicore__ inline T1 CeilDiv(T1 x, T2 y) +{ + if (y != 0 && x != 0) { + const T1 quotient = x / y; + return (x % y != 0 && ((x ^ y) >= 0)) ? (quotient + 1) : quotient; + } + + return x; +} + +template +__aicore__ inline void SetWaitFlag(HardEvent evt) +{ + event_t eventId = static_cast(GetTPipePtr()->FetchEventID(evt)); + SetFlag(eventId); + WaitFlag(eventId); +} + +} // namespace MoeGatingTopK +#endif // MOE_GATING_TOP_K_COMMON_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2261d8ff497c4e3ceee05475ef7b39a1c8297390 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k.cpp @@ -0,0 +1,79 @@ +/** + * 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 moe_gating_top_k.cpp + * \brief + */ + +#include "moe_gating_top_k_e_k_fullload.h" +#include "moe_gating_top_k_without_group.h" +#include "moe_gating_top_k_generalized.h" + +#define TILING_KEY_PER_GROUP_COUNT_32 0 +#define TILING_KEY_WITHOUT_GROUP 1 +#define TILING_KEY_GENERALIZED 2 +#define TILING_KEY_HASH_WITHOUT_GROUP_INT32_INT64 3 +#define TILING_KEY_HASH_WITHOUT_GROUP_INT32_INT32 4 +#define TILING_KEY_HASH_WITHOUT_GROUP_INT64_INT64 5 +#define TILING_KEY_HASH_WITHOUT_GROUP_INT64_INT32 6 + +using namespace AscendC; +using namespace MoeGatingTopK; +extern "C" __global__ __aicore__ void moe_gating_top_k(GM_ADDR x, GM_ADDR bias, GM_ADDR inputIds, GM_ADDR tid2eid, + GM_ADDR y, GM_ADDR expertIdx, GM_ADDR out, GM_ADDR workspace, + GM_ADDR tiling) +{ + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_AIV_ONLY); + if (g_coreType == AIC) { + return; + } + GET_TILING_DATA_WITH_STRUCT(MoeGatingTopKTilingData, tilingData, tiling); + if (workspace == nullptr) { + return; + } + + GM_ADDR userWS = GetUserWorkspace(workspace); + if (userWS == nullptr) { + return; + } + + const MoeGatingTopKTilingData *__restrict t = &tilingData; + TPipe tPipe; + if (TILING_KEY_IS(TILING_KEY_PER_GROUP_COUNT_32)) { + MoeGatingTopKEKFullload op; + op.Init(x, bias, y, expertIdx, out, userWS, t, &tPipe); + op.Process(); + } else if (TILING_KEY_IS(TILING_KEY_WITHOUT_GROUP)) { + MoeGatingTopKWithoutGroup op; + op.Init(x, bias, inputIds, tid2eid, y, expertIdx, out, userWS, t, &tPipe); + op.Process(); + } else if (TILING_KEY_IS(TILING_KEY_GENERALIZED)) { + MoeGatingTopKGenerlized op; + op.Init(x, bias, y, expertIdx, out, userWS, t, &tPipe); + op.Process(); + } else if (TILING_KEY_IS(TILING_KEY_HASH_WITHOUT_GROUP_INT32_INT64)) { + MoeGatingTopKWithoutGroup op; + op.Init(x, bias, inputIds, tid2eid, y, expertIdx, out, userWS, t, &tPipe); + op.Process(); + } else if (TILING_KEY_IS(TILING_KEY_HASH_WITHOUT_GROUP_INT32_INT32)) { + MoeGatingTopKWithoutGroup op; + op.Init(x, bias, inputIds, tid2eid, y, expertIdx, out, userWS, t, &tPipe); + op.Process(); + } else if (TILING_KEY_IS(TILING_KEY_HASH_WITHOUT_GROUP_INT64_INT64)) { + MoeGatingTopKWithoutGroup op; + op.Init(x, bias, inputIds, tid2eid, y, expertIdx, out, userWS, t, &tPipe); + op.Process(); + } else if (TILING_KEY_IS(TILING_KEY_HASH_WITHOUT_GROUP_INT64_INT32)) { + MoeGatingTopKWithoutGroup op; + op.Init(x, bias, inputIds, tid2eid, y, expertIdx, out, userWS, t, &tPipe); + op.Process(); + } +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k_apt.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k_apt.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d359421b050ca74bf3df678e58e6dd4292b38f9e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k_apt.cpp @@ -0,0 +1,64 @@ +/** + * 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 moe_gating_top_k_apt.cpp + * \brief + */ + +#include "arch35/moe_gating_top_k_regbase.h" +using namespace AscendC; +using namespace MoeGatingTopK; + +#define TILING_KEY_REGBASE 10000 +#define TILING_KEY_HASH_INT32_INT64 10001 +#define TILING_KEY_HASH_INT32_INT32 10002 +#define TILING_KEY_HASH_INT64_INT64 10003 +#define TILING_KEY_HASH_INT64_INT32 10004 + +extern "C" __global__ __aicore__ void moe_gating_top_k(GM_ADDR x, GM_ADDR bias, GM_ADDR inputIds, GM_ADDR tid2eid, + GM_ADDR y, GM_ADDR expertIdx, GM_ADDR out, GM_ADDR workspace, + GM_ADDR tiling) +{ + if (g_coreType == AIC) { + return; + } + + if (workspace == nullptr) { + return; + } + + GM_ADDR userWS = GetUserWorkspace(workspace); + if (userWS == nullptr) { + return; + } + + GET_TILING_DATA_WITH_STRUCT(MoeGatingTopKRegbaseTilingData, tiling_data_in, tiling); + const MoeGatingTopKRegbaseTilingData *__restrict tilingData = &tiling_data_in; + TPipe tPipe; + + if (TILING_KEY_IS(TILING_KEY_REGBASE) || TILING_KEY_IS(TILING_KEY_HASH_INT32_INT32)) { + MoeGatingTopKRegbase op; + op.Init(x, bias, inputIds, tid2eid, y, expertIdx, out, userWS, tilingData, &tPipe); + op.Process(); + } else if (TILING_KEY_IS(TILING_KEY_HASH_INT32_INT64)) { + MoeGatingTopKRegbase op; + op.Init(x, bias, inputIds, tid2eid, y, expertIdx, out, userWS, tilingData, &tPipe); + op.Process(); + } else if (TILING_KEY_IS(TILING_KEY_HASH_INT64_INT64)) { + MoeGatingTopKRegbase op; + op.Init(x, bias, inputIds, tid2eid, y, expertIdx, out, userWS, tilingData, &tPipe); + op.Process(); + } else if (TILING_KEY_IS(TILING_KEY_HASH_INT64_INT32)) { + MoeGatingTopKRegbase op; + op.Init(x, bias, inputIds, tid2eid, y, expertIdx, out, userWS, tilingData, &tPipe); + op.Process(); + } +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k_e_k_fullload.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k_e_k_fullload.h new file mode 100644 index 0000000000000000000000000000000000000000..c9e61d4e82b7df13238a75d4a05dc25820988d7b --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k_e_k_fullload.h @@ -0,0 +1,404 @@ +/** + * 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 moe_gating_top_k_e_k_fullload.h + * \brief + */ +#ifndef MOE_GATING_TOP_K_E_K_FULLLOAD_H +#define MOE_GATING_TOP_K_E_K_FULLLOAD_H +#include "kernel_operator.h" +#include "common.h" +namespace MoeGatingTopK { +using namespace AscendC; + +template +class MoeGatingTopKEKFullload { +public: + __aicore__ inline MoeGatingTopKEKFullload(){}; + __aicore__ inline void Init(GM_ADDR x, GM_ADDR bias, GM_ADDR y, GM_ADDR expertIdx, GM_ADDR out, GM_ADDR workspace, + const MoeGatingTopKTilingData *tilingData, TPipe *tPipe); + __aicore__ inline void Process(); + +private: + __aicore__ inline void CopyInBias(); + __aicore__ inline void CopyInX(int64_t progress); + __aicore__ inline void ComputeX(); + __aicore__ inline void SortInGroup(); + __aicore__ inline void SelectTopKGroupIndex(); + __aicore__ inline void SelectTopKExpertIdx(); + __aicore__ inline void SelectTopKExpertScore(); + __aicore__ inline void CopyOut(int64_t progress); + +private: + TPipe *pipe_; + TQue xInQueue_; + TBuf biasInQueue_; + TQue yOutQueue_; + TQue expertIdxOutQueue_; + TQue outOutQueue_; + + TQue xBiasQueue_; + TQue xSigmoidQueue_; + TQue sigmoidTmpQueue_; + TQue sortedInGroupQueue_; + TQue sortedGroupQueue_; + TBuf calcTmpBuffer_; + + GlobalTensor xGm_; + GlobalTensor biasGm_; + GlobalTensor yGm_; + GlobalTensor expertIdxGm_; + GlobalTensor outGm_; + + int64_t blockIdx_; + int64_t perCoreRowCount_; + int64_t curCoreRowCount_; + int64_t expertCount_; + bool addBias_; + int64_t k_; + int64_t kGroup_; + int64_t groupCount_; + int64_t groupSelectMode_; + int64_t renorm_; + int64_t normType_; + int64_t outFlag_; + float routedScalingFactor_; + float eps_; + + int64_t expertCountAlign_; + int64_t kAlign_; + int64_t perGroupExpertCount_; + + const MoeGatingTopKTilingData *tilingData_; +}; + +template +__aicore__ inline void MoeGatingTopKEKFullload::CopyInBias() +{ + LocalTensor biasTensor = biasInQueue_.Get(); + DataCopyExtParams dataCopyParams{1, static_cast(expertCount_ * sizeof(T)), 0, 0, 0}; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, static_cast(0)}; + if constexpr (IsSameType::value) { + DataCopyPad(biasTensor, biasGm_, dataCopyParams, dataCopyPadParams); + event_t eventIdMte2ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventIdMte2ToV); + WaitFlag(eventIdMte2ToV); + } else { + DataCopyPad(biasTensor[expertCountAlign_].ReinterpretCast(), biasGm_, dataCopyParams, dataCopyPadParams); + event_t eventIdMte2ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventIdMte2ToV); + WaitFlag(eventIdMte2ToV); + Cast(biasTensor, biasTensor[expertCountAlign_].ReinterpretCast(), RoundMode::CAST_NONE, expertCount_); + } +} + +template +__aicore__ inline void MoeGatingTopKEKFullload::CopyInX(int64_t row) +{ + LocalTensor xInLocalTensor = xInQueue_.AllocTensor(); + DataCopyExtParams dataCopyParams{1, static_cast(expertCount_ * sizeof(T)), 0, 0, 0}; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, static_cast(0)}; + if constexpr (IsSameType::value) { + DataCopyPad(xInLocalTensor, xGm_[row * expertCount_], dataCopyParams, dataCopyPadParams); + } else { + DataCopyPad(xInLocalTensor[expertCountAlign_].ReinterpretCast(), xGm_[row * expertCount_], dataCopyParams, + dataCopyPadParams); + event_t eventIdMte2ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventIdMte2ToV); + WaitFlag(eventIdMte2ToV); + Cast(xInLocalTensor, xInLocalTensor[expertCountAlign_].ReinterpretCast(), RoundMode::CAST_NONE, + expertCount_); + } + + xInQueue_.EnQue(xInLocalTensor); +} + +template +__aicore__ inline void MoeGatingTopKEKFullload::ComputeX() +{ + LocalTensor xSigmoidTensor = xSigmoidQueue_.AllocTensor(); + LocalTensor xInLocalTensor = xInQueue_.DeQue(); + LocalTensor xBiasTensor = xBiasQueue_.AllocTensor(); + LocalTensor biasTensor = biasInQueue_.Get(); + LocalTensor sharedTmpBuffer = sigmoidTmpQueue_.AllocTensor(); // 临时空间可以复用 + Sigmoid(xSigmoidTensor, xInLocalTensor, sharedTmpBuffer, expertCount_); + PipeBarrier(); + if (addBias_) { + Add(xBiasTensor, xSigmoidTensor, biasTensor, expertCount_); + } else { + Adds(xBiasTensor, xSigmoidTensor, static_cast(0), expertCount_); + } + + xSigmoidQueue_.EnQue(xSigmoidTensor); + xBiasQueue_.EnQue(xBiasTensor); + xInQueue_.FreeTensor(xInLocalTensor); + sigmoidTmpQueue_.FreeTensor(sharedTmpBuffer); +} + +template +__aicore__ inline void MoeGatingTopKEKFullload::SortInGroup() +{ + LocalTensor xBiasTensor = xBiasQueue_.DeQue(); + LocalTensor sortedInGroupTensor = sortedInGroupQueue_.AllocTensor(); // 组内排序的结果, 后续归并需要 + LocalTensor indexTensor = calcTmpBuffer_.Get(); // 用于存储排序时的索引 + ArithProgression(indexTensor.ReinterpretCast(), 0, 1, expertCount_); // 生成组索引0 1 2 ...... + PipeBarrier(); + Sort32(sortedInGroupTensor, xBiasTensor, indexTensor, expertCount_ / ONE_REPEAT_SORT_NUM); // 组内排序 + sortedInGroupQueue_.EnQue(sortedInGroupTensor); + xBiasQueue_.FreeTensor(xBiasTensor); +} + +template +__aicore__ inline void MoeGatingTopKEKFullload::SelectTopKGroupIndex() +{ + LocalTensor sortedInGroupTensor = sortedInGroupQueue_.DeQue(); + LocalTensor indexTensor = calcTmpBuffer_.Get(); + LocalTensor top2ValueInGroupTensor = sigmoidTmpQueue_.AllocTensor(); // 这个临时空间可以复用 + event_t eventIdVToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(eventIdVToS); + WaitFlag(eventIdVToS); + + indexTensor.SetValue(0, static_cast(5)); // b0101 + indexTensor.SetValue(1, static_cast(0)); + event_t eventIdSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIdSToV); + WaitFlag(eventIdSToV); + + uint64_t rsvdCnt = 0; // 用于保存筛选后保留下来的元素个数 + GatherMaskParams gatherMaskParams; + gatherMaskParams.repeatTimes = 8; + gatherMaskParams.src0BlockStride = 1; + gatherMaskParams.src0RepeatStride = 8; + gatherMaskParams.src1RepeatStride = 0; + GatherMask(top2ValueInGroupTensor, sortedInGroupTensor, indexTensor, true, static_cast(64), + gatherMaskParams, rsvdCnt); + PipeBarrier(); + LocalTensor groupTop2SumTensor = top2ValueInGroupTensor; + PairReduceSum(groupTop2SumTensor, top2ValueInGroupTensor, 1, groupCount_ * 2, 1, 1, + 1); // 计算每个组内最大的两个数之和 + PipeBarrier(); + + LocalTensor groupIndexTensor = indexTensor; + ArithProgression(groupIndexTensor.ReinterpretCast(), 0, 1, groupCount_); // 生成组索引 + PipeBarrier(); + // 用最小值补到32个数 + int64_t duplicateNum = ONE_REPEAT_SORT_NUM - groupCount_; + if (duplicateNum > 0) { + uint64_t mask0 = UINT64_MAX << groupCount_; + uint64_t mask[2] = {mask0, 0}; + Duplicate(groupTop2SumTensor, MIN_FP32, mask, 1, 1, 8); + PipeBarrier(); + } + // 排序,将kgroup选出来 + LocalTensor sortedGroupTensor = sortedGroupQueue_.AllocTensor(); + Sort32(sortedGroupTensor, groupTop2SumTensor, groupIndexTensor, 1); + + PipeBarrier(); + LocalTensor sortedGroupIndexTensor = indexTensor.ReinterpretCast(); + // 提取组序号 + uint8_t src1Pattern = 2; // 内置固定模式 + GatherMask(sortedGroupIndexTensor, sortedGroupTensor.template ReinterpretCast(), src1Pattern, false, + static_cast(0), {1, 1, 0, 0}, rsvdCnt); + + // 需要将组排序(这里是降序,所以下mrgsor的时候反着取,3、2、1、0) + Cast(sortedGroupTensor, sortedGroupIndexTensor, RoundMode::CAST_ROUND, kGroup_); + PipeBarrier(); + duplicateNum = ONE_REPEAT_SORT_NUM - kGroup_; + if (duplicateNum > 0) { + uint64_t mask0 = UINT64_MAX << kGroup_; + uint64_t mask[2] = {mask0, 0}; + Duplicate(sortedGroupTensor, MIN_FP32, mask, 1, 1, 8); + PipeBarrier(); + } + Sort32(top2ValueInGroupTensor, sortedGroupTensor, sortedGroupIndexTensor.template ReinterpretCast(), 1); + PipeBarrier(); + src1Pattern = 1; + GatherMask(sortedGroupTensor, top2ValueInGroupTensor, src1Pattern, false, static_cast(0), {1, 1, 0, 0}, + rsvdCnt); + PipeBarrier(); + Cast(sortedGroupIndexTensor, sortedGroupTensor, RoundMode::CAST_ROUND, kGroup_); + + sortedGroupQueue_.FreeTensor(sortedGroupTensor); + sortedInGroupQueue_.EnQue(sortedInGroupTensor); + sigmoidTmpQueue_.FreeTensor(top2ValueInGroupTensor); +} + +template +__aicore__ inline void MoeGatingTopKEKFullload::SelectTopKExpertIdx() +{ + LocalTensor expertIdxTensor = expertIdxOutQueue_.AllocTensor(); + LocalTensor topKGroupIndexTensor = calcTmpBuffer_.Get(); + LocalTensor sortedInGroupTensor = sortedInGroupQueue_.DeQue(); + LocalTensor sortedExpertTensor = xInQueue_.AllocTensor(); + AscendC::MrgSort4Info params; + params.elementLengths[0] = k_; + params.elementLengths[1] = k_; + params.elementLengths[2] = k_; + params.elementLengths[3] = k_; + params.ifExhaustedSuspension = true; + params.validBit = 0b1111; + params.repeatTimes = 1; + event_t eventIdVToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(eventIdVToS); + WaitFlag(eventIdVToS); + int64_t listOffset1 = topKGroupIndexTensor.GetValue(3) * perGroupExpertCount_ * 2; + int64_t listOffset2 = topKGroupIndexTensor.GetValue(2) * perGroupExpertCount_ * 2; + int64_t listOffset3 = topKGroupIndexTensor.GetValue(1) * perGroupExpertCount_ * 2; + int64_t listOffset4 = topKGroupIndexTensor.GetValue(0) * perGroupExpertCount_ * 2; + event_t eventIdSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIdSToV); + WaitFlag(eventIdSToV); + AscendC::MrgSortSrcList srcList; + srcList.src1 = sortedInGroupTensor[listOffset1]; + srcList.src2 = sortedInGroupTensor[listOffset2]; + srcList.src3 = sortedInGroupTensor[listOffset3]; + srcList.src4 = sortedInGroupTensor[listOffset4]; + MrgSort(sortedExpertTensor, srcList, params); + PipeBarrier(); + uint64_t rsvdCnt = 0; // 用于保存筛选后保留下来的元素个数 + uint8_t src1Pattern = 2; // 内置固定模式 + GatherMask(expertIdxTensor, sortedExpertTensor.template ReinterpretCast(), src1Pattern, false, + static_cast(0), {1, 1, 0, 0}, rsvdCnt); + xInQueue_.FreeTensor(sortedExpertTensor); + expertIdxOutQueue_.EnQue(expertIdxTensor); + sortedInGroupQueue_.FreeTensor(sortedInGroupTensor); +} + +template +__aicore__ inline void MoeGatingTopKEKFullload::SelectTopKExpertScore() +{ + LocalTensor expertIdxTensor = expertIdxOutQueue_.DeQue(); + LocalTensor expertByteIdxTensor = calcTmpBuffer_.Get(); + LocalTensor xSigmoidTensor = xSigmoidQueue_.DeQue(); + LocalTensor yTensor = yOutQueue_.AllocTensor(); + LocalTensor yOutTensor; + if constexpr (!IsSameType::value) { + yOutTensor = yTensor.template ReinterpretCast()[kAlign_]; + } else { + yOutTensor = yTensor; + } + Muls(expertByteIdxTensor, expertIdxTensor, static_cast(sizeof(float)), k_); + PipeBarrier(); + Gather(yOutTensor, xSigmoidTensor, expertByteIdxTensor.template ReinterpretCast(), + static_cast(0), k_); + + LocalTensor calTensor = calcTmpBuffer_.Get(); + PipeBarrier(); + ReduceSum(calTensor, yOutTensor, xSigmoidTensor, k_); + event_t eventIdVToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(eventIdVToS); + WaitFlag(eventIdVToS); + float sumValue = calTensor.GetValue(0) + eps_; + event_t eventIdSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIdSToV); + WaitFlag(eventIdSToV); + Duplicate(calTensor, sumValue, k_); + PipeBarrier(); + Div(yOutTensor, yOutTensor, calTensor, k_); + PipeBarrier(); + Muls(yOutTensor, yOutTensor, routedScalingFactor_, k_); + + if constexpr (!IsSameType::value) { + PipeBarrier(); + Cast(yTensor, yOutTensor, RoundMode::CAST_RINT, k_); + } + + xSigmoidQueue_.EnQue(xSigmoidTensor); + expertIdxOutQueue_.EnQue(expertIdxTensor); + yOutQueue_.EnQue(yTensor); +} + +template +__aicore__ inline void MoeGatingTopKEKFullload::CopyOut(int64_t row) +{ + LocalTensor yOutTensor = yOutQueue_.DeQue(); + LocalTensor expertIdxTensor = expertIdxOutQueue_.DeQue(); + LocalTensor xSigmoidTensor = xSigmoidQueue_.DeQue(); + DataCopyExtParams dataCopyParams{1, static_cast(k_ * sizeof(T)), 0, 0, 0}; + DataCopyPad(yGm_[row * k_], yOutTensor, dataCopyParams); + dataCopyParams.blockLen = k_ * sizeof(int32_t); + DataCopyPad(expertIdxGm_[row * k_], expertIdxTensor, dataCopyParams); + xSigmoidQueue_.FreeTensor(xSigmoidTensor); + expertIdxOutQueue_.FreeTensor(expertIdxTensor); + yOutQueue_.FreeTensor(yOutTensor); +} + +template +__aicore__ inline void MoeGatingTopKEKFullload::Init(GM_ADDR x, GM_ADDR bias, GM_ADDR y, GM_ADDR expertIdx, + GM_ADDR out, GM_ADDR workspace, + const MoeGatingTopKTilingData *tilingData, TPipe *tPipe) +{ + tilingData_ = tilingData; + pipe_ = tPipe; + blockIdx_ = GetBlockIdx(); + perCoreRowCount_ = tilingData_->perCoreRowCount; + if (blockIdx_ == GetBlockNum() - 1) { + curCoreRowCount_ = tilingData_->lastCoreRowCount; + } else { + curCoreRowCount_ = tilingData_->perCoreRowCount; + } + expertCount_ = tilingData_->expertCount; + addBias_ = tilingData_->addBias == 1; + k_ = tilingData_->k; + kGroup_ = tilingData_->kGroup; + groupCount_ = tilingData_->groupCount; + perGroupExpertCount_ = tilingData_->perGroupExpertCount; + routedScalingFactor_ = tilingData_->routedScalingFactor; + eps_ = tilingData_->eps; + + expertCountAlign_ = Align(expertCount_, sizeof(float)); + kAlign_ = Align(expertCount_, sizeof(float)); + + // init input gm buf + xGm_.SetGlobalBuffer((__gm__ T *)x + perCoreRowCount_ * expertCount_ * blockIdx_, expertCount_); + biasGm_.SetGlobalBuffer((__gm__ T *)bias, expertCount_); + + // init output gm buf + yGm_.SetGlobalBuffer((__gm__ T *)y + perCoreRowCount_ * k_ * blockIdx_, k_); + expertIdxGm_.SetGlobalBuffer((__gm__ int32_t *)expertIdx + perCoreRowCount_ * k_ * blockIdx_, k_); + outGm_.SetGlobalBuffer((__gm__ T *)out + perCoreRowCount_ * expertCount_ * blockIdx_, expertCount_); + + // init que + pipe_->InitBuffer(xInQueue_, 2, expertCountAlign_ * sizeof(float) * (sizeof(float) / sizeof(T))); + pipe_->InitBuffer(biasInQueue_, expertCountAlign_ * sizeof(float) * (sizeof(float) / sizeof(T))); + + pipe_->InitBuffer(xSigmoidQueue_, 1, AlignBytes(expertCount_, sizeof(float))); + pipe_->InitBuffer(xBiasQueue_, 2, AlignBytes(expertCount_, sizeof(float))); + + pipe_->InitBuffer(yOutQueue_, 2, kAlign_ * sizeof(float) * (sizeof(float) / sizeof(T))); + pipe_->InitBuffer(expertIdxOutQueue_, 2, AlignBytes(k_, sizeof(int32_t))); + pipe_->InitBuffer(outOutQueue_, 2, AlignBytes(expertCount_, sizeof(float))); + + pipe_->InitBuffer(sigmoidTmpQueue_, 2, AlignBytes(expertCount_, sizeof(float))); + pipe_->InitBuffer(sortedInGroupQueue_, 2, AlignBytes(expertCount_, sizeof(float)) * 2); + pipe_->InitBuffer(sortedGroupQueue_, 2, + (groupCount_ + ONE_REPEAT_SORT_NUM - 1) / ONE_REPEAT_SORT_NUM * ONE_REPEAT_SORT_NUM * + sizeof(float) * 2); + + pipe_->InitBuffer(calcTmpBuffer_, tilingData_->calTmpBufUbSize); +} + +template +__aicore__ inline void MoeGatingTopKEKFullload::Process() +{ + CopyInBias(); + for (int64_t row = 0; row < curCoreRowCount_; row++) { + CopyInX(row); + ComputeX(); + SortInGroup(); + SelectTopKGroupIndex(); + SelectTopKExpertIdx(); + SelectTopKExpertScore(); + CopyOut(row); + } +} +} // namespace MoeGatingTopK +#endif // MOE_GATING_TOP_K_E_K_FULLLOAD_H \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k_generalized.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k_generalized.h new file mode 100644 index 0000000000000000000000000000000000000000..cd8ae3edcf3ae77a7161b57670b0663b7126d660 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k_generalized.h @@ -0,0 +1,668 @@ +/** + * 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 moe_gating_top_k_generalized.h + * \brief + */ +#ifndef MOE_GATING_TOP_K_E_K_GENERALIZED_H +#define MOE_GATING_TOP_K_E_K_GENERALIZED_H +#include "kernel_operator.h" +#include "common.h" +#include "basic_api/kernel_operator_utils_intf.h" +namespace MoeGatingTopK { +using namespace AscendC; + +template +class MoeGatingTopKGenerlized { +public: + __aicore__ inline MoeGatingTopKGenerlized(){}; + __aicore__ inline void Init(GM_ADDR x, GM_ADDR bias, GM_ADDR y, GM_ADDR expertIdx, GM_ADDR out, GM_ADDR workspace, + const MoeGatingTopKTilingData *tilingData, TPipe *tPipe); + __aicore__ inline void Process(); + +private: + __aicore__ inline void CopyInBiasAndInitExpertId(); + __aicore__ inline void CopyInX(int64_t progress); + __aicore__ inline void ComputeX(); + __aicore__ inline void CopuOutXNorm(int64_t row); + __aicore__ inline void SortInGroup(); + __aicore__ inline void SelectTopKGroupIndex(); + __aicore__ inline void SelectTopKExpertIdx(); + __aicore__ inline void SelectTopKExpertScore(); + __aicore__ inline void CumputeActualTopKExpertId(); + __aicore__ inline void CopyOut(int64_t row); + +private: + TPipe *pipe_; + TQue xInQueue_; + TQue yOutQueue_; + TQue expertIdxOutQueue_; + TQue outOutQueue_; + + TBuf biasBuf_; // 存放输入bias + TBuf expertIdBuf_; // 专家编号 + TBuf xNormWithBiasBuf_; // 存放加了bias之后的值 + TBuf xNormBuf_; // 存放计算sigmoid或softmax的值 + TBuf sortedInGroupBuf_; // 存放组内排序后的结果 + TBuf topKExpertIdBuf_; + TBuf sortedGroupIndexBuf_; + TBuf calcTmpBuf_; + + GlobalTensor xGm_; + GlobalTensor biasGm_; + GlobalTensor yGm_; + GlobalTensor expertIdxGm_; + GlobalTensor outGm_; + + int64_t blockIdx_ = 0; + int64_t perCoreRowCount_ = 0; + int64_t curCoreRowCount_ = 0; + int64_t expertCount_ = 0; + bool addBias_ = false; + int64_t k_ = 0; + int64_t kGroup_ = 0; + int64_t groupCount_ = 0; + int64_t groupCountAlign_ = 0; + int64_t perGroupExpertCount_ = 0; + int64_t perGroupExpertCountAlign_ = 0; + int64_t groupSelectMode_ = 0; + int64_t renorm_ = 0; + int64_t normType_ = 0; + int64_t outFlag_ = 0; + + int64_t expertCountAlign_ = 0; + int64_t kAlign_ = 0; + bool isAlign_ = false; + + const MoeGatingTopKTilingData *tilingData_; +}; + +template +__aicore__ inline void MoeGatingTopKGenerlized::CopyInBiasAndInitExpertId() +{ + LocalTensor biasTensor = biasBuf_.Get(); + LocalTensor expertIdTensor = expertIdBuf_.Get(); + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = groupCount_; + dataCopyParams.blockLen = perGroupExpertCount_ * sizeof(T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = (perGroupExpertCountAlign_ - perGroupExpertCount_) * sizeof(T) / BLOCK_BYTES; + + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, static_cast(0)}; + if (addBias_) { + if constexpr (IsSameType::value) { + DataCopyPad(biasTensor, biasGm_, dataCopyParams, dataCopyPadParams); + event_t eventIdMte2ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventIdMte2ToV); + WaitFlag(eventIdMte2ToV); + } else { + DataCopyPad(biasTensor[expertCountAlign_].ReinterpretCast(), biasGm_, dataCopyParams, dataCopyPadParams); + event_t eventIdMte2ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventIdMte2ToV); + WaitFlag(eventIdMte2ToV); + Cast(biasTensor, biasTensor[expertCountAlign_].ReinterpretCast(), RoundMode::CAST_NONE, + expertCountAlign_); + PipeBarrier(); + } + + if (!isAlign_) { + int64_t duplicateNum = perGroupExpertCount_ % ONE_REPEAT_SORT_NUM; + int duplicateIndex = perGroupExpertCount_ - duplicateNum; + if (duplicateNum > 0) { + uint64_t mask0 = UINT64_MAX; + mask0 = mask0 << duplicateNum; + mask0 = mask0 & (UINT64_MAX >> ONE_REPEAT_SORT_NUM); + uint64_t mask[2] = {mask0, 0}; + Duplicate(biasTensor.ReinterpretCast()[duplicateIndex], FLOAT32_NEG_INF, mask, groupCount_, 1, + perGroupExpertCountAlign_ * sizeof(float) / BLOCK_BYTES); + } + } + } + ArithProgression(expertIdTensor, static_cast(0), static_cast(1), expertCountAlign_); +} + +template +__aicore__ inline void MoeGatingTopKGenerlized::CopyInX(int64_t row) +{ + LocalTensor xInLocalTensor = xInQueue_.AllocTensor(); + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = groupCount_; + dataCopyParams.blockLen = perGroupExpertCount_ * sizeof(T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = (perGroupExpertCountAlign_ - perGroupExpertCount_) * sizeof(T) / BLOCK_BYTES; + + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, static_cast(0)}; + if constexpr (IsSameType::value) { + DataCopyPad(xInLocalTensor, xGm_[row * expertCount_], dataCopyParams, dataCopyPadParams); + } else { + DataCopyPad(xInLocalTensor[expertCountAlign_].ReinterpretCast(), xGm_[row * expertCount_], dataCopyParams, + dataCopyPadParams); + } + xInQueue_.EnQue(xInLocalTensor); +} + +template +__aicore__ inline void MoeGatingTopKGenerlized::ComputeX() +{ + LocalTensor xNormTensor = xNormBuf_.Get(); + LocalTensor xInLocalTensor = xInQueue_.DeQue(); + LocalTensor xNormWithBiasTensor = xNormWithBiasBuf_.Get(); + LocalTensor biasTensor = biasBuf_.Get(); + + if constexpr (!IsSameType::value) { + Cast(xInLocalTensor, xInLocalTensor[expertCountAlign_].ReinterpretCast(), RoundMode::CAST_NONE, + expertCountAlign_); + PipeBarrier(); + } + + int64_t duplicateNum = perGroupExpertCount_ % ONE_REPEAT_SORT_NUM; + int duplicateIndex = perGroupExpertCount_ - duplicateNum; + if (!isAlign_ && duplicateNum > 0) { + uint64_t mask0 = UINT64_MAX; + mask0 = mask0 << duplicateNum; + mask0 = mask0 & (UINT64_MAX >> ONE_REPEAT_SORT_NUM); + uint64_t mask[2] = {mask0, 0}; + Duplicate(xInLocalTensor.ReinterpretCast()[duplicateIndex], FLOAT32_NEG_INF, mask, groupCount_, 1, + (perGroupExpertCountAlign_ * sizeof(float)) / BLOCK_BYTES); + PipeBarrier(); + } + if (normType_ == 1) { // sigmoid + LocalTensor calcNormTmpTensor = calcTmpBuf_.Get(); + Sigmoid(xNormTensor, xInLocalTensor, calcNormTmpTensor, expertCountAlign_); + PipeBarrier(); + } else if (normType_ == 0) { // softmax + LocalTensor reduceValueTensor = calcTmpBuf_.Get(); + LocalTensor calcTmp = calcTmpBuf_.Get()[BLOCK_BYTES]; + ReduceMax(reduceValueTensor, xInLocalTensor, calcTmp, expertCountAlign_); + event_t eventIdVToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(eventIdVToS); + WaitFlag(eventIdVToS); + float maxValue = reduceValueTensor.GetValue(0); + event_t eventIdSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIdSToV); + WaitFlag(eventIdSToV); + Adds(xNormTensor, xInLocalTensor, -maxValue, expertCountAlign_); + PipeBarrier(); + Exp(xNormTensor, xNormTensor, expertCountAlign_); + PipeBarrier(); + ReduceSum(reduceValueTensor, xNormTensor, calcTmp, expertCountAlign_); + eventIdVToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(eventIdVToS); + WaitFlag(eventIdVToS); + float sumValue = reduceValueTensor.GetValue(0); + eventIdSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIdSToV); + WaitFlag(eventIdSToV); + Muls(xNormTensor, xNormTensor, 1.0f / sumValue, expertCountAlign_); + PipeBarrier(); + } + if (addBias_) { + Add(xNormWithBiasTensor, xNormTensor, biasTensor, expertCountAlign_); + } else { + DataCopy(xNormWithBiasTensor, xNormTensor, expertCountAlign_); + } + + if (!isAlign_ && duplicateNum > 0) { + uint64_t mask0 = UINT64_MAX; + mask0 = mask0 << duplicateNum; + mask0 = mask0 & (UINT64_MAX >> ONE_REPEAT_SORT_NUM); + uint64_t mask[2] = {mask0, 0}; + PipeBarrier(); + Duplicate(xNormWithBiasTensor.ReinterpretCast()[duplicateIndex], + FLOAT32_NEG_INF, // MIN_FP32, + mask, groupCount_, 1, perGroupExpertCountAlign_ * sizeof(float) / BLOCK_BYTES); + } + xInQueue_.FreeTensor(xInLocalTensor); +} + +template +__aicore__ inline void MoeGatingTopKGenerlized::CopuOutXNorm(int64_t row) +{ + LocalTensor outOutTensor = outOutQueue_.AllocTensor(); + LocalTensor xNormTensor = xNormBuf_.Get(); + DataCopy(outOutTensor, xNormTensor, expertCountAlign_); + outOutQueue_.EnQue(outOutTensor); + outOutTensor = outOutQueue_.DeQue(); + DataCopyExtParams dataCopyParams{ + static_cast(groupCount_), static_cast(perGroupExpertCount_ * sizeof(float)), + static_cast((perGroupExpertCountAlign_ - perGroupExpertCount_) * sizeof(float) / BLOCK_BYTES), 0, 0}; + DataCopyPad(outGm_[row * expertCount_], outOutTensor, dataCopyParams); + outOutQueue_.FreeTensor(outOutTensor); +} + +template +__aicore__ inline void MoeGatingTopKGenerlized::SortInGroup() +{ + LocalTensor xNormWithBiasTensor = xNormWithBiasBuf_.Get(); + LocalTensor expertIdTensor = expertIdBuf_.Get(); + LocalTensor sortedInGroupTensor = sortedInGroupBuf_.Get(); + LocalTensor tmpLocal = calcTmpBuf_.Get(); + if (perGroupExpertCountAlign_ == ONE_REPEAT_SORT_NUM) { + PipeBarrier(); + Sort32(sortedInGroupTensor, xNormWithBiasTensor, expertIdTensor, groupCount_); + } else { + for (int64_t group = 0; group < groupCount_; group++) { + PipeBarrier(); + Sort(sortedInGroupTensor[group * perGroupExpertCountAlign_ * CONSTANT_TWO], + xNormWithBiasTensor[group * perGroupExpertCountAlign_], + expertIdTensor[group * perGroupExpertCountAlign_], tmpLocal, + perGroupExpertCountAlign_ / ONE_REPEAT_SORT_NUM); + } + } +} + +template +__aicore__ inline void MoeGatingTopKGenerlized::SelectTopKGroupIndex() +{ + LocalTensor sortedInGroupTensor = sortedInGroupBuf_.Get(); + LocalTensor valueSelectedFromGroupTensor = calcTmpBuf_.GetWithOffset(groupCountAlign_ * 2, 0); + LocalTensor maskTensor = + calcTmpBuf_.GetWithOffset(groupCountAlign_, groupCountAlign_ * 2 * sizeof(float)); + LocalTensor topValueInGroupTensor = + calcTmpBuf_.GetWithOffset(groupCountAlign_, groupCountAlign_ * 3 * sizeof(float)); + LocalTensor groupIndex = + calcTmpBuf_.GetWithOffset(groupCountAlign_, groupCountAlign_ * 4 * sizeof(float)); + LocalTensor sortedTopValue = + calcTmpBuf_.GetWithOffset(groupCountAlign_ * 2, groupCountAlign_ * 5 * sizeof(float)); + LocalTensor sortTmp = + calcTmpBuf_.GetWithOffset(groupCountAlign_ * 2, groupCountAlign_ * 7 * sizeof(float)); + + event_t eventIdVToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(eventIdVToS); + WaitFlag(eventIdVToS); + + uint64_t rsvdCnt = 0; // 用于保存筛选后保留下来的元素个数 + PipeBarrier(); + if (groupSelectMode_ == 1) { // top2 sum + // 提取每组组前两个元素 + maskTensor.SetValue(0, static_cast(5)); // b0101 + maskTensor.SetValue(1, static_cast(0)); + event_t eventIdSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIdSToV); + WaitFlag(eventIdSToV); + + GatherMaskParams gatherMaskParams; + gatherMaskParams.repeatTimes = groupCount_; + gatherMaskParams.src0BlockStride = 1; + gatherMaskParams.src0RepeatStride = + Ceil(perGroupExpertCountAlign_ * (sizeof(float) + sizeof(uint32_t)), BLOCK_BYTES); + gatherMaskParams.src1RepeatStride = 0; + GatherMask(valueSelectedFromGroupTensor, sortedInGroupTensor, maskTensor, true, + static_cast(ONE_REPEAT_SORT_NUM * CONSTANT_TWO), gatherMaskParams, rsvdCnt); + PipeBarrier(); + + // 计算每个组前两个数的和 + PairReduceSum(topValueInGroupTensor, valueSelectedFromGroupTensor, + Ceil(groupCount_ * sizeof(float) * 2, REPEAT_BYTES), REPEAT_BYTES / sizeof(float), 1, 1, + CONSTANT_EIGHT); // 计算每个组内最大的两个数之和 + } else { + maskTensor.SetValue(0, static_cast(1)); // b0101 + maskTensor.SetValue(1, static_cast(0)); + + event_t eventIdSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIdSToV); + WaitFlag(eventIdSToV); + uint64_t rsvdCnt = 0; // 用于保存筛选后保留下来的元素个数 + GatherMaskParams gatherMaskParams; + gatherMaskParams.repeatTimes = groupCount_; + gatherMaskParams.src0BlockStride = 1; + gatherMaskParams.src0RepeatStride = Ceil(perGroupExpertCountAlign_ * (sizeof(float) + sizeof(uint32_t)), 32); + gatherMaskParams.src1RepeatStride = 0; + GatherMask(topValueInGroupTensor, sortedInGroupTensor, maskTensor, true, + static_cast(ONE_REPEAT_SORT_NUM * CONSTANT_TWO), gatherMaskParams, rsvdCnt); + } + + PipeBarrier(); + // 生成组索引 + ArithProgression(groupIndex.ReinterpretCast(), static_cast(0), static_cast(1), + groupCount_); // 生成组索引 + PipeBarrier(); + + int64_t duplicateNum = groupCount_ % ONE_REPEAT_SORT_NUM; + int duplicateIndex = groupCount_ - duplicateNum; + if (duplicateNum > 0) { + uint64_t mask0 = UINT64_MAX; + mask0 = mask0 << duplicateNum; + mask0 = mask0 & (UINT64_MAX >> ONE_REPEAT_SORT_NUM); + uint64_t mask[2] = {mask0, 0}; + Duplicate(topValueInGroupTensor.ReinterpretCast()[duplicateIndex], FLOAT32_NEG_INF, mask, 1, 1, + REPEAT_BLOCKS); + PipeBarrier(); + } + PipeBarrier(); + + // 排序 + Sort(sortedTopValue, topValueInGroupTensor, groupIndex, sortTmp, Ceil(groupCount_, 32)); + PipeBarrier(); + + // 提取组序号 + uint8_t src1Pattern = 2; // 内置固定模式 + GatherMask(groupIndex, sortedTopValue.template ReinterpretCast(), src1Pattern, false, + static_cast(0), + {1, static_cast(Ceil(kGroup_ * sizeof(float) * CONSTANT_TWO, 256)), REPEAT_BLOCKS, 0}, rsvdCnt); + PipeBarrier(); + duplicateNum = kGroup_ % ONE_REPEAT_SORT_NUM; + if (duplicateNum > 0) { + duplicateIndex = kGroup_ - duplicateNum; + uint64_t mask0 = UINT64_MAX; + mask0 = mask0 << duplicateNum; + mask0 = mask0 & (UINT64_MAX >> ONE_REPEAT_SORT_NUM); + uint64_t mask[2] = {mask0, 0}; + PipeBarrier(); + Duplicate(groupIndex.ReinterpretCast()[duplicateIndex], FLOAT32_NEG_INF, mask, 1, 1, REPEAT_BLOCKS); + } + + // 将筛选出来的组序号降序排列 + LocalTensor sortedGroupIndex = sortedGroupIndexBuf_.Get(); + PipeBarrier(); + Sort(sortedGroupIndex, groupIndex.ReinterpretCast(), groupIndex, sortTmp, Ceil(kGroup_, 32)); +} + +template +__aicore__ inline void MoeGatingTopKGenerlized::SelectTopKExpertIdx() +{ + LocalTensor sortedInGroupTensor = sortedInGroupBuf_.Get(); + LocalTensor sortedGroupIndex = sortedGroupIndexBuf_.Get(); + LocalTensor topKExpertId = topKExpertIdBuf_.Get(); + LocalTensor mrgSort0Tensor = calcTmpBuf_.Get(); + + uint32_t offset[CONSTANT_FOUR] = {0, 0, 0, 0}; + uint16_t lenArr[CONSTANT_FOUR] = { + static_cast(perGroupExpertCount_), static_cast(perGroupExpertCount_), + static_cast(perGroupExpertCount_), static_cast(perGroupExpertCount_)}; + MrgSort4Info params{lenArr, false, 0b1111, 1}; + MrgSortSrcList srcList; + + event_t eventIdVToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(eventIdVToS); + WaitFlag(eventIdVToS); + + for (int32_t i = kGroup_ - 1; i >= 0; i -= CONSTANT_FOUR) { + int64_t mrgLen = Min(i + 1, CONSTANT_FOUR); + if (mrgLen > 1) { + if (mrgLen == MERGE_LIST_FOUR) { + offset[0] = sortedGroupIndex.GetValue(i * 2) * perGroupExpertCountAlign_ * 2; + offset[1] = sortedGroupIndex.GetValue((i - 1) * 2) * perGroupExpertCountAlign_ * 2; + offset[2] = sortedGroupIndex.GetValue((i - 2) * 2) * perGroupExpertCountAlign_ * 2; + offset[3] = sortedGroupIndex.GetValue((i - 3) * 2) * perGroupExpertCountAlign_ * 2; + } else if (mrgLen == MERGE_LIST_THREE) { + offset[0] = sortedGroupIndex.GetValue(i * 2) * perGroupExpertCountAlign_ * 2; + offset[1] = sortedGroupIndex.GetValue((i - 1) * 2) * perGroupExpertCountAlign_ * 2; + offset[2] = sortedGroupIndex.GetValue((i - 2) * 2) * perGroupExpertCountAlign_ * 2; + offset[3] = 0; + params.elementLengths[3] = 0; + params.validBit = 0b111; + } else { + offset[0] = sortedGroupIndex.GetValue(i * 2) * perGroupExpertCountAlign_ * 2; + offset[1] = sortedGroupIndex.GetValue((i - 1) * 2) * perGroupExpertCountAlign_ * 2; + offset[2] = 0; + offset[3] = 0; + params.elementLengths[2] = 0; + params.elementLengths[3] = 0; + params.validBit = 0b11; + } + + srcList.src1 = sortedInGroupTensor[offset[0]]; + srcList.src2 = sortedInGroupTensor[offset[1]]; + srcList.src3 = sortedInGroupTensor[offset[2]]; + srcList.src4 = sortedInGroupTensor[offset[3]]; + + PipeBarrier(); + MrgSort(mrgSort0Tensor[(kGroup_ - 1 - i) * perGroupExpertCountAlign_ * 2], srcList, params); + } else { + offset[0] = sortedGroupIndex.GetValue(i * 2) * perGroupExpertCountAlign_ * 2; + PipeBarrier(); + DataCopy(mrgSort0Tensor[(kGroup_ - 1 - i) * perGroupExpertCountAlign_ * 2], sortedInGroupTensor[offset[0]], + perGroupExpertCountAlign_ * 2); + } + } + int32_t baseLoop = 4; + LocalTensor srcTensor = mrgSort0Tensor; + LocalTensor dstTensor = mrgSort0Tensor; + for (int i = 0; i < tilingData_->vmsCount; i++) { + if (i % 2 == 0) { + srcTensor = mrgSort0Tensor; + dstTensor = sortedInGroupTensor; + } else { + srcTensor = sortedInGroupTensor; + dstTensor = mrgSort0Tensor; + } + + int32_t nextBaseRow = baseLoop * MERGE_LIST_FOUR; + int32_t quotient = kGroup_ / nextBaseRow; + int32_t remainder = kGroup_ - quotient * nextBaseRow; + if (quotient > 0) { + MrgSort4Info params; + MrgSortSrcList srcList; + params.ifExhaustedSuspension = false; + params.elementLengths[0] = perGroupExpertCount_ * baseLoop; + params.elementLengths[1] = perGroupExpertCount_ * baseLoop; + params.elementLengths[2] = perGroupExpertCount_ * baseLoop; + params.elementLengths[3] = perGroupExpertCount_ * baseLoop; + params.validBit = 0b1111; + params.repeatTimes = 1; + for (int j = 0; j < quotient; j++) { + srcList.src1 = srcTensor[perGroupExpertCountAlign_ * baseLoop * 8 * j]; + srcList.src2 = srcTensor[perGroupExpertCountAlign_ * baseLoop * (8 * j + 2)]; + srcList.src3 = srcTensor[perGroupExpertCountAlign_ * baseLoop * (8 * j + 4)]; + srcList.src4 = srcTensor[perGroupExpertCountAlign_ * baseLoop * (8 * j + 6)]; + PipeBarrier(); + MrgSort(dstTensor[perGroupExpertCountAlign_ * baseLoop * 8 * j], srcList, params); + } + } + + if (remainder > 0) { + int32_t baseOffset = quotient * nextBaseRow * perGroupExpertCountAlign_ * 2; + int32_t mrgLen = CeilDiv(remainder, baseLoop); + int32_t tailRow = remainder - (mrgLen - 1) * baseLoop; + if (mrgLen > 1) { + MrgSort4Info params; + MrgSortSrcList srcList; + params.repeatTimes = 1; + params.ifExhaustedSuspension = false; + params.elementLengths[0] = perGroupExpertCount_ * baseLoop; + params.elementLengths[1] = perGroupExpertCount_ * baseLoop; + params.elementLengths[2] = perGroupExpertCount_ * baseLoop; + params.elementLengths[3] = perGroupExpertCount_ * baseLoop; + srcList.src1 = srcTensor[baseOffset]; + srcList.src2 = srcTensor[baseOffset + perGroupExpertCountAlign_ * baseLoop * 2]; + if (mrgLen == MERGE_LIST_FOUR) { + srcList.src3 = srcTensor[baseOffset + perGroupExpertCountAlign_ * baseLoop * 2 * 2]; + srcList.src4 = srcTensor[baseOffset + perGroupExpertCountAlign_ * baseLoop * 2 * 3]; + params.elementLengths[3] = perGroupExpertCount_ * tailRow; + params.validBit = 0b1111; + } else if (mrgLen == MERGE_LIST_THREE) { + srcList.src3 = srcTensor[baseOffset + perGroupExpertCountAlign_ * baseLoop * 2 * 2]; + params.elementLengths[2] = perGroupExpertCount_ * tailRow; + params.elementLengths[3] = 0; + params.validBit = 0b111; + } else { + params.elementLengths[1] = perGroupExpertCount_ * tailRow; + params.elementLengths[2] = 0; + params.elementLengths[3] = 0; + params.validBit = 0b11; + } + PipeBarrier(); + MrgSort(dstTensor[baseOffset], srcList, params); + } else { + PipeBarrier(); + DataCopy(dstTensor[baseOffset], srcTensor[baseOffset], tailRow * perGroupExpertCountAlign_ * 2); + } + } + baseLoop = nextBaseRow; + } + + GatherMaskParams gatherMaskParams; + gatherMaskParams.repeatTimes = Ceil(k_ * sizeof(float) * 2, REPEAT_BYTES); + gatherMaskParams.src0BlockStride = 1; + gatherMaskParams.src0RepeatStride = REPEAT_BLOCKS; + gatherMaskParams.src1RepeatStride = 0; + + uint64_t rsvdCnt = 0; // 用于保存筛选后保留下来的元素个数 + uint8_t src1Pattern = 2; // 内置固定模式 + PipeBarrier(); + GatherMask(topKExpertId, dstTensor.template ReinterpretCast(), src1Pattern, false, + static_cast(0), gatherMaskParams, rsvdCnt); +} + +template +__aicore__ inline void MoeGatingTopKGenerlized::SelectTopKExpertScore() +{ + LocalTensor xNormTensor = xNormBuf_.Get(); + LocalTensor yOutTensor = yOutQueue_.AllocTensor(); + LocalTensor topKExpertId = topKExpertIdBuf_.Get(); + LocalTensor topKExpertIdWithByte = calcTmpBuf_.Get(); + PipeBarrier(); + Muls(topKExpertIdWithByte, topKExpertId, static_cast(sizeof(float)), k_); + PipeBarrier(); + Gather(yOutTensor, xNormTensor, topKExpertIdWithByte.template ReinterpretCast(), static_cast(0), + k_); + bool needRenorm = (normType_ == 1) || // 情况1:sigmoid + renorm + (normType_ == 0 && renorm_ == 1); // 情况3:softmax + renorm + if (needRenorm) { + LocalTensor maxValueTensor = calcTmpBuf_.Get(); + LocalTensor tmpTensor = calcTmpBuf_.Get()[32]; + PipeBarrier(); + ReduceSum(maxValueTensor, yOutTensor, tmpTensor, k_); + event_t eventIdVToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(eventIdVToS); + WaitFlag(eventIdVToS); + float sumValue = maxValueTensor.GetValue(0) + tilingData_->eps; + event_t eventIdSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIdSToV); + WaitFlag(eventIdSToV); + Duplicate(tmpTensor, sumValue, k_); + PipeBarrier(); + Div(yOutTensor, yOutTensor, tmpTensor, k_); + } + PipeBarrier(); + Muls(yOutTensor, yOutTensor, tilingData_->routedScalingFactor, k_); + + if constexpr (!IsSameType::value) { + PipeBarrier(); + Cast(yOutTensor.ReinterpretCast(), yOutTensor, RoundMode::CAST_RINT, k_); + } + + yOutQueue_.EnQue(yOutTensor); +} + +template +__aicore__ inline void MoeGatingTopKGenerlized::CumputeActualTopKExpertId() +{ + LocalTensor expertIdxOut = expertIdxOutQueue_.AllocTensor(); + LocalTensor topKExpertId = topKExpertIdBuf_.Get(); + LocalTensor topKExpertIdFp32 = calcTmpBuf_.Get(); + + PipeBarrier(); + Cast(topKExpertIdFp32, topKExpertId, RoundMode::CAST_ROUND, k_); + PipeBarrier(); + Muls(topKExpertIdFp32, topKExpertIdFp32, 1.0f / (float)perGroupExpertCountAlign_, k_); + PipeBarrier(); + Cast(expertIdxOut, topKExpertIdFp32, RoundMode::CAST_TRUNC, k_); + PipeBarrier(); + Muls(expertIdxOut, expertIdxOut, static_cast(perGroupExpertCountAlign_ - perGroupExpertCount_), k_); + PipeBarrier(); + Sub(expertIdxOut, topKExpertId, expertIdxOut, k_); + expertIdxOutQueue_.EnQue(expertIdxOut); +} + +template +__aicore__ inline void MoeGatingTopKGenerlized::CopyOut(int64_t row) +{ + LocalTensor yOutTensor = yOutQueue_.DeQue(); + LocalTensor expertIdxOut = expertIdxOutQueue_.DeQue(); + DataCopyExtParams dataCopyParams{1, static_cast(k_ * sizeof(T)), 0, 0, 0}; + DataCopyPad(yGm_[row * k_], yOutTensor, dataCopyParams); + dataCopyParams.blockLen = k_ * sizeof(int32_t); + DataCopyPad(expertIdxGm_[row * k_], expertIdxOut, dataCopyParams); + yOutQueue_.FreeTensor(yOutTensor); + expertIdxOutQueue_.FreeTensor(expertIdxOut); +} + +template +__aicore__ inline void MoeGatingTopKGenerlized::Init(GM_ADDR x, GM_ADDR bias, GM_ADDR y, GM_ADDR expertIdx, + GM_ADDR out, GM_ADDR workspace, + const MoeGatingTopKTilingData *tilingData, TPipe *tPipe) +{ + tilingData_ = tilingData; + pipe_ = tPipe; + blockIdx_ = GetBlockIdx(); + perCoreRowCount_ = tilingData_->perCoreRowCount; + if (blockIdx_ == GetBlockNum() - 1) { + curCoreRowCount_ = tilingData_->lastCoreRowCount; + } else { + curCoreRowCount_ = tilingData_->perCoreRowCount; + } + expertCount_ = tilingData_->expertCount; + addBias_ = tilingData_->addBias == 1; + k_ = tilingData_->k; + kGroup_ = tilingData_->kGroup; + groupCount_ = tilingData_->groupCount; + groupCountAlign_ = Ceil(groupCount_, ONE_REPEAT_SORT_NUM) * ONE_REPEAT_SORT_NUM; + perGroupExpertCount_ = tilingData_->perGroupExpertCount; + perGroupExpertCountAlign_ = tilingData_->perGroupExpertCountAlign; + renorm_ = tilingData_->renorm; + normType_ = tilingData_->normType; + groupSelectMode_ = tilingData_->groupSelectMode; + + expertCountAlign_ = Align(perGroupExpertCountAlign_ * groupCount_, sizeof(float)); + kAlign_ = Align(k_, sizeof(float)); + + isAlign_ = perGroupExpertCount_ == perGroupExpertCountAlign_; + + // init input gm buf + xGm_.SetGlobalBuffer((__gm__ T *)x + perCoreRowCount_ * expertCount_ * blockIdx_, expertCount_); + biasGm_.SetGlobalBuffer((__gm__ T *)bias, expertCount_); + + // init output gm buf + yGm_.SetGlobalBuffer((__gm__ T *)y + perCoreRowCount_ * k_ * blockIdx_, k_); + expertIdxGm_.SetGlobalBuffer((__gm__ int32_t *)expertIdx + perCoreRowCount_ * k_ * blockIdx_, k_); + outGm_.SetGlobalBuffer((__gm__ float *)out + perCoreRowCount_ * expertCount_ * blockIdx_, expertCount_); + + // init que + pipe_->InitBuffer(xInQueue_, 1, expertCountAlign_ * sizeof(float) * (sizeof(float) / sizeof(T))); + pipe_->InitBuffer(yOutQueue_, 1, kAlign_ * sizeof(float)); + pipe_->InitBuffer(expertIdxOutQueue_, 1, kAlign_ * sizeof(int32_t)); + pipe_->InitBuffer(outOutQueue_, 1, expertCountAlign_ * sizeof(float)); + + pipe_->InitBuffer(biasBuf_, expertCountAlign_ * sizeof(float) * (sizeof(float) / sizeof(T))); + pipe_->InitBuffer(expertIdBuf_, expertCountAlign_ * sizeof(int32_t)); + + pipe_->InitBuffer(xNormBuf_, expertCountAlign_ * sizeof(float)); + + pipe_->InitBuffer(xNormWithBiasBuf_, expertCountAlign_ * sizeof(float)); + pipe_->InitBuffer(sortedInGroupBuf_, expertCountAlign_ * (sizeof(float) + sizeof(uint32_t))); + + pipe_->InitBuffer(sortedGroupIndexBuf_, groupCountAlign_ * sizeof(float) * CONSTANT_TWO); + pipe_->InitBuffer(topKExpertIdBuf_, kAlign_ * sizeof(int32_t)); + pipe_->InitBuffer(calcTmpBuf_, expertCountAlign_ * sizeof(float) * 10); +} + +template +__aicore__ inline void MoeGatingTopKGenerlized::Process() +{ + CopyInBiasAndInitExpertId(); + for (int64_t row = 0; row < curCoreRowCount_; row++) { + CopyInX(row); + ComputeX(); + if (tilingData_->outFlag) { + CopuOutXNorm(row); + } + SortInGroup(); + SelectTopKGroupIndex(); + SelectTopKExpertIdx(); + SelectTopKExpertScore(); + CumputeActualTopKExpertId(); + CopyOut(row); + } +} +} // namespace MoeGatingTopK +#endif // MOE_GATING_TOP_K_E_K_GENERALIZED_H \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k_without_group.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k_without_group.h new file mode 100644 index 0000000000000000000000000000000000000000..049999b9bdb9f0f1378a290f56b43f0d55e9b8d2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/op_kernel/moe_gating_top_k_without_group.h @@ -0,0 +1,378 @@ +/** + * 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 moe_gating_top_k_without_group.h + * \brief + */ +#ifndef MOE_GATING_TOP_K_E_K_WITHOUT_GROUP_H +#define MOE_GATING_TOP_K_E_K_WITHOUT_GROUP_H +#include "kernel_operator.h" +#include "common.h" +#include "basic_api/kernel_operator_utils_intf.h" +namespace MoeGatingTopK { +using namespace AscendC; + +template +class MoeGatingTopKWithoutGroup { +public: + __aicore__ inline MoeGatingTopKWithoutGroup(){}; + __aicore__ inline void Init( + GM_ADDR x, GM_ADDR bias, GM_ADDR inputIds, GM_ADDR tid2eid, + GM_ADDR y, GM_ADDR expertIdx, GM_ADDR out, GM_ADDR workspace, + const MoeGatingTopKTilingData *tilingData, TPipe *tPipe); + __aicore__ inline void Process(); + +private: + __aicore__ inline void CopyInBiasAndInitExpertId(); + __aicore__ inline void CopyInX(int64_t progress); + __aicore__ inline void ComputeX(); + __aicore__ inline void CopuOutXNorm(int64_t row); + __aicore__ inline void SelectTopKExpertIdx(); + __aicore__ inline void SelectExpertIdxByHash(int64_t row); + __aicore__ inline void SelectTopKExpertScore(); + __aicore__ inline void CopyOut(int64_t row); + +private: + TPipe *pipe_; + TQue xInQueue_; + TQue yOutQueue_; + TQue expertIdxOutQueue_; + TQue outOutQueue_; + + TBuf biasBuf_; // 存放输入bias + TBuf expertIdBuf_; // 专家编号 + TBuf xNormWithBiasBuf_; // 存放加了bias之后的值 + TBuf xNormBuf_; // 存放计算sigmoid或softmax的值 + TBuf topKExpertIdBuf_; + TBuf calcTmpBuf_; + + GlobalTensor xGm_; + GlobalTensor biasGm_; + GlobalTensor inputIdsGm_; + GlobalTensor tid2eidGm_; + GlobalTensor yGm_; + GlobalTensor expertIdxGm_; + GlobalTensor outGm_; + + int64_t blockIdx_ = 0; + int64_t perCoreRowCount_ = 0; + int64_t curCoreRowCount_ = 0; + int64_t expertCount_ = 0; + bool addBias_ = false; + bool outFlag_ = false; + bool hashFlag_ = false; + int64_t k_ = 0; + int64_t renorm_ = 0; + int64_t normType_ = 0; + int64_t expertCountAlign_ = 0; + const MoeGatingTopKTilingData *tilingData_; +}; + +template +__aicore__ inline void MoeGatingTopKWithoutGroup::CopyInBiasAndInitExpertId() +{ + LocalTensor biasTensor = biasBuf_.Get(); + LocalTensor expertIdTensor = expertIdBuf_.Get(); + DataCopyExtParams dataCopyParams{1, static_cast(expertCount_ * sizeof(T)), 0, 0, 0}; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, static_cast(0)}; + if (addBias_) { + if constexpr (IsSameType::value) { + DataCopyPad(biasTensor, biasGm_, dataCopyParams, dataCopyPadParams); + event_t eventIdMte2ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventIdMte2ToV); + WaitFlag(eventIdMte2ToV); + } else { + DataCopyPad(biasTensor[expertCountAlign_].ReinterpretCast(), biasGm_, dataCopyParams, dataCopyPadParams); + event_t eventIdMte2ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventIdMte2ToV); + WaitFlag(eventIdMte2ToV); + Cast(biasTensor, biasTensor[expertCountAlign_].ReinterpretCast(), RoundMode::CAST_NONE, + expertCountAlign_); + PipeBarrier(); + } + } + ArithProgression(expertIdTensor, static_cast(0), static_cast(1), expertCount_); +} + +template +__aicore__ inline void MoeGatingTopKWithoutGroup::CopyInX(int64_t row) +{ + LocalTensor xInLocalTensor = xInQueue_.AllocTensor(); + DataCopyExtParams dataCopyParams{1, static_cast(expertCount_ * sizeof(T)), 0, 0, 0}; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, static_cast(0)}; + if constexpr (IsSameType::value) { + DataCopyPad(xInLocalTensor, xGm_[row * expertCount_], dataCopyParams, dataCopyPadParams); + } else { + DataCopyPad(xInLocalTensor[expertCountAlign_].ReinterpretCast(), xGm_[row * expertCount_], dataCopyParams, + dataCopyPadParams); + } + xInQueue_.EnQue(xInLocalTensor); +} + +template +__aicore__ inline void MoeGatingTopKWithoutGroup::ComputeX() +{ + LocalTensor xNormTensor = xNormBuf_.Get(); + LocalTensor xInLocalTensor = xInQueue_.DeQue(); + LocalTensor xNormWithBiasTensor = xNormWithBiasBuf_.Get(); + LocalTensor biasTensor = biasBuf_.Get(); + + if constexpr (!IsSameType::value) { + Cast(xInLocalTensor, xInLocalTensor[expertCountAlign_].ReinterpretCast(), RoundMode::CAST_NONE, + expertCount_); + PipeBarrier(); + } + + if (normType_ == 1) { // sigmoid + LocalTensor calcNormTmpTensor = calcTmpBuf_.Get(); + Sigmoid(xNormTensor, xInLocalTensor, calcNormTmpTensor, expertCount_); + PipeBarrier(); + } else if (normType_ == 0) { // softmax + LocalTensor reduceValueTensor = calcTmpBuf_.Get(); + LocalTensor calcTmp = calcTmpBuf_.Get()[8]; + ReduceMax(reduceValueTensor, xInLocalTensor, calcTmp, expertCount_); + event_t eventIdVToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(eventIdVToS); + WaitFlag(eventIdVToS); + float maxValue = reduceValueTensor.GetValue(0); + event_t eventIdSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIdSToV); + WaitFlag(eventIdSToV); + Adds(xNormTensor, xInLocalTensor, -maxValue, expertCount_); + PipeBarrier(); + Exp(xNormTensor, xNormTensor, expertCount_); + PipeBarrier(); + ReduceSum(reduceValueTensor, xNormTensor, calcTmp, expertCount_); + eventIdVToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(eventIdVToS); + WaitFlag(eventIdVToS); + float sumValue = reduceValueTensor.GetValue(0); + eventIdSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIdSToV); + WaitFlag(eventIdSToV); + Duplicate(xInLocalTensor, sumValue, expertCount_); + PipeBarrier(); + Div(xNormTensor, xNormTensor, xInLocalTensor, expertCount_); + PipeBarrier(); + } + if (addBias_) { + Add(xNormWithBiasTensor, xNormTensor, biasTensor, expertCount_); + } else { + DataCopy(xNormWithBiasTensor, xNormTensor, expertCountAlign_); + } + + int64_t duplicateNum = expertCount_ % ONE_REPEAT_SORT_NUM; + int duplicateIndex = expertCount_ - duplicateNum; + if (duplicateNum > 0) { + uint64_t mask0 = UINT64_MAX; + mask0 = mask0 << duplicateNum; + mask0 = mask0 & (UINT64_MAX >> ONE_REPEAT_SORT_NUM); + uint64_t mask[2] = {mask0, 0}; + Duplicate(xNormWithBiasTensor.ReinterpretCast()[duplicateIndex], FLOAT32_NEG_INF, mask, 1, 1, 1); + PipeBarrier(); + } + xInQueue_.FreeTensor(xInLocalTensor); +} + +template +__aicore__ inline void MoeGatingTopKWithoutGroup::CopuOutXNorm(int64_t row) +{ + LocalTensor outOutTensor = outOutQueue_.AllocTensor(); + LocalTensor xNormTensor = xNormBuf_.Get(); + DataCopy(outOutTensor, xNormTensor, expertCountAlign_); + outOutQueue_.EnQue(outOutTensor); + outOutTensor = outOutQueue_.DeQue(); + DataCopyExtParams dataCopyParams{1, static_cast(expertCount_ * sizeof(float)), 0, 0, 0}; + DataCopyPad(outGm_[row * expertCount_], outOutTensor, dataCopyParams); + outOutQueue_.FreeTensor(outOutTensor); +} + +template +__aicore__ inline void MoeGatingTopKWithoutGroup::SelectTopKExpertIdx() +{ + LocalTensor expertIdxOut = expertIdxOutQueue_.AllocTensor(); + LocalTensor xNormWithBiasTensor = xNormWithBiasBuf_.Get(); + LocalTensor expertIdTensor = expertIdBuf_.Get(); + LocalTensor topKExpertId = topKExpertIdBuf_.Get(); + LocalTensor sortedScore = calcTmpBuf_.Get(); + LocalTensor sortTmp = calcTmpBuf_.Get()[expertCountAlign_ * CONSTANT_TWO]; + PipeBarrier(); + Sort(sortedScore, xNormWithBiasTensor, expertIdTensor, sortTmp, + expertCountAlign_ / ONE_REPEAT_SORT_NUM); + + GatherMaskParams gatherMaskParams; + gatherMaskParams.repeatTimes = Ceil(k_ * sizeof(float) * CONSTANT_TWO, REPEAT_BYTES); + gatherMaskParams.src0BlockStride = 1; + gatherMaskParams.src0RepeatStride = REPEAT_BLOCKS; + gatherMaskParams.src1RepeatStride = 0; + + uint64_t rsvdCnt = 0; // 用于保存筛选后保留下来的元素个数 + uint8_t src1Pattern = 2; // 内置固定模式 + PipeBarrier(); + GatherMask(topKExpertId, sortedScore.template ReinterpretCast(), src1Pattern, false, + static_cast(0), gatherMaskParams, rsvdCnt); + + DataCopy(expertIdxOut, topKExpertId, expertCountAlign_); + expertIdxOutQueue_.EnQue(expertIdxOut); +} + +template +__aicore__ inline void MoeGatingTopKWithoutGroup::SelectTopKExpertScore() +{ + LocalTensor xNormTensor = xNormBuf_.Get(); + LocalTensor yOutTensor = yOutQueue_.AllocTensor(); + LocalTensor topKExpertId = topKExpertIdBuf_.Get(); + LocalTensor topKExpertIdWithByte = calcTmpBuf_.Get(); + PipeBarrier(); + Muls(topKExpertIdWithByte, topKExpertId, static_cast(sizeof(float)), k_); + PipeBarrier(); + Gather(yOutTensor, xNormTensor, topKExpertIdWithByte.template ReinterpretCast(), static_cast(0), + k_); + bool needRenorm = (normType_ == 1) || // 情况1:sigmoid + renorm + (normType_ == 0 && renorm_ == 1); // 情况3:softmax + renorm + if (needRenorm == 1) { + LocalTensor maxValueTensor = calcTmpBuf_.Get(); + LocalTensor tmpTensor = calcTmpBuf_.Get()[BLOCK_BYTES]; + PipeBarrier(); + ReduceSum(maxValueTensor, yOutTensor, tmpTensor, k_); + event_t eventIdVToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_S)); + SetFlag(eventIdVToS); + WaitFlag(eventIdVToS); + float sumValue = maxValueTensor.GetValue(0) + tilingData_->eps; + event_t eventIdSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIdSToV); + WaitFlag(eventIdSToV); + Duplicate(tmpTensor, sumValue, k_); + PipeBarrier(); + Div(yOutTensor, yOutTensor, tmpTensor, k_); + } + + PipeBarrier(); + Muls(yOutTensor, yOutTensor, tilingData_->routedScalingFactor, k_); + + if constexpr (!IsSameType::value) { + PipeBarrier(); + Cast(yOutTensor.ReinterpretCast(), yOutTensor, RoundMode::CAST_RINT, k_); + } + + yOutQueue_.EnQue(yOutTensor); +} + +template +__aicore__ inline void MoeGatingTopKWithoutGroup::SelectExpertIdxByHash(int64_t row) +{ + LocalTensor expertIdxOut = expertIdxOutQueue_.AllocTensor(); + LocalTensor hashExpertId = topKExpertIdBuf_.Get(); + LocalTensor hashExpertIdInt32 = hashExpertId.template ReinterpretCast(); + U1 key = inputIdsGm_.GetValue(row); + SetWaitFlag(HardEvent::S_MTE2); + DataCopyExtParams dataCopyParams{1, static_cast(k_ * sizeof(U2)), 0, 0, 0}; + DataCopyPadExtParams dataCopyPadParams{false, 0, 0, static_cast(0)}; + DataCopyPad(hashExpertId, tid2eidGm_[key * k_], dataCopyParams, dataCopyPadParams); + SetWaitFlag(HardEvent::MTE2_V); + if constexpr (IsSameType::value) { + DataCopy(expertIdxOut, hashExpertId, Align(k_, sizeof(int32_t))); + } else { + Cast(hashExpertIdInt32, hashExpertId, RoundMode::CAST_NONE, Align(k_, sizeof(U2))); + PipeBarrier(); + DataCopy(expertIdxOut, hashExpertIdInt32, Align(k_, sizeof(int32_t))); + } + expertIdxOutQueue_.EnQue(expertIdxOut); +} + +template +__aicore__ inline void MoeGatingTopKWithoutGroup::CopyOut(int64_t row) +{ + LocalTensor yOutTensor = yOutQueue_.DeQue(); + LocalTensor expertIdxOut = expertIdxOutQueue_.DeQue(); + DataCopyExtParams dataCopyParams{1, static_cast(k_ * sizeof(T)), 0, 0, 0}; + DataCopyPad(yGm_[row * k_], yOutTensor, dataCopyParams); + dataCopyParams.blockLen = k_ * sizeof(int32_t); + DataCopyPad(expertIdxGm_[row * k_], expertIdxOut, dataCopyParams); + yOutQueue_.FreeTensor(yOutTensor); + expertIdxOutQueue_.FreeTensor(expertIdxOut); +} + +template +__aicore__ inline void MoeGatingTopKWithoutGroup::Init( + GM_ADDR x, GM_ADDR bias, GM_ADDR inputIds, GM_ADDR tid2eid, + GM_ADDR y, GM_ADDR expertIdx, GM_ADDR out, GM_ADDR workspace, + const MoeGatingTopKTilingData *tilingData, TPipe *tPipe) +{ + tilingData_ = tilingData; + pipe_ = tPipe; + blockIdx_ = GetBlockIdx(); + perCoreRowCount_ = tilingData_->perCoreRowCount; + if (blockIdx_ == GetBlockNum() - 1) { + curCoreRowCount_ = tilingData_->lastCoreRowCount; + } else { + curCoreRowCount_ = tilingData_->perCoreRowCount; + } + expertCount_ = tilingData_->expertCount; + addBias_ = tilingData_->addBias == 1; + outFlag_ = tilingData_->outFlag == 1; + hashFlag_ = tilingData_->hashFlag == 1; + k_ = tilingData_->k; + renorm_ = tilingData_->renorm; + normType_ = tilingData_->normType; + expertCountAlign_ = Ceil(expertCount_, ONE_REPEAT_SORT_NUM) * ONE_REPEAT_SORT_NUM; + + // init input gm buf + xGm_.SetGlobalBuffer((__gm__ T *)x + perCoreRowCount_ * expertCount_ * blockIdx_, expertCount_); + biasGm_.SetGlobalBuffer((__gm__ T *)bias, expertCount_); + if (hashFlag_) { + inputIdsGm_.SetGlobalBuffer((__gm__ U1 *)inputIds); + tid2eidGm_.SetGlobalBuffer((__gm__ U2 *)tid2eid); + } + + // init output gm buf + yGm_.SetGlobalBuffer((__gm__ T *)y + perCoreRowCount_ * k_ * blockIdx_, k_); + expertIdxGm_.SetGlobalBuffer((__gm__ int32_t *)expertIdx + perCoreRowCount_ * k_ * blockIdx_, k_); + outGm_.SetGlobalBuffer((__gm__ float *)out + perCoreRowCount_ * expertCount_ * blockIdx_, expertCount_); + + // init que + pipe_->InitBuffer(xInQueue_, 1, expertCountAlign_ * sizeof(float) * (sizeof(float) / sizeof(T))); + pipe_->InitBuffer(yOutQueue_, 1, Align(k_, sizeof(float)) * sizeof(float)); + pipe_->InitBuffer(expertIdxOutQueue_, 1, Align(k_, sizeof(float)) * sizeof(int32_t)); + pipe_->InitBuffer(outOutQueue_, 1, expertCountAlign_ * sizeof(float)); + + // init calc buf + pipe_->InitBuffer(biasBuf_, expertCountAlign_ * sizeof(float) * (sizeof(float) / sizeof(T))); + pipe_->InitBuffer(expertIdBuf_, expertCountAlign_ * sizeof(int32_t)); + pipe_->InitBuffer(xNormBuf_, expertCountAlign_ * sizeof(float)); + pipe_->InitBuffer(xNormWithBiasBuf_, expertCountAlign_ * sizeof(float)); + pipe_->InitBuffer(topKExpertIdBuf_, Align(k_, sizeof(U2)) * sizeof(U2)); + + // init tmp buf + pipe_->InitBuffer(calcTmpBuf_, expertCountAlign_ * sizeof(float) * CONSTANT_EIGHT); +} + +template +__aicore__ inline void MoeGatingTopKWithoutGroup::Process() +{ + CopyInBiasAndInitExpertId(); + for (int64_t row = 0; row < curCoreRowCount_; row++) { + CopyInX(row); + ComputeX(); + if (outFlag_) { + CopuOutXNorm(row); + } + if (hashFlag_) { + SelectExpertIdxByHash(row + perCoreRowCount_ * blockIdx_); + } else { + SelectTopKExpertIdx(); + } + SelectTopKExpertScore(); + CopyOut(row); + } +} +} // namespace MoeGatingTopK +#endif // MOE_GATING_TOP_K_E_K_WITHOUT_GROUP_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/test_data/cases_manifest.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/test_data/cases_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..a28cb47ccaa299adbae6b7e02e73827b919a96b8 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/test_data/cases_manifest.json @@ -0,0 +1,206 @@ +{ + "op_name": "moe_gating_top_k", + "op_camel": "MoeGatingTopK", + "output_keys": [ + "y", + "expert_idx", + "out" + ], + "cases": [ + { + "id": 0, + "dtype": "fp32", + "x_shape": [ + 4, + 64 + ], + "attrs": { + "k": 8, + "kg": 1, + "gc": 1, + "gsm": 0, + "ren": 1, + "nt": 0, + "of": true, + "rsf": 1.5, + "eps": 1e-12 + } + }, + { + "id": 1, + "dtype": "fp16", + "x_shape": [ + 3, + 256 + ], + "attrs": { + "k": 8, + "kg": 4, + "gc": 8, + "gsm": 1, + "ren": 0, + "nt": 1, + "of": true, + "rsf": 1.0, + "eps": 1e-20, + "bias": true + } + }, + { + "id": 2, + "dtype": "bf16", + "x_shape": [ + 5, + 128 + ], + "attrs": { + "k": 2, + "kg": 2, + "gc": 4, + "gsm": 0, + "ren": 0, + "nt": 1, + "of": true, + "rsf": 0.5, + "eps": 1e-20, + "bias": true + } + }, + { + "id": 3, + "dtype": "fp16", + "x_shape": [ + 6, + 32 + ], + "attrs": { + "k": 16, + "kg": 1, + "gc": 1, + "gsm": 0, + "ren": 0, + "nt": 0, + "of": true, + "rsf": 2.0, + "eps": 1e-06, + "bias": true + } + }, + { + "id": 4, + "dtype": "fp32", + "x_shape": [ + 2, + 512 + ], + "attrs": { + "k": 4, + "kg": 4, + "gc": 16, + "gsm": 0, + "ren": 0, + "nt": 1, + "of": true, + "rsf": 1.0, + "eps": 1e-20 + } + }, + { + "id": 5, + "dtype": "fp16", + "x_shape": [ + 9, + 2048 + ], + "attrs": { + "k": 32, + "kg": 1, + "gc": 1, + "gsm": 0, + "ren": 0, + "nt": 1, + "of": true, + "rsf": 1.0, + "eps": 1e-20 + } + }, + { + "id": 6, + "dtype": "bf16", + "x_shape": [ + 4, + 64 + ], + "attrs": { + "k": 8, + "kg": 8, + "gc": 8, + "gsm": 1, + "ren": 0, + "nt": 0, + "of": true, + "rsf": 1.0, + "eps": 1e-20, + "bias": true + } + }, + { + "id": 7, + "dtype": "fp32", + "x_shape": [ + 1, + 128 + ], + "attrs": { + "k": 4, + "kg": 4, + "gc": 4, + "gsm": 1, + "ren": 0, + "nt": 1, + "of": true, + "rsf": 0.1, + "eps": 1e-20 + } + }, + { + "id": 8, + "dtype": "fp16", + "x_shape": [ + 7, + 64 + ], + "attrs": { + "k": 16, + "kg": 2, + "gc": 2, + "gsm": 1, + "ren": 0, + "nt": 1, + "of": true, + "rsf": 1.0, + "eps": 1e-20, + "bias": true + } + }, + { + "id": 9, + "dtype": "bf16", + "x_shape": [ + 2, + 300 + ], + "attrs": { + "k": 32, + "kg": 1, + "gc": 1, + "gsm": 0, + "ren": 1, + "nt": 0, + "of": true, + "rsf": 1.0, + "eps": 1e-20 + } + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..a005fa6f5f422a0b2f06fe88e7db4e7d408547c8 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/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.moe.moe_gating_top_k.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() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/st/aclnnMoeGatingTopK/atk_aclnnMoeGatingTopK.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/st/aclnnMoeGatingTopK/atk_aclnnMoeGatingTopK.json new file mode 100644 index 0000000000000000000000000000000000000000..008691fb4331b097acd471f2ad9da48708627629 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/st/aclnnMoeGatingTopK/atk_aclnnMoeGatingTopK.json @@ -0,0 +1 @@ +[{"id": 0, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.004, "bf16_error": 0.004}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 20, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 1, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [2, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 2, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [2, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 9, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 5, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 3, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [2, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 14, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 4, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 11, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 5, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 24, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 6, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 41, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 7, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 121, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 8, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 9, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 23, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 10, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 18, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 11, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 56, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 12, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 13, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 14, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 25, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 15, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 28, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 16, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 15, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 17, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [4, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 41, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 18, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [2, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 118, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 19, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [2, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 123, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 20, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [2, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 94, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 21, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [5, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 31, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 22, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [5, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 23, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [5, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 24, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [5, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 32, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 25, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [6, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 22, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 26, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 27, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [6, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 17, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 28, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 16, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 29, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [6, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 30, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 82, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 31, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 77, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 32, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 170, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 33, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 21, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 34, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 31, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 35, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 79, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 36, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 28, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 37, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 91, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 38, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 39, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 40, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 41, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 39, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 42, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 54, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 43, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 31, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 44, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 31, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 45, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 46, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 36, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 47, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 63, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 48, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 49, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [4, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 46, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 50, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [9, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 51, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [10, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 45, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 52, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [10, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 41, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 53, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [10, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 54, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [11, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 28, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 55, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 13, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 56, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 73, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 57, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [5, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 18, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 58, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [2, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 133, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 59, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [5, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 84, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 60, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [2, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 18, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 61, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [5, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 97, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 62, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [5, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 42, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 63, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [5, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 90, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 64, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [2, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 198, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 65, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [5, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 39, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 66, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 53, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 67, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [12, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 68, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [12, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 19, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 69, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [12, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 70, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [6, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 71, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [6, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 23, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 72, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [6, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 32, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 73, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [13, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 74, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [6, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 35, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 75, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [6, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 118, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 76, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 55, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 77, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [14, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 26, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 78, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [14, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 79, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 21, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 80, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 14, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 81, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 62, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 82, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 22, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 83, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 84, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 15, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 85, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 21, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 86, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 49, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 87, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 252, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 88, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [7, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 89, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 178, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 90, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 22, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 91, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 55, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 92, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [7, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 124, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 93, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 94, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 5, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 94, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [7, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 61, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 95, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [7, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 64, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 96, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 97, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 77, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 98, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 25, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 5, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 99, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 52, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 100, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 64], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [64], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 19, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 5, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 101, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 5, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 102, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 67, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 103, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 5, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 104, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 47, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 105, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 106, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 107, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 13, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 108, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [4, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 96, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 109, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 11, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 110, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [4, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 62, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 111, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [4, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 112, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [4, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 62, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 113, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [4, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 14, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 114, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 117, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 115, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [4, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 113, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 116, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [10, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 15, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 117, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [10, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 26, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 118, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [10, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 51, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 119, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [10, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 58, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 120, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [10, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 94, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 121, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [5, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 110, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 122, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [11, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 95, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 123, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [5, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 58, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 124, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [11, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 125, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [11, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 101, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 126, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [5, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 204, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 127, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [5, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 106, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 128, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [11, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 129, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [11, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 110, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 130, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [11, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 131, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 58, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 132, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [12, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 113, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 133, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 134, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [12, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 22, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 135, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [12, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 57, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 136, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [12, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 46, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 137, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [12, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 34, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 138, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [6, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 123, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 139, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 17, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 140, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [6, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 42, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 141, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 24, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 142, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [13, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 112, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 143, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [13, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 144, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [13, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 115, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 145, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 105, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 146, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 232, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 147, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [13, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 13, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 148, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [6, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 132, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 149, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [6, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 45, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 150, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [6, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 103, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 151, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [13, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 17, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 5, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 152, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [14, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 18, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 153, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 154, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 62, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 155, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 109, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 156, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 87, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 157, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 77, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 158, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 43, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 159, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [7, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 46, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 160, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 102, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 161, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 45, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 162, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 50, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 163, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 171, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 164, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 165, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 128], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [128], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 63, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 166, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 112, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 167, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 168, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [9, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 30, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 169, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 85, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 170, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 12, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 171, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 172, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 205, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 173, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 151, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 174, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 30, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 175, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 249, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 176, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [10, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 26, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 177, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [10, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 113, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 178, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [10, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 57, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 179, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [10, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 6, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 180, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [11, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 90, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 181, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [11, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 91, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 182, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [11, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 110, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 183, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [11, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 94, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 184, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [11, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 56, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 185, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [11, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 62, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 186, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [11, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 76, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 187, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [12, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 31, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 7, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 188, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [12, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 149, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 189, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [12, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 108, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 190, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 254, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 191, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [12, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 11, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 192, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [12, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 93, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 193, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [13, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 83, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 5, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 194, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [14, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 142, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 195, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [14, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 20, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 196, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [14, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 127, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 197, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [14, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 83, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 198, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 51, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 199, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [14, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 83, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 200, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [14, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 94, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 201, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 61, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 202, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 44, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 203, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 204, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 129, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 205, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 206, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [16, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 26, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 3, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 207, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 163, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 208, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 113, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 2, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "backward": false, "align_32B": null, "outlier_values": null}]}, {"id": 209, "name": "aclnnMoeGatingTopK", "aclnn_name": "aclnnMoeGatingTopK", "api_type": "function_MoeGatingTopK", "aclnn_api_type": "function_aclnnMoeGatingTopK", "standard": {"acc": {"single_bm": {"type": "high_precision", "fp16_error": 0.00390625, "bf16_error": 0.00390625}}, "perf": "not_key"}, "inputs": [{"name": "x", "type": "tensor", "required": true, "dtype": "fp32", "shape": [16, 256], "range_values": {"name": "nd", "mean": [0], "std": [0.01]}, "backward": true, "align_32B": null, "outlier_values": null}, {"name": "bias", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256], "range_values": [-1, 1], "backward": true, "align_32B": null, "outlier_values": null}, {"name": "k", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 8, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "k_group", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_count", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 4, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "group_select_mode", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "renorm", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "norm_type", "type": "attr", "required": true, "dtype": "int64_t", "shape": null, "range_values": 0, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "out_flag", "type": "attr", "required": true, "dtype": "attr_bool", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "routed_scaling_factor", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1, "backward": false, "align_32B": null, "outlier_values": null}, {"name": "eps", "type": "attr", "required": true, "dtype": "double", "shape": null, "range_values": 1e-20, "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/moe_gating_top_k/tests/st/aclnnMoeGatingTopK/executor_aclnnMoeGatingTopK.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/st/aclnnMoeGatingTopK/executor_aclnnMoeGatingTopK.py new file mode 100644 index 0000000000000000000000000000000000000000..1a7ba3ca0268c5361926e11c492909d42ca660dc --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/st/aclnnMoeGatingTopK/executor_aclnnMoeGatingTopK.py @@ -0,0 +1,125 @@ +# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. + +import numpy as np +import torch +from atk.configs.dataset_config import InputDataset +from atk.configs.results_config import TaskResult +from atk.tasks.api_execute import register +from atk.tasks.api_execute.base_api import BaseApi +from atk.tasks.api_execute.aclnn_base_api import AclnnBaseApi + + +@register("function_MoeGatingTopK") +class MoeGatingTopKMethod(BaseApi): + def __init__(self, task_result: TaskResult): + super(MoeGatingTopKMethod, self).__init__(task_result) + + @staticmethod + def softmax_func(x, axis=None): + # print("before softmax:",x) + if "float16" in x.dtype.name: + x = x.astype(np.float32) + x_max = x.max(axis=axis, keepdims=True) + x_sub = x - x_max + y = np.exp(x_sub) + x_sum = y.sum(axis=axis, keepdims=True) + # print(" x_sum:",x_sum) + ans = y / x_sum + # print(" ans:",ans) + return ans, x_max, x_sum + + def single_golden(self, x, k, bias, k_group, group_count, group_select_mode, renorm, + norm_type, y2_flag, routed_scaling_factor, eps): + dtype = x.dtype + # Convert to float32 if needed + if dtype != torch.float32: + x = x.to(torch.float32) + if bias is not None: + bias = bias.to(torch.float32) + + # Convert to numpy and process + x = x.numpy() + if bias is not None: + bias = bias.numpy() + + # softmax/ sigmoid processing + if norm_type == 0: + x, _, _ = self.softmax_func(x, axis=-1) + else: + x = 1 / (1 + np.exp(-x)) + + original_x = x + if bias is not None: + x = x + bias + + # group count processing + if group_count > 1: + x = x.reshape(x.shape[0], group_count, -1) + if group_select_mode == 0: + group_x = np.amax(x, axis=-1) + else: + group_x = np.partition(x, -2, axis=-1)[..., -2:].sum(axis=-1) + + indices = np.argsort(-group_x, axis=-1, kind='stable')[:, :k_group] + + mask = np.ones((x.shape[0], group_count), dtype=bool) + mask[np.arange(x.shape[0])[:, None], indices] = False + x = np.where(mask[..., None], float('-inf'), x).reshape(x.shape[0], -1) + + # Topk indices and gather + _, indices = torch.sort(torch.from_numpy(x), dim=-1, stable=True, descending=True) + indices = np.asarray(indices[:, :k]).astype(np.int32) + + y = np.take_along_axis(original_x, indices, axis=1) + + # Renorm and scaling + if norm_type == 1 or renorm == 1: + y /= (np.sum(y, axis=-1, keepdims=True) + eps) + y *= routed_scaling_factor + + # Process y2 if needed + if y2_flag: + y2 = torch.from_numpy(original_x).to(dtype) + else: + y2 = None + + # Convert back to torch tensors + y = torch.from_numpy(np.asarray(y)).to(dtype) + indices = torch.from_numpy(indices).to(torch.int32) + + return y, indices, y2.to(torch.float32) + + def __call__(self, input_data: InputDataset, with_output: bool = False): + if self.device == "cpu": + output = self.single_golden( + input_data.kwargs["x"], + input_data.kwargs["k"], + input_data.kwargs["bias"], + input_data.kwargs["k_group"], + input_data.kwargs["group_count"], + input_data.kwargs["group_select_mode"], + input_data.kwargs["renorm"], + input_data.kwargs["norm_type"], + input_data.kwargs["out_flag"], + input_data.kwargs["routed_scaling_factor"], + input_data.kwargs["eps"], + ) + return output + + + +@register("function_aclnnMoeGatingTopK") +class MoeGatingTopKAclnnApi(AclnnBaseApi): + def __call__(self): + super().__call__() + + def init_by_input_data(self, input_data: InputDataset): + input_args, output_packages = super().init_by_input_data(input_data) + return input_args, output_packages + + def after_call(self, output_packages): + output = [] + for output_pack in output_packages: + output.append(self.acl_tensor_to_torch(output_pack)) + + return output \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..94b120d1f8579069544f91c6792d06d5a9e10c1a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/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/moe_gating_top_k/tests/ut/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9947844423c100b61da61fe6a9cd60bcba6a5745 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/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/moe_gating_top_k/tests/ut/op_host/test_moe_gating_top_k_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_host/test_moe_gating_top_k_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1559ea2a9d120089654fc26061068a24bf7fd579 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_host/test_moe_gating_top_k_infershape.cpp @@ -0,0 +1,275 @@ +/** + * 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_moe_gating_top_k_infershape.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 MoeGatingTopK : public testing::Test +{ +protected: + static void SetUpTestCase() + { + std::cout << "MoeGatingTopK SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "MoeGatingTopK TearDown" << std::endl; + } +}; + +TEST_F(MoeGatingTopK, moe_gating_top_k_infer_shape_00) +{ + gert::InfershapeContextPara infershapeContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(1.0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }); + std::vector> expectOutputShape = {{16, 8}, {16, 8}, {16, 256}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(MoeGatingTopK, moe_gating_top_k_infer_shape_01) +{ + gert::InfershapeContextPara infershapeContextPara("MoeGatingTopK", + { + {{{-2}, {-2}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{-2}, {-2}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(1.0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }); + std::vector> expectOutputShape = {{-1, 8}, {-1, 8}, {-1, -1}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(MoeGatingTopK, moe_gating_top_k_infer_shape_02) +{ + gert::InfershapeContextPara infershapeContextPara("MoeGatingTopK", + { + {{{-1, -1}, {-1, -1}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{-2}, {-2}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(1.0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }); + std::vector> expectOutputShape = {{-1, 8}, {-1, 8}, {-1, -1}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(MoeGatingTopK, moe_gating_top_k_infer_shape_03) +{ + gert::InfershapeContextPara infershapeContextPara("MoeGatingTopK", + { + {{{-1, -1}, {-1, -1}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{-1}, {-1}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(1.0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }); + std::vector> expectOutputShape = {{-1, 8}, {-1, 8}, {-1, -1}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(MoeGatingTopK, moe_gating_top_k_infer_shape_fail_01) +{ + gert::InfershapeContextPara infershapeContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(-1)}, + }); + ExecuteTestCase(infershapeContextPara, ge::GRAPH_FAILED, {}); +} + +TEST_F(MoeGatingTopK, moe_gating_top_k_infer_shape_fail_02) +{ + gert::InfershapeContextPara infershapeContextPara("MoeGatingTopK", + { + {{{16}, {16}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + }); + ExecuteTestCase(infershapeContextPara, ge::GRAPH_FAILED, {}); +} + +TEST_F(MoeGatingTopK, moe_gating_top_k_infer_shape_fail_03) +{ + gert::InfershapeContextPara infershapeContextPara("MoeGatingTopK", + { + {{{1, 2, 3}, {1, 2, 3}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + }); + ExecuteTestCase(infershapeContextPara, ge::GRAPH_FAILED, {}); +} + +TEST_F(MoeGatingTopK, moe_gating_top_k_infer_shape_fail_04) +{ + gert::InfershapeContextPara infershapeContextPara("MoeGatingTopK", + { + {{{-3, 256}, {-3, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + }); + ExecuteTestCase(infershapeContextPara, ge::GRAPH_FAILED, {}); +} + +TEST_F(MoeGatingTopK, moe_gating_top_k_infer_datatype_00) +{ + ge::DataType xType = ge::DT_FLOAT16; + ge::DataType biasType = ge::DT_FLOAT16; + ge::DataType yType = ge::DT_UNDEFINED; + ge::DataType expertType = ge::DT_UNDEFINED; + ge::DataType outType = ge::DT_UNDEFINED; + + auto contextHolder = gert::InferDataTypeContextFaker() + .NodeIoNum(2, 3) + .NodeInputTd(0, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(1, ge::DT_FLOAT16, ge::FORMAT_ND, ge::FORMAT_ND) + .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({&xType, &biasType}) + .OutputDataTypes({&yType, &expertType, &outType}) + .Build(); + + auto spaceRegistry = gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry(); + ASSERT_NE(spaceRegistry, nullptr); + auto inferDtypeFunc = spaceRegistry->GetOpImpl("MoeGatingTopK")->infer_datatype; + ASSERT_NE(inferDtypeFunc, nullptr); + auto context = contextHolder.GetContext(); + EXPECT_EQ(inferDtypeFunc(context), ge::GRAPH_SUCCESS); + EXPECT_EQ(context->GetOutputDataType(0), ge::DT_FLOAT16); + EXPECT_EQ(context->GetOutputDataType(1), ge::DT_INT32); + EXPECT_EQ(context->GetOutputDataType(2), ge::DT_FLOAT); +} + +TEST_F(MoeGatingTopK, moe_gating_top_k_infer_datatype_01) +{ + ge::DataType xType = ge::DT_FLOAT; + ge::DataType biasType = ge::DT_FLOAT; + ge::DataType yType = ge::DT_UNDEFINED; + ge::DataType expertType = ge::DT_UNDEFINED; + ge::DataType outType = ge::DT_UNDEFINED; + + auto contextHolder = gert::InferDataTypeContextFaker() + .NodeIoNum(2, 3) + .NodeInputTd(0, ge::DT_FLOAT, ge::FORMAT_ND, ge::FORMAT_ND) + .NodeInputTd(1, 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) + .NodeOutputTd(2, ge::FORMAT_ND, ge::FORMAT_ND) + .InputDataTypes({&xType, &biasType}) + .OutputDataTypes({&yType, &expertType, &outType}) + .Build(); + + auto spaceRegistry = gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry(); + ASSERT_NE(spaceRegistry, nullptr); + auto inferDtypeFunc = spaceRegistry->GetOpImpl("MoeGatingTopK")->infer_datatype; + ASSERT_NE(inferDtypeFunc, nullptr); + auto context = contextHolder.GetContext(); + EXPECT_EQ(inferDtypeFunc(context), ge::GRAPH_SUCCESS); + EXPECT_EQ(context->GetOutputDataType(0), ge::DT_FLOAT); + EXPECT_EQ(context->GetOutputDataType(1), ge::DT_INT32); + EXPECT_EQ(context->GetOutputDataType(2), ge::DT_FLOAT); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_host/test_moe_gating_top_k_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_host/test_moe_gating_top_k_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ec31b3fe9a08dec917f430da9aa66c52e49c33d9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_host/test_moe_gating_top_k_tiling.cpp @@ -0,0 +1,730 @@ +/** + * 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_moe_gating_top_k_tiling.cpp + * \brief + */ + +#include +#include +#include "tiling_context_faker.h" +#include "tiling_case_executor.h" +#include "op_tiling_parse_context_builder.h" +#include "base/registry/op_impl_space_registry_v2.h" +#include "../../../op_host/moe_gating_top_k_tiling.h" + +using namespace std; + +class MoeGatingTopKTiling : public testing::Test +{ +protected: + static void SetUpTestCase() + { + std::cout << "MoeGatingTopKTiling SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "MoeGatingTopKTiling 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(MoeGatingTopKTiling, moe_gating_top_k_tiling_succ_01) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo); + uint64_t expectTilingKey = 0; + string expectTilingData = "16 16 1 1 256 1 8 4 8 32 32 1 0 1 0 0 0 1024 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_succ_02) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }, + &compileInfo); + uint64_t expectTilingKey = 1; + string expectTilingData = "16 16 1 1 256 1 8 1 1 256 256 1 0 1 0 0 2178868143328329728 1024 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_succ_03) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 64}, {16, 64}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{64}, {64}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 64}, {16, 64}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }, + &compileInfo); + uint64_t expectTilingKey = 1; + string expectTilingData = "16 16 1 1 64 1 8 8 8 8 32 0 0 0 0 1 2178868142262976512 256 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_succ_04) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 72}, {16, 72}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{72}, {72}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 72}, {16, 72}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(5)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(9)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }, + &compileInfo); + uint64_t expectTilingKey = 2; + string expectTilingData = "16 16 1 1 72 1 8 5 9 8 32 1 0 0 0 1 2178868142262976512 384 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_fail_01) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(-1)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo); + uint64_t expectTilingKey = 10000; + string expectTilingData = "16 16 1 1 256 1 8 1 1 256 256 1 0 1 0 0 2178868143328329728 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_fail_02) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(33)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo); + uint64_t expectTilingKey = 10000; + string expectTilingData = "16 16 1 1 256 1 8 1 1 256 256 1 0 1 0 0 2178868143328329728 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_fail_03) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(-1)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo); + uint64_t expectTilingKey = 10000; + string expectTilingData = "16 16 1 1 256 1 8 1 1 256 256 1 0 1 0 0 2178868143328329728 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_fail_04) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(3)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo); + uint64_t expectTilingKey = 2; + string expectTilingData = "16 16 1 1 256 1 8 3 8 32 32 1 0 1 0 0 0 1024 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_fail_05) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo); + uint64_t expectTilingKey = 10000; + string expectTilingData = "16 16 1 1 256 1 8 1 1 256 256 1 0 1 0 0 2178868143328329728 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_fail_06) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(9)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo); + uint64_t expectTilingKey = 10000; + string expectTilingData = "16 16 1 1 256 1 8 1 1 256 256 1 0 1 0 0 2178868143328329728 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_fail_07) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(3)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo); + uint64_t expectTilingKey = 10000; + string expectTilingData = "16 16 1 1 256 1 8 1 1 256 256 1 0 1 0 0 2178868143328329728 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_fail_08) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo); + uint64_t expectTilingKey = 2; + string expectTilingData = "16 16 1 1 256 1 8 4 8 32 32 0 0 1 0 0 0 1024 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_fail_09) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(-1)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo); + uint64_t expectTilingKey = 10000; + string expectTilingData = "16 16 1 1 256 1 8 1 1 256 256 1 0 1 0 0 2178868143328329728 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_fail_10) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(2)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo); + uint64_t expectTilingKey = 10000; + string expectTilingData = "16 16 1 1 256 1 8 1 1 256 256 1 0 1 0 0 2178868143328329728 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_fail_11) { + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group",Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count",Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode",Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type",Ops::Transformer::AnyValue::CreateFrom(2)}, + {"out_flag",Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor",Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps",Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo); + uint64_t expectTilingKey = 10000; + string expectTilingData = "16 16 1 1 256 1 8 1 1 256 256 1 0 1 0 0 2178868143328329728 0 "; + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_parse_succ_01) +{ + gert::OpTilingParseContextBuilder builder; + auto holder = builder.Build(); + auto parseContext = holder.GetContext(); + + auto spaceRegistry = gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry(); + ASSERT_NE(spaceRegistry, nullptr); + auto opImpl = spaceRegistry->GetOpImpl("MoeGatingTopK"); + ASSERT_NE(opImpl, nullptr); + ASSERT_NE(opImpl->tiling_parse, nullptr); + + auto ret = opImpl->tiling_parse(reinterpret_cast(parseContext)); + EXPECT_EQ(ret, ge::GRAPH_SUCCESS); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_regbase_succ_01) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", + Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", + Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_regbase_succ_02) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_select_mode", + Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", + Ops::Transformer::AnyValue::CreateFrom(1)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_regbase_succ_03) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 64}, {16, 64}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{64}, {64}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 64}, {16, 64}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", + Ops::Transformer::AnyValue::CreateFrom(0)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", + Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_regbase_succ_04) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 72}, {16, 72}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{72}, {72}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 72}, {16, 72}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(5)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(9)}, + {"group_select_mode", + Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", + Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_regbase_fail_01) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(-1)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", + Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", + Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_regbase_fail_02) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", + Ops::Transformer::AnyValue::CreateFrom(3)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", + Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTiling, moe_gating_top_k_tiling_regbase_fail_03) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara("MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", + Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", + Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_host/test_moe_gating_top_k_tiling_arch35.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_host/test_moe_gating_top_k_tiling_arch35.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07e1b0aee310759e3635f67c5733558194669274 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_host/test_moe_gating_top_k_tiling_arch35.cpp @@ -0,0 +1,1089 @@ +/** + * 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_moe_gating_top_k_tiling_arch35.cpp + * \brief + */ + +#include +#include +#include "tiling_context_faker.h" +#include "tiling_case_executor.h" +#include "op_tiling_parse_context_builder.h" +#include "base/registry/op_impl_space_registry_v2.h" +#include "../../../op_host/moe_gating_top_k_tiling.h" + +using namespace std; + +class MoeGatingTopKTilingArch35 : public testing::Test { +protected: + static void SetUpTestCase() + { + std::cout << "MoeGatingTopKTilingArch35 SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "MoeGatingTopKTilingArch35 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(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_succ_01) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_succ_02) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_succ_03) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 64}, {16, 64}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{64}, {64}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 64}, {16, 64}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_succ_04) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 72}, {16, 72}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{72}, {72}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 72}, {16, 72}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(5)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(9)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_succ_05_norm_type_softplus) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_succ_06_renorm_l1) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(1e-20f)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_succ_07_group_select_mode_max) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_succ_08_fp16) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_succ_09_bf16) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_succ_10_no_bias) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_succ_11_simplified_path_kgroup_eq_groupcount) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_succ_12_simplified_path_groupcount_eq_expertcount) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10000, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_fail_01_invalid_k) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(-1)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_fail_02_invalid_k_exceed_expert) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(33)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_fail_03_invalid_k_group) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(-1)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_fail_04_invalid_group_count_zero) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_fail_05_expert_not_divisible_by_group) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(9)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_fail_06_invalid_group_select_mode) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_fail_07_invalid_renorm) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(-1)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_fail_08_invalid_renorm_value) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_fail_09_invalid_norm_type) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(3)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_fail_10_kgroup_exceed_groupcount) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(9)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_fail_11_k_exceed_kgroup_times_groupexpert) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 64}, {16, 64}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{64}, {64}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 64}, {16, 64}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10000, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_hash_succ_01_inputids_int32_tid2eid_int64) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{8, 256}, {8, 256}}, ge::DT_INT64, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10001, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_hash_succ_02_inputids_int32_tid2eid_int32) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{8, 256}, {8, 256}}, ge::DT_INT32, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10002, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_hash_succ_03_inputids_int64_tid2eid_int64) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{8, 256}, {8, 256}}, ge::DT_INT64, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10003, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_hash_succ_04_inputids_int64_tid2eid_int32) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{8, 256}, {8, 256}}, ge::DT_INT32, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10004, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_hash_succ_05_groupcount_eq_expertcount) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{8, 256}, {8, 256}}, ge::DT_INT64, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + std::vector expectWorkspaces = {16777216}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, 10001, "", expectWorkspaces); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_hash_fail_01_k_exceed_64) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 65}, {16, 65}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{65, 256}, {65, 256}}, ge::DT_INT64, ge::FORMAT_ND}, + }, + { + {{{16, 65}, {16, 65}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 65}, {16, 65}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(65)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10001, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_hash_fail_02_tid2eid_dim1_not_eq_k) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{4, 256}, {4, 256}}, ge::DT_INT64, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10001, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_hash_fail_03_inputids_dim0_not_eq_rows) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{8, 8}, {8, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{8, 256}, {8, 256}}, ge::DT_INT64, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10001, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_hash_fail_04_non_simplified_path) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{8, 256}, {8, 256}}, ge::DT_INT64, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10001, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_hash_fail_05_inputids_invalid_dtype) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{8, 256}, {8, 256}}, ge::DT_INT64, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10001, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_hash_fail_06_tid2eid_invalid_dtype) +{ + optiling::MoeGatingTopKCompileInfo compileInfo = {}; + gert::TilingContextPara tilingContextPara( + "MoeGatingTopK", + { + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{256}, {256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{8, 256}, {8, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{16, 8}, {16, 8}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{16, 8}, {16, 8}}, ge::DT_INT32, ge::FORMAT_ND}, + {{{16, 256}, {16, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {"k", Ops::Transformer::AnyValue::CreateFrom(8)}, + {"k_group", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_count", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"group_select_mode", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"renorm", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"norm_type", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"out_flag", Ops::Transformer::AnyValue::CreateFrom(false)}, + {"routed_scaling_factor", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"eps", Ops::Transformer::AnyValue::CreateFrom(0)}, + }, + &compileInfo, "Ascend950"); + ExecuteTestCase(tilingContextPara, ge::GRAPH_FAILED, 10001, "", {}); +} + +TEST_F(MoeGatingTopKTilingArch35, moe_gating_top_k_tiling_arch35_parse_succ_01) +{ + gert::OpTilingParseContextBuilder builder; + auto holder = builder.Build(); + auto parseContext = holder.GetContext(); + + auto spaceRegistry = gert::DefaultOpImplSpaceRegistryV2::GetInstance().GetSpaceRegistry(); + ASSERT_NE(spaceRegistry, nullptr); + auto opImpl = spaceRegistry->GetOpImpl("MoeGatingTopK"); + ASSERT_NE(opImpl, nullptr); + ASSERT_NE(opImpl->tiling_parse, nullptr); + + auto ret = opImpl->tiling_parse(reinterpret_cast(parseContext)); + EXPECT_EQ(ret, ge::GRAPH_SUCCESS); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_kernel/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_kernel/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..b38db1a4f9f81d267d58c14802ac9ae094ed28b2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_kernel/CMakeLists.txt @@ -0,0 +1,36 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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依赖的文件添加到CMakeLists.txt中 + # set(elewise_common_tiling_files + # ${CANN_ROOT}/ops/built-in/op_tiling/runtime/elewise_tiling.cc + # ) + # 算子自己的tiling文件路径 + set(moe_gating_top_k_tiling_files + ${CMAKE_CURRENT_SOURCE_DIR}/../../../op_host/moe_gating_top_k_tiling.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../../../op_host/moe_gating_top_k_tiling_arch35.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/../../../op_host/moe_gating_top_k_tiling_base.cpp + ) + # 使用AddOpTestCase + # param1:算子名称,以kernel方式命名 + # param2:soc版本,多个以分号分隔,例如:"Ascend950PR_9599;AscendB1" + # param3:自定义编译选项,一般填写测试的一种典型数据类型组合,不需要则传入空字符串,例如:"-DDTYPE_X=float",多个使用空格分隔,例如:"-DDTYPE_X=float -DDTYPE_Y=float" + # param4:该算子依赖的所有tiling源码文件 + AddOpTestCase(moe_gating_top_k "ascend910B1" "-DDTYPE_X=float" "${moe_gating_top_k_tiling_files}") +endif() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_kernel/moe_gating_top_k_tiling.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_kernel/moe_gating_top_k_tiling.h new file mode 100644 index 0000000000000000000000000000000000000000..ff3815d16ad11717a169b315bb5ea7104e308c52 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_kernel/moe_gating_top_k_tiling.h @@ -0,0 +1,112 @@ +/** + * 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 moe_gating_top_k_tiling.h + * \brief + */ + +#ifndef __MOE_INIT_ROUTING_TILING_H__ +#define __MOE_INIT_ROUTING_TILING_H__ + +#include +#include + +#include "kernel_tiling/kernel_tiling.h" + +#pragma pack(1) +struct MoeGatingTopKTilingData { + int64_t needCoreNum = 0; + int64_t rowCount = 0; + int64_t perCoreRowCount = 0; + int64_t lastCoreRowCount = 0; + int64_t expertCount = 0; + int64_t addBias; + int64_t k = 0; + int64_t kGroup = 0; + int64_t groupCount = 0; + int64_t perGroupExpertCount = 0; + int64_t perGroupExpertCountAlign = 0; + int64_t groupSelectMode = 0; + int64_t renorm = 0; + int64_t normType = 0; + int64_t outFlag = 0; + int64_t vmsCount = 0; + float routedScalingFactor = 0; + float eps = 0; + int64_t calTmpBufUbSize = 0; + bool hashFlag = false; +}; +#pragma pack() + +#pragma pack(1) +struct MoeGatingTopKRegbaseTilingData { + int64_t needCoreNum = 0; + int64_t rowCount = 0; + int64_t perCoreRowCount = 0; + int64_t lastCoreRowCount = 0; + int64_t expertCount = 0; + int64_t addBias; + int64_t k = 0; + int64_t kGroup = 0; + int64_t groupCount = 0; + int64_t perGroupExpertCount = 0; + int64_t perGroupExpertCountAlign = 0; + int64_t groupSelectMode = 0; + int64_t renorm = 0; + int64_t normType = 0; + int64_t outFlag = 0; + int64_t vmsCount = 0; + float routedScalingFactor = 0; + float eps = 0; +}; +#pragma pack() + +#ifdef __NPU_TILING__ +inline[aicore] void InitTilingData(const __gm__ uint8_t *tiling, MoeGatingTopKTilingData *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(MoeGatingTopKTilingData) / 4; i++) + *(dst + i) = *(src + i); +} +#else +inline void InitTilingData(uint8_t *tiling, MoeGatingTopKTilingData *const_data) +{ + memcpy(const_data, tiling, sizeof(MoeGatingTopKTilingData)); +} +#endif + +#ifdef __NPU_TILING__ +inline[aicore] void InitTilingData(const __gm__ uint8_t *tiling, MoeGatingTopKRegbaseTilingData *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(MoeGatingTopKRegbaseTilingData) / 4; i++) + *(dst + i) = *(src + i); +} +#else +inline void InitTilingData(uint8_t *tiling, MoeGatingTopKRegbaseTilingData *const_data) +{ + memcpy(const_data, tiling, sizeof(MoeGatingTopKRegbaseTilingData)); +} +#endif + +#define GET_TILING_DATA_WITH_STRUCT(tiling_struct, tiling_data, tiling_arg) \ + tiling_struct tiling_data; \ + InitTilingData(tiling_arg, &tiling_data) + +#define GET_TILING_DATA(tiling_data, tiling_arg) \ + MoeGatingTopKTilingData tiling_data; \ + InitTilingData(tiling_arg, &tiling_data) + +#define DTYPE_X float + +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_kernel/test_moe_gating_top_k.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_kernel/test_moe_gating_top_k.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9adffdc609a2153990b418ef73b348533dfc8d7b --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_gating_top_k/tests/ut/op_kernel/test_moe_gating_top_k.cpp @@ -0,0 +1,166 @@ +/** + * 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_moe_gating_top_k.cpp + * \brief + */ + +#include +#include +#include +#include +#include +#include "gtest/gtest.h" +#include "tikicpulib.h" +#include "data_utils.h" +#include "tiling_case_executor.h" +#include "moe_gating_top_k_tiling.h" + +using namespace std; + +extern "C" __global__ __aicore__ void moe_gating_top_k( + uint8_t* x, uint8_t* bias, uint8_t* inputIds, uint8_t* tid2eid, uint8_t* y, uint8_t* expertIdx, uint8_t* out, + uint8_t* workspace, uint8_t* tiling); + +class moe_gating_top_k_test : public testing::Test +{ +protected: + static void SetUpTestCase() + { + cout << "moe_gating_top_k_test SetUp\n" << endl; + } + static void TearDownTestCase() + { + cout << "moe_gating_top_k_test TearDown\n" << endl; + } +}; + +TEST_F(moe_gating_top_k_test, test_case_0) +{ + size_t n = 16; + size_t k = 8; + size_t h = 256; + uint64_t tilingKey = 0; + uint32_t blockDim = 16; + + size_t x_FileSize = n * h * sizeof(float); + size_t bias_FileSize = n * h * sizeof(float); + size_t y_FileSize = n * k * sizeof(float); + size_t expertIdx_FileSize = n * k * sizeof(int32_t); + size_t out_FileSize = n * h * sizeof(float); + size_t workspace_FileSize = 16781184; + size_t tiling_FileSize = sizeof(MoeGatingTopKTilingData); + + uint8_t* x = (uint8_t*)AscendC::GmAlloc(x_FileSize); + uint8_t* bias = (uint8_t*)AscendC::GmAlloc(bias_FileSize); + uint8_t* y = (uint8_t*)AscendC::GmAlloc(y_FileSize); + uint8_t* expertIdx = (uint8_t*)AscendC::GmAlloc(expertIdx_FileSize); + uint8_t* out = (uint8_t*)AscendC::GmAlloc(out_FileSize); + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(workspace_FileSize); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_FileSize); + MoeGatingTopKTilingData* tiling_data = reinterpret_cast(tiling); + tiling_data->groupSelectMode = 1; + tiling_data->renorm = 0; + tiling_data->normType = 1; + tiling_data->groupCount = 8; + + ICPU_SET_TILING_KEY(tilingKey); + // ICPU_RUN_KF(moe_gating_top_k, blockDim, x, bias, y, expertIdx, out, workspace, (uint8_t*)tiling_data); + + AscendC::GmFree((void*)x); + AscendC::GmFree((void*)bias); + AscendC::GmFree((void*)y); + AscendC::GmFree((void*)expertIdx); + AscendC::GmFree((void*)out); + AscendC::GmFree((void*)workspace); + AscendC::GmFree((void*)tiling); +} + +TEST_F(moe_gating_top_k_test, test_case_1) +{ + size_t n = 16; + size_t k = 8; + size_t h = 256; + uint64_t tilingKey = 1; + uint32_t blockDim = 16; + + size_t x_FileSize = n * h * sizeof(float); + size_t bias_FileSize = n * h * sizeof(float); + size_t y_FileSize = n * k * sizeof(float); + size_t expertIdx_FileSize = n * k * sizeof(int32_t); + size_t out_FileSize = n * h * sizeof(float); + size_t workspace_FileSize = 16781184; + size_t tiling_FileSize = sizeof(MoeGatingTopKTilingData); + + uint8_t* x = (uint8_t*)AscendC::GmAlloc(x_FileSize); + uint8_t* bias = (uint8_t*)AscendC::GmAlloc(bias_FileSize); + uint8_t* y = (uint8_t*)AscendC::GmAlloc(y_FileSize); + uint8_t* expertIdx = (uint8_t*)AscendC::GmAlloc(expertIdx_FileSize); + uint8_t* out = (uint8_t*)AscendC::GmAlloc(out_FileSize); + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(workspace_FileSize); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_FileSize); + MoeGatingTopKTilingData* tiling_data = reinterpret_cast(tiling); + tiling_data->groupSelectMode = 1; + tiling_data->renorm = 0; + tiling_data->normType = 1; + tiling_data->groupCount = 1; + + ICPU_SET_TILING_KEY(tilingKey); + // ICPU_RUN_KF(moe_gating_top_k, blockDim, x, bias, y, expertIdx, out, workspace, (uint8_t *)tiling_data); + + AscendC::GmFree((void*)x); + AscendC::GmFree((void*)bias); + AscendC::GmFree((void*)y); + AscendC::GmFree((void*)expertIdx); + AscendC::GmFree((void*)out); + AscendC::GmFree((void*)workspace); + AscendC::GmFree((void*)tiling); +} + +TEST_F(moe_gating_top_k_test, test_case_2) +{ + size_t n = 16; + size_t k = 8; + size_t h = 64; + uint64_t tilingKey = 2; + uint32_t blockDim = 16; + + size_t x_FileSize = n * h * sizeof(float); + size_t bias_FileSize = n * h * sizeof(float); + size_t y_FileSize = n * k * sizeof(float); + size_t expertIdx_FileSize = n * k * sizeof(int32_t); + size_t out_FileSize = n * h * sizeof(float); + size_t workspace_FileSize = 16781184; + size_t tiling_FileSize = sizeof(MoeGatingTopKTilingData); + + uint8_t* x = (uint8_t*)AscendC::GmAlloc(x_FileSize); + uint8_t* bias = (uint8_t*)AscendC::GmAlloc(bias_FileSize); + uint8_t* y = (uint8_t*)AscendC::GmAlloc(y_FileSize); + uint8_t* expertIdx = (uint8_t*)AscendC::GmAlloc(expertIdx_FileSize); + uint8_t* out = (uint8_t*)AscendC::GmAlloc(out_FileSize); + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(workspace_FileSize); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tiling_FileSize); + MoeGatingTopKTilingData* tiling_data = reinterpret_cast(tiling); + tiling_data->groupSelectMode = 0; + tiling_data->renorm = 0; + tiling_data->normType = 0; + tiling_data->groupCount = 8; + + ICPU_SET_TILING_KEY(tilingKey); + // ICPU_RUN_KF(moe_gating_top_k, blockDim, x, bias, y, expertIdx, out, workspace, (uint8_t *)tiling_data); + AscendC::GmFree((void*)x); + AscendC::GmFree((void*)bias); + AscendC::GmFree((void*)y); + AscendC::GmFree((void*)tiling); + AscendC::GmFree((void*)expertIdx); + AscendC::GmFree((void*)out); + AscendC::GmFree((void*)workspace); +} diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..86b308249e318f7c5c97436daf1546e9cb362d96 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/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/moe_token_unpermute/README.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5a91872c1e3903f7b8af7bd4ac0b152658d1b8ce --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/README.md @@ -0,0 +1,127 @@ +# MoeTokenUnpermute + +## 产品支持情况 + +| 产品 | 是否支持 | +| :----------------------------------------------------------- |:-------:| +| Ascend 950PR/Ascend 950DT | √ | +| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | √ | +| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | √ | +| Atlas 200I/500 A2 推理产品 | × | +| Atlas 推理系列产品 | × | +| Atlas 训练系列产品 | × | +| Kirin X90 处理器系列产品 | √ | +| Kirin 9030 处理器系列产品 | √ | + +## 功能说明 + +- 算子功能:根据sortedIndices存储的下标,获取permutedTokens中存储的输入数据;如果存在probs数据,permutedTokens会与probs相乘;最后进行累加求和,并输出计算结果。 +- 计算公式: + + - probs非None时,计算公式如下: + + $$ + T[k] = T[S[k]] + $$ + + $$ + T[k] = T[k] * P[i][j] + $$ + + $$ + O[i] = \sum_{k=i*topK}^{(i+1)*topK - 1 } T[k] + $$ + + 其中$i \in {0,1,...,tokens-1}$;$j \in {0,1,...,topK-1}$;$k \in {0,1,...,tokens*topK-1}$;T表示permutedTokens;S表示sortedIndices;P表示probs;O表示out;topK表示topK\_num,表示处理每个token的专家个数;tokens表示tokens_num,表示输入token的个数。 + + - probs为None时,此时topK\_num=1,计算公式如下: + + $$ + T[i] = T[S[i]] + $$ + + $$ + O[i] = T[i] + $$ + + 其中 $i \in {0,1,...,tokens-1}$;T表示permutedTokens;S表示sortedIndices;O表示out;tokens表示tokens_num。 + +## 参数说明 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出/属性描述数据类型数据格式
permutedTokens输入待计算输入,对应公式中的`T`。FLOAT16、BFLOAT16、FLOAT32ND
sortedIndices输入表示需要计算的数据在permutedTokens中的位置,对应公式中的`S`。INT32ND
probsOptional可选输入对应公式中的`P`。FLOAT16、BFLOAT16、FLOAT32ND
paddedMode属性目前仅支持false。BOOL-
restoreShapeOptional属性目前仅支持nullptr。aclIntArray*-
out输出对应公式中的`O`。FLOAT16、BFLOAT16、FLOAT32ND
+ +- Kirin X90/Kirin 9030 处理器系列产品: 不支持BFLOAT16。 + +## 约束说明 + +- Atlas A2 训练系列产品/Atlas A2 推理系列产品、Atlas A3 训练系列产品/Atlas A3 推理系列产品:topK_num <= 512。 +- Ascend 950PR/Ascend 950DT: + 在调用本接口时,框架内部会调用`aclnnMoeFinalizeRoutingV2`接口,如果出现参数错误提示,请参考以下参数映射关系: + - permutedTokens输入等同于aclnnMoeFinalizeRoutingV2接口的expandedX输入。 + - sortedIndices输入等同于aclnnMoeFinalizeRoutingV2接口的expandedRowIdx输入。 + - probsOptional输入等同于aclnnMoeFinalizeRoutingV2接口的scalesOptional输入。 + - paddedMode输入等同于aclnnMoeFinalizeRoutingV2接口的dropPadMode输入。 + - out输出等同于aclnnMoeFinalizeRoutingV2接口的out输出。 +- |Atlas 推理系列产品: + - permutedTokens与probsOptional支持的数据类型为FLOAT16、FLOAT32。 + - topK_num <= 512。 + - hiddensize是128的倍数且小于10240。 + +## 调用说明 + +| 调用方式 | 样例代码 | 说明 | +| ---------------- | --------------------------- | --------------------------------------------------- | +| aclnn接口 | [test_aclnn_moe_token_unpermute](examples/test_aclnn_moe_token_unpermute.cpp) | 通过[aclnnMoeTokenUnpermute](docs/aclnnMoeTokenUnpermute.md)接口方式调用MoeTokenUnpermute算子。 | diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/moe_token_unpermute_collect.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/moe_token_unpermute_collect.py new file mode 100644 index 0000000000000000000000000000000000000000..67b304e159570ab07c879ca8d7ffa467bdee2858 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/moe_token_unpermute_collect.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +"""Collect golden data for moe_token_unpermute by running the NPU operator on every case. + +Re-run ONLY after an intentional kernel change — this overwrites the regression baseline. + +# case_0: in=[permuted_tokens:float16[16, 64], sorted_indices:int32[16], probs:float16[8, 2], padded_mode=False] -> out=[unpermuted_tokens:float16] +# case_1: in=[permuted_tokens:float16[64, 128], sorted_indices:int32[64], probs:float16[16, 4], padded_mode=False] -> out=[unpermuted_tokens:float16] +# case_2: in=[permuted_tokens:bfloat16[64, 64], sorted_indices:int32[64], probs:bfloat16[32, 2], padded_mode=False] -> out=[unpermuted_tokens:bfloat16] +# case_3: in=[permuted_tokens:float32[12, 256], sorted_indices:int32[12], probs:float32[4, 3], padded_mode=False] -> out=[unpermuted_tokens:float32] +# case_4: in=[permuted_tokens:float16[8, 128], sorted_indices:int32[8], padded_mode=False] -> out=[unpermuted_tokens:float16] +# case_5: in=[permuted_tokens:bfloat16[160, 256], sorted_indices:int32[160], probs:bfloat16[20, 8], padded_mode=False] -> out=[unpermuted_tokens:bfloat16] +# case_6: in=[permuted_tokens:float16[128, 64], sorted_indices:int32[128], probs:float16[64, 2], padded_mode=False] -> out=[unpermuted_tokens:float16] +# case_7: in=[permuted_tokens:float32[512, 512], sorted_indices:int32[512], probs:float32[128, 4], padded_mode=False] -> out=[unpermuted_tokens:float32] +# case_8: in=[permuted_tokens:bfloat16[512, 128], sorted_indices:int32[512], probs:bfloat16[256, 2], padded_mode=False] -> out=[unpermuted_tokens:bfloat16] +# case_9: in=[permuted_tokens:float16[30, 32], sorted_indices:int32[30], probs:float16[10, 3], padded_mode=False] -> out=[unpermuted_tokens:float16] +""" +import json, os, sys +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "moe_token_unpermute" +OP_CAMEL = "MoeTokenUnpermute" +DEVICE = "npu:0" +SEED = 2026 + +# Actual binding signature: +# _raw_moe_token_unpermute(x, sorted_indices, probs, padded_mode, restore_shape, out_tmpl) +PARAM_NAMES = ["permuted_tokens", "sorted_indices", "probs", "padded_mode", "restore_shape"] +OUTPUT_KEYS = ["unpermuted_tokens"] + +# 10 cases: mix of dtypes (fp16/bf16/fp32), with-probs and without-probs variants +CASES = [ + {"id": 0, "dtype": torch.float16, "shape": (16, 64), "with_probs": True, "topk": 2, "padded_mode": False}, + {"id": 1, "dtype": torch.float16, "shape": (64, 128), "with_probs": True, "topk": 4, "padded_mode": False}, + {"id": 2, "dtype": torch.bfloat16, "shape": (64, 64), "with_probs": True, "topk": 2, "padded_mode": False}, + {"id": 3, "dtype": torch.float32, "shape": (12, 256), "with_probs": True, "topk": 3, "padded_mode": False}, + {"id": 4, "dtype": torch.float16, "shape": (8, 128), "with_probs": False, "topk": 1, "padded_mode": False}, + {"id": 5, "dtype": torch.bfloat16, "shape": (160, 256), "with_probs": True, "topk": 8, "padded_mode": False}, + {"id": 6, "dtype": torch.float16, "shape": (128, 64), "with_probs": True, "topk": 2, "padded_mode": False}, + {"id": 7, "dtype": torch.float32, "shape": (512, 512), "with_probs": True, "topk": 4, "padded_mode": False}, + {"id": 8, "dtype": torch.bfloat16, "shape": (512, 128), "with_probs": True, "topk": 2, "padded_mode": False}, + {"id": 9, "dtype": torch.float16, "shape": (30, 32), "with_probs": True, "topk": 3, "padded_mode": False}, +] + +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.""" + torch.manual_seed(SEED + case["id"]) + dtype, shape = case["dtype"], case["shape"] + topk = case["topk"] + + # permuted_tokens: [num_permuted_tokens, hidden] + num_permuted = shape[0] + hidden = shape[1] + permuted_tokens = torch.randn(num_permuted, hidden, dtype=torch.float32, device=DEVICE).to(dtype) + + # sorted_indices: [num_permuted_tokens] — int32 indices into permuted_tokens + sorted_indices = torch.arange(num_permuted, dtype=torch.int32, device=DEVICE) + # Shuffle to make it non-trivial + perm = torch.randperm(num_permuted, device=DEVICE) + sorted_indices = sorted_indices[perm].to(torch.int32) + + inputs = { + "permuted_tokens": permuted_tokens, + "sorted_indices": sorted_indices, + "padded_mode": case["padded_mode"], + } + + if case["with_probs"]: + # probs: [num_unpermuted_tokens, topk] where num_unpermuted_tokens = num_permuted // topk + num_unpermuted = num_permuted // topk + probs = torch.randn(num_unpermuted, topk, dtype=torch.float32, device=DEVICE).to(dtype) + inputs["probs"] = probs + + return inputs + + +def make_output_buf(case): + """Shape/dtype for the single output.""" + dtype = case["dtype"] + topk = case["topk"] + num_permuted = case["shape"][0] + hidden = case["shape"][1] + if case["with_probs"]: + num_unpermuted = num_permuted // topk + else: + num_unpermuted = num_permuted + return (num_unpermuted, hidden), dtype + + +def build_call_args(case): + inputs = make_inputs(case) + args = [] + for pname in PARAM_NAMES: + if pname in inputs: + args.append(inputs[pname]) + elif pname == "probs": + args.append(None) + elif pname == "padded_mode": + args.append(inputs.get("padded_mode", False)) + elif pname == "restore_shape": + # restore_shape is the original shape before permutation; use input shape + args.append(list(case["shape"])) + else: + raise KeyError(f"Missing param '{pname}' for case_{case['id']}") + return args, inputs + + +def collect_case(case): + call_args, inputs = build_call_args(case) + + out_shape, out_dtype = make_output_buf(case) + out_buf = torch.empty(out_shape, dtype=out_dtype, device=DEVICE) + + # out_tmpl is the LAST positional argument + outputs = ops.npu_moe_token_unpermute(*call_args, out_buf) + 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") + + # Save inputs (tensors on CPU, others as-is) + saved_in = {} + for k, v in inputs.items(): + if isinstance(v, torch.Tensor): + saved_in[k] = v.cpu() + else: + saved_in[k] = v + 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.', '')}") + elif isinstance(val, list): + parts.append(f"{name}=[{len(val)}]") + 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" {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": list(case["shape"]), + "attrs": {k: v for k, v in case.items() if k not in ("id", "dtype", "shape")}, + }) + 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/moe_token_unpermute/moe_token_unpermute_test.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/moe_token_unpermute_test.py new file mode 100644 index 0000000000000000000000000000000000000000..13d71f91835fded2da87b2ea7a6d04b3c4fb3f3f --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/moe_token_unpermute_test.py @@ -0,0 +1,231 @@ +#!/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_ 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 = "moe_token_unpermute" +OP_CAMEL = "MoeTokenUnpermute" +DEVICE = "npu:0" + +# Actual binding signature (from op_desc inputs + attrs): +# _raw_moe_token_unpermute(permuted_tokens, sorted_indices, probs, +# padded_mode, restore_shape, out_tmpl) +PARAM_NAMES = ["permuted_tokens", "sorted_indices", "probs", "padded_mode", "restore_shape"] +# Order in which the operator returns its outputs. +OUTPUT_KEYS = ["unpermuted_tokens"] + +# 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 it. 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. Optional params are simply omitted from the dict. + call_kwargs = {} + for pname in PARAM_NAMES: + if pname == "restore_shape": + # restore_shape is the original (unpermuted) tensor shape — + # i.e. the shape of the output tensor before permutation was applied. + call_kwargs["restore_shape"] = list(golden["unpermuted_tokens"].shape) + elif pname == "probs": + # probs is optional — only include if present + if "probs" in input_data: + call_kwargs["probs"] = input_data["probs"].to(DEVICE) + elif pname not in input_data: + raise KeyError(f"{name}: missing param '{pname}' in golden_input") + else: + 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 buffer from the golden tensor — this also checks shape and dtype. + out_buf = None + for k in OUTPUT_KEYS: + if k in golden: + out_buf = torch.empty_like(golden[k]).to(DEVICE) + break + # Call by keyword — the wrapper (binding.py) exposes 'out' (not 'out_tmpl'), + # which it forwards as out_tmpl= to the raw pybind func. + outputs = ops.npu_moe_token_unpermute(**call_kwargs, out=out_buf) + 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/moe_token_unpermute/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..16061882d0ef0af9939b2002c946d13e8a429d2d --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/CMakeLists.txt @@ -0,0 +1,26 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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 (BUILD_OPEN_PROJECT) + set(moe_token_unpermute_depends moe/moe_finalize_routing_v2 CACHE INTERNAL "Dependencies for moe_token_unpermute") + target_sources(op_host_aclnnInner PRIVATE + moe_token_unpermute_def.cpp + ) + add_ops_compile_options( + OP_NAME MoeTokenUnpermute + OPTIONS --cce-auto-sync=on + -Wno-deprecated-declarations + -Werror + ) +endif() + +if(NOT BUILD_OPS_RTY_KERNEL) + add_modules_sources(OPTYPE moe_token_unpermute ACLNNTYPE aclnn_inner) +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend310p/moe_token_unpermute_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend310p/moe_token_unpermute_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..5aa1e254058ef616e6d871c08b437934935f47e8 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend310p/moe_token_unpermute_binary.json @@ -0,0 +1,241 @@ +{ + "op_type": "MoeTokenUnpermute", + "op_list": [ + { + "bin_filename": "MoeTokenUnpermute_fp16_int32_fp16_false", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_fp32_int32_fp32_false", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_fp16_int32_fp32_false", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_fp32_int32_fp16_false", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend310p/moe_token_unpermute_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend310p/moe_token_unpermute_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..00f9fd27ed2ce80d3d13d8868bcf3952609ce8bf --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend310p/moe_token_unpermute_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 中配置的算子名字和对于的平台决定 +[MoeTokenUnpermute] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend910_93/moe_token_unpermute_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend910_93/moe_token_unpermute_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..e29416c5afd72775f5d5da273d5cc2aba910ab0a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend910_93/moe_token_unpermute_binary.json @@ -0,0 +1,536 @@ +{ + "op_type": "MoeTokenUnpermute", + "op_list": [ + { + "bin_filename": "MoeTokenUnpermute_0", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_1", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_2", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_3", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_4", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_5", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_6", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_7", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_8", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend910_93/moe_token_unpermute_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend910_93/moe_token_unpermute_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..00f9fd27ed2ce80d3d13d8868bcf3952609ce8bf --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend910_93/moe_token_unpermute_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 中配置的算子名字和对于的平台决定 +[MoeTokenUnpermute] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend910b/moe_token_unpermute_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend910b/moe_token_unpermute_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..e29416c5afd72775f5d5da273d5cc2aba910ab0a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend910b/moe_token_unpermute_binary.json @@ -0,0 +1,536 @@ +{ + "op_type": "MoeTokenUnpermute", + "op_list": [ + { + "bin_filename": "MoeTokenUnpermute_0", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_1", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_2", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_3", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_4", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_5", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_6", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_7", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_8", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend910b/moe_token_unpermute_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend910b/moe_token_unpermute_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..00f9fd27ed2ce80d3d13d8868bcf3952609ce8bf --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/ascend910b/moe_token_unpermute_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 中配置的算子名字和对于的平台决定 +[MoeTokenUnpermute] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/kirin9030/moe_token_unpermute_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/kirin9030/moe_token_unpermute_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..5aa1e254058ef616e6d871c08b437934935f47e8 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/kirin9030/moe_token_unpermute_binary.json @@ -0,0 +1,241 @@ +{ + "op_type": "MoeTokenUnpermute", + "op_list": [ + { + "bin_filename": "MoeTokenUnpermute_fp16_int32_fp16_false", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_fp32_int32_fp32_false", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_fp16_int32_fp32_false", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_fp32_int32_fp16_false", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/kirin9030/moe_token_unpermute_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/kirin9030/moe_token_unpermute_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..00f9fd27ed2ce80d3d13d8868bcf3952609ce8bf --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/kirin9030/moe_token_unpermute_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 中配置的算子名字和对于的平台决定 +[MoeTokenUnpermute] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/kirinx90/moe_token_unpermute_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/kirinx90/moe_token_unpermute_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..5aa1e254058ef616e6d871c08b437934935f47e8 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/kirinx90/moe_token_unpermute_binary.json @@ -0,0 +1,241 @@ +{ + "op_type": "MoeTokenUnpermute", + "op_list": [ + { + "bin_filename": "MoeTokenUnpermute_fp16_int32_fp16_false", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_fp32_int32_fp32_false", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_fp16_int32_fp32_false", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + }, + { + "bin_filename": "MoeTokenUnpermute_fp32_int32_fp16_false", + "inputs": [ + { + "name": "permuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "sorted_indices", + "index": 1, + "dtype": "int32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + }, + { + "name": "probs", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "optional", + "shape": [ + -2 + ] + } + ], + "outputs": [ + { + "name": "unpermuted_tokens", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [ + -2 + ] + } + ], + "attrs": [ + { + "name": "padded_mode", + "dtype": "bool", + "value": false + }, + { + "name": "restore_shape", + "dtype": "list_int", + "value": [] + } + ] + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/kirinx90/moe_token_unpermute_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/kirinx90/moe_token_unpermute_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..00f9fd27ed2ce80d3d13d8868bcf3952609ce8bf --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/config/kirinx90/moe_token_unpermute_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 中配置的算子名字和对于的平台决定 +[MoeTokenUnpermute] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/moe_token_unpermute_def.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/moe_token_unpermute_def.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6931ebb746aa17974114e50687545ddf395c1ef4 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/moe_token_unpermute_def.cpp @@ -0,0 +1,123 @@ +/** + * 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 moe_token_unpermute_def.cpp + * \brief + */ +#include "register/op_def_registry.h" + +namespace ops { +class MoeTokenUnpermute : public OpDef +{ +public: + explicit MoeTokenUnpermute(const char* name) : OpDef(name) + { + this->Input("permuted_tokens") + .ParamType(REQUIRED) + .DataType( + {ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT16, ge::DT_FLOAT16, 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, 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, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("sorted_indices") + .ParamType(REQUIRED) + .DataType( + {ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, + ge::DT_INT32, ge::DT_INT32}) + .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, 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, ge::FORMAT_ND}) + .AutoContiguous(); + this->Input("probs") + .ParamType(OPTIONAL) + .DataType( + {ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_BF16, + ge::DT_FLOAT16, 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, 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, ge::FORMAT_ND}) + .AutoContiguous(); + + this->Attr("padded_mode").AttrType(OPTIONAL).Bool(false); + this->Attr("restore_shape").AttrType(OPTIONAL).ListInt(); + + this->Output("unpermuted_tokens") + .ParamType(REQUIRED) + .DataType( + {ge::DT_BF16, ge::DT_BF16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_FLOAT16, ge::DT_FLOAT16, 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, 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, ge::FORMAT_ND}); + + this->AICore().AddConfig("ascend910b"); + this->AICore().AddConfig("ascend910_93"); + + OpAICoreConfig config310p; + config310p.DynamicCompileStaticFlag(true).DynamicFormatFlag(true).DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true).NeedCheckSupportFlag(false).PrecisionReduceFlag(true); + config310p.Input("permuted_tokens") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT16, ge::DT_FLOAT16, 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}) + .AutoContiguous(); + config310p.Input("sorted_indices") + .ParamType(REQUIRED) + .DataType({ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, ge::DT_INT32, + ge::DT_INT32, ge::DT_INT32}) + .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}) + .AutoContiguous(); + config310p.Input("probs") + .ParamType(OPTIONAL) + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_FLOAT, + ge::DT_FLOAT16, 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}) + .AutoContiguous(); + config310p.Output("unpermuted_tokens") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT16, ge::DT_FLOAT16, ge::DT_FLOAT16, 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->AICore().AddConfig("ascend310p",config310p); + this->AICore().AddConfig("kirinx90",config310p); + this->AICore().AddConfig("kirin9030",config310p); + } +}; + +OP_ADD(MoeTokenUnpermute); +} // namespace ops diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/moe_token_unpermute_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/moe_token_unpermute_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56cd57f05c3242069c0ddc0b3e82a3e497d2aae5 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/moe_token_unpermute_infershape.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. + */ + +/*! + * \file moe_token_unpermute_infershape.cpp + * \brief + */ +#include "log/log.h" +#include "register/op_impl_registry.h" +#include "util/math_util.h" +#include "util/shape_util.h" +using namespace ge; + +namespace ops { +static ge::graphStatus InferShapeForMoeTokenUnpermute(gert::InferShapeContext* context) +{ + const gert::Shape* permuted_inputs_shape = context->GetInputShape(0); + const gert::Shape* probs_shape = context->GetInputShape(2); + int64_t tokens_num; + if (probs_shape == nullptr) { + const gert::Shape* indices_shape = context->GetInputShape(1); + tokens_num = indices_shape->GetDim(0); + } else { + tokens_num = probs_shape->GetDim(0); + } + + gert::Shape* out_shape = context->GetOutputShape(0); + const int8_t out_dim_num = 2; + out_shape->SetDimNum(out_dim_num); + out_shape->SetDim(0, tokens_num); + out_shape->SetDim(1, permuted_inputs_shape->GetDim(1)); + + return GRAPH_SUCCESS; +} + +static ge::graphStatus InferDataTypeForMoeTokenUnpermute(gert::InferDataTypeContext* context) +{ + context->SetOutputDataType(0, context->GetInputDataType(0)); + return GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(MoeTokenUnpermute) + .InferShape(InferShapeForMoeTokenUnpermute) + .InferDataType(InferDataTypeForMoeTokenUnpermute); +} // namespace ops diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/moe_token_unpermute_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/moe_token_unpermute_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..74344c0a098e3818a88ce9aacee60029e434cccb --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/moe_token_unpermute_tiling.cpp @@ -0,0 +1,379 @@ +/** + * 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 moe_token_unpermute_tiling.cpp + * \brief + */ +#include "moe_token_unpermute_tiling.h" + +namespace optiling { + +ge::graphStatus TilingMoeTokenUnpermute(gert::TilingContext* context); + +ge::graphStatus TilingMoeTokenUnpermute(gert::TilingContext* context) +{ + return TilingCompute(context, -1); +} + +static inline int64_t AlignN(const int64_t x, const int64_t N) +{ + return (x + N - 1) & ~(N - 1); +} + +static inline int64_t GetLengthByType(const int32_t dtype) +{ + switch (dtype) { + case ge::DT_FLOAT16: + case ge::DT_INT16: + case ge::DT_UINT16: + case ge::DT_BF16: + return sizeof(int16_t); + case ge::DT_FLOAT: + case ge::DT_INT32: + case ge::DT_UINT32: + return sizeof(int32_t); + case ge::DT_DOUBLE: + case ge::DT_INT64: + case ge::DT_UINT64: + return sizeof(int64_t); + default: + return 0; + } +} + +static inline int64_t safeMod(const int64_t a, const int64_t b) +{ + return b == 0 ? 0 : a % b; +} + +static inline int64_t safeDiv(const int64_t a, const int64_t b) +{ + return b == 0 ? 0 : a / b; +} + +static inline bool isFloatDtype(const int64_t inputDtypeSize) +{ + return inputDtypeSize == GetLengthByType(ge::DT_FLOAT); +} + +/* + * 计算hidden_size=1所需要的Btye + */ +static inline int64_t ComputeUnitHSpace(const int64_t inputDtypeSize, const int64_t bufferNum) +{ + int64_t castNum = isFloatDtype(inputDtypeSize) ? 0 : CAST_NUM; + return inputDtypeSize * (QUE_NUM + bufferNum - 1) + FLOAT_DATA_SIZE * castNum; +} + +static inline int64_t ComputeMaxHiddenSize(MoeTokenUnpermuteParam& param, int64_t bufferNum) +{ + // sorted_indices和probs的预留空间;topK_num为最大值512时,至少需要5120 Btye。 + const int64_t reserveSpace = 5120; + int64_t maxHiddenSize = + safeDiv((param.core.maxCoreMemery - reserveSpace), ComputeUnitHSpace(param.input.tokensDtypeSize, bufferNum)); + + return AlignN(maxHiddenSize - ALIGN_512, ALIGN_512); +} + +static inline ge::graphStatus InputParamCheck(const gert::TilingContext* context) +{ + const gert::StorageShape* tokensShape = context->GetInputShape(0); + const gert::StorageShape* indicesShape = context->GetInputShape(1); + const gert::StorageShape* probsShape = context->GetInputShape(2); + auto dataTensor0 = context->GetInputTensor(0); + auto dataTensor1 = context->GetInputTensor(1); + auto nodeName = context->GetNodeName(); + auto ascendcPlatform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo()); + auto is310P = (ascendcPlatform.GetSocVersion() == platform_ascendc::SocVersion::ASCEND310P); + OP_CHECK_IF( + tokensShape == nullptr || indicesShape == nullptr || dataTensor0 == nullptr || dataTensor1 == nullptr, + OP_LOGE(nodeName, "[MoeTokenUnpermute] permutedTokens or sortedIndices is nullptr."), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + tokensShape->GetStorageShape().GetDimNum() != 2, + OP_LOGE(nodeName, "[MoeTokenUnpermute] permutedTokens's shape is not 2D."), + return ge::GRAPH_FAILED); + if (is310P) { + int64_t hidden_size = tokensShape->GetStorageShape().GetDim(1); + OP_CHECK_IF( + hidden_size % ALIGN_128 != 0, + OP_LOGE( + nodeName, "permutedTokens's hiddensize is [%ld]. Hiddensize should be an integer multiple of 128 on 310p",hidden_size), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + hidden_size > MAX_HIDDEN_SIZE_310P, + OP_LOGE( + nodeName, "permutedTokens's hiddensize is [%ld]. Hiddensize should not be greater than 10240 on 310p",hidden_size), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + context->GetInputDesc(0)->GetDataType() == ge::DT_BF16, + OP_LOGE(nodeName, "permutedToekn's dtype is BF16, which is not support on 310p"), + return ge::GRAPH_FAILED); + + OP_CHECK_IF( + context->GetInputDesc(2) != nullptr && context->GetInputDesc(2)->GetDataType() == ge::DT_BF16, + OP_LOGE(nodeName, "probs's dtype is BF16, which is not support on 310p"), + return ge::GRAPH_FAILED); + } + if (probsShape != nullptr) { + OP_CHECK_IF( + probsShape->GetStorageShape().GetDimNum() != 2, + OP_LOGE(nodeName, "[MoeTokenUnpermute] probs's shape is not 2D."), + return ge::GRAPH_FAILED); + + int64_t tokensNum = probsShape->GetStorageShape().GetDim(0); + int64_t topK = probsShape->GetStorageShape().GetDim(1); + int64_t totalLength = indicesShape->GetStorageShape().GetDim(0); + + OP_CHECK_IF( + totalLength != tokensNum * topK, + OP_LOGE( + nodeName, + "[MoeTokenUnpermute] permutedTokens's dim(0) is not equal to probs's dim(0) * probs's dim(1)."), + return ge::GRAPH_FAILED); + OP_CHECK_IF( + topK > 512, OP_LOGE(nodeName, "[MoeTokenUnpermute] topK can not larger than 512."), + return ge::GRAPH_FAILED); + } + + return ge::GRAPH_SUCCESS; +} + +static inline void Init(const gert::TilingContext* context, const int64_t topK, MoeTokenUnpermuteParam& param) +{ + auto ascendPlaform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo()); + param.core.maxCoreNum = static_cast(ascendPlaform.GetCoreNumAiv()); + uint64_t maxCoreMemery; + ascendPlaform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, maxCoreMemery); + param.core.maxCoreMemery = static_cast(maxCoreMemery); + + const gert::StorageShape* tokensShape = context->GetInputShape(0); + const gert::StorageShape* sortedIndicesShape = context->GetInputShape(1); + const gert::StorageShape* probsShape = context->GetInputShape(2); + auto dataTensor0 = context->GetInputTensor(0); + auto dataTensor1 = context->GetInputTensor(1); + + param.input.tokensDtypeSize = GetLengthByType(dataTensor0->GetDataType()); + param.input.indicesDtypeSize = GetLengthByType(dataTensor1->GetDataType()); + param.input.numOutTokens = tokensShape->GetStorageShape().GetDim(0); // numOutTokens根据tokens第0维获取; + param.input.hiddenSize = tokensShape->GetStorageShape().GetDim(1); + param.input.totalLength = sortedIndicesShape->GetStorageShape().GetDim( + 0); // tokens可能存在numOutTokens,因此totalLength从sortedIndices获取。 + if (probsShape != nullptr) { + auto dataTensor2 = context->GetInputTensor(2); + param.input.probsDtypeSize = GetLengthByType(dataTensor2->GetDataType()); + param.input.haveProbs = true; + param.input.tokensNum = probsShape->GetStorageShape().GetDim(0); + param.input.topK = probsShape->GetStorageShape().GetDim(1); + } else { + param.input.topK = topK == -1 ? 1 : topK; + param.input.tokensNum = safeDiv(param.input.totalLength, param.input.topK); + } +} + +static void SetCoreNum(MoeTokenUnpermuteParam& param) +{ + if (param.input.tokensNum < param.core.maxCoreNum) { + param.core.usedCoreNum = param.input.tokensNum; + } else { + param.core.usedCoreNum = param.core.maxCoreNum; + } +} + +static inline void TilingHiddenSize(MoeTokenUnpermuteParam& param) +{ + int64_t maxHiddenSize = ComputeMaxHiddenSize(param, MIN_BUFFER_NUM); + if (AlignN(param.input.hiddenSize, ALIGN_512) <= maxHiddenSize) { + param.hiddenTiling.length = param.input.hiddenSize; + param.hiddenTiling.remain = 0; + param.hiddenTiling.num = 1; + } else { + param.hiddenTiling.length = maxHiddenSize; + param.hiddenTiling.remain = safeMod(param.input.hiddenSize, maxHiddenSize); + param.hiddenTiling.num = safeDiv(param.input.hiddenSize, maxHiddenSize); + } +} + +static inline void SetBufferNum(MoeTokenUnpermuteParam& param) +{ + const int64_t maxBufferNum = 4; + int64_t bufferNum = maxBufferNum; + while (bufferNum > MIN_BUFFER_NUM && param.hiddenTiling.length > ComputeMaxHiddenSize(param, bufferNum)) { + bufferNum--; + } + param.core.bufferNum = bufferNum; +} + +static inline void ComputeRemainMemerySpace(MoeTokenUnpermuteParam& param) +{ + param.core.remainMemerySpace = + param.core.maxCoreMemery - AlignN(param.hiddenTiling.length, ALIGN_512) * + ComputeUnitHSpace(param.input.tokensDtypeSize, param.core.bufferNum); + param.core.remainMemerySpace -= ALIGN_256; +} + +static inline void TilingToken(MoeTokenUnpermuteParam& param) +{ + param.tokenPerCore.length = safeDiv(param.input.tokensNum, param.core.usedCoreNum); + param.tokenPerCore.num = param.core.usedCoreNum; + param.tokenPerCore.remain = safeMod(param.input.tokensNum, param.core.usedCoreNum); + + int64_t unitTokenSpace = param.input.indicesDtypeSize; + if (param.input.haveProbs) { + unitTokenSpace += param.input.probsDtypeSize; + if (!isFloatDtype(param.input.probsDtypeSize)) { + unitTokenSpace += sizeof(float); + } + } + + int64_t probIndiceSpace = param.tokenPerCore.length * param.input.topK * unitTokenSpace; + + if (param.core.remainMemerySpace >= probIndiceSpace) { + param.tokenTiling.length = param.tokenPerCore.length; + param.tokenTiling.remain = 0; + param.tokenTiling.num = 1; + } else { + int64_t maxTokenSize = safeDiv(param.core.remainMemerySpace, (param.input.topK * unitTokenSpace)); + param.tokenTiling.length = maxTokenSize; + param.tokenTiling.remain = safeMod(param.tokenPerCore.length, maxTokenSize); + param.tokenTiling.num = safeDiv(param.tokenPerCore.length, maxTokenSize); + } +} +/* + tilingKey计算规则 + 第0位: + 0表示probs为None,1表示prob非None。 + 第1-2位: + 00 表示bfloat16数据类型; + 01 表示float16数据类型; + 10 表示float32数据类型。 + 第3-4位(mix位,probs与与permuted_tokens数据类型不一致时生效): + 00 表示probs不存在,或probs与permuted_tokens数据类型保持一致; + 01 表示probs数据类型为bfloat16数据类型; + 10 表示probs数据类型为float16数据类型; + 11 表示probs数据类型为float32数据类型。 + */ +static inline void SetTilingKey(const gert::TilingContext* context, MoeTokenUnpermuteParam& param) +{ + auto permuted_tokens_dtype = context->GetInputTensor(0)->GetDataType(); + if (permuted_tokens_dtype == ge::DT_FLOAT16) { + param.core.tilingKey += TILINGKEY_FLOAT16; + } else if (permuted_tokens_dtype == ge::DT_FLOAT) { + param.core.tilingKey += TILINGKEY_FLOAT; + } + if (param.input.haveProbs) { + // 存在probs + param.core.tilingKey += TILINGKEY_PROBS; + auto probs_dtype = context->GetInputTensor(2)->GetDataType(); + if (permuted_tokens_dtype != probs_dtype) { + // 支持混合精度类型 + if (probs_dtype == ge::DT_BF16) { + param.core.tilingKey += TILINGKEY_MIX_BF16; + } else if (probs_dtype == ge::DT_FLOAT16) { + param.core.tilingKey += TILINGKEY_MIX_FP16; + } else if (probs_dtype == ge::DT_FLOAT) { + param.core.tilingKey += TILINGKEY_MIX_FP32; + } + } + } +} + +static inline void SetTilingData(gert::TilingContext* context, const MoeTokenUnpermuteParam& param) +{ + MoeTokenUnpermuteTilingData tilingData; + tilingData.set_hidden_size(param.input.hiddenSize); + tilingData.set_top_k(param.input.topK); + tilingData.set_num_out_tokens(param.input.numOutTokens); + tilingData.set_hidden_splited_length(param.hiddenTiling.length); + tilingData.set_hidden_splited_num(param.hiddenTiling.num); + tilingData.set_hidden_splited_remain(param.hiddenTiling.remain); + tilingData.set_tokens_core_length(param.tokenPerCore.length); + tilingData.set_tokens_core_remain(param.tokenPerCore.remain); + tilingData.set_tokens_splited_length(param.tokenTiling.length); + tilingData.set_tokens_splited_remain(param.tokenTiling.remain); + tilingData.set_tokens_splited_num(param.tokenTiling.num); + tilingData.set_buffer_num(param.core.bufferNum); + tilingData.SaveToBuffer(context->GetRawTilingData()->GetData(), context->GetRawTilingData()->GetCapacity()); + context->GetRawTilingData()->SetDataSize(tilingData.GetDataSize()); + context->SetBlockDim(param.core.usedCoreNum); +} + +static inline void DebugPrint(const gert::TilingContext* context, const MoeTokenUnpermuteParam& param) +{ + auto nodeName = context->GetNodeName(); + OP_LOGD(nodeName, ">>>>>>>>>>>>>>> Start to print MoeTokenUnpermute tiling data <<<<<<<<<<<<<<<<"); + OP_LOGD(nodeName, "coreNum: %ld", param.core.usedCoreNum); + OP_LOGD(nodeName, "maxCoreMemery: %ld", param.core.maxCoreMemery); + OP_LOGD(nodeName, "maxCoreNum: %ld", param.core.maxCoreNum); + OP_LOGD(nodeName, "remainMemerySpace: %ld", param.core.remainMemerySpace); + OP_LOGD(nodeName, "tilingKey: %ld", param.core.tilingKey); + OP_LOGD(nodeName, "bufferNum: %ld", param.core.bufferNum); + + OP_LOGD(nodeName, "totalLength: %ld", param.input.totalLength); + OP_LOGD(nodeName, "tokensNum: %ld", param.input.tokensNum); + OP_LOGD(nodeName, "topK: %ld", param.input.topK); + OP_LOGD(nodeName, "hiddenSize: %ld", param.input.hiddenSize); + OP_LOGD(nodeName, "haveProbs: %d", param.input.haveProbs); + OP_LOGD(nodeName, "tokensDtypeSize: %ld", param.input.tokensDtypeSize); + OP_LOGD(nodeName, "indicesDtypeSize: %ld", param.input.indicesDtypeSize); + OP_LOGD(nodeName, "probsDtypeSize: %ld", param.input.probsDtypeSize); + OP_LOGD(nodeName, "numOutTokens: %ld", param.input.numOutTokens); + + OP_LOGD(nodeName, "hiddenTilingParam.length: %ld", param.hiddenTiling.length); + OP_LOGD(nodeName, "hiddenTilingParam.num: %ld", param.hiddenTiling.num); + OP_LOGD(nodeName, "hiddenTilingParam.remain: %ld", param.hiddenTiling.remain); + + OP_LOGD(nodeName, "tokenTilingParam.length: %ld", param.tokenTiling.length); + OP_LOGD(nodeName, "tokenTilingParam.num: %ld", param.tokenTiling.num); + OP_LOGD(nodeName, "tokenTilingParam.remain: %ld", param.tokenTiling.remain); + + OP_LOGD(nodeName, "tokenPerCore.length: %ld", param.tokenPerCore.length); + OP_LOGD(nodeName, "tokenPerCore.num: %ld", param.tokenPerCore.num); + OP_LOGD(nodeName, "tokenPerCore.remain: %ld", param.tokenPerCore.remain); + + OP_LOGD(nodeName, ">>>>>>>>>>>>>>> Print MoeTokenUnpermute tiling data end <<<<<<<<<<<<<<<<"); +} + +ge::graphStatus TilingCompute(gert::TilingContext* context, const int64_t topK) +{ + MoeTokenUnpermuteParam param; + + if (InputParamCheck(context) == ge::GRAPH_FAILED) { + return ge::GRAPH_FAILED; + } + Init(context, topK, param); + SetCoreNum(param); + TilingHiddenSize(param); + SetBufferNum(param); + ComputeRemainMemerySpace(param); + TilingToken(param); + SetTilingKey(context, param); + SetTilingData(context, param); + DebugPrint(context, param); + const auto ascendcPlatform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo()); + size_t* workspaces = context->GetWorkspaceSizes(1); + workspaces[0] = ascendcPlatform.GetLibApiWorkSpaceSize(); + OP_LOGD(context->GetNodeName(), "workspace is %zu", workspaces[0]); + return context->SetTilingKey(param.core.tilingKey); +} + +static ge::graphStatus TilingPrepareForMoeTokenUnpermute(gert::TilingParseContext* context) +{ + (void)context; + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_OPTILING(MoeTokenUnpermute) + .Tiling(TilingMoeTokenUnpermute) + .TilingParse(TilingPrepareForMoeTokenUnpermute); +} // namespace optiling diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/moe_token_unpermute_tiling.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/moe_token_unpermute_tiling.h new file mode 100644 index 0000000000000000000000000000000000000000..32ff116ce1de4090756916264b337ff82fa036aa --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/moe_token_unpermute_tiling.h @@ -0,0 +1,99 @@ +/** + * 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 moe_token_unpermute_tiling.h + * \brief + */ +#ifndef OPS_BUILT_IN_OP_TILING_RUNTIME_MOE_TOKEN_UNPERMUTE_H +#define OPS_BUILT_IN_OP_TILING_RUNTIME_MOE_TOKEN_UNPERMUTE_H + +#include "register/op_def_registry.h" +#include "register/tilingdata_base.h" +#include "tiling/platform/platform_ascendc.h" +#include "tiling/tiling_api.h" +#include "log/log.h" + +namespace optiling { + +constexpr int64_t FLOAT_DATA_SIZE = 4; +constexpr int64_t MIN_BUFFER_NUM = 2; +constexpr int64_t ALIGN_512 = 512; +constexpr int64_t ALIGN_256 = 256; +constexpr int64_t QUE_NUM = 2; +constexpr int64_t CAST_NUM = 2; +constexpr int64_t TILINGKEY_PROBS = 1; +constexpr int64_t TILINGKEY_FLOAT16 = 2; +constexpr int64_t TILINGKEY_FLOAT = 4; +constexpr int64_t TILINGKEY_MIX_BF16 = 8; +constexpr int64_t TILINGKEY_MIX_FP16 = 16; +constexpr int64_t TILINGKEY_MIX_FP32 = 24; +constexpr int64_t TILINGKEY_DROPPAD = 1000; +constexpr int64_t MAX_HIDDEN_SIZE_310P = 10240; +constexpr int64_t ALIGN_128 = 128; +struct CoreParam { + int64_t maxCoreMemery = 0; + int64_t maxCoreNum = 0; + int64_t usedCoreNum = 0; + int64_t remainMemerySpace = 0; + int64_t bufferNum = 0; + int64_t tilingKey = 0; +}; + +struct InputParam { + int64_t tokensNum = 0; + int64_t topK = 0; + int64_t hiddenSize = 0; + int64_t totalLength = 0; + int64_t numOutTokens = 0; + int64_t tokensDtypeSize = 0; + int64_t indicesDtypeSize = 0; + int64_t probsDtypeSize = 0; + bool haveProbs = false; +}; + +struct TilingParam { + int64_t length = 0; + int64_t num = 0; + int64_t remain = 0; +}; + +struct MoeTokenUnpermuteParam { + InputParam input; + TilingParam hiddenTiling; + TilingParam tokenTiling; + TilingParam tokenPerCore; + CoreParam core; +}; +ge::graphStatus TilingCompute(gert::TilingContext* context, const int64_t topK); +BEGIN_TILING_DATA_DEF(MoeTokenUnpermuteTilingData) +TILING_DATA_FIELD_DEF(int64_t, hidden_size); +TILING_DATA_FIELD_DEF(int64_t, top_k); +TILING_DATA_FIELD_DEF(int64_t, num_out_tokens); + +TILING_DATA_FIELD_DEF(int64_t, hidden_splited_length); +TILING_DATA_FIELD_DEF(int64_t, hidden_splited_num); +TILING_DATA_FIELD_DEF(int64_t, hidden_splited_remain); + +TILING_DATA_FIELD_DEF(int64_t, tokens_core_length); +TILING_DATA_FIELD_DEF(int64_t, tokens_core_remain); +TILING_DATA_FIELD_DEF(int64_t, tokens_splited_length); +TILING_DATA_FIELD_DEF(int64_t, tokens_splited_num); +TILING_DATA_FIELD_DEF(int64_t, tokens_splited_remain); + +TILING_DATA_FIELD_DEF(int64_t, buffer_num); +END_TILING_DATA_DEF; + +REGISTER_TILING_DATA_CLASS(MoeTokenUnpermute, MoeTokenUnpermuteTilingData) +struct MoeTokenUnpermuteCompileInfo { +}; + +} // namespace optiling +#endif // OPS_BUILT_IN_OP_TILING_RUNTIME_MOE_TOKEN_UNPERMUTE_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/op_api/aclnn_moe_token_unpermute.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/op_api/aclnn_moe_token_unpermute.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5b7e9630540a46f37cbfdffb529b3f802d1982d3 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/op_api/aclnn_moe_token_unpermute.cpp @@ -0,0 +1,138 @@ +/** + * 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_moe_token_unpermute.cpp + * \brief + */ +#include "aclnn_moe_token_unpermute.h" +#include "opdev/make_op_executor.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "aclnnInner_moe_token_unpermute.h" // 该文件为自动生成,在build/autogen/inner路径下 +#include "external/aclnn_kernels/aclnn_platform.h" +#include "aclnn_kernels/contiguous.h" +#include "opdev/tensor_view_utils.h" +#include "opdev/op_log.h" +#include "moe/moe_finalize_routing_v2/op_host/op_api/moe_finalize_routing_v2.h" + +using namespace op; + +namespace MoeTokenUnpermuteCheck { + +static const std::initializer_list MOE_DTYPE_SUPPORT_LIST_X = {DataType::DT_FLOAT16, DataType::DT_BF16, + DataType::DT_FLOAT}; +static const std::initializer_list MOE_DTYPE_SUPPORT_LIST_ROW_IDX = {DataType::DT_INT32}; + +static inline bool CheckNotNull(const aclTensor *permutedTokens, const aclTensor *sortedIndices, const aclTensor *out) +{ + OP_CHECK_NULL(permutedTokens, return false); + OP_CHECK_NULL(sortedIndices, return false); + OP_CHECK_NULL(out, return false); + return true; +} + +static inline bool CheckDtypeValid(const aclTensor *permutedTokens, const aclTensor *sortedIndices, + const aclTensor *probsOptional, const aclTensor *out) +{ + if (permutedTokens != nullptr && permutedTokens->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(permutedTokens, MOE_DTYPE_SUPPORT_LIST_X, return false); + } + if (sortedIndices != nullptr && sortedIndices->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(sortedIndices, MOE_DTYPE_SUPPORT_LIST_ROW_IDX, return false); + } + if (probsOptional != nullptr && probsOptional->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(probsOptional, MOE_DTYPE_SUPPORT_LIST_X, return false); + } + if (out != nullptr && out->GetViewShape().GetShapeSize() != 0) { + OP_CHECK_DTYPE_NOT_SUPPORT(out, MOE_DTYPE_SUPPORT_LIST_X, return false); + OP_CHECK_DTYPE_NOT_SAME(permutedTokens, out, return false); + } + return true; +} + +static aclnnStatus CheckParams(const aclTensor *permutedTokens, const aclTensor *sortedIndices, + const aclTensor *probsOptional, const aclTensor *out) +{ + CHECK_RET(CheckNotNull(permutedTokens, sortedIndices, out), ACLNN_ERR_PARAM_NULLPTR); + CHECK_RET(CheckDtypeValid(permutedTokens, sortedIndices, probsOptional, out), ACLNN_ERR_PARAM_INVALID); + return ACLNN_SUCCESS; +} + +} // namespace MoeTokenUnpermuteCheck + +#ifdef __cplusplus +extern "C" { +#endif + +constexpr int64_t READ_INDEX_BY_ROW = 2; + +aclnnStatus aclnnMoeTokenUnpermuteGetWorkspaceSize( + const aclTensor* permutedTokens, const aclTensor* sortedIndices, const aclTensor* probsOptional, bool paddedMode, + const aclIntArray* restoreShapeOptional, aclTensor* out, uint64_t* workspaceSize, aclOpExecutor** executor) +{ + OP_CHECK_COMM_INPUT(workspaceSize, executor); + L2_DFX_PHASE_1(aclnnMoeTokenUnpermute, + DFX_IN(permutedTokens, sortedIndices, probsOptional, paddedMode, restoreShapeOptional), + DFX_OUT(out)); + + bool useMoeFinalizeRoutingV2 = Ops::Transformer::AclnnUtil::IsRegbase(); + if (!useMoeFinalizeRoutingV2) { + return aclnnInnerMoeTokenUnpermuteGetWorkspaceSize( + permutedTokens, sortedIndices, probsOptional, paddedMode, restoreShapeOptional, out, workspaceSize, + executor); + } + CHECK_RET(paddedMode == false, ACLNN_ERR_PARAM_INVALID); + + aclnnStatus ret = MoeTokenUnpermuteCheck::CheckParams(permutedTokens, sortedIndices, probsOptional, out); + CHECK_RET(ret == ACLNN_SUCCESS, ret); + + // 创建OpExecutor + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + // 固定写法,将输入转换成连续的tensor + auto permutedTokensContiguous = l0op::Contiguous(permutedTokens, uniqueExecutor.get()); + CHECK_RET(permutedTokensContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + auto sortedIndicesContiguous = l0op::Contiguous(sortedIndices, uniqueExecutor.get()); + CHECK_RET(sortedIndicesContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + const aclTensor* probsContiguous = nullptr; + if (probsOptional != nullptr) { + probsContiguous = l0op::Contiguous(probsOptional, uniqueExecutor.get()); + CHECK_RET(probsContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + } + auto out_ = l0op::MoeFinalizeRoutingV2( + permutedTokensContiguous, sortedIndicesContiguous, nullptr, nullptr, nullptr, probsContiguous, nullptr, nullptr, + nullptr, nullptr, nullptr, READ_INDEX_BY_ROW, nullptr, nullptr, nullptr, 1, out, uniqueExecutor.get()); + CHECK_RET(out_ != nullptr, ACLNN_ERR_INNER_NULLPTR); + // copyout结果,如果出参out是非连续Tensor,需要把计算完的连续Tensor转非连续 + auto viewCopyOutResult = l0op::ViewCopy(out_, out, uniqueExecutor.get()); + CHECK_RET(viewCopyOutResult != nullptr, ACLNN_ERR_INNER_NULLPTR); + // 获取计算过程中需要使用的workspace大小 + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +aclnnStatus aclnnMoeTokenUnpermute(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream) +{ + static bool useMoeFinalizeRoutingV2 = Ops::Transformer::AclnnUtil::IsRegbase(); + if (!useMoeFinalizeRoutingV2) { + return aclnnInnerMoeTokenUnpermute(workspace, workspaceSize, executor, stream); + } + + L2_DFX_PHASE_2(aclnnMoeTokenUnpermute); + 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/moe_token_unpermute/op_host/op_api/aclnn_moe_token_unpermute.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/op_api/aclnn_moe_token_unpermute.h new file mode 100644 index 0000000000000000000000000000000000000000..8c46f384d9f1e800d37dae578fb168124ddfeb49 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/moe_token_unpermute/op_host/op_api/aclnn_moe_token_unpermute.h @@ -0,0 +1,40 @@ +/** + * 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_moe_token_unpermute.h + * \brief + */ +#ifndef OP_API_INC_MOE_TOKEN_UNPERMUTE_H_ +#define OP_API_INC_MOE_TOKEN_UNPERMUTE_H_ + +#include "aclnn/aclnn_base.h" +#include "aclnn_util.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief aclnnMoeTokenUnpermute的第一段接口,根据具体的计算流程,计算workspace大小。 + * @domain aclnn_ops_infer + */ +ACLNN_API aclnnStatus aclnnMoeTokenUnpermuteGetWorkspaceSize( + const aclTensor* permutedTokens, const aclTensor* sortedIndices, const aclTensor* probsOptional, bool paddedMode, + const aclIntArray* restoreShapeOptional, aclTensor* out, uint64_t* workspaceSize, aclOpExecutor** executor); +/* @brief aclnnMoeTokenUnpermute的第二段接口,用于执行计算。 */ +ACLNN_API aclnnStatus +aclnnMoeTokenUnpermute(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/rope_with_sin_cos_cache/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..0f5c02c697a2b99603f49c79ab2d363eddf434e0 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/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.rope.rope_with_sin_cos_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/rope_with_sin_cos_cache/README.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d313b500feba6d679b7b169f4491ef98b437b444 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/README.md @@ -0,0 +1,277 @@ +# RopeWithSinCosCache + +## 产品支持情况 + +|产品 | 是否支持 | +|:-------------------------|:----------:| +| Ascend 950PR/Ascend 950DT | √ | +| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | √ | +| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | √ | +| Atlas 200I/500 A2 推理产品 | × | +| Atlas 推理系列产品 | × | +| Atlas 训练系列产品 | × | +| Kirin X90 处理器系列产品 | √ | +| Kirin 9030 处理器系列产品 | √ | + +## 功能说明 + +- 算子功能:推理网络为了提升性能,将sin和cos输入通过cache传入,执行旋转位置编码计算。 +- 计算公式: + + 1、**mrope模式**:positions的shape输入是[3, numTokens]: + + $$ + cosSin[i] = cosSinCache[positions[i]] + $$ + + $$ + cos, sin = cosSin.chunk(2, dim=-1) + $$ + + $$ + cos0 = cos[0, :, :mropeSection[0]] + $$ + + $$ + cos1 = cos[1, :, mropeSection[0]:(mropeSection[0] + mropeSection[1])] + $$ + + $$ + cos2 = cos[2, :, (mropeSection[0] + mropeSection[1]):(mropeSection[0] + mropeSection[1] + mropeSection[2])] + $$ + + $$ + cos = torch.cat((cos0, cos1, cos2), dim=-1) + $$ + + $$ + sin0 = sin[0, :, :mropeSection[0]] + $$ + + $$ + sin1 = sin[1, :, mropeSection[0]:(mropeSection[0] + mropeSection[1])] + $$ + + $$ + sin2 = sin[2, :, (mropeSection[0] + mropeSection[1]):(mropeSection[0] + mropeSection[1] + mropeSection[2])] + $$ + + $$ + sin= torch.cat((sin0, sin1, sin2), dim=-1) + $$ + + $$ + queryRot = query[..., :rotaryDim] + $$ + + $$ + queryPass = query[..., rotaryDim:] + $$ + + (1)rotate\_half(GPT-NeoX style)计算模式: + + $$ + x1, x2 = torch.chunk(queryRot, 2, dim=-1) + $$ + + $$ + o1[i] = x1[i] * cos[i] - x2[i] * sin[i] + $$ + + $$ + o2[i] = x2[i] * cos[i] + x1[i] * sin[i] + $$ + + $$ + queryRot = torch.cat((o1, o2), dim=-1) + $$ + + $$ + query = torch.cat((queryRot, queryPass), dim=-1) + $$ + + (2)rotate\_interleaved(GPT-J style)计算模式: + + $$ + x1 = queryRot[..., ::2] + $$ + + $$ + x2 = queryRot[..., 1::2] + $$ + + $$ + o1[i] = x1[i] * cos[i] - x2[i] * sin[i] + $$ + + $$ + o2[i] = x2[i] * cos[i] + x1[i] * sin[i] + $$ + + $$ + queryRot = torch.stack((o1, o2), dim=-1) + $$ + + $$ + query = torch.cat((queryRot, queryPass), dim=-1) + $$ + + 2、**rope模式**:positions的shape输入是[numTokens]: + + $$ + cosSin[i] = cosSinCache[positions[i]] + $$ + + $$ + cos, sin = cosSin.chunk(2, dim=-1) + $$ + + $$ + queryRot = query[..., :rotaryDim] + $$ + + $$ + queryPass = query[..., rotaryDim:] + $$ + + (1)rotate\_half(GPT-NeoX style)计算模式: + + $$ + x1, x2 = torch.chunk(queryRot, 2, dim=-1) + $$ + + $$ + o1[i] = x1[i] * cos[i] - x2[i] * sin[i] + $$ + + $$ + o2[i] = x2[i] * cos[i] + x1[i] * sin[i] + $$ + + $$ + queryRot = torch.cat((o1, o2), dim=-1) + $$ + + $$ + query = torch.cat((queryRot, queryPass), dim=-1) + $$ + + (2)rotate\_interleaved(GPT-J style)计算模式: + + $$ + x1 = queryRot[..., ::2] + $$ + + $$ + x2 = queryRot[..., 1::2] + $$ + + $$ + o1[i] = x1[i] * cos[i] - x2[i] * sin[i] + $$ + + $$ + o2[i] = x2[i] * cos[i] + x1[i] * sin[i] + $$ + + $$ + queryRot = torch.stack((o1, o2), dim=-1) + $$ + + $$ + query = torch.cat((queryRot, queryPass), dim=-1) + $$ + +## 参数说明 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出/属性描述数据类型数据格式
positions输入Device侧的aclTensor,输入索引。INT32、INT64ND
queryIn输入Device侧的aclTensor,表示要执行旋转位置编码的第一个张量,公式中的`query`。BFLOAT16、FLOAT16、FLOAT32ND
keyIn输入Device侧的aclTensor,表示要执行旋转位置编码的第二个张量。BFLOAT16、FLOAT16、FLOAT32ND
cosSinCache输入Device侧的aclTensor,表示参与计算的位置编码张量。BFLOAT16、FLOAT16、FLOAT32ND
mropeSection输入mrope模式下用于整合输入的位置编码张量信息,公式中的`mropeSection`。INT64-
headSize输入表示每个注意力头维度大小。INT64-
isNeoxStyle输入true表示rotate\_half(GPT-NeoX style)计算模式,false表示rotate\_interleaved(GPT-J style)计算模式。BOOL-
queryOut输出输出query执行旋转位置编码后的结果。FLOAT、FLOAT16、BFLOAT16ND
keyOut输出输出key执行旋转位置编码后的结果。FLOAT、FLOAT16、BFLOAT16ND
+ +- Kirin X90/Kirin 9030 处理器系列产品: 不支持BFLOAT16。 + +## 约束说明 + +- queryIn、keyIn、cosSinCache只支持2维shape输入。 +- headSize: 数据类型为BFLOAT16或FLOAT16时为32的倍数,数据类型为FLOAT32时为16的倍数。 +- rotaryDim: 始终小于等于headSize;数据类型为BFLOAT16或FLOAT16时为32的倍数,数据类型为FLOAT32时为16的倍数;mrope模式下应满足rotaryDim = mropeSection[0] + mropeSection[1] + mropeSection[2]。 +- 输入tensor positions的取值应小于cosSinCache的0维maxSeqLen。 +- aclnnRopeWithSinCosCache默认确定性实现。 +- mropeSection:取值限制为[16, 24, 24]。 + +## 调用说明 + +| 调用方式 | 样例代码 | 说明 | +| ---------------- | --------------------------- | --------------------------------------------------- | +| aclnn接口 | [test_aclnn_rope_with_sin_cos_cache](examples/test_aclnn_rope_with_sin_cos_cache.cpp) | 通过[aclnnRopeWithSinCosCache](docs/aclnnRopeWithSinCosCache.md)接口方式调用RopeWithSinCosCache算子。 | diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/docs/aclnnRopeWithSinCosCache.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/docs/aclnnRopeWithSinCosCache.md new file mode 100644 index 0000000000000000000000000000000000000000..f079156036e81c91eeb24f9131a335bbc5e08ba9 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/docs/aclnnRopeWithSinCosCache.md @@ -0,0 +1,696 @@ +# aclnnRopeWithSinCosCache + +[📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/posembedding/rope_with_sin_cos_cache) + +## 产品支持情况 + +| 产品 | 是否支持 | +| :----------------------------------------------------------- | :------: | +| Ascend 950PR/Ascend 950DT | √ | +| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | √ | +| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | √ | +| Atlas 200I/500 A2 推理产品 | × | +| Atlas 推理系列产品 | × | +| Atlas 训练系列产品 | × | + +## 功能说明 + +* 接口功能:推理网络为了提升性能,将sin和cos输入通过cache传入,执行旋转位置编码计算。 +* 计算公式: + + 1、**mrope模式**:positions的shape输入是[m, numTokens], m为mropeSection的元素数,支持3或4: + + $$ + cosSin[i] = cosSinCache[positions[i]] + $$ + + $$ + cos, sin = cosSin.chunk(2, dim=-1) + $$ + + - mropeSection的元素数为3: + + $$ + cos0 = cos[0, :, :mropeSection[0]] + $$ + + $$ + cos1 = cos[1, :, mropeSection[0]:(mropeSection[0] + mropeSection[1])] + $$ + + $$ + cos2 = cos[2, :, (mropeSection[0] + mropeSection[1]):(mropeSection[0] + mropeSection[1] + mropeSection[2])] + $$ + + $$ + cos = torch.cat((cos0, cos1, cos2), dim=-1) + $$ + + $$ + sin0 = sin[0, :, :mropeSection[0]] + $$ + + $$ + sin1 = sin[1, :, mropeSection[0]:(mropeSection[0] + mropeSection[1])] + $$ + + $$ + sin2 = sin[2, :, (mropeSection[0] + mropeSection[1]):(mropeSection[0] + mropeSection[1] + mropeSection[2])] + $$ + + $$ + sin= torch.cat((sin0, sin1, sin2), dim=-1) + $$ + + $$ + queryRot = query[..., :rotaryDim] + $$ + + $$ + queryPass = query[..., rotaryDim:] + $$ + + - mropeSection的元素数为4: + + $$ + cos = torch.cat([m[i]\ for\ i, m\ in\ enumerate(cos.split(mropeSection, dim=-1))], dim=-1) + $$ + + $$ + sin = torch.cat([m[i]\ for\ i, m\ in\ enumerate(sin.split(mropeSection, dim=-1))], dim=-1) + $$ + + $$ + queryRot = query[..., :rotaryDim] + $$ + + $$ + queryPass = query[..., rotaryDim:] + $$ + + (1)rotate\_half(GPT-NeoX style)计算模式: + + $$ + x1, x2 = torch.chunk(queryRot, 2, dim=-1) + $$ + + $$ + o1[i] = x1[i] * cos[i] - x2[i] * sin[i] + $$ + + $$ + o2[i] = x2[i] * cos[i] + x1[i] * sin[i] + $$ + + $$ + queryRot = torch.cat((o1, o2), dim=-1) + $$ + + $$ + query = torch.cat((queryRot, queryPass), dim=-1) + $$ + + (2)rotate\_interleaved(GPT-J style)计算模式: + + $$ + x1 = queryRot[..., ::2] + $$ + + $$ + x2 = queryRot[..., 1::2] + $$ + + $$ + o1[i] = x1[i] * cos[i] - x2[i] * sin[i] + $$ + + $$ + o2[i] = x2[i] * cos[i] + x1[i] * sin[i] + $$ + + $$ + queryRot = torch.stack((o1, o2), dim=-1) + $$ + + $$ + query = torch.cat((queryRot, queryPass), dim=-1) + $$ + + 2、**rope模式**:positions的shape输入是[numTokens]: + + $$ + cosSin[i] = cosSinCache[positions[i]] + $$ + + $$ + cos, sin = cosSin.chunk(2, dim=-1) + $$ + + $$ + queryRot = query[..., :rotaryDim] + $$ + + $$ + queryPass = query[..., rotaryDim:] + $$ + + (1)rotate\_half(GPT-NeoX style)计算模式: + + $$ + x1, x2 = torch.chunk(queryRot, 2, dim=-1) + $$ + + $$ + o1[i] = x1[i] * cos[i] - x2[i] * sin[i] + $$ + + $$ + o2[i] = x2[i] * cos[i] + x1[i] * sin[i] + $$ + + $$ + queryRot = torch.cat((o1, o2), dim=-1) + $$ + + $$ + query = torch.cat((queryRot, queryPass), dim=-1) + $$ + + (2)rotate\_interleaved(GPT-J style)计算模式: + + $$ + x1 = queryRot[..., ::2] + $$ + + $$ + x2 = queryRot[..., 1::2] + $$ + + $$ + o1[i] = x1[i] * cos[i] - x2[i] * sin[i] + $$ + + $$ + o2[i] = x2[i] * cos[i] + x1[i] * sin[i] + $$ + + $$ + queryRot = torch.stack((o1, o2), dim=-1) + $$ + + $$ + query = torch.cat((queryRot, queryPass), dim=-1) + $$ + +## 函数原型 + +该算子采用两段式接口,必须先调用“aclnnRopeWithSinCosCacheGetWorkspaceSize”接口获取计算所需workspace大小以及包含了算子计算流程的执行器,再调用“aclnnRopeWithSinCosCache”接口执行计算。 + +```c++ +aclnnStatus aclnnRopeWithSinCosCacheGetWorkspaceSize( + const aclTensor *positions, + const aclTensor *queryIn, + const aclTensor *keyIn, + const aclTensor *cosSinCache, + const aclIntArray *mropeSection, + int64_t headSize, + bool isNeoxStyle, + aclTensor *queryOut, + aclTensor *keyOut, + uint64_t *workspaceSize, + aclOpExecutor **executor) +``` + +```c++ +aclnnStatus aclnnRopeWithSinCosCache( + void *workspace, + uint64_t workspaceSize, + aclOpExecutor *executor, + aclrtStream stream) +``` + +## aclnnRopeWithSinCosCacheGetWorkspaceSize + +- **参数说明**: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述使用说明数据类型数据格式维度(shape)非连续Tensor
positions输入公式中的positions,用于选取位置编码张量。
  • 不支持空tensor。
  • rope模式shape为(numTokens)。
  • mrope模式shape为(3, numTokens)或(4, numTokens)。
INT64ND1-2√
queryIn输入公式中的query,要执行旋转位置编码的第一个张量。
  • 不支持空tensor。
  • 要求是一个2D的Tensor,shape为(numTokens, numQHeads*headSize)。
BFLOAT16、FLOAT16、FLOAT32ND2√
keyIn输入要执行旋转位置编码的第二个张量。
  • 不支持空tensor。
  • 要求是一个2D的Tensor,shape为(numTokens, numKHeads*headSize)。
BFLOAT16、FLOAT16、FLOAT32ND2√
cosSinCache输入表示参与计算的位置编码张量。
  • 不支持空tensor。
  • 要求是一个2D的Tensor,shape为(maxSeqLen, rotaryDim),maxSeqLen表示模型处理的序列的最大长度,rotaryDim表示旋转位置嵌入的维度大小。
BFLOAT16、FLOAT16、FLOAT32ND2√
mropeSection输入公式中的mropeSection,mrope模式下用于整合输入的位置编码张量信息。输入mropeSection属性表示开启mrope模式,不开启mrope模式(即rope模式)输入为nullptr。aclIntArray---
headSize输入每个注意力头维度大小。-INT64---
isNeoxStyle输入表示是否使用GPT-NeoX计算模式。
  • true表示GPT-NeoX style计算模式。
  • false表示GPT-J style计算模式。
BOOL---
queryOut输出query执行旋转位置编码后的结果。
  • 数据类型同query。
  • 要求是一个2D的Tensor,shape为(numTokens, numQHeads*headSize)。
FLOAT32、FLOAT16、BFLOAT16ND2×
keyOut输出key执行旋转位置编码后的结果。
  • 数据类型同key。
  • 要求是一个2D的Tensor,shape为(numTokens, numKHeads*headSize)。
FLOAT32、FLOAT16、BFLOAT16ND2×
workspaceSize输出返回用户需要在Device侧申请的workspace大小。-----
executor输出返回op执行器,包含了算子计算流程。-----
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + + 第一段接口完成入参校验,出现以下场景时报错: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
返回值错误码描述
ACLNN_ERR_PARAM_NULLPTR 161001 传入的必选输入、必选输出或者必选属性,是空指针。
ACLNN_ERR_PARAM_INVALID 161002 输入和输出的数据类型和数据格式不在支持的范围之内。
ACLNN_ERR_INNER_TILING_ERROR 561002 多个输入tensor之间的shape信息不匹配。
输入属性和输入tensor之间的shape信息不匹配。
ACLNN_ERR_INNER_TILING_ERROR 361001 query或者key非64B对齐。
rotaryDim>headSize。
+ +## aclnnRopeWithSinCosCache + +- **参数说明:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述
workspace输入在Device侧申请的workspace内存地址。
workspaceSize输入在Device侧申请的workspace大小,由第一段接口aclnnRopeWithSinCosCacheGetWorkspaceSize获取。
executor输入op执行器,包含了算子计算流程。
stream输入指定执行任务的Stream。
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + +## 约束说明 + +- 确定性计算: + - aclnnRopeWithSinCosCache默认确定性实现。 +- queryIn、keyIn、cosSinCache只支持2维shape输入。 +- queryIn、keyIn、cosSinCache输入的数据类型需要保持一致。 +- headSize:数据类型为BFLOAT16或FLOAT16时为32的倍数,数据类型为FLOAT32时为16的倍数。 +- rotaryDim:始终小于等于headSize;数据类型为BFLOAT16或FLOAT16时为32的倍数,数据类型为FLOAT32时为16的倍数;mrope模式下应满足mropeSection所有元素累加为rotaryDim值的一半。 +- 输入tensor positions的取值应小于cosSinCache的0维maxSeqLen。 +- mrope模式下,mropeSection:取值当前仅支持[16, 24, 24]、[24, 20, 20]、[8, 12, 12]和[16, 16, 16, 16]。 + +## 调用示例 + +以下示例代码展示接口调用流程,可供编译和运行时参考。 + +```Cpp +#include +#include +#include "acl/acl.h" +#include "aclnnop/level2/aclnn_rope_with_sin_cos_cache.h" +#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 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: %f\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 positionsShape = {2}; + std::vector queryInShape = {2, 64}; + std::vector keyInShape = {2, 64}; + std::vector cosSinCacheShape = {2, 32}; + std::vector queryOutShape = {2, 64}; + std::vector keyOutShape = {2, 64}; + void* positionsDeviceAddr = nullptr; + void* queryInDeviceAddr = nullptr; + void* keyInDeviceAddr = nullptr; + void* cosSinCacheDeviceAddr = nullptr; + void* queryOutDeviceAddr = nullptr; + void* keyOutDeviceAddr = nullptr; + + aclTensor* positions = nullptr; + aclTensor* queryIn = nullptr; + aclTensor* keyIn = nullptr; + aclTensor* cosSinCache = nullptr; + int64_t headSize = 32; + bool isNeoxStyle = true; + aclTensor *queryOut = nullptr; + aclTensor *keyOut = nullptr; + + std::vector positionsHostData = {0, 1}; + std::vector queryInHostData = {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, 14, 49, 128, 59, 18, 37, 123, 76, 14, 63, 10, + 39, 107, 124, 79, 16, 17, 76, 80, 47, 90, 41, 58, 82, 75, 80, 69, 37, 74, 36, 54, + 26, 32, 54, 13, 100, 105, 15, 13, 69, 122, 26, 94, 59, 29, 14, 60, 8, 24, 17, 45, + 33, 107, 122, 63, 111, 75, 128, 68, 31, 105, 6, 82, 99}; + std::vector keyInHostData = {112, 32, 66, 114, 69, 31, 117, 122, 77, 57, 78, 119, 115, 25, 54, 27, 122, 65, 15, 85, + 33, 16, 36, 6, 95, 15, 43, 6, 66, 91, 14, 101, 78, 51, 110, 74, 56, 30, 127, 61, 53, 29, + 32, 65, 114, 77, 26, 116, 89, 38, 75, 14, 96, 91, 87, 34, 25, 42, 57, 26, 51, 43, 23, 42, + 40, 17, 98, 117, 53, 75, 68, 75, 38, 41, 115, 76, 67, 22, 76, 10, 24, 46, 85, 54, 61, 114, + 10, 59, 6, 123, 58, 10, 115, 9, 13, 58, 66, 120, 23, 30, 83, 13, 11, 76, 18, 82, 57, 4, + 117, 105, 8, 73, 127, 5, 91, 56, 12, 125, 20, 3, 104, 40, 46, 18, 89, 63, 99, 104}; + std::vector cosSinCacheHostData = {112, 32, 66, 114, 69, 31, 117, 122, 77, 57, 78, 119, 115, 25, 54, 27, 122, 65, 15, 85, + 33, 16, 36, 6, 95, 15, 43, 6, 66, 91, 14, 101, 78, 51, 110, 74, 56, 30, 127, 61, 53, 29, + 32, 65, 114, 77, 26, 116, 89, 38, 75, 14, 96, 91, 87, 34, 25, 42, 57, 26, 51, 43, 23, 42}; + std::vector queryOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + std::vector keyOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + + ret = CreateAclTensor(positionsHostData, positionsShape, + &positionsDeviceAddr, aclDataType::ACL_INT64, + &positions); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(queryInHostData, queryInShape, &queryInDeviceAddr, + aclDataType::ACL_FLOAT, &queryIn); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(keyInHostData, keyInShape, &keyInDeviceAddr, + aclDataType::ACL_FLOAT, &keyIn); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(cosSinCacheHostData, cosSinCacheShape, &cosSinCacheDeviceAddr, + aclDataType::ACL_FLOAT, &cosSinCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + ret = CreateAclTensor(queryOutHostData, queryOutShape, &queryOutDeviceAddr, aclDataType::ACL_FLOAT, + &queryOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(keyOutHostData, keyOutShape, &keyOutDeviceAddr, aclDataType::ACL_FLOAT, + &keyOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3. 调用CANN算子库API,需要修改为具体的Api名称 + uint64_t workspaceSize = 0; + aclOpExecutor *executor; + + // 调用aclnnRopeWithSinCosCache第一段接口 + ret = aclnnRopeWithSinCosCacheGetWorkspaceSize(positions, queryIn, keyIn, cosSinCache, nullptr, headSize, isNeoxStyle, + queryOut, keyOut, &workspaceSize, &executor); + CHECK_RET( + ret == ACL_SUCCESS, + LOG_PRINT("aclnnRopeWithSinCosCacheGetWorkspaceSize 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); + } + + // 调用aclnnRopeWithSinCosCache第二段接口 + ret = aclnnRopeWithSinCosCache(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, + LOG_PRINT("aclnnRopeWithSinCosCache 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(queryOutShape, &queryOutDeviceAddr); + PrintOutResult(keyOutShape, &keyOutDeviceAddr); + + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(positions); + aclDestroyTensor(queryIn); + aclDestroyTensor(keyIn); + aclDestroyTensor(cosSinCache); + aclDestroyTensor(queryOut); + aclDestroyTensor(keyOut); + + // 7. 释放device资源 + aclrtFree(positionsDeviceAddr); + aclrtFree(queryInDeviceAddr); + aclrtFree(keyInDeviceAddr); + aclrtFree(cosSinCacheDeviceAddr); + aclrtFree(queryOutDeviceAddr); + aclrtFree(keyOutDeviceAddr); + + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; +} +``` diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/docs/aclnnRopeWithSinCosCacheV2.md b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/docs/aclnnRopeWithSinCosCacheV2.md new file mode 100644 index 0000000000000000000000000000000000000000..888337d399d5aeed28f33d978025064a7fb5aa84 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/docs/aclnnRopeWithSinCosCacheV2.md @@ -0,0 +1,746 @@ +# aclnnRopeWithSinCosCacheV2 + +[📄 查看源码](https://gitcode.com/cann/ops-transformer/tree/master/posembedding/rope_with_sin_cos_cache) + +## 产品支持情况 + +| 产品 | 是否支持 | +| :----------------------------------------------------------- | :------: | +| Ascend 950PR/Ascend 950DT | x | +| Atlas A3 训练系列产品/Atlas A3 推理系列产品 | √ | +| Atlas A2 训练系列产品/Atlas A2 推理系列产品 | √ | +| Atlas 200I/500 A2 推理产品 | × | +| Atlas 推理系列产品 | × | +| Atlas 训练系列产品 | × | + +## 功能说明 + +* 接口功能:推理网络为了提升性能,将sin和cos输入通过cache传入,执行旋转位置编码计算。**该接口相较于[aclnnRopeWithSinCosCache](./aclnnRopeWithSinCosCache.md)接口,新增cacheMode参数,指示拼接cos和sin的方式**: + - cacheMode=0时,与[aclnnRopeWithSinCosCache](./aclnnRopeWithSinCosCache.md)实现相同,为分段式拼接cos和sin。 + - cacheMode=1时,为交错式拼接cos和sin。 +* 计算公式: + + 1、**mrope模式**:positions的shape输入是[m, numTokens], m为mropeSection的元素数,支持3或4: + + $$ + cosSin[i] = cosSinCache[positions[i]] + $$ + + $$ + cos, sin = cosSin.chunk(2, dim=-1) + $$ + + (1)cacheMode为0: + - mropeSection的元素数为3: + + $$ + cos0 = cos[0, :, :mropeSection[0]] + $$ + + $$ + cos1 = cos[1, :, mropeSection[0]:(mropeSection[0] + mropeSection[1])] + $$ + + $$ + cos2 = cos[2, :, (mropeSection[0] + mropeSection[1]):(mropeSection[0] + mropeSection[1] + mropeSection[2])] + $$ + + $$ + cos = torch.cat((cos0, cos1, cos2), dim=-1) + $$ + + $$ + sin0 = sin[0, :, :mropeSection[0]] + $$ + + $$ + sin1 = sin[1, :, mropeSection[0]:(mropeSection[0] + mropeSection[1])] + $$ + + $$ + sin2 = sin[2, :, (mropeSection[0] + mropeSection[1]):(mropeSection[0] + mropeSection[1] + mropeSection[2])] + $$ + + $$ + sin= torch.cat((sin0, sin1, sin2), dim=-1) + $$ + + $$ + queryRot = query[..., :rotaryDim] + $$ + + $$ + queryPass = query[..., rotaryDim:] + $$ + + - mropeSection的元素数为4: + + $$ + cos = torch.cat([m[i]\ for\ i, m\ in\ enumerate(cos.split(mropeSection, dim=-1))], dim=-1) + $$ + + $$ + sin = torch.cat([m[i]\ for\ i, m\ in\ enumerate(sin.split(mropeSection, dim=-1))], dim=-1) + $$ + + $$ + queryRot = query[..., :rotaryDim] + $$ + + $$ + queryPass = query[..., rotaryDim:] + $$ + + (2)cacheMode为1: + + $$ + cosTmp = cos + $$ + + $$ + cos [..., 1:mropeSection[1] * 3:3] = cosTmp[1, ..., 1:mropeSection[1] * 3:3] + $$ + + $$ + cos[..., 2:mropeSection[1] * 3:3] = cosTmp[2, ..., 2:mropeSection[1] * 3:3] + $$ + + $$ + sinTmp = sin + $$ + + $$ + sin[..., 1:mropeSection[1] * 3:3] = sinTmp [1, ..., 1:mropeSection[1] * 3:3] + $$ + + $$ + sin[..., 2:mropeSection[1] * 3:3] = sinTmp [2, ..., 2:mropeSection[1] * 3:3] + $$ + + $$ + queryRot = query[..., :rotaryDim] + $$ + + $$ + queryPass = query[..., rotaryDim:] + $$ + + (1)rotate\_half(GPT-NeoX style)计算模式: + + $$ + x1, x2 = torch.chunk(queryRot, 2, dim=-1) + $$ + + $$ + o1[i] = x1[i] * cos[i] - x2[i] * sin[i] + $$ + + $$ + o2[i] = x2[i] * cos[i] + x1[i] * sin[i] + $$ + + $$ + queryRot = torch.cat((o1, o2), dim=-1) + $$ + + $$ + query = torch.cat((queryRot, queryPass), dim=-1) + $$ + + (2)rotate\_interleaved(GPT-J style)计算模式: + + $$ + x1 = queryRot[..., ::2] + $$ + + $$ + x2 = queryRot[..., 1::2] + $$ + + $$ + o1[i] = x1[i] * cos[i] - x2[i] * sin[i] + $$ + + $$ + o2[i] = x2[i] * cos[i] + x1[i] * sin[i] + $$ + + $$ + queryRot = torch.stack((o1, o2), dim=-1) + $$ + + $$ + query = torch.cat((queryRot, queryPass), dim=-1) + $$ + + 2、**rope模式**:positions的shape输入是[numTokens]: + + $$ + cosSin[i] = cosSinCache[positions[i]] + $$ + + $$ + cos, sin = cosSin.chunk(2, dim=-1) + $$ + + $$ + queryRot = query[..., :rotaryDim] + $$ + + $$ + queryPass = query[..., rotaryDim:] + $$ + + (1)rotate\_half(GPT-NeoX style)计算模式: + + $$ + x1, x2 = torch.chunk(queryRot, 2, dim=-1) + $$ + + $$ + o1[i] = x1[i] * cos[i] - x2[i] * sin[i] + $$ + + $$ + o2[i] = x2[i] * cos[i] + x1[i] * sin[i] + $$ + + $$ + queryRot = torch.cat((o1, o2), dim=-1) + $$ + + $$ + query = torch.cat((queryRot, queryPass), dim=-1) + $$ + + (2)rotate\_interleaved(GPT-J style)计算模式: + + $$ + x1 = queryRot[..., ::2] + $$ + + $$ + x2 = queryRot[..., 1::2] + $$ + + $$ + o1[i] = x1[i] * cos[i] - x2[i] * sin[i] + $$ + + $$ + o2[i] = x2[i] * cos[i] + x1[i] * sin[i] + $$ + + $$ + queryRot = torch.stack((o1, o2), dim=-1) + $$ + + $$ + query = torch.cat((queryRot, queryPass), dim=-1) + $$ + +## 函数原型 + +该算子采用两段式接口,必须先调用“aclnnRopeWithSinCosCacheV2GetWorkspaceSize”接口获取计算所需workspace大小以及包含了算子计算流程的执行器,再调用“aclnnRopeWithSinCosCacheV2”接口执行计算。 + +```c++ +aclnnStatus aclnnRopeWithSinCosCacheV2GetWorkspaceSize( + const aclTensor *positions, + const aclTensor *queryIn, + const aclTensor *keyIn, + const aclTensor *cosSinCache, + const aclIntArray *mropeSection, + int64_t headSize, + bool isNeoxStyle, + int64_t cacheMode, + aclTensor *queryOut, + aclTensor *keyOut, + uint64_t *workspaceSize, + aclOpExecutor **executor) +``` + +```c++ +aclnnStatus aclnnRopeWithSinCosCacheV2( + void *workspace, + uint64_t workspaceSize, + aclOpExecutor *executor, + aclrtStream stream) +``` + +## aclnnRopeWithSinCosCacheV2GetWorkspaceSize + +- **参数说明**: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述使用说明数据类型数据格式维度(shape)非连续Tensor
positions输入公式中的positions,用于选取位置编码张量。
  • 不支持空tensor。
  • rope模式shape为(numTokens)。
  • mrope模式shape为(3, numTokens)或(4, numTokens)。
INT64ND1-2√
queryIn输入公式中的query,要执行旋转位置编码的第一个张量。
  • 不支持空tensor。
  • 要求是一个2D的Tensor,shape为(numTokens, numQHeads*headSize)。
BFLOAT16、FLOAT16、FLOAT32ND2√
keyIn输入要执行旋转位置编码的第二个张量。
  • 不支持空tensor。
  • 要求是一个2D的Tensor,shape为(numTokens, numKHeads*headSize)。
BFLOAT16、FLOAT16、FLOAT32ND2√
cosSinCache输入表示参与计算的位置编码张量。
  • 不支持空tensor。
  • 要求是一个2D的Tensor,shape为(maxSeqLen, rotaryDim),maxSeqLen表示模型处理的序列的最大长度,rotaryDim表示旋转位置嵌入的维度大小。
BFLOAT16、FLOAT16、FLOAT32ND2√
mropeSection输入公式中的mropeSection,mrope模式下用于整合输入的位置编码张量信息。输入mropeSection属性表示开启mrope模式,不开启mrope模式(即rope模式)输入为nullptr。aclIntArray---
headSize输入每个注意力头维度大小。-INT64---
isNeoxStyle输入表示是否使用GPT-NeoX计算模式。
  • true表示GPT-NeoX style计算模式。
  • false表示GPT-J style计算模式。
BOOL---
cacheMode输入表示使用分段式或者交错式拼接cos和sin。
  • 0表示分段式。
  • 1表示交错式。
INT64---
queryOut输出query执行旋转位置编码后的结果。
  • 数据类型同query。
  • 要求是一个2D的Tensor,shape为(numTokens, numQHeads*headSize)。
FLOAT32、FLOAT16、BFLOAT16ND2×
keyOut输出key执行旋转位置编码后的结果。
  • 数据类型同key。
  • 要求是一个2D的Tensor,shape为(numTokens, numKHeads*headSize)。
FLOAT32、FLOAT16、BFLOAT16ND2×
workspaceSize输出返回用户需要在Device侧申请的workspace大小。-----
executor输出返回op执行器,包含了算子计算流程。-----
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + + 第一段接口完成入参校验,出现以下场景时报错: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
返回值错误码描述
ACLNN_ERR_PARAM_NULLPTR 161001 传入的必选输入、必选输出或者必选属性,是空指针。
ACLNN_ERR_PARAM_INVALID 161002 输入和输出的数据类型和数据格式不在支持的范围之内。
ACLNN_ERR_INNER_TILING_ERROR 561002 多个输入tensor之间的shape信息不匹配。
输入属性和输入tensor之间的shape信息不匹配。
ACLNN_ERR_INNER_TILING_ERROR 361001 query或者key非64B对齐。
rotaryDim>headSize。
+ +## aclnnRopeWithSinCosCacheV2 + +- **参数说明:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
参数名输入/输出描述
workspace输入在Device侧申请的workspace内存地址。
workspaceSize输入在Device侧申请的workspace大小,由第一段接口aclnnRopeWithSinCosCacheV2GetWorkspaceSize获取。
executor输入op执行器,包含了算子计算流程。
stream输入指定执行任务的Stream。
+ +- **返回值:** + + aclnnStatus:返回算子的执行状态码。 + +## 约束说明 + +- 确定性计算: + - aclnnRopeWithSinCosCacheV2默认确定性实现。 +- queryIn、keyIn、cosSinCache只支持2维shape输入。 +- queryIn、keyIn、cosSinCache输入的数据类型需要保持一致。 +- headSize:数据类型为BFLOAT16或FLOAT16时为32的倍数,数据类型为FLOAT32时为16的倍数。 +- rotaryDim:始终小于等于headSize;数据类型为BFLOAT16或FLOAT16时为32的倍数,数据类型为FLOAT32时为16的倍数;mrope模式下应满足mropeSection所有元素累加和为rotaryDim值的一半。 +- 输入tensor positions的取值应小于cosSinCache的0维maxSeqLen。 +- mrope模式下,mropeSection:取值当前仅支持[16, 24, 24]、[24, 20, 20]、[8, 12, 12]和[16, 16, 16, 16]。 +- mrope模式下,cacheMode仅支持0和1,当mropeSection为[16, 16, 16, 16]时,仅支持0。 + +## 调用示例 + +以下示例代码展示接口调用流程,可供编译和运行时参考。 + +```Cpp +#include +#include +#include "acl/acl.h" +#include "aclnnop/level2/aclnn_rope_with_sin_cos_cache_v2.h" +#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 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: %f\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 positionsShape = {2}; + std::vector queryInShape = {2, 64}; + std::vector keyInShape = {2, 64}; + std::vector cosSinCacheShape = {2, 32}; + std::vector queryOutShape = {2, 64}; + std::vector keyOutShape = {2, 64}; + void* positionsDeviceAddr = nullptr; + void* queryInDeviceAddr = nullptr; + void* keyInDeviceAddr = nullptr; + void* cosSinCacheDeviceAddr = nullptr; + void* queryOutDeviceAddr = nullptr; + void* keyOutDeviceAddr = nullptr; + + aclTensor* positions = nullptr; + aclTensor* queryIn = nullptr; + aclTensor* keyIn = nullptr; + aclTensor* cosSinCache = nullptr; + int64_t headSize = 32; + bool isNeoxStyle = true; + int64_t cacheMode = 1; + aclTensor *queryOut = nullptr; + aclTensor *keyOut = nullptr; + + std::vector positionsHostData = {0, 1}; + std::vector queryInHostData = {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, 14, 49, 128, 59, 18, 37, 123, 76, 14, 63, 10, + 39, 107, 124, 79, 16, 17, 76, 80, 47, 90, 41, 58, 82, 75, 80, 69, 37, 74, 36, 54, + 26, 32, 54, 13, 100, 105, 15, 13, 69, 122, 26, 94, 59, 29, 14, 60, 8, 24, 17, 45, + 33, 107, 122, 63, 111, 75, 128, 68, 31, 105, 6, 82, 99}; + std::vector keyInHostData = {112, 32, 66, 114, 69, 31, 117, 122, 77, 57, 78, 119, 115, 25, 54, 27, 122, 65, 15, 85, + 33, 16, 36, 6, 95, 15, 43, 6, 66, 91, 14, 101, 78, 51, 110, 74, 56, 30, 127, 61, 53, 29, + 32, 65, 114, 77, 26, 116, 89, 38, 75, 14, 96, 91, 87, 34, 25, 42, 57, 26, 51, 43, 23, 42, + 40, 17, 98, 117, 53, 75, 68, 75, 38, 41, 115, 76, 67, 22, 76, 10, 24, 46, 85, 54, 61, 114, + 10, 59, 6, 123, 58, 10, 115, 9, 13, 58, 66, 120, 23, 30, 83, 13, 11, 76, 18, 82, 57, 4, + 117, 105, 8, 73, 127, 5, 91, 56, 12, 125, 20, 3, 104, 40, 46, 18, 89, 63, 99, 104}; + std::vector cosSinCacheHostData = {112, 32, 66, 114, 69, 31, 117, 122, 77, 57, 78, 119, 115, 25, 54, 27, 122, 65, 15, 85, + 33, 16, 36, 6, 95, 15, 43, 6, 66, 91, 14, 101, 78, 51, 110, 74, 56, 30, 127, 61, 53, 29, + 32, 65, 114, 77, 26, 116, 89, 38, 75, 14, 96, 91, 87, 34, 25, 42, 57, 26, 51, 43, 23, 42}; + std::vector queryOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + std::vector keyOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + + ret = CreateAclTensor(positionsHostData, positionsShape, + &positionsDeviceAddr, aclDataType::ACL_INT64, + &positions); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(queryInHostData, queryInShape, &queryInDeviceAddr, + aclDataType::ACL_FLOAT, &queryIn); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(keyInHostData, keyInShape, &keyInDeviceAddr, + aclDataType::ACL_FLOAT, &keyIn); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(cosSinCacheHostData, cosSinCacheShape, &cosSinCacheDeviceAddr, + aclDataType::ACL_FLOAT, &cosSinCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + ret = CreateAclTensor(queryOutHostData, queryOutShape, &queryOutDeviceAddr, aclDataType::ACL_FLOAT, + &queryOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(keyOutHostData, keyOutShape, &keyOutDeviceAddr, aclDataType::ACL_FLOAT, + &keyOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3. 调用CANN算子库API,需要修改为具体的Api名称 + uint64_t workspaceSize = 0; + aclOpExecutor *executor; + + // 调用aclnnRopeWithSinCosCacheV2第一段接口 + ret = aclnnRopeWithSinCosCacheV2GetWorkspaceSize(positions, queryIn, keyIn, cosSinCache, nullptr, headSize, isNeoxStyle, cacheMode, + queryOut, keyOut, &workspaceSize, &executor); + CHECK_RET( + ret == ACL_SUCCESS, + LOG_PRINT("aclnnRopeWithSinCosCacheV2GetWorkspaceSize 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); + } + + // 调用aclnnRopeWithSinCosCacheV2第二段接口 + ret = aclnnRopeWithSinCosCacheV2(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, + LOG_PRINT("aclnnRopeWithSinCosCacheV2 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(queryOutShape, &queryOutDeviceAddr); + PrintOutResult(keyOutShape, &keyOutDeviceAddr); + + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(positions); + aclDestroyTensor(queryIn); + aclDestroyTensor(keyIn); + aclDestroyTensor(cosSinCache); + aclDestroyTensor(queryOut); + aclDestroyTensor(keyOut); + + // 7. 释放device资源 + aclrtFree(positionsDeviceAddr); + aclrtFree(queryInDeviceAddr); + aclrtFree(keyInDeviceAddr); + aclrtFree(cosSinCacheDeviceAddr); + aclrtFree(queryOutDeviceAddr); + aclrtFree(keyOutDeviceAddr); + + if (workspaceSize > 0) { + aclrtFree(workspaceAddr); + } + aclrtDestroyStream(stream); + aclrtResetDevice(deviceId); + aclFinalize(); + + return 0; +} +``` diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/examples/test_aclnn_rope_with_sin_cos_cache.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/examples/test_aclnn_rope_with_sin_cos_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14a783ab0db937e07d1cea111c07471ceafec158 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/examples/test_aclnn_rope_with_sin_cos_cache.cpp @@ -0,0 +1,232 @@ +/** + * 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 "acl/acl.h" +#include "aclnnop/aclnn_rope_with_sin_cos_cache.h" +#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 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: %f\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初始化,参考AscendCL对外接口列表 + // 根据自己的实际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 positionsShape = {2}; + std::vector queryInShape = {2, 64}; + std::vector keyInShape = {2, 64}; + std::vector cosSinCacheShape = {2, 32}; + std::vector queryOutShape = {2, 64}; + std::vector keyOutShape = {2, 64}; + void* positionsDeviceAddr = nullptr; + void* queryInDeviceAddr = nullptr; + void* keyInDeviceAddr = nullptr; + void* cosSinCacheDeviceAddr = nullptr; + void* queryOutDeviceAddr = nullptr; + void* keyOutDeviceAddr = nullptr; + + aclTensor* positions = nullptr; + aclTensor* queryIn = nullptr; + aclTensor* keyIn = nullptr; + aclTensor* cosSinCache = nullptr; + int64_t headSize = 32; + bool isNeoxStyle = true; + aclTensor *queryOut = nullptr; + aclTensor *keyOut = nullptr; + + std::vector positionsHostData = {0, 1}; + std::vector queryInHostData = {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, 14, 49, 128, 59, 18, 37, 123, 76, 14, 63, 10, + 39, 107, 124, 79, 16, 17, 76, 80, 47, 90, 41, 58, 82, 75, 80, 69, 37, 74, 36, 54, + 26, 32, 54, 13, 100, 105, 15, 13, 69, 122, 26, 94, 59, 29, 14, 60, 8, 24, 17, 45, + 33, 107, 122, 63, 111, 75, 128, 68, 31, 105, 6, 82, 99}; + std::vector keyInHostData = {112, 32, 66, 114, 69, 31, 117, 122, 77, 57, 78, 119, 115, 25, 54, 27, 122, 65, 15, 85, + 33, 16, 36, 6, 95, 15, 43, 6, 66, 91, 14, 101, 78, 51, 110, 74, 56, 30, 127, 61, 53, 29, + 32, 65, 114, 77, 26, 116, 89, 38, 75, 14, 96, 91, 87, 34, 25, 42, 57, 26, 51, 43, 23, 42, + 40, 17, 98, 117, 53, 75, 68, 75, 38, 41, 115, 76, 67, 22, 76, 10, 24, 46, 85, 54, 61, 114, + 10, 59, 6, 123, 58, 10, 115, 9, 13, 58, 66, 120, 23, 30, 83, 13, 11, 76, 18, 82, 57, 4, + 117, 105, 8, 73, 127, 5, 91, 56, 12, 125, 20, 3, 104, 40, 46, 18, 89, 63, 99, 104}; + std::vector cosSinCacheHostData = {112, 32, 66, 114, 69, 31, 117, 122, 77, 57, 78, 119, 115, 25, 54, 27, 122, 65, 15, 85, + 33, 16, 36, 6, 95, 15, 43, 6, 66, 91, 14, 101, 78, 51, 110, 74, 56, 30, 127, 61, 53, 29, + 32, 65, 114, 77, 26, 116, 89, 38, 75, 14, 96, 91, 87, 34, 25, 42, 57, 26, 51, 43, 23, 42}; + std::vector queryOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + std::vector keyOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + + ret = CreateAclTensor(positionsHostData, positionsShape, + &positionsDeviceAddr, aclDataType::ACL_INT64, + &positions); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(queryInHostData, queryInShape, &queryInDeviceAddr, + aclDataType::ACL_BF16, &queryIn); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(keyInHostData, keyInShape, &keyInDeviceAddr, + aclDataType::ACL_BF16, &keyIn); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(cosSinCacheHostData, cosSinCacheShape, &cosSinCacheDeviceAddr, + aclDataType::ACL_BF16, &cosSinCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + ret = CreateAclTensor(queryOutHostData, queryOutShape, &queryOutDeviceAddr, aclDataType::ACL_BF16, + &queryOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(keyOutHostData, keyOutShape, &keyOutDeviceAddr, aclDataType::ACL_BF16, + &keyOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3. 调用CANN算子库API,需要修改为具体的Api名称 + uint64_t workspaceSize = 0; + aclOpExecutor *executor; + + // 调用aclnnRopeWithSinCosCache第一段接口 + ret = aclnnRopeWithSinCosCacheGetWorkspaceSize(positions, queryIn, keyIn, cosSinCache, nullptr, headSize, isNeoxStyle, + queryOut, keyOut, &workspaceSize, &executor); + CHECK_RET( + ret == ACL_SUCCESS, + LOG_PRINT("aclnnRopeWithSinCosCacheGetWorkspaceSize 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); + } + + // 调用aclnnRopeWithSinCosCache第二段接口 + ret = aclnnRopeWithSinCosCache(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, + LOG_PRINT("aclnnRopeWithSinCosCache 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(queryOutShape, &queryOutDeviceAddr); + PrintOutResult(keyOutShape, &keyOutDeviceAddr); + + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(positions); + aclDestroyTensor(queryIn); + aclDestroyTensor(keyIn); + aclDestroyTensor(cosSinCache); + aclDestroyTensor(queryOut); + aclDestroyTensor(keyOut); + + // 7. 释放device资源 + aclrtFree(positionsDeviceAddr); + aclrtFree(queryInDeviceAddr); + aclrtFree(keyInDeviceAddr); + aclrtFree(cosSinCacheDeviceAddr); + aclrtFree(queryOutDeviceAddr); + aclrtFree(keyOutDeviceAddr); + + 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/rope_with_sin_cos_cache/examples/test_aclnn_rope_with_sin_cos_cache_v2.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/examples/test_aclnn_rope_with_sin_cos_cache_v2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da46450715461738a840bcd900ee9f32079c05e0 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/examples/test_aclnn_rope_with_sin_cos_cache_v2.cpp @@ -0,0 +1,233 @@ +/** + * 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 "acl/acl.h" +#include "aclnnop/level2/aclnn_rope_with_sin_cos_cache_v2.h" +#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 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: %f\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 positionsShape = {2}; + std::vector queryInShape = {2, 64}; + std::vector keyInShape = {2, 64}; + std::vector cosSinCacheShape = {2, 32}; + std::vector queryOutShape = {2, 64}; + std::vector keyOutShape = {2, 64}; + void* positionsDeviceAddr = nullptr; + void* queryInDeviceAddr = nullptr; + void* keyInDeviceAddr = nullptr; + void* cosSinCacheDeviceAddr = nullptr; + void* queryOutDeviceAddr = nullptr; + void* keyOutDeviceAddr = nullptr; + + aclTensor* positions = nullptr; + aclTensor* queryIn = nullptr; + aclTensor* keyIn = nullptr; + aclTensor* cosSinCache = nullptr; + int64_t headSize = 32; + bool isNeoxStyle = true; + int64_t cacheMode = 1; + aclTensor *queryOut = nullptr; + aclTensor *keyOut = nullptr; + + std::vector positionsHostData = {0, 1}; + std::vector queryInHostData = {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, 14, 49, 128, 59, 18, 37, 123, 76, 14, 63, 10, + 39, 107, 124, 79, 16, 17, 76, 80, 47, 90, 41, 58, 82, 75, 80, 69, 37, 74, 36, 54, + 26, 32, 54, 13, 100, 105, 15, 13, 69, 122, 26, 94, 59, 29, 14, 60, 8, 24, 17, 45, + 33, 107, 122, 63, 111, 75, 128, 68, 31, 105, 6, 82, 99}; + std::vector keyInHostData = {112, 32, 66, 114, 69, 31, 117, 122, 77, 57, 78, 119, 115, 25, 54, 27, 122, 65, 15, 85, + 33, 16, 36, 6, 95, 15, 43, 6, 66, 91, 14, 101, 78, 51, 110, 74, 56, 30, 127, 61, 53, 29, + 32, 65, 114, 77, 26, 116, 89, 38, 75, 14, 96, 91, 87, 34, 25, 42, 57, 26, 51, 43, 23, 42, + 40, 17, 98, 117, 53, 75, 68, 75, 38, 41, 115, 76, 67, 22, 76, 10, 24, 46, 85, 54, 61, 114, + 10, 59, 6, 123, 58, 10, 115, 9, 13, 58, 66, 120, 23, 30, 83, 13, 11, 76, 18, 82, 57, 4, + 117, 105, 8, 73, 127, 5, 91, 56, 12, 125, 20, 3, 104, 40, 46, 18, 89, 63, 99, 104}; + std::vector cosSinCacheHostData = {112, 32, 66, 114, 69, 31, 117, 122, 77, 57, 78, 119, 115, 25, 54, 27, 122, 65, 15, 85, + 33, 16, 36, 6, 95, 15, 43, 6, 66, 91, 14, 101, 78, 51, 110, 74, 56, 30, 127, 61, 53, 29, + 32, 65, 114, 77, 26, 116, 89, 38, 75, 14, 96, 91, 87, 34, 25, 42, 57, 26, 51, 43, 23, 42}; + std::vector queryOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + std::vector keyOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + + ret = CreateAclTensor(positionsHostData, positionsShape, + &positionsDeviceAddr, aclDataType::ACL_INT64, + &positions); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(queryInHostData, queryInShape, &queryInDeviceAddr, + aclDataType::ACL_FLOAT, &queryIn); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(keyInHostData, keyInShape, &keyInDeviceAddr, + aclDataType::ACL_FLOAT, &keyIn); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(cosSinCacheHostData, cosSinCacheShape, &cosSinCacheDeviceAddr, + aclDataType::ACL_FLOAT, &cosSinCache); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + ret = CreateAclTensor(queryOutHostData, queryOutShape, &queryOutDeviceAddr, aclDataType::ACL_FLOAT, + &queryOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + ret = CreateAclTensor(keyOutHostData, keyOutShape, &keyOutDeviceAddr, aclDataType::ACL_FLOAT, + &keyOut); + CHECK_RET(ret == ACL_SUCCESS, return ret); + + // 3. 调用CANN算子库API,需要修改为具体的Api名称 + uint64_t workspaceSize = 0; + aclOpExecutor *executor; + + // 调用aclnnRopeWithSinCosCacheV2第一段接口 + ret = aclnnRopeWithSinCosCacheV2GetWorkspaceSize(positions, queryIn, keyIn, cosSinCache, nullptr, headSize, isNeoxStyle, cacheMode, + queryOut, keyOut, &workspaceSize, &executor); + CHECK_RET( + ret == ACL_SUCCESS, + LOG_PRINT("aclnnRopeWithSinCosCacheV2GetWorkspaceSize 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); + } + + // 调用aclnnRopeWithSinCosCacheV2第二段接口 + ret = aclnnRopeWithSinCosCacheV2(workspaceAddr, workspaceSize, executor, stream); + CHECK_RET(ret == ACL_SUCCESS, + LOG_PRINT("aclnnRopeWithSinCosCacheV2 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(queryOutShape, &queryOutDeviceAddr); + PrintOutResult(keyOutShape, &keyOutDeviceAddr); + + // 6. 释放aclTensor和aclScalar,需要根据具体API的接口定义修改 + aclDestroyTensor(positions); + aclDestroyTensor(queryIn); + aclDestroyTensor(keyIn); + aclDestroyTensor(cosSinCache); + aclDestroyTensor(queryOut); + aclDestroyTensor(keyOut); + + // 7. 释放device资源 + aclrtFree(positionsDeviceAddr); + aclrtFree(queryInDeviceAddr); + aclrtFree(keyInDeviceAddr); + aclrtFree(cosSinCacheDeviceAddr); + aclrtFree(queryOutDeviceAddr); + aclrtFree(keyOutDeviceAddr); + + 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/rope_with_sin_cos_cache/op_graph/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_graph/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..d7b9f7ddebfb3ecc3e68f2dfacbe864efd2b9cff --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_graph/CMakeLists.txt @@ -0,0 +1,11 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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.fusedop.rope_with_sin_cos_cache.graph_plugin.CMakeLists.txt ") diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_graph/fusion_pass/.gitkeep b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_graph/fusion_pass/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_graph/rope_with_sin_cos_cache_proto.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_graph/rope_with_sin_cos_cache_proto.h new file mode 100644 index 0000000000000000000000000000000000000000..3bc70158c9f74621a5743585612898b912a3ce4e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_graph/rope_with_sin_cos_cache_proto.h @@ -0,0 +1,62 @@ +/** + * 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 apply_rotary_pos_emb_proto.h + * \brief + */ +#ifndef OPS_OP_PROTO_INC_ROPE_WITH_SIN_COS_CACHE_OPS_H_ +#define OPS_OP_PROTO_INC_ROPE_WITH_SIN_COS_CACHE_OPS_H_ + +#include "graph/operator_reg.h" + +namespace ge { +/** +* @brief RopeWithSinCosCache. + +* @par Inputs: +* @li positions: A tensor of type int32 of int64. +* @li queryIn: A tensor of type float, bf16, float16. +* @li keyIn: A tensor of type float, bf16, float16. +* @li cosSinCache: A tensor of type float, bf16, float16. + +* @par Attributes: +* @li numQHeads: A int attr. +* @li numKHeads: A int attr. +* @li headSize: A int attr. +* @li mropeSection: A ListInt attr. +* @li qStride: A int attr. +* @li KStride: A int attr. +* @li isNeoxStyle: A bool attr. + +* @par Outputs: +* @li queryOut: A tensor of type FP16/FP32/BF16. +* @li keyOut: A tensor of type FP16/FP32/BF16. +*/ + +REG_OP(RopeWithSinCosCache) + .INPUT(positions, TensorType({DT_INT32, DT_INT64})) + .INPUT(queryIn, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT32})) + .INPUT(keyIn, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT32})) + .INPUT(cosSinCache, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT32})) + .OUTPUT(queryOut, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT32})) + .OUTPUT(keyOut, TensorType({DT_FLOAT16, DT_BF16, DT_FLOAT32})) + .REQUIRED_ATTR(numQHeads, Int) + .REQUIRED_ATTR(numKHeads, Int) + .REQUIRED_ATTR(headSize, Int) + .ATTR(mropeSection, ListInt, {0, 0, 0}) + .ATTR(qStride, Int, 0) + .ATTR(kStride, Int, 0) + .ATTR(isNeoxStyle, Bool, true) + .OP_END_FACTORY_REG(RopeWithSinCosCache) + +} // namespace ge + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7a34b54fa0dfcea906dbf06ee4a00bb8d424ae70 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/CMakeLists.txt @@ -0,0 +1,32 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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 (BUILD_OPEN_PROJECT) + target_sources(op_host_aclnnExc PRIVATE + rope_with_sin_cos_cache_def.cpp + ) + add_ops_compile_options( + OP_NAME RopeWithSinCosCache + OPTIONS --cce-auto-sync=on + -Wno-deprecated-declarations + -Werror + ) + if ("${ASCEND_COMPUTE_UNIT}" STREQUAL "ascend950") + add_ops_compile_options( + OP_NAME RopeWithSinCosCache + COMPUTE_UNIT Ascend950PR_9599 + OPTIONS -mllvm -cce-aicore-dcci-before-kernel-end=false + ) + endif() +endif() + +if(NOT BUILD_OPS_RTY_KERNEL) + add_modules_sources(OPTYPE rope_with_sin_cos_cache ACLNNTYPE aclnn_exclude) +endif() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend910_93/rope_with_sin_cos_cache_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend910_93/rope_with_sin_cos_cache_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..79531f91402a50bfa6c1d7262bcf8bff775992a2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend910_93/rope_with_sin_cos_cache_binary.json @@ -0,0 +1,281 @@ +{ + "op_type": "RopeWithSinCosCache", + "op_list": [ + { + "bin_filename": "RopeWithSinCosCache_0", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + }, + { + "bin_filename": "RopeWithSinCosCache_1", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + }, + { + "bin_filename": "RopeWithSinCosCache_2", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend910_93/rope_with_sin_cos_cache_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend910_93/rope_with_sin_cos_cache_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..ddb995e34dcf77e93f85ac3e175fa53154cc2008 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend910_93/rope_with_sin_cos_cache_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 中配置的算子名字和对于的平台决定 +[RopeWithSinCosCache] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend910b/rope_with_sin_cos_cache_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend910b/rope_with_sin_cos_cache_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..79531f91402a50bfa6c1d7262bcf8bff775992a2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend910b/rope_with_sin_cos_cache_binary.json @@ -0,0 +1,281 @@ +{ + "op_type": "RopeWithSinCosCache", + "op_list": [ + { + "bin_filename": "RopeWithSinCosCache_0", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + }, + { + "bin_filename": "RopeWithSinCosCache_1", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + }, + { + "bin_filename": "RopeWithSinCosCache_2", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend910b/rope_with_sin_cos_cache_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend910b/rope_with_sin_cos_cache_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..ddb995e34dcf77e93f85ac3e175fa53154cc2008 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend910b/rope_with_sin_cos_cache_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 中配置的算子名字和对于的平台决定 +[RopeWithSinCosCache] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend950/rope_with_sin_cos_cache_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend950/rope_with_sin_cos_cache_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..79531f91402a50bfa6c1d7262bcf8bff775992a2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend950/rope_with_sin_cos_cache_binary.json @@ -0,0 +1,281 @@ +{ + "op_type": "RopeWithSinCosCache", + "op_list": [ + { + "bin_filename": "RopeWithSinCosCache_0", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "bfloat16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + }, + { + "bin_filename": "RopeWithSinCosCache_1", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + }, + { + "bin_filename": "RopeWithSinCosCache_2", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend950/rope_with_sin_cos_cache_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend950/rope_with_sin_cos_cache_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..ddb995e34dcf77e93f85ac3e175fa53154cc2008 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/ascend950/rope_with_sin_cos_cache_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 中配置的算子名字和对于的平台决定 +[RopeWithSinCosCache] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/kirin9030/rope_with_sin_cos_cache_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/kirin9030/rope_with_sin_cos_cache_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..1cbc7e7c7789eef7cc11e8d7ecd266eadc45f903 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/kirin9030/rope_with_sin_cos_cache_binary.json @@ -0,0 +1,189 @@ +{ + "op_type": "RopeWithSinCosCache", + "op_list": [ + { + "bin_filename": "RopeWithSinCosCache_1", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + }, + { + "bin_filename": "RopeWithSinCosCache_2", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/kirin9030/rope_with_sin_cos_cache_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/kirin9030/rope_with_sin_cos_cache_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..ddb995e34dcf77e93f85ac3e175fa53154cc2008 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/kirin9030/rope_with_sin_cos_cache_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 中配置的算子名字和对于的平台决定 +[RopeWithSinCosCache] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/kirinx90/rope_with_sin_cos_cache_binary.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/kirinx90/rope_with_sin_cos_cache_binary.json new file mode 100644 index 0000000000000000000000000000000000000000..1cbc7e7c7789eef7cc11e8d7ecd266eadc45f903 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/kirinx90/rope_with_sin_cos_cache_binary.json @@ -0,0 +1,189 @@ +{ + "op_type": "RopeWithSinCosCache", + "op_list": [ + { + "bin_filename": "RopeWithSinCosCache_1", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "float16", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + }, + { + "bin_filename": "RopeWithSinCosCache_2", + "inputs": [ + { + "name": "positions", + "index": 0, + "dtype": "int64", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "queryIn", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyIn", + "index": 2, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "cosSinCache", + "index": 3, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "outputs": [ + { + "name": "queryOut", + "index": 0, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + }, + { + "name": "keyOut", + "index": 1, + "dtype": "float32", + "format": "ND", + "paramType": "required", + "shape": [-2] + } + ], + "attrs": [ + { + "name": "numQHeads", + "dtype": "int", + "value": null + }, + { + "name": "numKHeads", + "dtype": "int", + "value": null + }, + { + "name": "headSize", + "dtype": "int", + "value": null + }, + { + "name": "mropeSection", + "dtype": "list_int", + "value": [] + }, + { + "name": "qStride", + "dtype": "int", + "value": null + }, + { + "name": "kStride", + "dtype": "int", + "value": null + }, + { + "name": "isNeoxStyle", + "dtype": "bool", + "value": null + } + ] + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/kirinx90/rope_with_sin_cos_cache_simplified_key.ini b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/kirinx90/rope_with_sin_cos_cache_simplified_key.ini new file mode 100644 index 0000000000000000000000000000000000000000..ddb995e34dcf77e93f85ac3e175fa53154cc2008 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/config/kirinx90/rope_with_sin_cos_cache_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 中配置的算子名字和对于的平台决定 +[RopeWithSinCosCache] +default=0 \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/aclnn_rope_with_sin_cos_cache.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/aclnn_rope_with_sin_cos_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb2e89091bb48661baf2291a2cb0b2ebda1de1b2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/aclnn_rope_with_sin_cos_cache.cpp @@ -0,0 +1,334 @@ +/** + * 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_rope_with_sin_cos_cache.cpp + * \brief + */ + +#include "rope_with_sin_cos_cache.h" +#include "aclnn_kernels/contiguous.h" +#include "aclnn_kernels/reshape.h" +#include "level0/add.h" +#include "rsqrt.h" +#include "aclnn_kernels/cast.h" +#include "aclnn_rope_with_sin_cos_cache.h" +#include "aclnn_rope_with_sin_cos_cache_v2.h" +#include "aclnn_kernels/common/op_error_check.h" +#include "external/aclnn_kernels/aclnn_platform.h" +#include "aclnn/aclnn_base.h" +#include "opdev/common_types.h" +#include "opdev/data_type_utils.h" +#include "opdev/format_utils.h" +#include "opdev/op_dfx.h" +#include "opdev/op_executor.h" +#include "opdev/op_log.h" +#include "opdev/tensor_view_utils.h" +#include "opdev/make_op_executor.h" +#include "iostream" + +using namespace op; +#ifdef __cplusplus +extern "C" { +#endif + +static const int64_t QUERY_OUT_INDEX = 0; +static const int64_t KEY_OUT_INDEX = 1; + +static const int64_t DIM_ZERO = 0; +static const int64_t DIM_ONE = 1; +static const int64_t DIM_NUM = 2; + +static const std::initializer_list ASCEND910B_DTYPE_SUPPORT_LIST = { + op::DataType::DT_FLOAT16, + op::DataType::DT_BF16, + op::DataType::DT_FLOAT, +}; + +static const std::initializer_list positions_dtype_list = {op::DataType::DT_INT64}; + +static const std::initializer_list emptyDtypes = {}; + +static const std::initializer_list> mropeSupportList = { + {16, 24, 24}, {8, 12, 12}, {24, 20, 20}, {11, 11, 10}, {16, 16, 16, 16}}; // 支持的mrope输入 + +static const std::initializer_list cacheModeSupportList = {0, 1}; + +static const std::initializer_list &GetSupportDtypeList() +{ + auto socVersion = GetCurrentPlatformInfo().GetSocVersion(); + if (socVersion == SocVersion::ASCEND910B || socVersion == SocVersion::ASCEND910_93 || + Ops::Transformer::AclnnUtil::IsRegbase()) { + return ASCEND910B_DTYPE_SUPPORT_LIST; + } else { + return emptyDtypes; + } +} + +static bool CheckNotNull(const aclTensor *positions, const aclTensor *queryIn, const aclTensor *keyIn, + const aclTensor *cosSinCache, const aclTensor *queryOut, const aclTensor *keyOut) +{ + OP_CHECK_NULL(positions, return false); + OP_CHECK_NULL(queryIn, return false); + OP_CHECK_NULL(keyIn, return false); + OP_CHECK_NULL(cosSinCache, return false); + OP_CHECK_NULL(queryOut, return false); + OP_CHECK_NULL(keyOut, return false); + return true; +} + +static bool CheckDtypeValid(const aclTensor *positions, const aclTensor *queryIn, const aclTensor *keyIn, + const aclTensor *cosSinCache, const aclTensor *queryOut, const aclTensor *keyOut) +{ + // 检查positions queryIn的数据类型是否在支持列表内 + auto socVersion = GetCurrentPlatformInfo().GetSocVersion(); + const auto &supportList = GetSupportDtypeList(); + if (supportList.size() == 0) { + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "support for %s is not implemented", ToString(socVersion).GetString()); + } + OP_CHECK_DTYPE_NOT_SUPPORT(positions, positions_dtype_list, return false); + OP_CHECK_DTYPE_NOT_SUPPORT(queryIn, supportList, return false); + + // keyIn, cosSinCache, queryOut, keyOut的数据类型是否与out一致 + OP_CHECK_DTYPE_NOT_MATCH(keyIn, queryIn->GetDataType(), return false); + OP_CHECK_DTYPE_NOT_MATCH(cosSinCache, queryIn->GetDataType(), return false); + OP_CHECK_DTYPE_NOT_MATCH(queryOut, queryIn->GetDataType(), return false); + OP_CHECK_DTYPE_NOT_MATCH(keyOut, queryIn->GetDataType(), return false); + return true; +} + +static bool CheckShape(const aclTensor *positions, const aclTensor *queryIn, const aclTensor *keyIn, + const aclTensor *cosSinCache, const aclTensor *queryOut, const aclTensor *keyOut) +{ + // 检查输入的所有shape是不是2维; + if (queryIn->GetViewShape().GetDimNum() != DIM_NUM) { + OP_LOGE(ACLNN_ERR_PARAM_INVALID, + "Expected queryIn to be a vector of size 2, " + "but got queryIn of shape %s.", + op::ToString(queryIn->GetViewShape()).GetString()); + return false; + } + + if (keyIn->GetViewShape().GetDimNum() != DIM_NUM) { + OP_LOGE(ACLNN_ERR_PARAM_INVALID, + "Expected keyIn to be a vector of size 2, " + "but got keyIn of shape %s.", + op::ToString(keyIn->GetViewShape()).GetString()); + return false; + } + + if (cosSinCache->GetViewShape().GetDimNum() != DIM_NUM) { + OP_LOGE(ACLNN_ERR_PARAM_INVALID, + "Expected cosSinCache to be a vector of size 2, " + "but got cosSinCache of shape %s.", + op::ToString(cosSinCache->GetViewShape()).GetString()); + return false; + } + + // 检查是否有维度为0 + if (queryIn->IsEmpty() || keyIn->IsEmpty() || cosSinCache->IsEmpty() || positions->IsEmpty()) { + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "RopeWithSinCosCache not support to process empty tensor currently", + op::ToString(positions->GetViewShape()).GetString()); + return false; + } + + // 检查keyIn的1维度是不是等于queryIn的一维 + OP_CHECK(keyIn->GetViewShape()[0] == queryIn->GetViewShape()[0], + OP_LOGE(ACLNN_ERR_PARAM_INVALID, + "Expected keyIn.shape[0] == queryIn->GetViewShape()[0] to be true, but got false."), + return false); + // 检查输入和输出的shape 是否相同 + OP_CHECK_SHAPE_NOT_EQUAL(queryOut, queryIn, return false); + OP_CHECK_SHAPE_NOT_EQUAL(keyOut, keyIn, return false); + + return true; +} + +static bool CheckMropeSection(const std::vector &target, const std::vector> &support) +{ + for (const auto &vec : support) { + if (vec == target) + return true; + } + return false; +} + +static bool CheckCacheMode(const int64_t target, const std::initializer_list support) +{ + for (const auto &item : support) { + if (item == target) { + return true; + } + } + return false; +} + +static aclnnStatus CheckParams(const aclTensor *positions, const aclTensor *queryIn, const aclTensor *keyIn, + const aclTensor *cosSinCache, const aclIntArray *mropeSection, aclTensor *queryOut, + aclTensor *keyOut) +{ + // 1. 检查参数是否为空指针 + CHECK_RET(CheckNotNull(positions, queryIn, keyIn, cosSinCache, queryOut, keyOut), ACLNN_ERR_PARAM_NULLPTR); + + // 2. 检查输入的数据类型是否在API支持的数据类型范围之内 + CHECK_RET(CheckDtypeValid(positions, queryIn, keyIn, cosSinCache, queryOut, keyOut), ACLNN_ERR_PARAM_INVALID); + + // 3. 检查shape是否支持 + CHECK_RET(CheckShape(positions, queryIn, keyIn, cosSinCache, queryOut, keyOut), ACLNN_ERR_PARAM_INVALID); + + // 4. 检查mrope模式下是否满足mropeSection[0] + mropeSection[1] + mropeSection[2] == rotaryDim/2 + if (mropeSection != nullptr) { + uint64_t mropeSectionSize = 0U; + aclGetIntArraySize(mropeSection, &mropeSectionSize); + OP_CHECK((mropeSectionSize == 3 || mropeSectionSize == 4), + OP_LOGE(ACLNN_ERR_PARAM_INVALID, + "[aclnnRopeWithSinCosCache] Expected mropeSectionSize is 3 or 4, " + "but got %ld.", + mropeSectionSize), + return ACLNN_ERR_PARAM_INVALID); + std::vector mropeSectionIn; + int64_t mropeSectionSum = 0; + mropeSectionIn.reserve(mropeSectionSize); + for (size_t i = 0; i < mropeSectionSize; ++i) { + OP_CHECK(static_cast((*mropeSection)[i]) >= 0, + OP_LOGE(ACLNN_ERR_PARAM_INVALID, + "[aclnnRopeWithSinCosCache] The value of mropeSection must be non-negative, " + "but got %ld.", + static_cast((*mropeSection)[i])), + return ACLNN_ERR_PARAM_INVALID); + int64_t val = static_cast((*mropeSection)[i]); + mropeSectionIn.push_back(val); + mropeSectionSum += val; + } + int64_t rotary_dim = cosSinCache->GetViewShape()[1]; + // kernel中mropesection[0]>0为mrope模式,否则rope模式 + if (mropeSectionIn[0] > 0) { + OP_CHECK(mropeSectionSum * 2 == rotary_dim, + OP_LOGE(ACLNN_ERR_PARAM_INVALID, + "[aclnnRopeWithSinCosCache] The accumulated value of mropeSection" + "should be equal to rotaryDim/2, but got %ld.", + mropeSectionSum), + return ACLNN_ERR_PARAM_INVALID); + OP_CHECK(CheckMropeSection(mropeSectionIn, mropeSupportList), + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "[aclnnRopeWithSinCosCache] The input mropeSection " + "must be in the supported list."), + return ACLNN_ERR_PARAM_INVALID); + } + } + return ACLNN_SUCCESS; +} + +aclnnStatus aclnnRopeWithSinCosCacheGetWorkspaceSizeCommon(const aclTensor *positions, const aclTensor *queryIn, + const aclTensor *keyIn, const aclTensor *cosSinCache, + const aclIntArray *mropeSection, int64_t headSize, + bool isNeoxStyle, int64_t cacheMode, aclTensor *queryOut, + aclTensor *keyOut, uint64_t *workspaceSize, + aclOpExecutor **executor) +{ + // 固定写法,参数检查 + auto ret = CheckParams(positions, queryIn, keyIn, cosSinCache, mropeSection, queryOut, keyOut); + CHECK_RET(ret == ACLNN_SUCCESS, ret); + CHECK_RET(headSize != 0, ACLNN_ERR_PARAM_INVALID); + + // 固定写法,创建OpExecutor + auto uniqueExecutor = CREATE_EXECUTOR(); + CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR); + + // 固定写法,将输入positions转换成连续的tensor + auto positionsContiguous = l0op::Contiguous(positions, uniqueExecutor.get()); + CHECK_RET(positionsContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + + // 固定写法,将输入cosSinCosCache转换成连续的tensor + auto cosSinCacheContiguous = l0op::Contiguous(cosSinCache, uniqueExecutor.get()); + CHECK_RET(cosSinCacheContiguous != nullptr, ACLNN_ERR_INNER_NULLPTR); + + int64_t numQheads = queryIn->GetViewShape()[1] / headSize; + int64_t numKheads = keyIn->GetViewShape()[1] / headSize; + + int64_t queryStride = queryIn->GetViewStrides()[0]; + int64_t keyStride = keyIn->GetViewStrides()[0]; + + std::tuple result = l0op::RopeWithSinCosCache( + positionsContiguous, queryIn, keyIn, cosSinCacheContiguous, mropeSection, headSize, isNeoxStyle, queryStride, + keyStride, numQheads, numKheads, cacheMode, uniqueExecutor.get()); + auto query = std::get<0>(result); + CHECK_RET(query != nullptr, ACLNN_ERR_INNER_NULLPTR); + auto key = std::get<1>(result); + CHECK_RET(key != nullptr, ACLNN_ERR_INNER_NULLPTR); + + // 固定写法,将计算结果拷贝到输出out上,out可能是非连续的tensor + auto queryViewCopyResult = l0op::ViewCopy(query, queryOut, uniqueExecutor.get()); + CHECK_RET(queryViewCopyResult != nullptr, ACLNN_ERR_INNER_NULLPTR); + + auto keyViewCopyResult = l0op::ViewCopy(key, keyOut, uniqueExecutor.get()); + CHECK_RET(keyViewCopyResult != nullptr, ACLNN_ERR_INNER_NULLPTR); + // 固定写法,获取计算过程中需要使用的workspace大小 + *workspaceSize = uniqueExecutor->GetWorkspaceSize(); + uniqueExecutor.ReleaseTo(executor); + return ACLNN_SUCCESS; +} + +aclnnStatus aclnnRopeWithSinCosCacheGetWorkspaceSize(const aclTensor *positions, const aclTensor *queryIn, + const aclTensor *keyIn, const aclTensor *cosSinCache, + const aclIntArray *mropeSection, int64_t headSize, + bool isNeoxStyle, aclTensor *queryOut, aclTensor *keyOut, + uint64_t *workspaceSize, aclOpExecutor **executor) +{ + // V1版本只支持cacheMode为0 + int64_t cacheMode = 0; + L2_DFX_PHASE_1(aclnnRopeWithSinCosCache, + DFX_IN(positions, queryIn, keyIn, cosSinCache, mropeSection, headSize, isNeoxStyle, cacheMode), + DFX_OUT(queryOut, keyOut)); + + return aclnnRopeWithSinCosCacheGetWorkspaceSizeCommon(positions, queryIn, keyIn, cosSinCache, mropeSection, + headSize, isNeoxStyle, cacheMode, queryOut, keyOut, + workspaceSize, executor); +} + +// 固定写法,获取计算过程中需要使用的workspace大小 +aclnnStatus aclnnRopeWithSinCosCache(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + aclrtStream stream) +{ + L2_DFX_PHASE_2(aclnnRopeWithSinCosCache); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +aclnnStatus aclnnRopeWithSinCosCacheV2GetWorkspaceSize(const aclTensor *positions, const aclTensor *queryIn, + const aclTensor *keyIn, const aclTensor *cosSinCache, + const aclIntArray *mropeSection, int64_t headSize, + bool isNeoxStyle, int64_t cacheMode, aclTensor *queryOut, + aclTensor *keyOut, uint64_t *workspaceSize, + aclOpExecutor **executor) +{ + L2_DFX_PHASE_1(aclnnRopeWithSinCosCacheV2, + DFX_IN(positions, queryIn, keyIn, cosSinCache, mropeSection, headSize, isNeoxStyle, cacheMode), + DFX_OUT(queryOut, keyOut)); + + OP_CHECK(CheckCacheMode(cacheMode, cacheModeSupportList), + OP_LOGE(ACLNN_ERR_PARAM_INVALID, "[aclnnRopeWithSinCosCache] cacheMode only support 0 or 1, but got %ld", + cacheMode), + return ACLNN_ERR_PARAM_INVALID); + + return aclnnRopeWithSinCosCacheGetWorkspaceSizeCommon(positions, queryIn, keyIn, cosSinCache, mropeSection, + headSize, isNeoxStyle, cacheMode, queryOut, keyOut, + workspaceSize, executor); +} + +// 固定写法,获取计算过程中需要使用的workspace大小 +aclnnStatus aclnnRopeWithSinCosCacheV2(void *workspace, uint64_t workspaceSize, aclOpExecutor *executor, + aclrtStream stream) +{ + L2_DFX_PHASE_2(aclnnRopeWithSinCosCacheV2); + return CommonOpExecutorRun(workspace, workspaceSize, executor, stream); +} + +#ifdef __cplusplus +} +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/aclnn_rope_with_sin_cos_cache.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/aclnn_rope_with_sin_cos_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..07d8bd07d18cc6c94661a3cb3acaec8c116ba39c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/aclnn_rope_with_sin_cos_cache.h @@ -0,0 +1,69 @@ +/** + * 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_ROPE_WITH_SIN_COS_CACHE_H_ +#define OP_API_INC_ROPE_WITH_SIN_COS_CACHE_H_ + +#include "aclnn/aclnn_base.h" +#include "aclnn_util.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief aclnnRopeWithSinCosCache的第一段接口,根据具体的计算流程,计算workspace大小。 + * @domain aclnn_ops_infer + * + * 算子功能:完成rope计算。支持连续和非连续的输入。 + * 计算公式: + * o1= x1 * cos - x2 * sin + * o2= x2 * cos + x1 * sin + * 其中x1、x2分别表示queryIn/keyIn的前半部分与后半部分,o1、o2分别表示queryOut/keyOut的前半部分与后半部分。 + * 参数描述: + * @param [in] positions: device的aclTensor,为cossincache中的索引信息 + * @param [in] queryIn: device的aclTensor,表示要执行旋转位置编码的第一个张量,支持BFLOAT16,FLOAT16,FLOAT32 + * @param [in] keyIn: device的aclTensor,表示要执行旋转位置编码的第二个张量,支持BFLOAT16,FLOAT16,FLOAT32 + * @param [in] cosSinCache: device的aclTensor,表示参与计算的位置编码张量,支持BFLOAT16,FLOAT16,FLOAT32 + * @param [in] mropeSection: + * device的aclTensor,mrope模式下用于整合输入的位置编码张量信息;不使能mrope模式(即rope模式)输入为nullptr + * @param [in] headSize: 属性,表示每个注意力头维度大小,数据类型int64 + * @param [in] isNeoxStyle: 属性,true表示rotate_half(GPT-NeoX style)计算模式,false表示rotate_interleaved(GPT-J + * style)计算模式,数据类型bool + * @param [out] queryOut: device的aclTensor,输出query执行旋转位置编码后的结果, 类型同queryIn + * @param [out] keyOut: device的aclTensor,输出key执行旋转位置编码后的结果,类型同keyIn + * @param [out] workspaceSize: 返回用户需要在npu device侧申请的workspace大小。 + * @param [out] executor: 返回op执行器,包含算子计算流程。 + * @return aclnnStatus: 返回状态码 + */ +ACLNN_API aclnnStatus aclnnRopeWithSinCosCacheGetWorkspaceSize( + const aclTensor* positions, const aclTensor* queryIn, const aclTensor* keyIn, const aclTensor* cosSinCache, + const aclIntArray* mropeSection, int64_t headSize, bool isNeoxStyle, aclTensor* queryOut, aclTensor* keyOut, + uint64_t* workspaceSize, aclOpExecutor** executor); + +/** + * @brief aclnnRopeWithSinCosCache的第二段接口,根据具体的计算流程,计算workspace大小。 + * @domain aclnn_ops_infer + * 算子功能:完成rope计算。支持连续和非连续的输入 + * 参数描述: + * @param [in] workspace: 在npu device侧申请的workspace内存起址。 + * @param [in] workspace_size: 在npu device侧申请的workspace大小,由第一段接口aclnnRsubsGetWorkspaceSize获取。 + * @param [in] executor: op执行器,包含了算子计算流程。 + * @param [in] stream: acl stream流。 + * @return aclnnStatus: 返回状态码。 + */ +ACLNN_API aclnnStatus +aclnnRopeWithSinCosCache(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // OP_API_INC_ROPE_WITH_SIN_COS_CACHE_NORM_H_ diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/aclnn_rope_with_sin_cos_cache_v2.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/aclnn_rope_with_sin_cos_cache_v2.h new file mode 100644 index 0000000000000000000000000000000000000000..69a054fc4e88a5d90c8094b358fc6109f6a452ad --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/aclnn_rope_with_sin_cos_cache_v2.h @@ -0,0 +1,70 @@ +/** + * 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_ROPE_WITH_SIN_COS_CACHE_V2_H_ +#define OP_API_INC_ROPE_WITH_SIN_COS_CACHE_V2_H_ + +#include "aclnn/aclnn_base.h" +#include "aclnn_util.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief aclnnRopeWithSinCosCache的第一段接口,根据具体的计算流程,计算workspace大小。 + * @domain aclnn_ops_infer + * + * 算子功能:完成rope计算。支持连续和非连续的输入。 + * 计算公式: + * o1= x1 * cos - x2 * sin + * o2= x2 * cos + x1 * sin + * 其中x1、x2分别表示queryIn/keyIn的前半部分与后半部分,o1、o2分别表示queryOut/keyOut的前半部分与后半部分。 + * 参数描述: + * @param [in] positions: device的aclTensor,为cossincache中的索引信息 + * @param [in] queryIn: device的aclTensor,表示要执行旋转位置编码的第一个张量,支持BFLOAT16,FLOAT16,FLOAT32 + * @param [in] keyIn: device的aclTensor,表示要执行旋转位置编码的第二个张量,支持BFLOAT16,FLOAT16,FLOAT32 + * @param [in] cosSinCache: device的aclTensor,表示参与计算的位置编码张量,支持BFLOAT16,FLOAT16,FLOAT32 + * @param [in] mropeSection: + * device的aclTensor,mrope模式下用于整合输入的位置编码张量信息;不使能mrope模式(即rope模式)输入为nullptr + * @param [in] headSize: 属性,表示每个注意力头维度大小,数据类型int64 + * @param [in] isNeoxStyle: 属性,true表示rotate_half(GPT-NeoX style)计算模式,false表示rotate_interleaved(GPT-J + * style)计算模式,数据类型bool + * @param [in] cacheMode: 属性,表示从cache中获取cos和sin的方式,目前只支持0和1。0代表分段式,1代表交错式 + * @param [out] queryOut: device的aclTensor,输出query执行旋转位置编码后的结果, 类型同queryIn + * @param [out] keyOut: device的aclTensor,输出key执行旋转位置编码后的结果,类型同keyIn + * @param [out] workspaceSize: 返回用户需要在npu device侧申请的workspace大小。 + * @param [out] executor: 返回op执行器,包含算子计算流程。 + * @return aclnnStatus: 返回状态码 + */ +ACLNN_API aclnnStatus aclnnRopeWithSinCosCacheV2GetWorkspaceSize( + const aclTensor* positions, const aclTensor* queryIn, const aclTensor* keyIn, const aclTensor* cosSinCache, + const aclIntArray* mropeSection, int64_t headSize, bool isNeoxStyle, int64_t cacheMode, aclTensor* queryOut, aclTensor* keyOut, + uint64_t* workspaceSize, aclOpExecutor** executor); + +/** + * @brief aclnnRopeWithSinCosCache的第二段接口,根据具体的计算流程,计算workspace大小。 + * @domain aclnn_ops_infer + * 算子功能:完成rope计算。支持连续和非连续的输入 + * 参数描述: + * @param [in] workspace: 在npu device侧申请的workspace内存起址。 + * @param [in] workspace_size: 在npu device侧申请的workspace大小,由第一段接口aclnnRsubsGetWorkspaceSize获取。 + * @param [in] executor: op执行器,包含了算子计算流程。 + * @param [in] stream: acl stream流。 + * @return aclnnStatus: 返回状态码。 + */ +ACLNN_API aclnnStatus +aclnnRopeWithSinCosCacheV2(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor, aclrtStream stream); + +#ifdef __cplusplus +} +#endif + +#endif // OP_API_INC_ROPE_WITH_SIN_COS_CACHE_NORM_H_ diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/rope_with_sin_cos_cache.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/rope_with_sin_cos_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6446a1156e666e23a9aea66e71146df1ca2dfb63 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/rope_with_sin_cos_cache.cpp @@ -0,0 +1,64 @@ +/** + * 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 rope_with_sin_cos_cache.cpp + * \brief + */ + +#include "rope_with_sin_cos_cache.h" +#include "opdev/aicpu/aicpu_task.h" +#include "opdev/op_log.h" +#include "opdev/op_executor.h" +#include "opdev/make_op_executor.h" +#include "opdev/shape_utils.h" +#include "opdev/op_def.h" +#include "opdev/op_dfx.h" +#include "aclnn_kernels/common/op_error_check.h" + +using namespace op; + +namespace l0op { +OP_TYPE_REGISTER(RopeWithSinCosCache); + +// AICORE算子kernel +const std::tuple RoepWithSinCosCacheAICore( + const aclTensor* positions, const aclTensor* queryIn, const aclTensor* keyIn, const aclTensor* cosSinCache, + const aclIntArray* mropeSection, int64_t headSize, bool isNeoxStyle, int64_t qStride, int64_t kStride, + int64_t numQHeads, int64_t numKHeads, int64_t cacheMode, aclTensor* queryOut, aclTensor* keyOut, aclOpExecutor* executor) +{ + L0_DFX( + RoepWithSinCosCacheAICore, positions, queryIn, keyIn, cosSinCache, mropeSection, headSize, isNeoxStyle, qStride, + kStride, numQHeads, numKHeads, cacheMode, queryOut, keyOut); + // 使用框架宏 ADD_TO_LAUNCHER_LIST_AICORE,将算子加入任务队列 + auto retAicore = ADD_TO_LAUNCHER_LIST_AICORE( + RopeWithSinCosCache, OP_INPUT(positions, queryIn, keyIn, cosSinCache), OP_OUTPUT(queryOut, keyOut), + OP_ATTR(numQHeads, numKHeads, headSize, mropeSection, qStride, kStride, isNeoxStyle, cacheMode)); + if (retAicore != ACLNN_SUCCESS) { + OP_LOGE(ACLNN_ERR_INNER_NULLPTR, "RoepWithSinCosCacheAICore ADD_TO_LAUNCHER_LIST_AICORE failed."); + return std::tuple(nullptr, nullptr); + } + return std::tie(queryOut, keyOut); +} + +const std::tuple RopeWithSinCosCache( + const aclTensor* positions, const aclTensor* queryIn, const aclTensor* keyIn, const aclTensor* cosSinCache, + const aclIntArray* mropeSection, int64_t headSize, bool isNeoxStyle, int64_t qStride, int64_t kStride, + int64_t numQHeads, int64_t numKHeads, int64_t cacheMode, aclOpExecutor* executor) +{ + // 根据推导出的输出shape申请输出tensor + auto queryOut = executor->AllocTensor(queryIn->GetViewShape(), queryIn->GetDataType(), queryIn->GetViewFormat()); + auto keyOut = executor->AllocTensor(keyIn->GetViewShape(), keyIn->GetDataType(), keyIn->GetViewFormat()); + + return RoepWithSinCosCacheAICore( + positions, queryIn, keyIn, cosSinCache, mropeSection, headSize, isNeoxStyle, qStride, kStride, numQHeads, + numKHeads, cacheMode, queryOut, keyOut, executor); +} +} // namespace l0op \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/rope_with_sin_cos_cache.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/rope_with_sin_cos_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..77c63c244ef3357a198e547eb8dc7558698a2360 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/rope_with_sin_cos_cache.h @@ -0,0 +1,28 @@ +/** + * 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 rope_with_sin_cos_cache.h + * \brief + */ +#ifndef PTA_NPU_OP_API_INC_LEVEL0_OP_ROPE_WITH_SIN_COS_CACHE_OP_H_ +#define PTA_NPU_OP_API_INC_LEVEL0_OP_ROPE_WITH_SIN_COS_CACHE_OP_H_ + +#include "opdev/op_executor.h" + +namespace l0op { +const std::tuple RopeWithSinCosCache(const aclTensor* positions, const aclTensor* queryIn, + const aclTensor* keyIn, const aclTensor* cosSinCache, + const aclIntArray *mropeSection, int64_t headSize, + bool isNeoxStyle, int64_t qStride, int64_t kStride, + int64_t numQHeads, int64_t numKHeads, int64_t cacheMode, + aclOpExecutor *executor); +} +#endif // OP_API_INC_LEVEL0_OP_ROPE_WITH_SIN_COS_CACHE_OP_H_ diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/rsqrt.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/rsqrt.h new file mode 100644 index 0000000000000000000000000000000000000000..78dbed8b94579714ccc9a1d26c26961e5bbf14bf --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/op_api/rsqrt.h @@ -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. + */ + +#ifndef PTA_NPU_OP_API_INC_LEVEL0_OP_RSQRT_H_ +#define PTA_NPU_OP_API_INC_LEVEL0_OP_RSQRT_H_ + +#include "opdev/op_executor.h" + +namespace l0op { +const aclTensor *Rsqrt(const aclTensor *self, aclOpExecutor *executor); +} + +#endif // PTA_NPU_OP_API_INC_LEVEL0_OP_RSQRT_H_ diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/rope_with_sin_cos_cache_def.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/rope_with_sin_cos_cache_def.cpp new file mode 100644 index 0000000000000000000000000000000000000000..efdd1bfc953d5ca86de64d38c128db39fbd9680e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/rope_with_sin_cos_cache_def.cpp @@ -0,0 +1,127 @@ +/** + * 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 rope_with_sin_cos_cache.cpp + * \brief + */ +#include "register/op_def_registry.h" + +namespace ops { +class RopeWithSinCosCache : public OpDef +{ +public: + explicit RopeWithSinCosCache(const char* name) : OpDef(name) + { + this->Input("positions") + .ParamType(REQUIRED) + .DataType({ge::DT_INT64, ge::DT_INT64, ge::DT_INT64}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("queryIn") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("keyIn") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Input("cosSinCache") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("queryOut") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Output("keyOut") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16, ge::DT_BF16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND}); + this->Attr("numQHeads").AttrType(REQUIRED).Int(1); + this->Attr("numKHeads").AttrType(REQUIRED).Int(1); + this->Attr("headSize").AttrType(REQUIRED).Int(1); + this->Attr("mropeSection").AttrType(OPTIONAL).ListInt({0, 0, 0}); + this->Attr("qStride").AttrType(OPTIONAL).Int(0); + this->Attr("kStride").AttrType(OPTIONAL).Int(0); + this->Attr("isNeoxStyle").AttrType(OPTIONAL).Bool(true); + this->Attr("cacheMode").AttrType(OPTIONAL).Int(0); + + OpAICoreConfig membaseCfg; + membaseCfg.DynamicCompileStaticFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .ExtendCfgInfo("opFile.value", "rope_with_sin_cos_cache"); + this->AICore().AddConfig("ascend910b", membaseCfg); + this->AICore().AddConfig("ascend910_93", membaseCfg); + + OpAICoreConfig regbaseCfg; + regbaseCfg.DynamicCompileStaticFlag(true) + .DynamicRankSupportFlag(true) + .DynamicShapeSupportFlag(true) + .ExtendCfgInfo("opFile.value", "rope_with_sin_cos_cache_apt"); + this->AICore().AddConfig("ascend950", regbaseCfg); + + 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("positions") + .ParamType(REQUIRED) + .DataType({ge::DT_INT64, ge::DT_INT64}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + config_kirin.Input("queryIn") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + config_kirin.Input("keyIn") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + config_kirin.Input("cosSinCache") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + config_kirin.Output("queryOut") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + config_kirin.Output("keyOut") + .ParamType(REQUIRED) + .DataType({ge::DT_FLOAT, ge::DT_FLOAT16}) + .Format({ge::FORMAT_ND, ge::FORMAT_ND}) + .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND}); + return config_kirin; + } +}; + +OP_ADD(RopeWithSinCosCache); +} // namespace ops \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/rope_with_sin_cos_cache_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/rope_with_sin_cos_cache_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6605e9e5994d61fdc6ca820b9d00d491422c8a4f --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/rope_with_sin_cos_cache_infershape.cpp @@ -0,0 +1,67 @@ +/** + * 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 rope_with_sin_cos_cache.cc + * \brief + */ + +#include "log/log.h" +#include "register/op_impl_registry.h" + +static constexpr int INPUT_NODE_NUM = 4; +static constexpr int OUTPUT_NODE_NUM = 2; + +static constexpr int INDEX_INPUT_QUERY_IN = 1; +static constexpr int INDEX_INPUT_KEY_IN = 2; + +static constexpr int INDEX_OUTPUT_QUERY_OUT = 0; +static constexpr int INDEX_OUTPUT_KEY_OUT = 1; + +using namespace ge; +namespace ops { +static ge::graphStatus InferShapeForRopeWithSinCosCache(gert::InferShapeContext* context) +{ + if (context == nullptr) { + OP_LOGE("InferShape4RopeWithSinCosCache", "Context is nullptr, check failed."); + return GRAPH_FAILED; + } + if (context->GetComputeNodeInputNum() != INPUT_NODE_NUM || + context->GetComputeNodeOutputNum() != OUTPUT_NODE_NUM) { + return GRAPH_FAILED; + } + + const gert::Shape* query_in_shape = context->GetInputShape(INDEX_INPUT_QUERY_IN); + OP_CHECK_NULL_WITH_CONTEXT(context, query_in_shape); + const gert::Shape* key_in_shape = context->GetInputShape(INDEX_INPUT_KEY_IN); + OP_CHECK_NULL_WITH_CONTEXT(context, key_in_shape); + + gert::Shape* query_out_shape = context->GetOutputShape(INDEX_OUTPUT_QUERY_OUT); + OP_CHECK_NULL_WITH_CONTEXT(context, query_out_shape); + gert::Shape* key_out_shape = context->GetOutputShape(INDEX_OUTPUT_KEY_OUT); + OP_CHECK_NULL_WITH_CONTEXT(context, key_out_shape); + + *query_out_shape = *query_in_shape; + *key_out_shape = *key_in_shape; + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus InferDataTypeForRopeWithSinCosCache(gert::InferDataTypeContext* context) +{ + const auto input_data_type_1 = context->GetInputDataType(1); + context->SetOutputDataType(0, input_data_type_1); + context->SetOutputDataType(1, input_data_type_1); + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_INFERSHAPE(RopeWithSinCosCache) + .InferShape(InferShapeForRopeWithSinCosCache) + .InferDataType(InferDataTypeForRopeWithSinCosCache); +} // namespace ops \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/rope_with_sin_cos_cache_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/rope_with_sin_cos_cache_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..02fa771e9077667b894d119c1ba0c20b9b65d3a2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/rope_with_sin_cos_cache_tiling.cpp @@ -0,0 +1,402 @@ +/** + * 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 rope_with_sin_cos_cache.cpp + * \brief + */ +#include +#include +#include +#include "register/op_def_registry.h" +#include "tiling/tiling_api.h" +#include "rope_with_sin_cos_cache_tiling.h" + +namespace { +constexpr uint32_t INPUT_POSITION_INDEX = 0; +constexpr uint32_t INPUT_QUERY_IN_INDEX = 1; +constexpr uint32_t INPUT_KEY_IN_INDEX = 2; +constexpr uint32_t INPUT_COSSINCACHE_INDEX = 3; + +constexpr uint32_t INPUT_NUM_QHEADS_INDEX = 0; +constexpr uint32_t INPUT_NUM_KHEADS_INDEX = 1; +constexpr uint32_t INPUT_HEAD_SIZE_INDEX = 2; +constexpr uint32_t INPUT_MROPE_SECTION_INDEX = 3; +constexpr uint32_t INPUT_QSTRIDE_INDEX = 4; +constexpr uint32_t INPUT_KSTRIDE_INDEX = 5; +constexpr uint32_t INPUT_IS_NEOXSTYLE_INDEX = 6; +constexpr uint32_t INPUT_CACHE_MODE_INDEX = 7; + +constexpr uint32_t INDEX_QUERYOUT_OUTPUT_ = 0; +constexpr uint32_t INDEX_KEYOUT_OUTPUT = 1; + +static constexpr uint32_t TILING_BF16 = 20; +static constexpr uint32_t TILING_FP16 = 21; +static constexpr uint32_t TILING_FP32 = 22; +static constexpr uint32_t HAlignSize = 64; +static constexpr uint32_t MRopeSectionMaxSize = 4; + +constexpr size_t DIM_0 = 0; +constexpr size_t DIM_1 = 1; + +constexpr int64_t UB_SIZE = static_cast(192) * 1024; +constexpr uint32_t FP32_DTYPE_SIZE = 4; + +struct TilingParams { + uint64_t core_num_use = 0; + uint64_t num_tokens = 0; + uint64_t num_q_heads = 0; + uint64_t num_kv_heads = 0; + uint64_t head_size = 0; + uint64_t rotary_dim = 0; + uint64_t mrope_section0 = 0; + uint64_t mrope_section1 = 0; + uint64_t mrope_section2 = 0; + uint64_t mrope_section3 = 0; + uint64_t q_leading_dimension = 0; + uint64_t k_leading_dimension = 0; + uint64_t isNeoxStyle = 0; + uint64_t front_core = 0; + uint64_t tail_core = 0; + uint64_t num_tokens_front_core_each_loop = 0; + uint64_t num_tokens_tail_core_each_loop = 0; + uint64_t num_tokens_each_front_core = 0; + uint64_t num_tokens_each_tail_core = 0; + uint64_t loop_time_each_front_core = 0; + uint64_t loop_time_each_tail_core = 0; + uint64_t num_tokens_front_core_last_loop = 0; + uint64_t num_tokens_tail_core_last_loop = 0; + uint64_t loop_for_one_token = 0; + uint64_t num_heads_each_loop = 0; + uint64_t num_heads_last_loop = 0; + uint64_t loop_along_qheads = 0; + uint64_t loop_along_kheads = 0; + uint64_t num_qheads_each_loop = 0; + uint64_t num_qheads_last_loop = 0; + uint64_t num_kheads_each_loop = 0; + uint64_t num_kheads_last_loop = 0; + uint64_t tilingKey = 0; + uint64_t cacheMode = 0; +}; +} // namespace + +namespace optiling { + +inline uint32_t GetLengthByType(int32_t dtype) +{ + switch (dtype) { + case ge::DT_FLOAT16: + case ge::DT_INT16: + case ge::DT_UINT16: + case ge::DT_BF16: + return sizeof(int16_t); + case ge::DT_FLOAT: + case ge::DT_INT32: + case ge::DT_UINT32: + return sizeof(int32_t); + case ge::DT_DOUBLE: + case ge::DT_INT64: + case ge::DT_UINT64: + return sizeof(int64_t); + default: + return 0; + } +} + +static void SetTiling(TilingParams& params, RopeWithSinCosCacheTilingData& tiling) +{ + tiling.set_core_num_use(params.core_num_use); + tiling.set_num_tokens(params.num_tokens); + tiling.set_num_q_heads(params.num_q_heads); + tiling.set_num_kv_heads(params.num_kv_heads); + tiling.set_head_size(params.head_size); + tiling.set_rotary_dim(params.rotary_dim); + tiling.set_mrope_section0(params.mrope_section0); + tiling.set_mrope_section1(params.mrope_section1); + tiling.set_mrope_section2(params.mrope_section2); + tiling.set_mrope_section3(params.mrope_section3); + tiling.set_q_leading_dimension(params.q_leading_dimension); + tiling.set_k_leading_dimension(params.k_leading_dimension); + tiling.set_isNeoxStyle(params.isNeoxStyle); + tiling.set_cacheMode(params.cacheMode); + tiling.set_front_core(params.front_core); + tiling.set_tail_core(params.tail_core); + tiling.set_num_tokens_front_core_each_loop(params.num_tokens_front_core_each_loop); + tiling.set_num_tokens_tail_core_each_loop(params.num_tokens_tail_core_each_loop); + tiling.set_num_tokens_each_front_core(params.num_tokens_each_front_core); + tiling.set_num_tokens_each_tail_core(params.num_tokens_each_tail_core); + tiling.set_loop_time_each_front_core(params.loop_time_each_front_core); + tiling.set_loop_time_each_tail_core(params.loop_time_each_tail_core); + tiling.set_num_tokens_front_core_last_loop(params.num_tokens_front_core_last_loop); + tiling.set_num_tokens_tail_core_last_loop(params.num_tokens_tail_core_last_loop); + tiling.set_loop_for_one_token(params.loop_for_one_token); + tiling.set_loop_along_qheads(params.loop_along_qheads); + tiling.set_loop_along_kheads(params.loop_along_kheads); + tiling.set_num_qheads_each_loop(params.num_qheads_each_loop); + tiling.set_num_qheads_last_loop(params.num_qheads_last_loop); + tiling.set_num_kheads_each_loop(params.num_kheads_each_loop); + tiling.set_num_kheads_last_loop(params.num_kheads_last_loop); +} + +static void PrintTilingData(const gert::TilingContext* context, RopeWithSinCosCacheTilingData& tiling) +{ + OP_LOGD(context->GetNodeName(), ">>>>>>>>>> Start to print RopeWithSinCosCache tiling data <<<<<<<<<<"); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: coreNumUse is %ld.", tiling.get_core_num_use()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num tokens is %ld.", tiling.get_num_tokens()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num_q_heads is %ld.", tiling.get_num_q_heads()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num_kv_heads is %ld.", tiling.get_num_kv_heads()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: head_size is %ld.", tiling.get_head_size()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: rotary_dim is %ld.", tiling.get_rotary_dim()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: mrope_section0 is %ld.", tiling.get_mrope_section0()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: mrope_section1 is %ld.", tiling.get_mrope_section1()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: mrope_section2 is %ld.", tiling.get_mrope_section2()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: mrope_section3 is %ld.", tiling.get_mrope_section3()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: q_leading_dimension is %ld.", tiling.get_q_leading_dimension()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: k_leading_dimension is %ld.", tiling.get_k_leading_dimension()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: isNeoxStyle is %ld.", tiling.get_isNeoxStyle()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: cacheMode is %ld.", tiling.get_cacheMode()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: front_core is %ld.", tiling.get_front_core()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: tail_core is %ld.", tiling.get_tail_core()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num_tokens_front_core_each_loop is %ld.", tiling.get_num_tokens_front_core_each_loop()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num_tokens_tail_core_each_loop is %ld.", tiling.get_num_tokens_tail_core_each_loop()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num_tokens_each_front_core is %ld.", tiling.get_num_tokens_each_front_core()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num_tokens_each_tail_core is %ld.", tiling.get_num_tokens_each_tail_core()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: loop_time_each_front_core is %ld.", tiling.get_loop_time_each_front_core()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: loop_time_each_tail_core is %ld.", tiling.get_loop_time_each_tail_core()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num_tokens_front_core_last_loop is %ld.", tiling.get_num_tokens_front_core_last_loop()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num_tokens_tail_core_last_loop is %ld.", tiling.get_num_tokens_tail_core_last_loop()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: loop_for_one_token is %ld.", tiling.get_loop_for_one_token()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: loop_along_qheads is %ld.", tiling.get_loop_along_qheads()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: loop_along_kheads is %ld.", tiling.get_loop_along_kheads()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num_qheads_each_loop is %ld.", tiling.get_num_qheads_each_loop()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num_qheads_last_loop is %ld.", tiling.get_num_qheads_last_loop()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num_kheads_each_loop is %ld.", tiling.get_num_kheads_each_loop()); + OP_LOGD(context->GetNodeName(), "RopeWithSinCosCache_tiling: num_kheads_last_loop is %ld.", tiling.get_num_kheads_last_loop()); +} + +static ge::graphStatus TilingKeyChose(const gert::TilingContext* context, TilingParams& params) +{ + auto qDtype = context->GetInputDesc(INPUT_QUERY_IN_INDEX)->GetDataType(); + if (qDtype == ge::DT_BF16) { + params.tilingKey = TILING_BF16; + return ge::GRAPH_SUCCESS; + } + if (qDtype == ge::DT_FLOAT) { + params.tilingKey = TILING_FP32; + return ge::GRAPH_SUCCESS; + } + if (qDtype == ge::DT_FLOAT16) { + params.tilingKey = TILING_FP16; + return ge::GRAPH_SUCCESS; + } + return ge::GRAPH_FAILED; +} + +static ge::graphStatus TilingCompute(gert::TilingContext *context, TilingParams ¶ms) +{ + uint64_t numTokens = + static_cast(context->GetOutputShape(INDEX_QUERYOUT_OUTPUT_)->GetStorageShape().GetDim(DIM_0)); + uint64_t numQheads = params.num_q_heads; + uint64_t numKheads = params.num_kv_heads; + uint64_t headSize = params.head_size; + + auto cosSinSize = context->GetInputShape(INPUT_COSSINCACHE_INDEX)->GetStorageShape().GetDimNum(); + uint64_t rotaryDim = static_cast( + context->GetInputShape(INPUT_COSSINCACHE_INDEX)->GetStorageShape().GetDim(cosSinSize - 1)); + + int32_t qDtype = context->GetInputDesc(INPUT_QUERY_IN_INDEX)->GetDataType(); + uint32_t queryInTypeLength = GetLengthByType(qDtype); + OP_CHECK_IF((queryInTypeLength == 0), + OP_LOGE(context->GetNodeName(), "queryInTypeLength can't be 0."), + return ge::GRAPH_FAILED); + + OP_CHECK_IF((headSize % (HAlignSize / queryInTypeLength) != 0), + OP_LOGE(context->GetNodeName(), "headSize must be 64-byte aligned."), + return ge::GRAPH_FAILED); + + OP_CHECK_IF((rotaryDim % (HAlignSize / queryInTypeLength) != 0), + OP_LOGE(context->GetNodeName(), "rotaryDim must be 64-byte aligned."), + return ge::GRAPH_FAILED); + + OP_CHECK_IF((headSize < rotaryDim), + OP_LOGE(context->GetNodeName(), "headSize can't be smaller than rotaryDim."), + return ge::GRAPH_FAILED); + + auto platformInfo = context->GetPlatformInfo(); + if (platformInfo == nullptr) { + return ge::GRAPH_FAILED; + } + auto ascendcPlatform = platform_ascendc::PlatformAscendC(platformInfo); + uint64_t coreNum = static_cast(ascendcPlatform.GetCoreNum()); + + uint64_t ubSizePlatForm; + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSizePlatForm); + auto maxUbSize = static_cast(ubSizePlatForm); + + uint64_t totalDataNum = numTokens; + uint64_t dataTypeSize = FP32_DTYPE_SIZE; + uint64_t front_core = totalDataNum % coreNum != 0 ? static_cast(totalDataNum % coreNum) : coreNum; + uint64_t tail_core = totalDataNum <= coreNum ? 0 : coreNum - front_core; + uint64_t numBlocks = front_core + tail_core; + + uint64_t numHeadsMax = numQheads > numKheads ? numQheads : numKheads; + uint64_t allSize = params.isNeoxStyle == 1UL ? + static_cast(numHeadsMax * (rotaryDim * 5UL + headSize * 2UL) * dataTypeSize) : + static_cast(numHeadsMax * (rotaryDim * 6UL + headSize * 2UL) * dataTypeSize); + uint64_t maxNPerLoopForUb = + (maxUbSize - rotaryDim * 10UL * dataTypeSize) / allSize; // ub每次能载入最大行数(包括所有计算数据); + + uint64_t num_tokens_each_front_core = (totalDataNum + coreNum - 1) / coreNum; + uint64_t loop_time_each_front_core = maxNPerLoopForUb == 0 ? 0 : + (num_tokens_each_front_core + maxNPerLoopForUb - 1UL) / static_cast(maxNPerLoopForUb); + + uint64_t num_tokens_front_core_each_loop = + loop_time_each_front_core == 1UL ? num_tokens_each_front_core : maxNPerLoopForUb; + uint64_t num_tokens_front_core_last_loop = + loop_time_each_front_core == 1UL ? + 0 : + num_tokens_each_front_core - num_tokens_front_core_each_loop * (loop_time_each_front_core - 1UL); + uint64_t num_tokens_each_tail_core = totalDataNum / coreNum; + uint64_t loop_time_each_tail_core = maxNPerLoopForUb == 0 ? 0 : + (num_tokens_each_tail_core + maxNPerLoopForUb - 1) / maxNPerLoopForUb; + uint64_t num_tokens_tail_core_each_loop = + loop_time_each_tail_core <= 1UL ? num_tokens_each_tail_core : maxNPerLoopForUb; + uint64_t num_tokens_tail_core_last_loop = + static_cast(loop_time_each_front_core) == 1UL ? + 0 : + num_tokens_each_tail_core - num_tokens_tail_core_each_loop * (loop_time_each_tail_core - 1UL); + + uint64_t numHeadsForUb = + params.isNeoxStyle == 1UL ? + (maxUbSize - rotaryDim * 10UL * dataTypeSize) / ((rotaryDim * 5UL + headSize * 2UL) * dataTypeSize) : + (maxUbSize - rotaryDim * 10UL * dataTypeSize) / ((rotaryDim * 6UL + headSize * 2UL) * dataTypeSize); + + uint64_t loop_for_one_token = numHeadsMax > numHeadsForUb ? 1UL : 0UL; // 取1时,对numheads循环,maxNPerLoopForUb == 0 + uint64_t loop_along_qheads = numHeadsForUb == 0 ? 0 : (numQheads + numHeadsForUb - 1UL) / numHeadsForUb; + uint64_t loop_along_kheads = numHeadsForUb == 0 ? 0 : (numKheads + numHeadsForUb - 1UL) / numHeadsForUb; + uint64_t num_qheads_each_loop = loop_along_qheads == 1UL ? numQheads : numHeadsForUb; + uint64_t num_qheads_last_loop = + loop_along_qheads == 1UL ? 0 : numQheads - num_qheads_each_loop * (loop_along_qheads - 1UL); + uint64_t num_kheads_each_loop = loop_along_kheads == 1UL ? numKheads : numHeadsForUb; + uint64_t num_kheads_last_loop = + loop_along_kheads == 1UL ? 0 : numKheads - num_kheads_each_loop * (loop_along_kheads - 1UL); + + params.num_tokens = numTokens; + params.rotary_dim = rotaryDim; + params.core_num_use = numBlocks; + params.front_core = front_core; + params.tail_core = tail_core; + + params.num_tokens_each_front_core = num_tokens_each_front_core; + params.loop_time_each_front_core = loop_time_each_front_core; + params.num_tokens_front_core_each_loop = num_tokens_front_core_each_loop; + params.num_tokens_front_core_last_loop = num_tokens_front_core_last_loop; + params.num_tokens_each_tail_core = num_tokens_each_tail_core; + params.loop_time_each_tail_core = loop_time_each_tail_core; + params.num_tokens_tail_core_each_loop = num_tokens_tail_core_each_loop; + params.num_tokens_tail_core_last_loop = num_tokens_tail_core_last_loop; + + params.loop_for_one_token = loop_for_one_token; + params.loop_along_qheads = loop_along_qheads; + params.loop_along_kheads = loop_along_kheads; + params.num_qheads_each_loop = num_qheads_each_loop; + params.num_qheads_last_loop = num_qheads_last_loop; + params.num_kheads_each_loop = num_kheads_each_loop; + params.num_kheads_last_loop = num_kheads_last_loop; + + context->SetBlockDim(numBlocks); + context->SetTilingKey(params.tilingKey); + return ge::GRAPH_SUCCESS; +} + +static ge::graphStatus TilingRopeWithSinCosCache(gert::TilingContext* context) +{ + TilingParams params; + RopeWithSinCosCacheTilingData tiling; + + const auto ascendcPlatform = platform_ascendc::PlatformAscendC(context->GetPlatformInfo()); + uint32_t totalCoreNum = ascendcPlatform.GetCoreNumAiv(); + context->SetBlockDim(totalCoreNum); + params.core_num_use = context->GetBlockDim(); + + auto* attrs = context->GetAttrs(); + + const uint64_t* attrNumQHeads = attrs->GetAttrPointer(0); + OP_CHECK_NULL_WITH_CONTEXT(context, attrNumQHeads); + params.num_q_heads = static_cast(*attrNumQHeads); + + const uint64_t* attrNumKVHeads = attrs->GetAttrPointer(1); + OP_CHECK_NULL_WITH_CONTEXT(context, attrNumKVHeads); + params.num_kv_heads = static_cast(*attrNumKVHeads); + + const uint64_t* attrHeadSize = attrs->GetAttrPointer(2); + OP_CHECK_NULL_WITH_CONTEXT(context, attrHeadSize); + params.head_size = static_cast(*attrHeadSize); + + const auto attrMRopeSection = attrs->GetAttrPointer(3); + const uint64_t* attrMRopeSectionData = reinterpret_cast(attrMRopeSection->GetData()); + if (attrMRopeSectionData != nullptr) { + params.mrope_section0 = attrMRopeSectionData[0]; + params.mrope_section1 = attrMRopeSectionData[1]; + params.mrope_section2 = attrMRopeSectionData[2]; + params.mrope_section3 = attrMRopeSection->GetSize() == MRopeSectionMaxSize ? attrMRopeSectionData[3] : 0; + } + + const uint64_t* attrQStride = attrs->GetAttrPointer(4); + OP_CHECK_NULL_WITH_CONTEXT(context, attrQStride); + params.q_leading_dimension = static_cast(*attrQStride); + + const uint64_t* attrKStride = attrs->GetAttrPointer(5); + OP_CHECK_NULL_WITH_CONTEXT(context, attrKStride); + params.k_leading_dimension = static_cast(*attrKStride); + + const bool* attrIsNeoxStyle = attrs->GetAttrPointer(6); + OP_CHECK_NULL_WITH_CONTEXT(context, attrIsNeoxStyle); + params.isNeoxStyle = static_cast(*attrIsNeoxStyle); + + const uint64_t* attrCacheMode = attrs->GetAttrPointer(INPUT_CACHE_MODE_INDEX); + OP_CHECK_NULL_WITH_CONTEXT(context, attrCacheMode); + params.cacheMode = static_cast(*attrCacheMode); + OP_CHECK_IF((attrMRopeSection->GetSize() == MRopeSectionMaxSize) && (params.cacheMode != 0), + OP_LOGE(context->GetNodeName(), + "cacheMode is only support to be 0 but got %lu when the size of mRopeSection equals %u.", + params.cacheMode, MRopeSectionMaxSize), + return ge::GRAPH_FAILED); + + TilingKeyChose(context, params); + TilingCompute(context, params); + SetTiling(params, tiling); + PrintTilingData(context, tiling); + tiling.SaveToBuffer(context->GetRawTilingData()->GetData(), context->GetRawTilingData()->GetCapacity()); + context->GetRawTilingData()->SetDataSize(tiling.GetDataSize()); + + size_t sysWorkspaceSize = ascendcPlatform.GetLibApiWorkSpaceSize(); + size_t* workspaces = context->GetWorkspaceSizes(1); + + size_t UserWorkspaceSize = 0; + + workspaces[0] = sysWorkspaceSize + UserWorkspaceSize; + + return ge::GRAPH_SUCCESS; +} + +struct TilingmropeCompileInfo { +}; + +static ge::graphStatus TilingPreparemrope(gert::TilingParseContext* context) +{ + (void)context; + return ge::GRAPH_SUCCESS; +} + +IMPL_OP_OPTILING(RopeWithSinCosCache) + .Tiling(TilingRopeWithSinCosCache) + .TilingParse(TilingPreparemrope); +} // namespace optiling diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/rope_with_sin_cos_cache_tiling.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/rope_with_sin_cos_cache_tiling.h new file mode 100644 index 0000000000000000000000000000000000000000..39fe326e3b2df78f4f823bbf2fa0f07a58b8af47 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_host/rope_with_sin_cos_cache_tiling.h @@ -0,0 +1,59 @@ +/** + * 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 rope_with_sin_cos_cache.h + * \brief + */ + +#ifndef ROPE_WITH_SIN_COS_CACHE_H +#define ROPE_WITH_SIN_COS_CACHE_H + +#include "register/tilingdata_base.h" + +namespace optiling { +BEGIN_TILING_DATA_DEF(RopeWithSinCosCacheTilingData) +TILING_DATA_FIELD_DEF(uint64_t, core_num_use); +TILING_DATA_FIELD_DEF(uint64_t, num_tokens); +TILING_DATA_FIELD_DEF(uint64_t, num_q_heads); +TILING_DATA_FIELD_DEF(uint64_t, num_kv_heads); +TILING_DATA_FIELD_DEF(uint64_t, head_size); +TILING_DATA_FIELD_DEF(uint64_t, rotary_dim); +TILING_DATA_FIELD_DEF(uint64_t, mrope_section0); +TILING_DATA_FIELD_DEF(uint64_t, mrope_section1); +TILING_DATA_FIELD_DEF(uint64_t, mrope_section2); +TILING_DATA_FIELD_DEF(uint64_t, mrope_section3); +TILING_DATA_FIELD_DEF(uint64_t, q_leading_dimension); +TILING_DATA_FIELD_DEF(uint64_t, k_leading_dimension); +TILING_DATA_FIELD_DEF(uint64_t, isNeoxStyle); +TILING_DATA_FIELD_DEF(uint64_t, cacheMode); +TILING_DATA_FIELD_DEF(uint64_t, front_core); +TILING_DATA_FIELD_DEF(uint64_t, tail_core); +TILING_DATA_FIELD_DEF(uint64_t, num_tokens_each_front_core); +TILING_DATA_FIELD_DEF(uint64_t, num_tokens_each_tail_core); +TILING_DATA_FIELD_DEF(uint64_t, num_tokens_front_core_each_loop); +TILING_DATA_FIELD_DEF(uint64_t, num_tokens_tail_core_each_loop); +TILING_DATA_FIELD_DEF(uint64_t, loop_time_each_front_core); +TILING_DATA_FIELD_DEF(uint64_t, loop_time_each_tail_core); +TILING_DATA_FIELD_DEF(uint64_t, num_tokens_front_core_last_loop); +TILING_DATA_FIELD_DEF(uint64_t, num_tokens_tail_core_last_loop); +TILING_DATA_FIELD_DEF(uint64_t, loop_for_one_token); +TILING_DATA_FIELD_DEF(uint64_t, loop_along_qheads); +TILING_DATA_FIELD_DEF(uint64_t, loop_along_kheads); +TILING_DATA_FIELD_DEF(uint64_t, num_qheads_each_loop); +TILING_DATA_FIELD_DEF(uint64_t, num_qheads_last_loop); +TILING_DATA_FIELD_DEF(uint64_t, num_kheads_each_loop); +TILING_DATA_FIELD_DEF(uint64_t, num_kheads_last_loop); +END_TILING_DATA_DEF; + +REGISTER_TILING_DATA_CLASS(RopeWithSinCosCache, RopeWithSinCosCacheTilingData) +} // namespace optiling + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/arch35/rope_with_sin_cos_cache_base.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/arch35/rope_with_sin_cos_cache_base.h new file mode 100644 index 0000000000000000000000000000000000000000..fd2405d792dd6b72d22c5512f4aa5b3aa40f2eec --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/arch35/rope_with_sin_cos_cache_base.h @@ -0,0 +1,173 @@ +/** + * 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 rope_with_sin_cos_cache_base.h + * \brief rope_with_sin_cos_cache_base.h + */ +#ifndef ROPE_WITH_SIN_COS_CACHE_ARCH35_BASE_H +#define ROPE_WITH_SIN_COS_CACHE_ARCH35_BASE_H + +#include "kernel_operator.h" + +namespace RopeWithSinCosCache { +using namespace AscendC; +using AscendC::Duplicate; +using AscendC::HardEvent; + +template +class RopeWithSinCosCacheBase +{ +public: + // 构造函数 + __aicore__ inline RopeWithSinCosCacheBase(){}; + __aicore__ inline void InitData(const RopeWithSinCosCacheTilingData& tilingData); + __aicore__ inline void SToMTE2Sync(); + __aicore__ inline void MTE2ToSSync(); + __aicore__ inline void SToMTE3Sync(); + __aicore__ inline void MTE3ToSSync(); + __aicore__ inline void SToVSync(); + __aicore__ inline void MTE3ToVSync(); + __aicore__ inline void MTE2ToVSync(); + +protected: + uint32_t blockIdx_; + uint64_t core_num_use; + uint64_t num_tokens; + uint64_t num_q_heads; + uint64_t num_kv_heads; + uint64_t rotary_dim; + uint64_t mrope_section0; + uint64_t mrope_section1; + uint64_t mrope_section2; + uint64_t head_size; + uint64_t q_leading_dimension; + uint64_t k_leading_dimension; + uint64_t front_core; + uint64_t tail_core; + uint64_t num_tokens_each_front_core; + uint64_t num_tokens_each_tail_core; + uint64_t is_neox_style; + + uint64_t loop_time_current_core{0}; // 当前核批处理数据轮数 + uint64_t num_tokens_each_loop_current_core{0}; // 当前核每轮处理的token数 + uint64_t num_tokens_last_loop_current_core{0}; // 当前核最后一轮轮处理的token数 + + uint64_t loop_for_one_token; + uint64_t loop_along_qheads; + uint64_t loop_along_kheads; + uint64_t num_heads_each_loop; + uint64_t num_qheads_each_loop; + uint64_t num_qheads_last_loop; + uint64_t num_kheads_each_loop; + uint64_t num_kheads_last_loop; + uint64_t num_tokens_current_core; +}; + +template +__aicore__ inline void RopeWithSinCosCacheBase::InitData(const RopeWithSinCosCacheTilingData& tilingData) +{ + blockIdx_ = AscendC::GetBlockIdx(); + + core_num_use = tilingData.core_num_use; + num_tokens = tilingData.num_tokens; + num_q_heads = tilingData.num_q_heads; + num_kv_heads = tilingData.num_kv_heads; + rotary_dim = tilingData.rotary_dim; + mrope_section0 = tilingData.mrope_section0; + mrope_section1 = tilingData.mrope_section1; + mrope_section2 = tilingData.mrope_section2; + head_size = tilingData.head_size; + q_leading_dimension = tilingData.q_leading_dimension; + k_leading_dimension = tilingData.k_leading_dimension; + front_core = tilingData.front_core; + tail_core = tilingData.tail_core; + num_tokens_each_front_core = tilingData.num_tokens_each_front_core; + num_tokens_each_tail_core = tilingData.num_tokens_each_tail_core; + is_neox_style = tilingData.isNeoxStyle; + + loop_time_current_core = + (blockIdx_ < front_core) ? tilingData.loop_time_each_front_core : tilingData.loop_time_each_tail_core; + num_tokens_each_loop_current_core = (blockIdx_ < front_core) ? tilingData.num_tokens_front_core_each_loop : + tilingData.num_tokens_tail_core_each_loop; + num_tokens_last_loop_current_core = (blockIdx_ < front_core) ? tilingData.num_tokens_front_core_last_loop : + tilingData.num_tokens_tail_core_last_loop; + + loop_for_one_token = tilingData.loop_for_one_token; + loop_along_qheads = tilingData.loop_along_qheads; + loop_along_kheads = tilingData.loop_along_kheads; + num_qheads_each_loop = tilingData.num_qheads_each_loop; + num_qheads_last_loop = tilingData.num_qheads_last_loop; + num_kheads_each_loop = tilingData.num_kheads_each_loop; + num_kheads_last_loop = tilingData.num_kheads_last_loop; + num_heads_each_loop = num_qheads_each_loop > num_kheads_each_loop ? num_qheads_each_loop : num_kheads_each_loop; + num_tokens_current_core = (blockIdx_ < front_core) ? tilingData.num_tokens_each_front_core : tilingData.num_tokens_each_tail_core; +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::SToMTE2Sync() +{ + event_t eventIDSToMTE2 = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_MTE2)); + SetFlag(eventIDSToMTE2); + WaitFlag(eventIDSToMTE2); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::MTE2ToSSync() +{ + event_t eventIDMTE2ToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_S)); + SetFlag(eventIDMTE2ToS); + WaitFlag(eventIDMTE2ToS); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::SToMTE3Sync() +{ + event_t eventIDSToMTE3 = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_MTE3)); + SetFlag(eventIDSToMTE3); + WaitFlag(eventIDSToMTE3); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::MTE3ToSSync() +{ + event_t eventIDMTE3ToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_S)); + SetFlag(eventIDMTE3ToS); + WaitFlag(eventIDMTE3ToS); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::SToVSync() +{ + event_t eventIDSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIDSToV); + WaitFlag(eventIDSToV); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::MTE3ToVSync() +{ + event_t eventIDMTE3ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_V)); + SetFlag(eventIDMTE3ToV); + WaitFlag(eventIDMTE3ToV); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::MTE2ToVSync() +{ + event_t eventIDMTE2ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventIDMTE2ToV); + WaitFlag(eventIDMTE2ToV); +} + +} // namespace RopeWithSinCosCache + +#endif // namespace RopeWithSinCosCache + diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/arch35/rope_with_sin_cos_cache_f_bf16.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/arch35/rope_with_sin_cos_cache_f_bf16.h new file mode 100644 index 0000000000000000000000000000000000000000..823d142ebe417cabb805de726492a055d6c36f1b --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/arch35/rope_with_sin_cos_cache_f_bf16.h @@ -0,0 +1,699 @@ +/** + * 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 rope_with_sin_cos_cache_f_bf16.h + * \brief rope_with_sin_cos_cache_f_bf16.h + */ + +#ifndef ROPE_WITH_SIN_COS_CACHE_ARCH35_BF16_H +#define ROPE_WITH_SIN_COS_CACHE_ARCH35_BF16_H + +#include "rope_with_sin_cos_cache_base.h" + +namespace RopeWithSinCosCache { +using namespace AscendC; + +template +class RopeWithSinCosCacheFP16 : public RopeWithSinCosCacheBase +{ +public: + __aicore__ inline RopeWithSinCosCacheFP16(){}; + __aicore__ inline void Init( + GM_ADDR position_id, GM_ADDR query_in, GM_ADDR key_in, GM_ADDR cos_sin_cache, GM_ADDR query_out, + GM_ADDR key_out, const RopeWithSinCosCacheTilingData& tiling_data, TPipe* pipe); + __aicore__ inline void Process(); + __aicore__ inline void Compute(uint64_t index, uint64_t loopN); + __aicore__ inline void ComputeAlongHeads(uint64_t indexToken, uint64_t indexHeads); + __aicore__ inline void GetCosSinCache(LocalTensor inQueueCosSinCacheBeforeCastLocal, + LocalTensor copyBuf0Local, LocalTensor inCosSin, + LocalTensor CosSin, uint64_t offsetPos, uint64_t cosSinOffset, uint64_t localStartAddr, + uint32_t (&rcShape_)[2], uint32_t (&dstShape_)[2]); + +protected: + static constexpr uint64_t BLOCK_SIZE = 32; + static constexpr uint64_t BUFFER_NUM = 1; + static constexpr uint64_t ELE_NUM_FP32 = 8; + static constexpr uint64_t ELE_NUM_FP16 = 16; + static constexpr uint64_t MASK = 64; + uint64_t blockOffset; + uint16_t headBlockLen{0}; + uint16_t rotaryBlockLen{0}; + uint16_t calBlockLen{0}; + uint16_t calBlockLenFP16{0}; + uint64_t q_size; + uint64_t k_size; + uint64_t num_heads_max; + + GlobalTensor position_id_GM; + GlobalTensor query_in_GM; + GlobalTensor key_in_GM; + GlobalTensor cos_sin_cache_GM; + + GlobalTensor queryGM; + GlobalTensor keyGM; + + TBuf inQQue, inQueueCosSinCache; + TBuf outQue; + TBuf reverseBuf, negOneBuf, cosSinBuf, temp1, offsetBuf, inQueCalBuf; + TBuf copyBuf0, copyBuf1, copyBuf2; + + TQue inQQueBeforeCast, inQueueCosSinCacheBeforeCast; + TQue outQueAfterCast; +}; + +template +__aicore__ inline void RopeWithSinCosCacheFP16::Init( + GM_ADDR position_id, GM_ADDR query_in, GM_ADDR key_in, GM_ADDR cos_sin_cache, GM_ADDR query_out, GM_ADDR key_out, + const RopeWithSinCosCacheTilingData& tiling_data, TPipe* pipe) +{ + this->InitData(tiling_data); + headBlockLen = static_cast(this->head_size / ELE_NUM_FP32); + rotaryBlockLen = static_cast(this->rotary_dim / ELE_NUM_FP32); + calBlockLenFP16 = static_cast(this->rotary_dim / 2 / ELE_NUM_FP16); + calBlockLen = rotaryBlockLen / 2; + + if (this->blockIdx_ < this->front_core) { + blockOffset = this->num_tokens_each_front_core * this->blockIdx_; + } else { + blockOffset = this->num_tokens_each_front_core * (this->front_core) + + (this->blockIdx_ - this->front_core) * this->num_tokens_each_tail_core; + } + + position_id_GM.SetGlobalBuffer((__gm__ uint64_t*)position_id + blockOffset); + query_in_GM.SetGlobalBuffer((__gm__ T*)query_in + blockOffset * this->q_leading_dimension); + key_in_GM.SetGlobalBuffer((__gm__ T*)key_in + blockOffset * this->k_leading_dimension); + cos_sin_cache_GM.SetGlobalBuffer((__gm__ T*)cos_sin_cache); + + queryGM.SetGlobalBuffer((__gm__ T*)query_out + blockOffset * this->num_q_heads * this->head_size); + keyGM.SetGlobalBuffer((__gm__ T*)key_out + blockOffset * this->num_kv_heads * this->head_size); + + num_heads_max = (this->num_q_heads > this->num_kv_heads) ? this->num_q_heads : this->num_kv_heads; + if (this->loop_for_one_token == 0) { + pipe->InitBuffer(inQQue, + this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(inQueueCosSinCache, this->rotary_dim * sizeof(float)); + pipe->InitBuffer(reverseBuf, + this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(negOneBuf, + this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(cosSinBuf, + this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(inQueCalBuf, + this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(T)); + + pipe->InitBuffer(inQQueBeforeCast, BUFFER_NUM, + this->num_tokens_each_loop_current_core * num_heads_max * this->head_size * sizeof(T)); + pipe->InitBuffer(inQueueCosSinCacheBeforeCast, BUFFER_NUM, this->rotary_dim * sizeof(T)); + pipe->InitBuffer(outQueAfterCast, BUFFER_NUM, + this->num_tokens_each_loop_current_core * num_heads_max * this->head_size * sizeof(T)); + + pipe->InitBuffer(copyBuf0, this->rotary_dim / 2 * sizeof(T)); + pipe->InitBuffer(copyBuf1, this->rotary_dim / 2 * sizeof(T)); + pipe->InitBuffer(copyBuf2, this->rotary_dim / 2 * sizeof(T)); + + if (this->is_neox_style == 0) { + pipe->InitBuffer(offsetBuf, this->rotary_dim * sizeof(uint32_t)); + pipe->InitBuffer(temp1, this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * + sizeof(float)); + } else { + pipe->InitBuffer(offsetBuf, 0 * sizeof(uint32_t)); + pipe->InitBuffer(temp1, 0 * sizeof(float)); + } + } else { + pipe->InitBuffer(inQQue, this->num_heads_each_loop * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(inQueueCosSinCache, this->rotary_dim * sizeof(float)); + pipe->InitBuffer(reverseBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(negOneBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(cosSinBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(inQueCalBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(T)); + + pipe->InitBuffer(inQQueBeforeCast, BUFFER_NUM, this->num_heads_each_loop * this->head_size * sizeof(T)); + pipe->InitBuffer(inQueueCosSinCacheBeforeCast, BUFFER_NUM, this->rotary_dim * sizeof(T)); + pipe->InitBuffer(outQueAfterCast, BUFFER_NUM, this->num_heads_each_loop * this->head_size * sizeof(T)); + + pipe->InitBuffer(copyBuf0, this->rotary_dim / 2 * sizeof(T)); + pipe->InitBuffer(copyBuf1, this->rotary_dim / 2 * sizeof(T)); + pipe->InitBuffer(copyBuf2, this->rotary_dim / 2 * sizeof(T)); + + if (this->is_neox_style == 0) { + pipe->InitBuffer(offsetBuf, this->rotary_dim * sizeof(uint32_t)); + pipe->InitBuffer(temp1, this->num_heads_each_loop * this->rotary_dim * sizeof(float)); + } else { + pipe->InitBuffer(offsetBuf, 0 * sizeof(uint32_t)); + pipe->InitBuffer(temp1, 0 * sizeof(float)); + } + } +} + +template +__aicore__ inline void +RopeWithSinCosCacheFP16::GetCosSinCache(LocalTensor inQueueCosSinCacheBeforeCastLocal, + LocalTensor copyBuf0Local, LocalTensor inCosSin, + LocalTensor cosSin, uint64_t offsetPos, uint64_t cosSinOffset, + uint64_t localStartAddr, uint32_t (&srcShape_)[2], uint32_t (&dstShape_)[2]) +{ + if (this->mrope_section0 > 0) { + // dataCopy和Copy的组合方式解决起始地址对齐和搬运单元对齐的问题 + uint64_t pos0 = position_id_GM.GetValue(offsetPos); + uint64_t pos1 = position_id_GM.GetValue(offsetPos + this->num_tokens); + uint64_t pos2 = position_id_GM.GetValue(offsetPos + 2 * this->num_tokens); + + uint8_t padding2 = ((this->mrope_section0 + this->mrope_section1) * sizeof(T) % BLOCK_SIZE) / sizeof(T); + DataCopyPad(inQueueCosSinCacheBeforeCastLocal[this->mrope_section0 + + static_cast(this->mrope_section1) - padding2], + cos_sin_cache_GM[pos2 * this->rotary_dim + + static_cast(this->mrope_section0 + this->mrope_section1) + cosSinOffset], + {1, static_cast(this->mrope_section2 * sizeof(T)), 0, 0}, {true, padding2, 0, 0}); + PipeBarrier(); + + uint8_t padding1 = (this->mrope_section0 * sizeof(T) % BLOCK_SIZE) / sizeof(T); + DataCopyPad( + copyBuf0Local, + cos_sin_cache_GM[pos1 * this->rotary_dim + static_cast(this->mrope_section0) + cosSinOffset], + {1, static_cast(this->mrope_section1 * sizeof(T)), 0, 0}, {true, padding1, 0, 0}); + PipeBarrier(); + Copy(inQueueCosSinCacheBeforeCastLocal[this->mrope_section0 - padding1], copyBuf0Local, + this->mrope_section1 + padding1, 1, {1, 1, 0, 0}); + PipeBarrier(); + DataCopyPad(copyBuf0Local, cos_sin_cache_GM[pos0 * this->rotary_dim + cosSinOffset], + {1, static_cast(this->mrope_section0 * sizeof(T)), 0, 0}, {false, 0, 0, 0}); + PipeBarrier(); + Copy(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, this->mrope_section0, 1, {1, 1, 0, 0}); + } else { + uint64_t pos = position_id_GM.GetValue(offsetPos); + PipeBarrier(); + DataCopy(inQueueCosSinCacheBeforeCastLocal, cos_sin_cache_GM[pos * this->rotary_dim + cosSinOffset], + {1, calBlockLenFP16, 0, 0}); + PipeBarrier(); + } + Cast(inCosSin, inQueueCosSinCacheBeforeCastLocal, AscendC::RoundMode::CAST_NONE, + static_cast(this->rotary_dim)); + PipeBarrier(); + DataCopy(inCosSin[this->rotary_dim / 2], inCosSin, {1, calBlockLen, 0, 0}); + PipeBarrier(); + Broadcast(cosSin[localStartAddr], inCosSin, dstShape_, srcShape_); +} + +template +__aicore__ inline void RopeWithSinCosCacheFP16::Compute(uint64_t index, uint64_t loopN) +{ + q_size = this->num_q_heads * this->head_size; + k_size = this->num_kv_heads * this->head_size; + uint64_t query_in_offset = index * this->num_tokens_each_loop_current_core * this->q_leading_dimension; + uint64_t key_in_offset = index * this->num_tokens_each_loop_current_core * this->k_leading_dimension; + uint64_t offset = index * this->num_tokens_each_loop_current_core * q_size; + uint64_t offsetk = index * this->num_tokens_each_loop_current_core * k_size; + + uint32_t dstShape_[2] = {static_cast(this->num_heads_max), static_cast(this->rotary_dim)}; + uint32_t dstShape_4Negone_[2] = { + static_cast(loopN * this->num_heads_max), static_cast(this->rotary_dim)}; + uint32_t srcShape_[2] = {1, static_cast(this->rotary_dim)}; + + LocalTensor inQQueBeforeCastLocal = inQQueBeforeCast.AllocTensor(); + LocalTensor inQueueCosSinCacheBeforeCastLocal = inQueueCosSinCacheBeforeCast.AllocTensor(); + LocalTensor outQueAfterCastLocal = outQueAfterCast.AllocTensor(); + + LocalTensor inLocal = inQQue.Get(); + LocalTensor inCosSin = inQueueCosSinCache.Get(); + LocalTensor reverseQ = reverseBuf.Get(); + LocalTensor negOne = negOneBuf.Get(); + LocalTensor cosSin = cosSinBuf.Get(); + LocalTensor inQueCalLocal = inQueCalBuf.Get(); + LocalTensor offsetLocal = offsetBuf.Get(); + LocalTensor temp1Local = temp1.Get(); + + LocalTensor copyBuf0Local = copyBuf0.Get(); + LocalTensor copyBuf1Local = copyBuf1.Get(); + LocalTensor copyBuf2Local = copyBuf2.Get(); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < this->rotary_dim / 2; i++) { + offsetLocal.SetValue(i * 2, i * 4); + offsetLocal.SetValue(i * 2 + 1, (this->rotary_dim / 2 + i) * 4); + } + } + + DataCopy( + inQQueBeforeCastLocal, query_in_GM[query_in_offset], + {static_cast(loopN), static_cast(this->num_q_heads * headBlockLen / 2), + static_cast(this->q_leading_dimension / ELE_NUM_FP16 - this->q_size / ELE_NUM_FP16), 0}); + this->MTE2ToVSync(); + DataCopy( + inQueCalLocal, inQQueBeforeCastLocal, + {static_cast(loopN * this->num_q_heads), static_cast(rotaryBlockLen / 2), + static_cast(headBlockLen / 2 - rotaryBlockLen / 2), 0}); + + if (this->is_neox_style == 0) { + Cast( + temp1Local, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopN * this->num_q_heads * this->rotary_dim)); + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopN * this->num_q_heads; i++) { + GatherMask( + inLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], static_cast(1), true, + this->rotary_dim, {1, 1, 0, 0}, rsv); + GatherMask( + inLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + } + } else { + Cast( + inLocal, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopN * this->num_q_heads * this->rotary_dim)); + } + + DataCopy( + reverseQ, inLocal[this->rotary_dim / 2], + {static_cast(loopN * this->num_q_heads), calBlockLen, calBlockLen, calBlockLen}); + DataCopy( + reverseQ[this->rotary_dim / 2], inLocal, + {static_cast(loopN * this->num_q_heads), calBlockLen, calBlockLen, calBlockLen}); + + float One = 1.0; + float None = -1.0; + Duplicate(negOne, None, this->rotary_dim / 2); + Duplicate(negOne[this->rotary_dim / 2], One, this->rotary_dim / 2); + Broadcast(negOne[this->rotary_dim], negOne, dstShape_4Negone_, srcShape_); + uint64_t localStartAddr = 0; + uint64_t cosSinOffset = 0; + for (uint32_t i = 0; i < loopN; ++i) { + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_q_heads * this->rotary_dim; + } + Mul(inLocal, cosSin, inLocal, loopN * this->num_q_heads * this->rotary_dim); + Mul(reverseQ, negOne, reverseQ, loopN * this->num_q_heads * this->rotary_dim); + localStartAddr = 0; + cosSinOffset = this->rotary_dim / 2; + for (uint32_t i = 0; i < loopN; ++i) { + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_q_heads * this->rotary_dim; + } + Mul(reverseQ, cosSin, reverseQ, loopN * this->num_q_heads * this->rotary_dim); + Add(inLocal, reverseQ, inLocal, loopN * this->num_q_heads * this->rotary_dim); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < loopN * this->num_q_heads; i++) { + Gather( + temp1Local[i * this->rotary_dim], inLocal[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + PipeBarrier(); + } + + Cast( + inQueCalLocal, temp1Local, AscendC::RoundMode::CAST_RINT, + static_cast(loopN * this->num_q_heads * this->rotary_dim)); + } else { + Cast( + inQueCalLocal, inLocal, AscendC::RoundMode::CAST_RINT, + static_cast(loopN * this->num_q_heads * this->rotary_dim)); + } + + if (this->head_size != this->rotary_dim) { + DataCopy( + outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopN * this->num_q_heads), static_cast(rotaryBlockLen / 2), 0, + static_cast(headBlockLen / 2 - rotaryBlockLen / 2)}); + DataCopy( + outQueAfterCastLocal[this->rotary_dim], inQQueBeforeCastLocal[this->rotary_dim], + {static_cast(loopN * this->num_q_heads), + static_cast(headBlockLen / 2 - rotaryBlockLen / 2), static_cast(rotaryBlockLen / 2), + static_cast(rotaryBlockLen / 2)}); + } else { + DataCopy( + outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopN), static_cast(this->num_q_heads * headBlockLen / 2), 0, 0}); + } + PipeBarrier(); + DataCopy( + queryGM[offset], outQueAfterCastLocal, + {static_cast(loopN), static_cast(this->num_q_heads * headBlockLen / 2), 0, 0}); + PipeBarrier(); + + // 处理key + DataCopy( + inQQueBeforeCastLocal, key_in_GM[key_in_offset], + {static_cast(loopN), static_cast(this->num_kv_heads * headBlockLen / 2), + static_cast(this->k_leading_dimension / ELE_NUM_FP16 - this->k_size / ELE_NUM_FP16), 0}); + this->MTE2ToVSync(); + DataCopy( + inQueCalLocal, inQQueBeforeCastLocal, + {static_cast(loopN * this->num_kv_heads), static_cast(rotaryBlockLen / 2), + static_cast(headBlockLen / 2 - rotaryBlockLen / 2), 0}); + + if (this->is_neox_style == 0) { + Cast( + temp1Local, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopN * this->num_kv_heads * this->rotary_dim)); + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopN * this->num_kv_heads; i++) { + GatherMask( + inLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], static_cast(1), true, + this->rotary_dim, {1, 1, 0, 0}, rsv); + GatherMask( + inLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + } + } else { + Cast( + inLocal, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopN * this->num_kv_heads * this->rotary_dim)); + } + + DataCopy( + reverseQ, inLocal[this->rotary_dim / 2], + {static_cast(loopN * this->num_kv_heads), calBlockLen, calBlockLen, calBlockLen}); + DataCopy( + reverseQ[this->rotary_dim / 2], inLocal, + {static_cast(loopN * this->num_kv_heads), calBlockLen, calBlockLen, calBlockLen}); + + localStartAddr = 0; + cosSinOffset = 0; + for (uint32_t i = 0; i < loopN; ++i) { + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_kv_heads * this->rotary_dim; + } + + Mul(inLocal, cosSin, inLocal, loopN * this->num_kv_heads * this->rotary_dim); + Mul(reverseQ, negOne, reverseQ, loopN * this->num_kv_heads * this->rotary_dim); + localStartAddr = 0; + cosSinOffset = this->rotary_dim / 2; + for (uint32_t i = 0; i < loopN; ++i) { + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_kv_heads * this->rotary_dim; + PipeBarrier(); + } + + Mul(reverseQ, cosSin, reverseQ, loopN * this->num_kv_heads * this->rotary_dim); + Add(inLocal, reverseQ, inLocal, loopN * this->num_kv_heads * this->rotary_dim); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < loopN * this->num_kv_heads; i++) { + Gather( + temp1Local[i * this->rotary_dim], inLocal[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + } + Cast( + inQueCalLocal, temp1Local, AscendC::RoundMode::CAST_RINT, + static_cast(loopN * this->num_kv_heads * this->rotary_dim)); + } else { + Cast( + inQueCalLocal, inLocal, AscendC::RoundMode::CAST_RINT, + static_cast(loopN * this->num_kv_heads * this->rotary_dim)); + } + + if (this->head_size != this->rotary_dim) { + DataCopy( + outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopN * this->num_kv_heads), static_cast(rotaryBlockLen / 2), 0, + static_cast(headBlockLen / 2 - rotaryBlockLen / 2)}); + DataCopy( + outQueAfterCastLocal[this->rotary_dim], inQQueBeforeCastLocal[this->rotary_dim], + {static_cast(loopN * this->num_kv_heads), + static_cast(headBlockLen / 2 - rotaryBlockLen / 2), static_cast(rotaryBlockLen / 2), + static_cast(rotaryBlockLen / 2)}); + } else { + DataCopy( + outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopN), static_cast(this->num_kv_heads * headBlockLen / 2), 0, 0}); + } + PipeBarrier(); + DataCopy( + keyGM[offsetk], outQueAfterCastLocal, + {static_cast(loopN), static_cast(this->num_kv_heads * headBlockLen / 2), 0, 0}); + PipeBarrier(); + + inQQueBeforeCast.FreeTensor(inQQueBeforeCastLocal); + inQueueCosSinCacheBeforeCast.FreeTensor(inQueueCosSinCacheBeforeCastLocal); + outQueAfterCast.FreeTensor(outQueAfterCastLocal); +} + +template +__aicore__ inline void RopeWithSinCosCacheFP16::ComputeAlongHeads(uint64_t indexToken, uint64_t indexHeads){ + q_size = this->num_q_heads * this->head_size; + k_size = this->num_kv_heads * this->head_size; + uint64_t offsetQHead = indexHeads * this->num_qheads_each_loop * this->head_size; + uint64_t offsetKHead = indexHeads * this->num_kheads_each_loop * this->head_size; + uint64_t offset = indexToken * q_size + offsetQHead;//非连续? + uint64_t offsetk = indexToken * k_size + offsetKHead; + uint64_t query_in_offset = indexToken * this->q_leading_dimension + offsetQHead; + uint64_t key_in_offset = indexToken * this->k_leading_dimension + offsetKHead; + + uint32_t dstShape_[2] = {static_cast(this->num_heads_each_loop), static_cast(this->rotary_dim)}; + uint32_t dstShape_4Negone_[2] = {static_cast(this->num_heads_each_loop), + static_cast(this->rotary_dim)}; + uint32_t srcShape_[2] = {1, static_cast(this->rotary_dim)}; + + LocalTensor inQQueBeforeCastLocal = inQQueBeforeCast.AllocTensor(); + LocalTensor inQueueCosSinCacheBeforeCastLocal = inQueueCosSinCacheBeforeCast.AllocTensor(); + LocalTensor outQueAfterCastLocal = outQueAfterCast.AllocTensor(); + + LocalTensor inLocal = inQQue.Get(); + LocalTensor inCosSin = inQueueCosSinCache.Get(); + LocalTensor reverseQ = reverseBuf.Get(); + LocalTensor negOne = negOneBuf.Get(); + LocalTensor cosSin = cosSinBuf.Get(); + LocalTensor offsetLocal = offsetBuf.Get(); + LocalTensor temp1Local = temp1.Get(); + LocalTensor inQueCalLocal = inQueCalBuf.Get(); + + LocalTensor copyBuf0Local = copyBuf0.Get(); + LocalTensor copyBuf1Local = copyBuf1.Get(); + LocalTensor copyBuf2Local = copyBuf2.Get(); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < this->rotary_dim / 2; i++) { + offsetLocal.SetValue(i * 2, i * 4); + offsetLocal.SetValue(i * 2 + 1, (this->rotary_dim / 2 + i) * 4); + } + } + + if (indexHeads < this->loop_along_qheads) { + uint64_t loopNQhead = (indexHeads == this->loop_along_qheads - 1 && this->num_qheads_last_loop != 0) ? + this->num_qheads_last_loop : + this->num_qheads_each_loop; + DataCopy(inQQueBeforeCastLocal, query_in_GM[query_in_offset], + {1, static_cast(loopNQhead * headBlockLen / 2), 0, 0}); + PipeBarrier(); + DataCopy(inQueCalLocal, inQQueBeforeCastLocal, + {static_cast(loopNQhead), static_cast(rotaryBlockLen / 2), + static_cast(headBlockLen / 2 - rotaryBlockLen / 2), 0}); + PipeBarrier(); + if (this->is_neox_style == 0) { + Cast(temp1Local, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopNQhead * this->rotary_dim)); + PipeBarrier(); + + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopNQhead; i++) { + GatherMask(inLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], + static_cast(1), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + PipeBarrier(); + GatherMask(inLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + PipeBarrier(); + } + } else { + Cast(inLocal, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopNQhead * this->rotary_dim)); + PipeBarrier(); + } + + DataCopy(reverseQ, inLocal[this->rotary_dim / 2], + {static_cast(loopNQhead), calBlockLen, calBlockLen, calBlockLen}); + PipeBarrier(); + DataCopy(reverseQ[this->rotary_dim / 2], inLocal, + {static_cast(loopNQhead), calBlockLen, calBlockLen, calBlockLen}); + PipeBarrier(); + + float One = 1.0; + float None = -1.0; + Duplicate(negOne, None, this->rotary_dim / 2); + Duplicate(negOne[this->rotary_dim / 2], One, this->rotary_dim / 2); + Broadcast(negOne[this->rotary_dim], negOne, dstShape_4Negone_, srcShape_); + PipeBarrier(); + + uint64_t offsetPos = indexToken; + uint64_t cosSinOffset = 0; + uint64_t localStartAddr = 0; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(inLocal, cosSin, inLocal, loopNQhead * this->rotary_dim); + PipeBarrier(); + Mul(reverseQ, negOne, reverseQ, loopNQhead * this->rotary_dim); + PipeBarrier(); + + offsetPos = indexToken; + cosSinOffset = this->rotary_dim / 2; + localStartAddr = 0; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + PipeBarrier(); + Mul(reverseQ, cosSin, reverseQ, loopNQhead * this->rotary_dim); + PipeBarrier(); + Add(inLocal, reverseQ, inLocal, loopNQhead * this->rotary_dim); + PipeBarrier(); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < loopNQhead; i++) { + Gather(temp1Local[i * this->rotary_dim], inLocal[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + PipeBarrier(); + } + Cast(inQueCalLocal, temp1Local, AscendC::RoundMode::CAST_RINT, + static_cast(loopNQhead * this->rotary_dim)); + PipeBarrier(); + } else { + Cast(inQueCalLocal, inLocal, AscendC::RoundMode::CAST_RINT, + static_cast(loopNQhead * this->rotary_dim)); + PipeBarrier(); + } + + if (this->head_size != this->rotary_dim) { + DataCopy(outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopNQhead), static_cast(rotaryBlockLen/2), 0, + static_cast(headBlockLen/2 - rotaryBlockLen/2)}); + PipeBarrier(); + DataCopy(outQueAfterCastLocal[this->rotary_dim], inQQueBeforeCastLocal[this->rotary_dim], + {static_cast(loopNQhead), static_cast(headBlockLen/2 - rotaryBlockLen/2), + static_cast(rotaryBlockLen/2), static_cast(rotaryBlockLen/2)}); + PipeBarrier(); + } else { + DataCopy(outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopNQhead), static_cast(headBlockLen/2), 0, 0}); + PipeBarrier(); + } + DataCopy(queryGM[offset], outQueAfterCastLocal, + {static_cast(loopNQhead), static_cast(headBlockLen/2), 0, 0}); + PipeBarrier(); + } + //key + if (indexHeads < this->loop_along_kheads) { + uint64_t loopNKhead = (indexHeads == this->loop_along_kheads - 1 && this->num_kheads_last_loop != 0) ? + this->num_kheads_last_loop : + this->num_kheads_each_loop; + DataCopy(inQQueBeforeCastLocal, key_in_GM[key_in_offset], + {1, static_cast(loopNKhead * headBlockLen / 2), 0, 0}); + PipeBarrier(); + DataCopy(inQueCalLocal, inQQueBeforeCastLocal, + {static_cast(loopNKhead), static_cast(rotaryBlockLen / 2), + static_cast(headBlockLen / 2 - rotaryBlockLen / 2), 0}); + PipeBarrier(); + if (this->is_neox_style == 0) { + Cast(temp1Local, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopNKhead * this->rotary_dim)); + PipeBarrier(); + + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopNKhead; i++) { + GatherMask(inLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], static_cast(1), + true, this->rotary_dim, {1, 1, 0, 0}, rsv); + PipeBarrier(); + GatherMask(inLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + PipeBarrier(); + } + } else { + Cast(inLocal, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopNKhead * this->rotary_dim)); + PipeBarrier(); + } + + DataCopy(reverseQ, inLocal[this->rotary_dim / 2], + {static_cast(loopNKhead), calBlockLen, calBlockLen, calBlockLen}); + PipeBarrier(); + DataCopy(reverseQ[this->rotary_dim / 2], inLocal, + {static_cast(loopNKhead), calBlockLen, calBlockLen, calBlockLen}); + PipeBarrier(); + + uint64_t offsetPos = indexToken; + uint64_t cosSinOffset = 0; + uint64_t localStartAddr = 0; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(inLocal, cosSin, inLocal, loopNKhead * this->rotary_dim); + PipeBarrier(); + Mul(reverseQ, negOne, reverseQ, loopNKhead * this->rotary_dim); + PipeBarrier(); + + offsetPos = indexToken; + cosSinOffset = this->rotary_dim / 2; + localStartAddr = 0; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(reverseQ, cosSin, reverseQ, loopNKhead * this->rotary_dim); + PipeBarrier(); + Add(inLocal, reverseQ, inLocal, loopNKhead * this->rotary_dim); + PipeBarrier(); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < loopNKhead; i++) { + Gather(temp1Local[i * this->rotary_dim], inLocal[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + PipeBarrier(); + } + Cast(inQueCalLocal, temp1Local, AscendC::RoundMode::CAST_RINT, + static_cast(loopNKhead * this->rotary_dim)); + PipeBarrier(); + } else { + Cast(inQueCalLocal, inLocal, AscendC::RoundMode::CAST_RINT, + static_cast(loopNKhead * this->rotary_dim)); + PipeBarrier(); + } + + if (this->head_size != this->rotary_dim) { + DataCopy(outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopNKhead), static_cast(rotaryBlockLen / 2), 0, + static_cast(headBlockLen / 2 - rotaryBlockLen / 2)}); + PipeBarrier(); + DataCopy(outQueAfterCastLocal[this->rotary_dim], inQQueBeforeCastLocal[this->rotary_dim], + {static_cast(loopNKhead), static_cast(headBlockLen / 2 - rotaryBlockLen / 2), + static_cast(rotaryBlockLen / 2), static_cast(rotaryBlockLen / 2)}); + PipeBarrier(); + } else { + DataCopy(outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopNKhead), static_cast(headBlockLen / 2), 0, 0}); + PipeBarrier(); + } + DataCopy(keyGM[offsetk], outQueAfterCastLocal, + {static_cast(loopNKhead), static_cast(headBlockLen / 2), 0, 0}); + PipeBarrier(); + } + + inQQueBeforeCast.FreeTensor(inQQueBeforeCastLocal); + inQueueCosSinCacheBeforeCast.FreeTensor(inQueueCosSinCacheBeforeCastLocal); + outQueAfterCast.FreeTensor(outQueAfterCastLocal); +} + +template +__aicore__ inline void RopeWithSinCosCacheFP16::Process() +{ + if (this->loop_for_one_token == 0) { + for (uint64_t n = 0; n < this->loop_time_current_core - 1; n++) { + Compute(n, this->num_tokens_each_loop_current_core); + } + if (this->num_tokens_last_loop_current_core == 0) { + Compute(this->loop_time_current_core - 1, this->num_tokens_each_loop_current_core); + } else { + Compute(this->loop_time_current_core - 1, this->num_tokens_last_loop_current_core); + } + } else { + uint64_t loop_along_heads = + this->loop_along_qheads > this->loop_along_kheads ? this->loop_along_qheads : this->loop_along_kheads; + for (uint64_t n = 0; n < this->num_tokens_current_core; n++) { + for (uint64_t m = 0; m < loop_along_heads; m++) { + ComputeAlongHeads(n, m); + } + } + } +} +} // namespace RopeWithSinCosCache + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/arch35/rope_with_sin_cos_cache_fp32.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/arch35/rope_with_sin_cos_cache_fp32.h new file mode 100644 index 0000000000000000000000000000000000000000..7bd69dc78b8097979d2e8c5d75add4412c8949cc --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/arch35/rope_with_sin_cos_cache_fp32.h @@ -0,0 +1,666 @@ +/** + * 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 rope_with_sin_cos_cache_fp32.h + * \brief rope_with_sin_cos_cache_fp32.h + */ + +#ifndef ROPE_WITH_SIN_COS_CACHE_ARCH35_FP32_H +#define ROPE_WITH_SIN_COS_CACHE_ARCH35_FP32_H + +#include "rope_with_sin_cos_cache_base.h" + +namespace RopeWithSinCosCache { +using namespace AscendC; + +template +class RopeWithSinCosCacheF32 : public RopeWithSinCosCacheBase +{ +public: + __aicore__ inline RopeWithSinCosCacheF32(){}; + __aicore__ inline void Init( + GM_ADDR position_id, GM_ADDR query_in, GM_ADDR key_in, GM_ADDR cos_sin_cache, GM_ADDR query_out, + GM_ADDR key_out, const RopeWithSinCosCacheTilingData& tiling_data, TPipe* pipe); + __aicore__ inline void Process(); + __aicore__ inline void Compute(uint64_t index, uint64_t loopN); + __aicore__ inline void ComputeAlongHeads(uint64_t indexToken, uint64_t indexHeads); + __aicore__ inline void GetCosSinCache( + LocalTensor copyBuf0Local, LocalTensor inCosSin, + LocalTensor CosSin, uint64_t offsetPos, uint64_t cosSinOffset, uint64_t localStartAddr, + uint32_t (&rcShape_)[2], uint32_t (&dstShape_)[2]); + +protected: + static constexpr uint64_t BLOCK_SIZE = 32; + static constexpr uint64_t BUFFER_NUM = 1; + static constexpr uint64_t ELE_NUM_FP32 = 8; + static constexpr uint64_t MASK = 64; + static constexpr uint64_t MROPE_SECTION_BASE_SIZE = 8; + uint64_t blockOffset; + uint16_t headBlockLen{0}; + uint16_t rotaryBlockLen{0}; + uint16_t calBlockLen{0}; + uint64_t q_size; + uint64_t k_size; + uint64_t num_heads_max; + + GlobalTensor position_id_GM; + GlobalTensor query_in_GM; + GlobalTensor key_in_GM; + GlobalTensor cos_sin_cache_GM; + + GlobalTensor queryGM; + GlobalTensor keyGM; + + TQue inQQue, inQueueCosSinCache; + TQue outQue; + TBuf reverseBuf, negOneBuf, cosSinBuf, temp1, offsetBuf, inQueCalBuf; + TBuf copyBuf0; +}; + +template +__aicore__ inline void RopeWithSinCosCacheF32::Init( + GM_ADDR position_id, GM_ADDR query_in, GM_ADDR key_in, GM_ADDR cos_sin_cache, GM_ADDR query_out, GM_ADDR key_out, + const RopeWithSinCosCacheTilingData& tiling_data, TPipe* pipe) +{ + this->InitData(tiling_data); + headBlockLen = static_cast(this->head_size / ELE_NUM_FP32); + rotaryBlockLen = static_cast(this->rotary_dim / ELE_NUM_FP32); + calBlockLen = rotaryBlockLen / 2; + num_heads_max = (this->num_q_heads > this->num_kv_heads) ? this->num_q_heads : this->num_kv_heads; + + if (this->blockIdx_ < this->front_core) { + blockOffset = this->num_tokens_each_front_core * this->blockIdx_; + } else { + blockOffset = this->num_tokens_each_front_core * (this->front_core) + + (this->blockIdx_ - this->front_core) * this->num_tokens_each_tail_core; + } + + position_id_GM.SetGlobalBuffer((__gm__ uint64_t*)position_id + blockOffset); + query_in_GM.SetGlobalBuffer((__gm__ T*)query_in + blockOffset * this->num_q_heads * this->head_size); + key_in_GM.SetGlobalBuffer((__gm__ T*)key_in + blockOffset * this->num_kv_heads * this->head_size); + cos_sin_cache_GM.SetGlobalBuffer((__gm__ T*)cos_sin_cache); + + queryGM.SetGlobalBuffer((__gm__ T*)query_out + blockOffset * this->num_q_heads * this->head_size); + keyGM.SetGlobalBuffer((__gm__ T*)key_out + blockOffset * this->num_kv_heads * this->head_size); + + pipe->InitBuffer(copyBuf0, this->rotary_dim / 2 * sizeof(T)); + if(this->loop_for_one_token==0){ + pipe->InitBuffer( + inQQue, BUFFER_NUM, this->num_tokens_each_loop_current_core * num_heads_max * this->head_size * sizeof(T)); + pipe->InitBuffer( + inQueueCosSinCache, BUFFER_NUM, this->num_tokens_each_loop_current_core * this->rotary_dim * sizeof(T)); + pipe->InitBuffer( + outQue, BUFFER_NUM, this->num_tokens_each_loop_current_core * num_heads_max * this->head_size * sizeof(T)); + pipe->InitBuffer( + reverseBuf, this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(negOneBuf, this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(cosSinBuf, this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(T)); + pipe->InitBuffer( + inQueCalBuf, this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(T)); + + if (this->is_neox_style == 0) { + pipe->InitBuffer(temp1, this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(offsetBuf, this->rotary_dim * sizeof(uint32_t)); + } else { +#ifndef __CCE_KT_TEST__ + pipe->InitBuffer(temp1, 0 * sizeof(T)); + pipe->InitBuffer(offsetBuf, 0 * sizeof(uint32_t)); +#else + pipe->InitBuffer(temp1, 1 * sizeof(T)); + pipe->InitBuffer(offsetBuf, 1 * sizeof(uint32_t)); +#endif + } + } else { + pipe->InitBuffer(inQQue, BUFFER_NUM, this->num_heads_each_loop * this->head_size * sizeof(T)); + pipe->InitBuffer(inQueueCosSinCache, BUFFER_NUM, this->rotary_dim * sizeof(T)); + pipe->InitBuffer(outQue, BUFFER_NUM, this->num_heads_each_loop * this->head_size * sizeof(T)); + pipe->InitBuffer(reverseBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(negOneBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(cosSinBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(inQueCalBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(T)); + + if (this->is_neox_style == 0) { + pipe->InitBuffer(temp1, this->num_heads_each_loop * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(offsetBuf, this->rotary_dim * sizeof(uint32_t)); + } else { +#ifndef __CCE_KT_TEST__ + pipe->InitBuffer(temp1, 0 * sizeof(T)); + pipe->InitBuffer(offsetBuf, 0 * sizeof(uint32_t)); +#else + pipe->InitBuffer(temp1, 1 * sizeof(T)); + pipe->InitBuffer(offsetBuf, 1 * sizeof(uint32_t)); +#endif + } + } +} + +template +__aicore__ inline void +RopeWithSinCosCacheF32::GetCosSinCache(LocalTensor copyBuf0Local, LocalTensor inCosSin, + LocalTensor cosSin, uint64_t offsetPos, uint64_t cosSinOffset, + uint64_t localStartAddr, uint32_t (&srcShape_)[2], uint32_t (&dstShape_)[2]) +{ + if (this->mrope_section0 > 0) { + uint64_t pos0 = position_id_GM.GetValue(offsetPos); + uint64_t pos1 = position_id_GM.GetValue(offsetPos + this->num_tokens); + uint64_t pos2 = position_id_GM.GetValue(offsetPos + 2 * this->num_tokens); + + uint8_t padding2 = ((this->mrope_section0 + this->mrope_section1) * sizeof(T) % BLOCK_SIZE) / sizeof(T); + DataCopyPad(inCosSin[this->mrope_section0 + static_cast(this->mrope_section1) - padding2], + cos_sin_cache_GM[pos2 * this->rotary_dim + + static_cast(this->mrope_section0 + this->mrope_section1) + cosSinOffset], + {1, static_cast(this->mrope_section2 * sizeof(T)), 0, 0}, {true, padding2, 0, 0}); + PipeBarrier(); + + // 如果mrope_section不是32B对齐,DataCopyPad接口会自动填充,同时为了兼容旧版16 24 24做法,避免该场景性能劣化 + uint8_t padding1 = (this->mrope_section0 * sizeof(T) % BLOCK_SIZE) / sizeof(T); + if (this->mrope_section1 % MROPE_SECTION_BASE_SIZE == 0) { + DataCopyPad( + inCosSin[this->mrope_section0 - padding1], + cos_sin_cache_GM[pos1 * this->rotary_dim + static_cast(this->mrope_section0) + cosSinOffset], + {1, static_cast(this->mrope_section1 * sizeof(float)), 0, 0}, {true, padding1, 0, 0}); + PipeBarrier(); + } else { + DataCopyPad( + copyBuf0Local, + cos_sin_cache_GM[pos1 * this->rotary_dim + static_cast(this->mrope_section0) + cosSinOffset], + {1, static_cast(this->mrope_section1 * sizeof(T)), 0, 0}, {true, padding1, 0, 0}); + PipeBarrier(); + Copy(inCosSin[this->mrope_section0 - padding1], copyBuf0Local, this->mrope_section1 + padding1, 1, + {1, 1, 0, 0}); + } + if (this->mrope_section0 % MROPE_SECTION_BASE_SIZE == 0) { + DataCopyPad(inCosSin, cos_sin_cache_GM[pos0 * this->rotary_dim + cosSinOffset], + {1, static_cast(this->mrope_section0 * sizeof(float)), 0, 0}, {false, 0, 0, 0}); + PipeBarrier(); + } else { + DataCopyPad(copyBuf0Local, cos_sin_cache_GM[pos0 * this->rotary_dim + cosSinOffset], + {1, static_cast(this->mrope_section0 * sizeof(T)), 0, 0}, {false, 0, 0, 0}); + PipeBarrier(); + Copy(inCosSin, copyBuf0Local, this->mrope_section0, 1, {1, 1, 0, 0}); + } + } else { + uint64_t pos = position_id_GM.GetValue(offsetPos); + PipeBarrier(); + DataCopy(inCosSin, cos_sin_cache_GM[pos * this->rotary_dim + cosSinOffset], {1, calBlockLen, 0, 0}); + PipeBarrier(); + } + + DataCopy(inCosSin[this->rotary_dim / 2], inCosSin, {1, calBlockLen, 0, 0}); + PipeBarrier(); + Broadcast(cosSin[localStartAddr], inCosSin, dstShape_, srcShape_); +} + +template +__aicore__ inline void RopeWithSinCosCacheF32::Compute(uint64_t index, uint64_t loopN) +{ + q_size = this->num_q_heads * this->head_size; + k_size = this->num_kv_heads * this->head_size; + uint64_t offset = index * this->num_tokens_each_loop_current_core * q_size; + uint64_t offsetk = index * this->num_tokens_each_loop_current_core * k_size; + uint64_t offsetCosSin = index * loopN * this->rotary_dim; + + uint32_t dstShape_[2] = {static_cast(this->num_heads_max), static_cast(this->rotary_dim)}; +#ifndef __CCE_KT_TEST__ + uint32_t dstShape_4Negone_[2] = { + static_cast(loopN * this->num_heads_max), static_cast(this->rotary_dim)}; +#else + uint32_t dstShape_4Negone_[2] = {static_cast(loopN * (this->num_heads_max - 1)), + static_cast(this->rotary_dim)}; +#endif + uint32_t srcShape_[2] = {1, static_cast(this->rotary_dim)}; + + LocalTensor inLocal = inQQue.AllocTensor(); + LocalTensor inCosSin = inQueueCosSinCache.AllocTensor(); + LocalTensor outLocal = outQue.AllocTensor(); + LocalTensor reverseQ = reverseBuf.Get(); + LocalTensor negOne = negOneBuf.Get(); + LocalTensor cosSin = cosSinBuf.Get(); + LocalTensor offsetLocal = offsetBuf.Get(); + LocalTensor temp1Local = temp1.Get(); + LocalTensor inQueCalLocal = inQueCalBuf.Get(); + LocalTensor copyBuf0Local = copyBuf0.Get(); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < this->rotary_dim / 2; i++) { + offsetLocal.SetValue(i * 2, i * 4); + offsetLocal.SetValue(i * 2 + 1, (this->rotary_dim / 2 + i) * 4); + } + } + DataCopy( + inLocal, query_in_GM[offset], + {static_cast(loopN), static_cast(this->num_q_heads * headBlockLen), + static_cast(this->q_leading_dimension / ELE_NUM_FP32 - this->q_size / ELE_NUM_FP32), 0}); + this->MTE2ToVSync(); + + if (this->is_neox_style == 0) { + DataCopy( + temp1Local, inLocal, + {static_cast(loopN * this->num_q_heads), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopN * this->num_q_heads; i++) { + GatherMask( + inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], static_cast(1), true, + this->rotary_dim, {1, 1, 0, 0}, rsv); + GatherMask( + inQueCalLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + } + } else { + DataCopy( + inQueCalLocal, inLocal, + {static_cast(loopN * this->num_q_heads), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + } + + DataCopy( + reverseQ, inQueCalLocal[this->rotary_dim / 2], + {static_cast(loopN * this->num_q_heads), calBlockLen, calBlockLen, calBlockLen}); + DataCopy( + reverseQ[this->rotary_dim / 2], inQueCalLocal, + {static_cast(loopN * this->num_q_heads), calBlockLen, calBlockLen, calBlockLen}); + + float One = 1.0; + float None = -1.0; + Duplicate(negOne, None, this->rotary_dim / 2); + Duplicate(negOne[this->rotary_dim / 2], One, this->rotary_dim / 2); + + Broadcast(negOne[this->rotary_dim], negOne, dstShape_4Negone_, srcShape_); + uint64_t localStartAddr = 0; + uint64_t cosSinOffset = 0; + for (uint32_t i = 0; i < loopN; ++i) { + PipeBarrier(); + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_q_heads * this->rotary_dim; + } + Mul(inQueCalLocal, cosSin, inQueCalLocal, loopN * this->num_q_heads * this->rotary_dim); + Mul(reverseQ, negOne, reverseQ, loopN * this->num_q_heads * this->rotary_dim); + localStartAddr = 0; + cosSinOffset = this->rotary_dim / 2; + for (uint32_t i = 0; i < loopN; ++i) { + PipeBarrier(); + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_q_heads * this->rotary_dim; + } + Mul(reverseQ, cosSin, reverseQ, loopN * this->num_q_heads * this->rotary_dim); + + if (this->is_neox_style == 0) { + Add(temp1Local, reverseQ, inQueCalLocal, loopN * this->num_q_heads * this->rotary_dim); + for (uint32_t i = 0; i < loopN * this->num_q_heads; i++) { + Gather( + inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + } + } else { + Add(inQueCalLocal, reverseQ, inQueCalLocal, loopN * this->num_q_heads * this->rotary_dim); + } + + if (this->head_size != this->rotary_dim) { + DataCopy( + outLocal, inQueCalLocal, + {static_cast(loopN * this->num_q_heads), static_cast(rotaryBlockLen), 0, + static_cast(headBlockLen - rotaryBlockLen)}); + DataCopy( + outLocal[this->rotary_dim], inLocal[this->rotary_dim], + {static_cast(loopN * this->num_q_heads), static_cast(headBlockLen - rotaryBlockLen), + static_cast(rotaryBlockLen), static_cast(rotaryBlockLen)}); + } else { + DataCopy( + outLocal, inQueCalLocal, + {static_cast(loopN), static_cast(this->num_q_heads * headBlockLen), 0, 0}); + } + PipeBarrier(); + DataCopy( + queryGM[offset], outLocal, + {static_cast(loopN), static_cast(this->num_q_heads * headBlockLen), 0, 0}); + PipeBarrier(); + // key的处理 + DataCopy( + inLocal, key_in_GM[offsetk], + {static_cast(loopN), static_cast(this->num_kv_heads * headBlockLen), + static_cast(this->k_leading_dimension / ELE_NUM_FP32 - this->k_size / ELE_NUM_FP32), 0}); + this->MTE2ToVSync(); + + if (this->is_neox_style == 0) { + DataCopy( + temp1Local, inLocal, + {static_cast(loopN * this->num_kv_heads), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopN * this->num_kv_heads; i++) { + GatherMask( + inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], static_cast(1), true, + this->rotary_dim, {1, 1, 0, 0}, rsv); + GatherMask( + inQueCalLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + } + } else { + DataCopy( + inQueCalLocal, inLocal, + {static_cast(loopN * this->num_kv_heads), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + } + DataCopy( + reverseQ, inQueCalLocal[this->rotary_dim / 2], + {static_cast(loopN * this->num_kv_heads), calBlockLen, calBlockLen, calBlockLen}); + DataCopy( + reverseQ[this->rotary_dim / 2], inQueCalLocal, + {static_cast(loopN * this->num_kv_heads), calBlockLen, calBlockLen, calBlockLen}); + + localStartAddr = 0; + cosSinOffset = 0; + for (uint32_t i = 0; i < loopN; ++i) { + PipeBarrier(); + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_kv_heads * this->rotary_dim; + } + + Mul(inQueCalLocal, cosSin, inQueCalLocal, loopN * this->num_kv_heads * this->rotary_dim); + Mul(reverseQ, negOne, reverseQ, loopN * this->num_kv_heads * this->rotary_dim); + + localStartAddr = 0; + cosSinOffset = this->rotary_dim / 2; + for (uint32_t i = 0; i < loopN; ++i) { + PipeBarrier(); + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_kv_heads * this->rotary_dim; + } + + Mul(reverseQ, cosSin, reverseQ, loopN * this->num_kv_heads * this->rotary_dim); + + if (this->is_neox_style == 0) { + Add(temp1Local, reverseQ, inQueCalLocal, loopN * this->num_kv_heads * this->rotary_dim); + + for (uint32_t i = 0; i < loopN * this->num_kv_heads; i++) { + Gather( + inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + } + } else { + Add(inQueCalLocal, reverseQ, inQueCalLocal, loopN * this->num_kv_heads * this->rotary_dim); + } + + if (this->head_size != this->rotary_dim) { + DataCopy( + outLocal, inQueCalLocal, + {static_cast(loopN * this->num_kv_heads), static_cast(rotaryBlockLen), 0, + static_cast(headBlockLen - rotaryBlockLen)}); + + DataCopy( + outLocal[this->rotary_dim], inLocal[this->rotary_dim], + {static_cast(loopN * this->num_kv_heads), static_cast(headBlockLen - rotaryBlockLen), + static_cast(rotaryBlockLen), static_cast(rotaryBlockLen)}); + } else { + DataCopy( + outLocal, inQueCalLocal, + {static_cast(loopN), static_cast(this->num_kv_heads * headBlockLen), 0, 0}); + } + PipeBarrier(); + + DataCopy( + keyGM[offsetk], outLocal, + {static_cast(loopN), static_cast(this->num_kv_heads * headBlockLen), 0, 0}); + PipeBarrier(); + + inQueueCosSinCache.FreeTensor(inCosSin); + inQQue.FreeTensor(inLocal); + outQue.FreeTensor(outLocal); +} + +template +__aicore__ inline void RopeWithSinCosCacheF32::ComputeAlongHeads(uint64_t indexToken, uint64_t indexHeads){ + q_size = this->num_q_heads * this->head_size; + k_size = this->num_kv_heads * this->head_size; + uint64_t offsetQHead = indexHeads * this->num_qheads_each_loop * this->head_size; + uint64_t offsetKHead = indexHeads * this->num_kheads_each_loop * this->head_size; + uint64_t offset = indexToken * q_size + offsetQHead;//非连续? + uint64_t offsetk = indexToken * k_size + offsetKHead; + + uint32_t dstShape_[2] = {static_cast(this->num_heads_each_loop), static_cast(this->rotary_dim)}; + uint32_t dstShape_4Negone_[2] = {static_cast(this->num_heads_each_loop), + static_cast(this->rotary_dim)}; + uint32_t srcShape_[2] = {1, static_cast(this->rotary_dim)}; + + LocalTensor inLocal = inQQue.AllocTensor(); + LocalTensor inCosSin = inQueueCosSinCache.AllocTensor(); + LocalTensor outLocal = outQue.AllocTensor(); + LocalTensor reverseQ = reverseBuf.Get(); + LocalTensor negOne = negOneBuf.Get(); + LocalTensor cosSin = cosSinBuf.Get(); + LocalTensor offsetLocal = offsetBuf.Get(); + LocalTensor temp1Local = temp1.Get(); + LocalTensor inQueCalLocal = inQueCalBuf.Get(); + LocalTensor copyBuf0Local = copyBuf0.Get(); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < this->rotary_dim / 2; i++) { + offsetLocal.SetValue(i * 2, i * 4); + offsetLocal.SetValue(i * 2 + 1, (this->rotary_dim / 2 + i) * 4); + } + } + + if (indexHeads < this->loop_along_qheads) { + uint64_t loopNQhead = (indexHeads == this->loop_along_qheads - 1 && this->num_qheads_last_loop != 0) ? + this->num_qheads_last_loop : + this->num_qheads_each_loop; + DataCopy(inLocal, query_in_GM[offset], {1, static_cast(loopNQhead * headBlockLen), 0, 0}); + PipeBarrier(); + if (this->is_neox_style == 0) { + PipeBarrier(); + DataCopy(temp1Local, inLocal, + {static_cast(loopNQhead), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + PipeBarrier(); + + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopNQhead; i++) { + GatherMask(inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], + static_cast(1), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + PipeBarrier(); + GatherMask(inQueCalLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + PipeBarrier(); + } + } else { + PipeBarrier(); + DataCopy(inQueCalLocal, inLocal, + {static_cast(loopNQhead), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + PipeBarrier(); + } + + DataCopy(reverseQ, inQueCalLocal[this->rotary_dim / 2], + {static_cast(loopNQhead), calBlockLen, calBlockLen, calBlockLen}); + PipeBarrier(); + DataCopy(reverseQ[this->rotary_dim / 2], inQueCalLocal, + {static_cast(loopNQhead), calBlockLen, calBlockLen, calBlockLen}); + PipeBarrier(); + + float One = 1.0; + float None = -1.0; + Duplicate(negOne, None, this->rotary_dim / 2); + Duplicate(negOne[this->rotary_dim / 2], One, this->rotary_dim / 2); + PipeBarrier(); + + Broadcast(negOne[this->rotary_dim], negOne, dstShape_4Negone_, srcShape_); + PipeBarrier(); + + uint64_t offsetPos = indexToken; + uint64_t cosSinOffset = 0; + uint64_t localStartAddr = 0; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(inQueCalLocal, cosSin, inQueCalLocal, loopNQhead * this->rotary_dim); + PipeBarrier(); + Mul(reverseQ, negOne, reverseQ, loopNQhead * this->rotary_dim); + PipeBarrier(); + offsetPos = indexToken; + cosSinOffset = this->rotary_dim / 2; + localStartAddr = 0; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(reverseQ, cosSin, reverseQ, loopNQhead * this->rotary_dim); + PipeBarrier(); + + if (this->is_neox_style == 0) { + Add(temp1Local, reverseQ, inQueCalLocal, loopNQhead * this->rotary_dim); + PipeBarrier(); + for (uint32_t i = 0; i < loopNQhead; i++) { + Gather(inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + PipeBarrier(); + } + } else { + Add(inQueCalLocal, reverseQ, inQueCalLocal, loopNQhead * this->rotary_dim); + PipeBarrier(); + } + + if (this->head_size != this->rotary_dim) { + DataCopy(outLocal, inQueCalLocal, + {static_cast(loopNQhead), static_cast(rotaryBlockLen), 0, + static_cast(headBlockLen - rotaryBlockLen)}); + PipeBarrier(); + DataCopy(outLocal[this->rotary_dim], inLocal[this->rotary_dim], + {static_cast(loopNQhead), static_cast(headBlockLen - rotaryBlockLen), + static_cast(rotaryBlockLen), static_cast(rotaryBlockLen)}); + PipeBarrier(); + } else { + DataCopy(outLocal, inQueCalLocal, + {static_cast(loopNQhead), static_cast(headBlockLen), 0, 0}); + PipeBarrier(); + } + DataCopy(queryGM[offset], outLocal, + {static_cast(loopNQhead), static_cast(headBlockLen), 0, 0}); + PipeBarrier(); + } + //key + if (indexHeads < this->loop_along_kheads) { + uint64_t loopNKhead = (indexHeads == this->loop_along_kheads - 1 && this->num_kheads_last_loop != 0) ? + this->num_kheads_last_loop : + this->num_kheads_each_loop; + DataCopy(inLocal, key_in_GM[offsetk], {1, static_cast(loopNKhead * headBlockLen), 0, 0}); + PipeBarrier(); + if (this->is_neox_style == 0) { + PipeBarrier(); + DataCopy(temp1Local, inLocal, + {static_cast(loopNKhead), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + PipeBarrier(); + + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopNKhead; i++) { + GatherMask(inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], + static_cast(1), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + PipeBarrier(); + GatherMask(inQueCalLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + PipeBarrier(); + } + } else { + PipeBarrier(); + DataCopy(inQueCalLocal, inLocal, + {static_cast(loopNKhead), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + PipeBarrier(); + } + + DataCopy(reverseQ, inQueCalLocal[this->rotary_dim / 2], + {static_cast(loopNKhead), calBlockLen, calBlockLen, calBlockLen}); + PipeBarrier(); + DataCopy(reverseQ[this->rotary_dim / 2], inQueCalLocal, + {static_cast(loopNKhead), calBlockLen, calBlockLen, calBlockLen}); + PipeBarrier(); + + uint64_t offsetPos = indexToken; + uint64_t cosSinOffset = 0; + uint64_t localStartAddr = 0; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + + Mul(inQueCalLocal, cosSin, inQueCalLocal, loopNKhead * this->rotary_dim); + PipeBarrier(); + Mul(reverseQ, negOne, reverseQ, loopNKhead * this->rotary_dim); + PipeBarrier(); + offsetPos = indexToken; + cosSinOffset = this->rotary_dim / 2; + localStartAddr = 0; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(reverseQ, cosSin, reverseQ, loopNKhead * this->rotary_dim); + PipeBarrier(); + + if (this->is_neox_style == 0) { + Add(temp1Local, reverseQ, inQueCalLocal, loopNKhead * this->rotary_dim); + PipeBarrier(); + for (uint32_t i = 0; i < loopNKhead; i++) { + Gather(inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + PipeBarrier(); + } + } else { + Add(inQueCalLocal, reverseQ, inQueCalLocal, loopNKhead * this->rotary_dim); + PipeBarrier(); + } + + if (this->head_size != this->rotary_dim) { + DataCopy(outLocal, inQueCalLocal, + {static_cast(loopNKhead), static_cast(rotaryBlockLen), 0, + static_cast(headBlockLen - rotaryBlockLen)}); + PipeBarrier(); + DataCopy(outLocal[this->rotary_dim], inLocal[this->rotary_dim], + {static_cast(loopNKhead), static_cast(headBlockLen - rotaryBlockLen), + static_cast(rotaryBlockLen), static_cast(rotaryBlockLen)}); + PipeBarrier(); + } else { + DataCopy(outLocal, inQueCalLocal, + {static_cast(loopNKhead), static_cast(headBlockLen), 0, 0}); + PipeBarrier(); + } + DataCopy(keyGM[offsetk], outLocal, + {static_cast(loopNKhead), static_cast(headBlockLen), 0, 0}); + PipeBarrier(); + } + + inQueueCosSinCache.FreeTensor(inCosSin); + inQQue.FreeTensor(inLocal); + outQue.FreeTensor(outLocal); +} + +template +__aicore__ inline void RopeWithSinCosCacheF32::Process() +{ + if(this->loop_for_one_token==0){ + for (uint64_t n = 0; n < this->loop_time_current_core - 1; n++) { + Compute(n, this->num_tokens_each_loop_current_core); + } + + if (this->num_tokens_last_loop_current_core == 0) { + Compute(this->loop_time_current_core - 1, this->num_tokens_each_loop_current_core); + } else { + Compute(this->loop_time_current_core - 1, this->num_tokens_last_loop_current_core); + } + } + else{ + uint64_t loop_along_heads = + this->loop_along_qheads > this->loop_along_kheads ? this->loop_along_qheads : this->loop_along_kheads; + for(uint64_t n=0;nnum_tokens_current_core;n++){ + for(uint64_t m=0;m op; + op.Init(position_id, query_in, key_in, cos_sin_cache, query_out, key_out, tilingData, ptr); + op.Process(); + } + } +#elif ORIG_DTYPE_QUERYIN == DT_FLOAT16 + if (TILING_KEY_IS(21)) { + TPipe* ptr = &pipe; + if (ptr != nullptr) { + RopeWithSinCosCacheFP16 op; + op.Init(position_id, query_in, key_in, cos_sin_cache, query_out, key_out, tilingData, ptr); + op.Process(); + } + } +#elif ORIG_DTYPE_QUERYIN == DT_FLOAT + if (TILING_KEY_IS(22)) { + TPipe* ptr = &pipe; + if (ptr != nullptr) { + RopeWithSinCosCacheF32 op; + op.Init(position_id, query_in, key_in, cos_sin_cache, query_out, key_out, tilingData, ptr); + op.Process(); + } + } +#endif +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/rope_with_sin_cos_cache_apt.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/rope_with_sin_cos_cache_apt.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c5159fd464dab3e89e0a56ee4a0cd0ab635e930 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/rope_with_sin_cos_cache_apt.cpp @@ -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. + */ + +/*! + * \file rope_with_sin_cos_cache_apt.cpp + * \brief 950 (A5) 平台入口文件,复用 membase 实现逻辑 + */ +#include "kernel_operator.h" +#include "arch35/rope_with_sin_cos_cache_fp32.h" +#include "arch35/rope_with_sin_cos_cache_f_bf16.h" + +using namespace AscendC; +using namespace RopeWithSinCosCache; + +extern "C" __global__ __aicore__ void rope_with_sin_cos_cache( + GM_ADDR position_id, GM_ADDR query_in, GM_ADDR key_in, GM_ADDR cos_sin_cache, GM_ADDR query_out, GM_ADDR key_out, + GM_ADDR workspace, GM_ADDR tiling) +{ + GET_TILING_DATA(tilingData, tiling); + GM_ADDR usrWorkspace = AscendC::GetUserWorkspace(workspace); + TPipe pipe; +#if ORIG_DTYPE_QUERYIN == DT_BF16 + if (TILING_KEY_IS(20)) { + TPipe* ptr = &pipe; + if (ptr != nullptr) { + RopeWithSinCosCacheFP16 op; + op.Init(position_id, query_in, key_in, cos_sin_cache, query_out, key_out, tilingData, ptr); + op.Process(); + } + } +#elif ORIG_DTYPE_QUERYIN == DT_FLOAT16 + if (TILING_KEY_IS(21)) { + TPipe* ptr = &pipe; + if (ptr != nullptr) { + RopeWithSinCosCacheFP16 op; + op.Init(position_id, query_in, key_in, cos_sin_cache, query_out, key_out, tilingData, ptr); + op.Process(); + } + } +#elif ORIG_DTYPE_QUERYIN == DT_FLOAT + if (TILING_KEY_IS(22)) { + TPipe* ptr = &pipe; + if (ptr != nullptr) { + RopeWithSinCosCacheF32 op; + op.Init(position_id, query_in, key_in, cos_sin_cache, query_out, key_out, tilingData, ptr); + op.Process(); + } + } +#endif +} + diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/rope_with_sin_cos_cache_base.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/rope_with_sin_cos_cache_base.h new file mode 100644 index 0000000000000000000000000000000000000000..e85744b10b552af2f550900f86475360a3e42307 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/rope_with_sin_cos_cache_base.h @@ -0,0 +1,193 @@ +/** + * 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 rope_with_sin_cos_cache_base.h + * \brief rope_with_sin_cos_cache_base.h + */ +#ifndef ROPE_WITH_SIN_COS_CACHE_BASE_H +#define ROPE_WITH_SIN_COS_CACHE_BASE_H + +#include "kernel_operator.h" + +namespace RopeWithSinCosCache { +using namespace AscendC; +using AscendC::Duplicate; +using AscendC::HardEvent; + +template +class RopeWithSinCosCacheBase +{ +public: + // 构造函数 + __aicore__ inline RopeWithSinCosCacheBase(){}; + __aicore__ inline void InitData(const RopeWithSinCosCacheTilingData& tilingData); + __aicore__ inline void SToMTE2Sync(); + __aicore__ inline void MTE2ToSSync(); + __aicore__ inline void SToMTE3Sync(); + __aicore__ inline void MTE3ToSSync(); + __aicore__ inline void SToVSync(); + __aicore__ inline void MTE3ToVSync(); + __aicore__ inline void MTE2ToVSync(); + __aicore__ inline void VToMTE2Sync(); + __aicore__ inline void VToMTE3Sync(); + +protected: + uint32_t blockIdx_; + uint64_t core_num_use; + uint64_t num_tokens; + uint64_t num_q_heads; + uint64_t num_kv_heads; + uint64_t rotary_dim; + uint64_t mrope_section0; + uint64_t mrope_section1; + uint64_t mrope_section2; + uint64_t mrope_section3; + uint64_t head_size; + uint64_t q_leading_dimension; + uint64_t k_leading_dimension; + uint64_t front_core; + uint64_t tail_core; + uint64_t num_tokens_each_front_core; + uint64_t num_tokens_each_tail_core; + uint64_t is_neox_style; + uint64_t cacheMode; + + uint64_t loop_time_current_core{0}; // 当前核批处理数据轮数 + uint64_t num_tokens_each_loop_current_core{0}; // 当前核每轮处理的token数 + uint64_t num_tokens_last_loop_current_core{0}; // 当前核最后一轮轮处理的token数 + + uint64_t loop_for_one_token; + uint64_t loop_along_qheads; + uint64_t loop_along_kheads; + uint64_t num_heads_each_loop; + uint64_t num_qheads_each_loop; + uint64_t num_qheads_last_loop; + uint64_t num_kheads_each_loop; + uint64_t num_kheads_last_loop; + uint64_t num_tokens_current_core; +}; + +template +__aicore__ inline void RopeWithSinCosCacheBase::InitData(const RopeWithSinCosCacheTilingData& tilingData) +{ + blockIdx_ = AscendC::GetBlockIdx(); + + core_num_use = tilingData.core_num_use; + num_tokens = tilingData.num_tokens; + num_q_heads = tilingData.num_q_heads; + num_kv_heads = tilingData.num_kv_heads; + rotary_dim = tilingData.rotary_dim; + mrope_section0 = tilingData.mrope_section0; + mrope_section1 = tilingData.mrope_section1; + mrope_section2 = tilingData.mrope_section2; + mrope_section3 = tilingData.mrope_section3; + head_size = tilingData.head_size; + q_leading_dimension = tilingData.q_leading_dimension; + k_leading_dimension = tilingData.k_leading_dimension; + front_core = tilingData.front_core; + tail_core = tilingData.tail_core; + num_tokens_each_front_core = tilingData.num_tokens_each_front_core; + num_tokens_each_tail_core = tilingData.num_tokens_each_tail_core; + is_neox_style = tilingData.isNeoxStyle; + cacheMode = tilingData.cacheMode; + + loop_time_current_core = + (blockIdx_ < front_core) ? tilingData.loop_time_each_front_core : tilingData.loop_time_each_tail_core; + num_tokens_each_loop_current_core = (blockIdx_ < front_core) ? tilingData.num_tokens_front_core_each_loop : + tilingData.num_tokens_tail_core_each_loop; + num_tokens_last_loop_current_core = (blockIdx_ < front_core) ? tilingData.num_tokens_front_core_last_loop : + tilingData.num_tokens_tail_core_last_loop; + + loop_for_one_token = tilingData.loop_for_one_token; + loop_along_qheads = tilingData.loop_along_qheads; + loop_along_kheads = tilingData.loop_along_kheads; + num_qheads_each_loop = tilingData.num_qheads_each_loop; + num_qheads_last_loop = tilingData.num_qheads_last_loop; + num_kheads_each_loop = tilingData.num_kheads_each_loop; + num_kheads_last_loop = tilingData.num_kheads_last_loop; + num_heads_each_loop = num_qheads_each_loop > num_kheads_each_loop ? num_qheads_each_loop : num_kheads_each_loop; + num_tokens_current_core = (blockIdx_ < front_core) ? tilingData.num_tokens_each_front_core : tilingData.num_tokens_each_tail_core; +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::SToMTE2Sync() +{ + event_t eventIDSToMTE2 = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_MTE2)); + SetFlag(eventIDSToMTE2); + WaitFlag(eventIDSToMTE2); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::MTE2ToSSync() +{ + event_t eventIDMTE2ToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_S)); + SetFlag(eventIDMTE2ToS); + WaitFlag(eventIDMTE2ToS); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::SToMTE3Sync() +{ + event_t eventIDSToMTE3 = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_MTE3)); + SetFlag(eventIDSToMTE3); + WaitFlag(eventIDSToMTE3); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::MTE3ToSSync() +{ + event_t eventIDMTE3ToS = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_S)); + SetFlag(eventIDMTE3ToS); + WaitFlag(eventIDMTE3ToS); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::SToVSync() +{ + event_t eventIDSToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::S_V)); + SetFlag(eventIDSToV); + WaitFlag(eventIDSToV); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::MTE3ToVSync() +{ + event_t eventIDMTE3ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE3_V)); + SetFlag(eventIDMTE3ToV); + WaitFlag(eventIDMTE3ToV); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::MTE2ToVSync() +{ + event_t eventIDMTE2ToV = static_cast(GetTPipePtr()->FetchEventID(HardEvent::MTE2_V)); + SetFlag(eventIDMTE2ToV); + WaitFlag(eventIDMTE2ToV); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::VToMTE2Sync() +{ + event_t eventIDVtoMTE2 = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_MTE2)); + SetFlag(eventIDVtoMTE2); + WaitFlag(eventIDVtoMTE2); +} + +template +__aicore__ inline void RopeWithSinCosCacheBase::VToMTE3Sync() +{ + event_t eventIDVtoMTE3 = static_cast(GetTPipePtr()->FetchEventID(HardEvent::V_MTE3)); + SetFlag(eventIDVtoMTE3); + WaitFlag(eventIDVtoMTE3); +} +} // namespace RopeWithSinCosCache + +#endif // namespace RopeWithSinCosCache \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/rope_with_sin_cos_cache_f_bf16.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/rope_with_sin_cos_cache_f_bf16.h new file mode 100644 index 0000000000000000000000000000000000000000..65df85560743fe56bd597f3f623f2cfce0a22e07 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/rope_with_sin_cos_cache_f_bf16.h @@ -0,0 +1,710 @@ +/** + * 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 rope_with_sin_cos_cache_f_bf16.h + * \brief rope_with_sin_cos_cache_f_bf16.h + */ + +#ifndef ROPE_WITH_SIN_COS_CACHE_f_BF16_H +#define ROPE_WITH_SIN_COS_CACHE_f_BF16_H + +#include "rope_with_sin_cos_cache_base.h" + +namespace RopeWithSinCosCache { +using namespace AscendC; + +template +class RopeWithSinCosCacheFP16 : public RopeWithSinCosCacheBase +{ +public: + __aicore__ inline RopeWithSinCosCacheFP16(){}; + __aicore__ inline void Init( + GM_ADDR position_id, GM_ADDR query_in, GM_ADDR key_in, GM_ADDR cos_sin_cache, GM_ADDR query_out, + GM_ADDR key_out, const RopeWithSinCosCacheTilingData& tiling_data, TPipe* pipe); + __aicore__ inline void Process(); + __aicore__ inline void Compute(uint64_t index, uint64_t loopN); + __aicore__ inline void ComputeAlongHeads(uint64_t indexToken, uint64_t indexHeads); + __aicore__ inline void GetCosSinCache(LocalTensor inQueueCosSinCacheBeforeCastLocal, + LocalTensor copyBuf0Local, LocalTensor inCosSin, + LocalTensor CosSin, uint64_t offsetPos, uint64_t cosSinOffset, uint64_t localStartAddr, + uint32_t (&rcShape_)[2], uint32_t (&dstShape_)[2]); + +protected: + static constexpr uint64_t BLOCK_SIZE = 32; + static constexpr uint64_t BUFFER_NUM = 1; + static constexpr uint64_t ELE_NUM_FP32 = 8; + static constexpr uint64_t ELE_NUM_FP16 = 16; + static constexpr uint64_t MASK = 64; + uint64_t blockOffset; + uint16_t headBlockLen{0}; + uint16_t rotaryBlockLen{0}; + uint16_t calBlockLen{0}; + uint16_t calBlockLenFP16{0}; + uint64_t q_size; + uint64_t k_size; + uint64_t num_heads_max; + + GlobalTensor position_id_GM; + GlobalTensor query_in_GM; + GlobalTensor key_in_GM; + GlobalTensor cos_sin_cache_GM; + + GlobalTensor queryGM; + GlobalTensor keyGM; + + TBuf inQQue, inQueueCosSinCache; + TBuf outQue; + TBuf reverseBuf, negOneBuf, cosSinBuf, temp1, offsetBuf, inQueCalBuf; + TBuf copyBuf0, copyBuf1, copyBuf2; + + TQue inQQueBeforeCast, inQueueCosSinCacheBeforeCast; + TQue outQueAfterCast; +}; + +template +__aicore__ inline void RopeWithSinCosCacheFP16::Init( + GM_ADDR position_id, GM_ADDR query_in, GM_ADDR key_in, GM_ADDR cos_sin_cache, GM_ADDR query_out, GM_ADDR key_out, + const RopeWithSinCosCacheTilingData& tiling_data, TPipe* pipe) +{ + this->InitData(tiling_data); + headBlockLen = static_cast(this->head_size / ELE_NUM_FP32); + rotaryBlockLen = static_cast(this->rotary_dim / ELE_NUM_FP32); + calBlockLenFP16 = static_cast(this->rotary_dim / 2 / ELE_NUM_FP16); + calBlockLen = rotaryBlockLen / 2; + + if (this->blockIdx_ < this->front_core) { + blockOffset = this->num_tokens_each_front_core * this->blockIdx_; + } else { + blockOffset = this->num_tokens_each_front_core * (this->front_core) + + (this->blockIdx_ - this->front_core) * this->num_tokens_each_tail_core; + } + + position_id_GM.SetGlobalBuffer((__gm__ uint64_t*)position_id + blockOffset); + query_in_GM.SetGlobalBuffer((__gm__ T*)query_in + blockOffset * this->q_leading_dimension); + key_in_GM.SetGlobalBuffer((__gm__ T*)key_in + blockOffset * this->k_leading_dimension); + cos_sin_cache_GM.SetGlobalBuffer((__gm__ T*)cos_sin_cache); + + queryGM.SetGlobalBuffer((__gm__ T*)query_out + blockOffset * this->num_q_heads * this->head_size); + keyGM.SetGlobalBuffer((__gm__ T*)key_out + blockOffset * this->num_kv_heads * this->head_size); + + num_heads_max = (this->num_q_heads > this->num_kv_heads) ? this->num_q_heads : this->num_kv_heads; + if (this->loop_for_one_token == 0) { + pipe->InitBuffer(inQQue, + this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(inQueueCosSinCache, this->rotary_dim * sizeof(float)); + pipe->InitBuffer(reverseBuf, + this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(negOneBuf, + this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(cosSinBuf, + this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(inQueCalBuf, + this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(T)); + + pipe->InitBuffer(inQQueBeforeCast, BUFFER_NUM, + this->num_tokens_each_loop_current_core * num_heads_max * this->head_size * sizeof(T)); + pipe->InitBuffer(inQueueCosSinCacheBeforeCast, BUFFER_NUM, this->rotary_dim * sizeof(T)); + pipe->InitBuffer(outQueAfterCast, BUFFER_NUM, + this->num_tokens_each_loop_current_core * num_heads_max * this->head_size * sizeof(T)); + + pipe->InitBuffer(copyBuf0, this->rotary_dim / 2 * sizeof(T)); + pipe->InitBuffer(copyBuf1, this->rotary_dim / 2 * sizeof(T)); + pipe->InitBuffer(copyBuf2, this->rotary_dim / 2 * sizeof(T)); + + if (this->is_neox_style == 0) { + pipe->InitBuffer(offsetBuf, this->rotary_dim * sizeof(uint32_t)); + pipe->InitBuffer(temp1, this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * + sizeof(float)); + } else { + pipe->InitBuffer(offsetBuf, 0 * sizeof(uint32_t)); + pipe->InitBuffer(temp1, 0 * sizeof(float)); + } + } else { + pipe->InitBuffer(inQQue, this->num_heads_each_loop * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(inQueueCosSinCache, this->rotary_dim * sizeof(float)); + pipe->InitBuffer(reverseBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(negOneBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(cosSinBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(float)); + pipe->InitBuffer(inQueCalBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(T)); + + pipe->InitBuffer(inQQueBeforeCast, BUFFER_NUM, this->num_heads_each_loop * this->head_size * sizeof(T)); + pipe->InitBuffer(inQueueCosSinCacheBeforeCast, BUFFER_NUM, this->rotary_dim * sizeof(T)); + pipe->InitBuffer(outQueAfterCast, BUFFER_NUM, this->num_heads_each_loop * this->head_size * sizeof(T)); + + pipe->InitBuffer(copyBuf0, this->rotary_dim / 2 * sizeof(T)); + pipe->InitBuffer(copyBuf1, this->rotary_dim / 2 * sizeof(T)); + pipe->InitBuffer(copyBuf2, this->rotary_dim / 2 * sizeof(T)); + + if (this->is_neox_style == 0) { + pipe->InitBuffer(offsetBuf, this->rotary_dim * sizeof(uint32_t)); + pipe->InitBuffer(temp1, this->num_heads_each_loop * this->rotary_dim * sizeof(float)); + } else { + pipe->InitBuffer(offsetBuf, 0 * sizeof(uint32_t)); + pipe->InitBuffer(temp1, 0 * sizeof(float)); + } + } +} + +template +__aicore__ inline void +RopeWithSinCosCacheFP16::GetCosSinCache(LocalTensor inQueueCosSinCacheBeforeCastLocal, + LocalTensor copyBuf0Local, LocalTensor inCosSin, + LocalTensor cosSin, uint64_t offsetPos, uint64_t cosSinOffset, + uint64_t localStartAddr, uint32_t (&srcShape_)[2], uint32_t (&dstShape_)[2]) +{ + if (this->mrope_section0 > 0) { + // dataCopy和Copy的组合方式解决起始地址对齐和搬运单元对齐的问题 + uint64_t pos0 = position_id_GM.GetValue(offsetPos); + uint64_t pos1 = position_id_GM.GetValue(offsetPos + this->num_tokens); + uint64_t pos2 = position_id_GM.GetValue(offsetPos + 2 * this->num_tokens); + if (this->cacheMode == 0) { + if (this->mrope_section3 == 0) { + uint8_t padding2 = ((this->mrope_section0 + this->mrope_section1) * sizeof(T) % BLOCK_SIZE) / sizeof(T); + this->VToMTE2Sync(); + DataCopyPad(inQueueCosSinCacheBeforeCastLocal[this->mrope_section0 + + static_cast(this->mrope_section1) - padding2], + cos_sin_cache_GM[pos2 * this->rotary_dim + + static_cast(this->mrope_section0 + this->mrope_section1) + cosSinOffset], + {1, static_cast(this->mrope_section2 * sizeof(T)), 0, 0}, {true, padding2, 0, 0}); + } else if (this->mrope_section3 > 0){ + //第四段 + uint64_t pos3 = position_id_GM.GetValue(offsetPos + 3 * this->num_tokens); + uint8_t padding3 = ((this->mrope_section0 + this->mrope_section1 + this->mrope_section2) * sizeof(T) % BLOCK_SIZE) / sizeof(T); + this->VToMTE2Sync(); + DataCopyPad(inQueueCosSinCacheBeforeCastLocal[static_cast(this->mrope_section0 + + this->mrope_section1 + this->mrope_section2) - padding3], + cos_sin_cache_GM[pos3 * this->rotary_dim + + static_cast(this->mrope_section0 + this->mrope_section1 + this->mrope_section2) + cosSinOffset], + {1, static_cast(this->mrope_section3 * sizeof(T)), 0, 0}, {true, padding3, 0, 0}); + //第三段 + uint8_t padding2 = ((this->mrope_section0 + this->mrope_section1) * sizeof(T) % BLOCK_SIZE) / sizeof(T); + DataCopyPad( + copyBuf0Local, + cos_sin_cache_GM[pos2 * this->rotary_dim + static_cast(this->mrope_section0 + this->mrope_section1) + cosSinOffset], + {1, static_cast(this->mrope_section2 * sizeof(T)), 0, 0}, {true, padding2, 0, 0}); + this->MTE2ToVSync(); + Copy(inQueueCosSinCacheBeforeCastLocal[this->mrope_section0 + this->mrope_section1 - padding2], copyBuf0Local, + this->mrope_section2 + padding2, 1, {1, 1, 0, 0}); + this->VToMTE2Sync(); + } + uint8_t padding1 = (this->mrope_section0 * sizeof(T) % BLOCK_SIZE) / sizeof(T); + DataCopyPad( + copyBuf0Local, + cos_sin_cache_GM[pos1 * this->rotary_dim + static_cast(this->mrope_section0) + cosSinOffset], + {1, static_cast(this->mrope_section1 * sizeof(T)), 0, 0}, {true, padding1, 0, 0}); + this->MTE2ToVSync(); + Copy(inQueueCosSinCacheBeforeCastLocal[this->mrope_section0 - padding1], copyBuf0Local, + this->mrope_section1 + padding1, 1, {1, 1, 0, 0}); + this->VToMTE2Sync(); + DataCopyPad(copyBuf0Local, cos_sin_cache_GM[pos0 * this->rotary_dim + cosSinOffset], + {1, static_cast(this->mrope_section0 * sizeof(T)), 0, 0}, {false, 0, 0, 0}); + this->MTE2ToVSync(); + Copy(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, this->mrope_section0, 1, {1, 1, 0, 0}); + } else if (this->cacheMode == 1) { + // 新的处理方式 + this->VToMTE2Sync(); + DataCopyPad(inQueueCosSinCacheBeforeCastLocal, + cos_sin_cache_GM[pos0 * this->rotary_dim + cosSinOffset], + {1, static_cast(this->rotary_dim / 2 * sizeof(T)), 0, 0}, {false, 0, 0, 0}); + float pos1Value = 0; + float pos2Value = 0; + uint32_t i = 0; + for (i = 0; i < this->rotary_dim / 2; i++) { + if (i < this->mrope_section1) { + pos1Value = cos_sin_cache_GM.GetValue(pos1 * this->rotary_dim + cosSinOffset + i * 3 + 1); + inQueueCosSinCacheBeforeCastLocal.SetValue(i * 3 + 1, pos1Value); + } + if (i < this->mrope_section2) { + pos2Value = cos_sin_cache_GM.GetValue(pos2 * this->rotary_dim + cosSinOffset + i * 3 + 2); + inQueueCosSinCacheBeforeCastLocal.SetValue(i * 3 + 2, pos2Value); + } + if (i > this->mrope_section1 && i > this->mrope_section2){ + break; + } + } + } + } else { + uint64_t pos = position_id_GM.GetValue(offsetPos); + this->VToMTE2Sync(); + DataCopy(inQueueCosSinCacheBeforeCastLocal, cos_sin_cache_GM[pos * this->rotary_dim + cosSinOffset], + {1, calBlockLenFP16, 0, 0}); + this->MTE2ToVSync(); + } + Cast(inCosSin, inQueueCosSinCacheBeforeCastLocal, AscendC::RoundMode::CAST_NONE, + static_cast(this->rotary_dim)); + DataCopy(inCosSin[this->rotary_dim / 2], inCosSin, {1, calBlockLen, 0, 0}); + Broadcast(cosSin[localStartAddr], inCosSin, dstShape_, srcShape_); +} + +template +__aicore__ inline void RopeWithSinCosCacheFP16::Compute(uint64_t index, uint64_t loopN) +{ + q_size = this->num_q_heads * this->head_size; + k_size = this->num_kv_heads * this->head_size; + uint64_t query_in_offset = index * this->num_tokens_each_loop_current_core * this->q_leading_dimension; + uint64_t key_in_offset = index * this->num_tokens_each_loop_current_core * this->k_leading_dimension; + uint64_t offset = index * this->num_tokens_each_loop_current_core * q_size; + uint64_t offsetk = index * this->num_tokens_each_loop_current_core * k_size; + + uint32_t dstShape_[2] = {static_cast(this->num_heads_max), static_cast(this->rotary_dim)}; + uint64_t negOneRows = loopN * this->num_heads_max; + uint32_t dstShape_4Negone_[2] = { + static_cast(negOneRows - 1), static_cast(this->rotary_dim)}; + uint32_t srcShape_[2] = {1, static_cast(this->rotary_dim)}; + + LocalTensor inQQueBeforeCastLocal = inQQueBeforeCast.AllocTensor(); + LocalTensor inQueueCosSinCacheBeforeCastLocal = inQueueCosSinCacheBeforeCast.AllocTensor(); + LocalTensor outQueAfterCastLocal = outQueAfterCast.AllocTensor(); + + LocalTensor inLocal = inQQue.Get(); + LocalTensor inCosSin = inQueueCosSinCache.Get(); + LocalTensor reverseQ = reverseBuf.Get(); + LocalTensor negOne = negOneBuf.Get(); + LocalTensor cosSin = cosSinBuf.Get(); + LocalTensor inQueCalLocal = inQueCalBuf.Get(); + LocalTensor offsetLocal = offsetBuf.Get(); + LocalTensor temp1Local = temp1.Get(); + + LocalTensor copyBuf0Local = copyBuf0.Get(); + LocalTensor copyBuf1Local = copyBuf1.Get(); + LocalTensor copyBuf2Local = copyBuf2.Get(); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < this->rotary_dim / 2; i++) { + offsetLocal.SetValue(i * 2, i * 4); + offsetLocal.SetValue(i * 2 + 1, (this->rotary_dim / 2 + i) * 4); + } + } + + DataCopy( + inQQueBeforeCastLocal, query_in_GM[query_in_offset], + {static_cast(loopN), static_cast(this->num_q_heads * headBlockLen / 2), + static_cast(this->q_leading_dimension / ELE_NUM_FP16 - this->q_size / ELE_NUM_FP16), 0}); + this->MTE2ToVSync(); + DataCopy( + inQueCalLocal, inQQueBeforeCastLocal, + {static_cast(loopN * this->num_q_heads), static_cast(rotaryBlockLen / 2), + static_cast(headBlockLen / 2 - rotaryBlockLen / 2), 0}); + + if (this->is_neox_style == 0) { + Cast( + temp1Local, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopN * this->num_q_heads * this->rotary_dim)); + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopN * this->num_q_heads; i++) { + GatherMask( + inLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], static_cast(1), true, + this->rotary_dim, {1, 1, 0, 0}, rsv); + GatherMask( + inLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + } + } else { + Cast( + inLocal, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopN * this->num_q_heads * this->rotary_dim)); + } + + DataCopy( + reverseQ, inLocal[this->rotary_dim / 2], + {static_cast(loopN * this->num_q_heads), calBlockLen, calBlockLen, calBlockLen}); + DataCopy( + reverseQ[this->rotary_dim / 2], inLocal, + {static_cast(loopN * this->num_q_heads), calBlockLen, calBlockLen, calBlockLen}); + + float One = 1.0; + float None = -1.0; + Duplicate(negOne, None, this->rotary_dim / 2); + Duplicate(negOne[this->rotary_dim / 2], One, this->rotary_dim / 2); + if (negOneRows > 1) { + Broadcast(negOne[this->rotary_dim], negOne, dstShape_4Negone_, srcShape_); + } + uint64_t localStartAddr = 0; + uint64_t cosSinOffset = 0; + for (uint32_t i = 0; i < loopN; ++i) { + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_q_heads * this->rotary_dim; + } + Mul(inLocal, cosSin, inLocal, loopN * this->num_q_heads * this->rotary_dim); + Mul(reverseQ, negOne, reverseQ, loopN * this->num_q_heads * this->rotary_dim); + localStartAddr = 0; + cosSinOffset = this->rotary_dim / 2; + for (uint32_t i = 0; i < loopN; ++i) { + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_q_heads * this->rotary_dim; + } + Mul(reverseQ, cosSin, reverseQ, loopN * this->num_q_heads * this->rotary_dim); + Add(inLocal, reverseQ, inLocal, loopN * this->num_q_heads * this->rotary_dim); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < loopN * this->num_q_heads; i++) { + Gather( + temp1Local[i * this->rotary_dim], inLocal[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + } + + Cast( + inQueCalLocal, temp1Local, AscendC::RoundMode::CAST_RINT, + static_cast(loopN * this->num_q_heads * this->rotary_dim)); + } else { + Cast( + inQueCalLocal, inLocal, AscendC::RoundMode::CAST_RINT, + static_cast(loopN * this->num_q_heads * this->rotary_dim)); + } + + if (this->head_size != this->rotary_dim) { + DataCopy( + outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopN * this->num_q_heads), static_cast(rotaryBlockLen / 2), 0, + static_cast(headBlockLen / 2 - rotaryBlockLen / 2)}); + DataCopy( + outQueAfterCastLocal[this->rotary_dim], inQQueBeforeCastLocal[this->rotary_dim], + {static_cast(loopN * this->num_q_heads), + static_cast(headBlockLen / 2 - rotaryBlockLen / 2), static_cast(rotaryBlockLen / 2), + static_cast(rotaryBlockLen / 2)}); + } else { + DataCopy( + outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopN), static_cast(this->num_q_heads * headBlockLen / 2), 0, 0}); + } + this->VToMTE3Sync(); + DataCopy( + queryGM[offset], outQueAfterCastLocal, + {static_cast(loopN), static_cast(this->num_q_heads * headBlockLen / 2), 0, 0}); + + // 处理key + this->MTE3ToVSync(); + this->VToMTE2Sync(); + DataCopy( + inQQueBeforeCastLocal, key_in_GM[key_in_offset], + {static_cast(loopN), static_cast(this->num_kv_heads * headBlockLen / 2), + static_cast(this->k_leading_dimension / ELE_NUM_FP16 - this->k_size / ELE_NUM_FP16), 0}); + this->MTE2ToVSync(); + DataCopy( + inQueCalLocal, inQQueBeforeCastLocal, + {static_cast(loopN * this->num_kv_heads), static_cast(rotaryBlockLen / 2), + static_cast(headBlockLen / 2 - rotaryBlockLen / 2), 0}); + + if (this->is_neox_style == 0) { + Cast( + temp1Local, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopN * this->num_kv_heads * this->rotary_dim)); + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopN * this->num_kv_heads; i++) { + GatherMask( + inLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], static_cast(1), true, + this->rotary_dim, {1, 1, 0, 0}, rsv); + GatherMask( + inLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + } + } else { + Cast( + inLocal, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopN * this->num_kv_heads * this->rotary_dim)); + } + + DataCopy( + reverseQ, inLocal[this->rotary_dim / 2], + {static_cast(loopN * this->num_kv_heads), calBlockLen, calBlockLen, calBlockLen}); + DataCopy( + reverseQ[this->rotary_dim / 2], inLocal, + {static_cast(loopN * this->num_kv_heads), calBlockLen, calBlockLen, calBlockLen}); + + localStartAddr = 0; + cosSinOffset = 0; + for (uint32_t i = 0; i < loopN; ++i) { + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_kv_heads * this->rotary_dim; + } + + Mul(inLocal, cosSin, inLocal, loopN * this->num_kv_heads * this->rotary_dim); + Mul(reverseQ, negOne, reverseQ, loopN * this->num_kv_heads * this->rotary_dim); + localStartAddr = 0; + cosSinOffset = this->rotary_dim / 2; + for (uint32_t i = 0; i < loopN; ++i) { + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_kv_heads * this->rotary_dim; + } + + Mul(reverseQ, cosSin, reverseQ, loopN * this->num_kv_heads * this->rotary_dim); + Add(inLocal, reverseQ, inLocal, loopN * this->num_kv_heads * this->rotary_dim); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < loopN * this->num_kv_heads; i++) { + Gather( + temp1Local[i * this->rotary_dim], inLocal[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + } + Cast( + inQueCalLocal, temp1Local, AscendC::RoundMode::CAST_RINT, + static_cast(loopN * this->num_kv_heads * this->rotary_dim)); + } else { + Cast( + inQueCalLocal, inLocal, AscendC::RoundMode::CAST_RINT, + static_cast(loopN * this->num_kv_heads * this->rotary_dim)); + } + + if (this->head_size != this->rotary_dim) { + DataCopy( + outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopN * this->num_kv_heads), static_cast(rotaryBlockLen / 2), 0, + static_cast(headBlockLen / 2 - rotaryBlockLen / 2)}); + DataCopy( + outQueAfterCastLocal[this->rotary_dim], inQQueBeforeCastLocal[this->rotary_dim], + {static_cast(loopN * this->num_kv_heads), + static_cast(headBlockLen / 2 - rotaryBlockLen / 2), static_cast(rotaryBlockLen / 2), + static_cast(rotaryBlockLen / 2)}); + } else { + DataCopy( + outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopN), static_cast(this->num_kv_heads * headBlockLen / 2), 0, 0}); + } + this->VToMTE3Sync(); + DataCopy( + keyGM[offsetk], outQueAfterCastLocal, + {static_cast(loopN), static_cast(this->num_kv_heads * headBlockLen / 2), 0, 0}); + + inQQueBeforeCast.FreeTensor(inQQueBeforeCastLocal); + inQueueCosSinCacheBeforeCast.FreeTensor(inQueueCosSinCacheBeforeCastLocal); + outQueAfterCast.FreeTensor(outQueAfterCastLocal); +} + +template +__aicore__ inline void RopeWithSinCosCacheFP16::ComputeAlongHeads(uint64_t indexToken, uint64_t indexHeads){ + q_size = this->num_q_heads * this->head_size; + k_size = this->num_kv_heads * this->head_size; + uint64_t offsetQHead = indexHeads * this->num_qheads_each_loop * this->head_size; + uint64_t offsetKHead = indexHeads * this->num_kheads_each_loop * this->head_size; + uint64_t offset = indexToken * q_size + offsetQHead;//非连续? + uint64_t offsetk = indexToken * k_size + offsetKHead; + uint64_t query_in_offset = indexToken * this->q_leading_dimension + offsetQHead; + uint64_t key_in_offset = indexToken * this->k_leading_dimension + offsetKHead; + + uint32_t dstShape_[2] = {static_cast(this->num_heads_each_loop), static_cast(this->rotary_dim)}; + uint32_t dstShape_4Negone_[2] = {static_cast(this->num_heads_each_loop - 1), + static_cast(this->rotary_dim)}; + uint32_t srcShape_[2] = {1, static_cast(this->rotary_dim)}; + + LocalTensor inQQueBeforeCastLocal = inQQueBeforeCast.AllocTensor(); + LocalTensor inQueueCosSinCacheBeforeCastLocal = inQueueCosSinCacheBeforeCast.AllocTensor(); + LocalTensor outQueAfterCastLocal = outQueAfterCast.AllocTensor(); + + LocalTensor inLocal = inQQue.Get(); + LocalTensor inCosSin = inQueueCosSinCache.Get(); + LocalTensor reverseQ = reverseBuf.Get(); + LocalTensor negOne = negOneBuf.Get(); + LocalTensor cosSin = cosSinBuf.Get(); + LocalTensor offsetLocal = offsetBuf.Get(); + LocalTensor temp1Local = temp1.Get(); + LocalTensor inQueCalLocal = inQueCalBuf.Get(); + + LocalTensor copyBuf0Local = copyBuf0.Get(); + LocalTensor copyBuf1Local = copyBuf1.Get(); + LocalTensor copyBuf2Local = copyBuf2.Get(); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < this->rotary_dim / 2; i++) { + offsetLocal.SetValue(i * 2, i * 4); + offsetLocal.SetValue(i * 2 + 1, (this->rotary_dim / 2 + i) * 4); + } + } + + if (indexHeads < this->loop_along_qheads) { + uint64_t loopNQhead = (indexHeads == this->loop_along_qheads - 1 && this->num_qheads_last_loop != 0) ? + this->num_qheads_last_loop : + this->num_qheads_each_loop; + DataCopy(inQQueBeforeCastLocal, query_in_GM[query_in_offset], + {1, static_cast(loopNQhead * headBlockLen / 2), 0, 0}); + this->MTE2ToVSync(); + DataCopy(inQueCalLocal, inQQueBeforeCastLocal, + {static_cast(loopNQhead), static_cast(rotaryBlockLen / 2), + static_cast(headBlockLen / 2 - rotaryBlockLen / 2), 0}); + if (this->is_neox_style == 0) { + Cast(temp1Local, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopNQhead * this->rotary_dim)); + + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopNQhead; i++) { + GatherMask(inLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], + static_cast(1), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + GatherMask(inLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + } + } else { + Cast(inLocal, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopNQhead * this->rotary_dim)); + } + + DataCopy(reverseQ, inLocal[this->rotary_dim / 2], + {static_cast(loopNQhead), calBlockLen, calBlockLen, calBlockLen}); + DataCopy(reverseQ[this->rotary_dim / 2], inLocal, + {static_cast(loopNQhead), calBlockLen, calBlockLen, calBlockLen}); + + float One = 1.0; + float None = -1.0; + Duplicate(negOne, None, this->rotary_dim / 2); + Duplicate(negOne[this->rotary_dim / 2], One, this->rotary_dim / 2); + if (this->num_heads_each_loop > 1) { + Broadcast(negOne[this->rotary_dim], negOne, dstShape_4Negone_, srcShape_); + } + + uint64_t offsetPos = indexToken; + uint64_t cosSinOffset = 0; + uint64_t localStartAddr = 0; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(inLocal, cosSin, inLocal, loopNQhead * this->rotary_dim); + Mul(reverseQ, negOne, reverseQ, loopNQhead * this->rotary_dim); + + offsetPos = indexToken; + cosSinOffset = this->rotary_dim / 2; + localStartAddr = 0; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(reverseQ, cosSin, reverseQ, loopNQhead * this->rotary_dim); + Add(inLocal, reverseQ, inLocal, loopNQhead * this->rotary_dim); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < loopNQhead; i++) { + Gather(temp1Local[i * this->rotary_dim], inLocal[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + } + Cast(inQueCalLocal, temp1Local, AscendC::RoundMode::CAST_RINT, + static_cast(loopNQhead * this->rotary_dim)); + } else { + Cast(inQueCalLocal, inLocal, AscendC::RoundMode::CAST_RINT, + static_cast(loopNQhead * this->rotary_dim)); + } + + if (this->head_size != this->rotary_dim) { + DataCopy(outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopNQhead), static_cast(rotaryBlockLen/2), 0, + static_cast(headBlockLen/2 - rotaryBlockLen/2)}); + DataCopy(outQueAfterCastLocal[this->rotary_dim], inQQueBeforeCastLocal[this->rotary_dim], + {static_cast(loopNQhead), static_cast(headBlockLen/2 - rotaryBlockLen/2), + static_cast(rotaryBlockLen/2), static_cast(rotaryBlockLen/2)}); + } else { + DataCopy(outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopNQhead), static_cast(headBlockLen/2), 0, 0}); + } + this->VToMTE3Sync(); + DataCopy(queryGM[offset], outQueAfterCastLocal, + {static_cast(loopNQhead), static_cast(headBlockLen/2), 0, 0}); + } + //key + this->MTE3ToVSync(); + this->VToMTE2Sync(); + if (indexHeads < this->loop_along_kheads) { + uint64_t loopNKhead = (indexHeads == this->loop_along_kheads - 1 && this->num_kheads_last_loop != 0) ? + this->num_kheads_last_loop : + this->num_kheads_each_loop; + DataCopy(inQQueBeforeCastLocal, key_in_GM[key_in_offset], + {1, static_cast(loopNKhead * headBlockLen / 2), 0, 0}); + this->MTE2ToVSync(); + DataCopy(inQueCalLocal, inQQueBeforeCastLocal, + {static_cast(loopNKhead), static_cast(rotaryBlockLen / 2), + static_cast(headBlockLen / 2 - rotaryBlockLen / 2), 0}); + if (this->is_neox_style == 0) { + Cast(temp1Local, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopNKhead * this->rotary_dim)); + + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopNKhead; i++) { + GatherMask(inLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], static_cast(1), + true, this->rotary_dim, {1, 1, 0, 0}, rsv); + GatherMask(inLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + } + } else { + Cast(inLocal, inQueCalLocal, AscendC::RoundMode::CAST_NONE, + static_cast(loopNKhead * this->rotary_dim)); + } + + DataCopy(reverseQ, inLocal[this->rotary_dim / 2], + {static_cast(loopNKhead), calBlockLen, calBlockLen, calBlockLen}); + DataCopy(reverseQ[this->rotary_dim / 2], inLocal, + {static_cast(loopNKhead), calBlockLen, calBlockLen, calBlockLen}); + + uint64_t offsetPos = indexToken; + uint64_t cosSinOffset = 0; + uint64_t localStartAddr = 0; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(inLocal, cosSin, inLocal, loopNKhead * this->rotary_dim); + Mul(reverseQ, negOne, reverseQ, loopNKhead * this->rotary_dim); + + offsetPos = indexToken; + cosSinOffset = this->rotary_dim / 2; + localStartAddr = 0; + GetCosSinCache(inQueueCosSinCacheBeforeCastLocal, copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(reverseQ, cosSin, reverseQ, loopNKhead * this->rotary_dim); + Add(inLocal, reverseQ, inLocal, loopNKhead * this->rotary_dim); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < loopNKhead; i++) { + Gather(temp1Local[i * this->rotary_dim], inLocal[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + } + Cast(inQueCalLocal, temp1Local, AscendC::RoundMode::CAST_RINT, + static_cast(loopNKhead * this->rotary_dim)); + } else { + Cast(inQueCalLocal, inLocal, AscendC::RoundMode::CAST_RINT, + static_cast(loopNKhead * this->rotary_dim)); + } + + if (this->head_size != this->rotary_dim) { + DataCopy(outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopNKhead), static_cast(rotaryBlockLen / 2), 0, + static_cast(headBlockLen / 2 - rotaryBlockLen / 2)}); + DataCopy(outQueAfterCastLocal[this->rotary_dim], inQQueBeforeCastLocal[this->rotary_dim], + {static_cast(loopNKhead), static_cast(headBlockLen / 2 - rotaryBlockLen / 2), + static_cast(rotaryBlockLen / 2), static_cast(rotaryBlockLen / 2)}); + } else { + DataCopy(outQueAfterCastLocal, inQueCalLocal, + {static_cast(loopNKhead), static_cast(headBlockLen / 2), 0, 0}); + } + this->VToMTE3Sync(); + DataCopy(keyGM[offsetk], outQueAfterCastLocal, + {static_cast(loopNKhead), static_cast(headBlockLen / 2), 0, 0}); + } + + inQQueBeforeCast.FreeTensor(inQQueBeforeCastLocal); + inQueueCosSinCacheBeforeCast.FreeTensor(inQueueCosSinCacheBeforeCastLocal); + outQueAfterCast.FreeTensor(outQueAfterCastLocal); +} + +template +__aicore__ inline void RopeWithSinCosCacheFP16::Process() +{ + if (this->loop_for_one_token == 0) { + for (uint64_t n = 0; n < this->loop_time_current_core - 1; n++) { + Compute(n, this->num_tokens_each_loop_current_core); + } + if (this->num_tokens_last_loop_current_core == 0) { + Compute(this->loop_time_current_core - 1, this->num_tokens_each_loop_current_core); + } else { + Compute(this->loop_time_current_core - 1, this->num_tokens_last_loop_current_core); + } + } else { + uint64_t loop_along_heads = + this->loop_along_qheads > this->loop_along_kheads ? this->loop_along_qheads : this->loop_along_kheads; + for (uint64_t n = 0; n < this->num_tokens_current_core; n++) { + for (uint64_t m = 0; m < loop_along_heads; m++) { + ComputeAlongHeads(n, m); + } + } + } +} +} // namespace RopeWithSinCosCache + +#endif \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/rope_with_sin_cos_cache_fp32.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/rope_with_sin_cos_cache_fp32.h new file mode 100644 index 0000000000000000000000000000000000000000..7d76dd2c3ac56591048377601a4d8d6d964dd76c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/op_kernel/rope_with_sin_cos_cache_fp32.h @@ -0,0 +1,673 @@ +/** + * 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 rope_with_sin_cos_cache_fp32.h + * \brief rope_with_sin_cos_cache_fp32.h + */ + +#ifndef ROPE_WITH_SIN_COS_CACHE_FP32_H +#define ROPE_WITH_SIN_COS_CACHE_FP32_H + +#include "rope_with_sin_cos_cache_base.h" + +namespace RopeWithSinCosCache { +using namespace AscendC; + +template +class RopeWithSinCosCacheF32 : public RopeWithSinCosCacheBase +{ +public: + __aicore__ inline RopeWithSinCosCacheF32(){}; + __aicore__ inline void Init( + GM_ADDR position_id, GM_ADDR query_in, GM_ADDR key_in, GM_ADDR cos_sin_cache, GM_ADDR query_out, + GM_ADDR key_out, const RopeWithSinCosCacheTilingData& tiling_data, TPipe* pipe); + __aicore__ inline void Process(); + __aicore__ inline void Compute(uint64_t index, uint64_t loopN); + __aicore__ inline void ComputeAlongHeads(uint64_t indexToken, uint64_t indexHeads); + __aicore__ inline void GetCosSinCache( + LocalTensor copyBuf0Local, LocalTensor inCosSin, + LocalTensor CosSin, uint64_t offsetPos, uint64_t cosSinOffset, uint64_t localStartAddr, + uint32_t (&rcShape_)[2], uint32_t (&dstShape_)[2]); + +protected: + static constexpr uint64_t BLOCK_SIZE = 32; + static constexpr uint64_t BUFFER_NUM = 1; + static constexpr uint64_t ELE_NUM_FP32 = 8; + static constexpr uint64_t MASK = 64; + static constexpr uint64_t MROPE_SECTION_BASE_SIZE = 8; + uint64_t blockOffset; + uint16_t headBlockLen{0}; + uint16_t rotaryBlockLen{0}; + uint16_t calBlockLen{0}; + uint64_t q_size; + uint64_t k_size; + uint64_t num_heads_max; + + GlobalTensor position_id_GM; + GlobalTensor query_in_GM; + GlobalTensor key_in_GM; + GlobalTensor cos_sin_cache_GM; + + GlobalTensor queryGM; + GlobalTensor keyGM; + + TQue inQQue, inQueueCosSinCache; + TQue outQue; + TBuf reverseBuf, negOneBuf, cosSinBuf, temp1, offsetBuf, inQueCalBuf; + TBuf copyBuf0; +}; + +template +__aicore__ inline void RopeWithSinCosCacheF32::Init( + GM_ADDR position_id, GM_ADDR query_in, GM_ADDR key_in, GM_ADDR cos_sin_cache, GM_ADDR query_out, GM_ADDR key_out, + const RopeWithSinCosCacheTilingData& tiling_data, TPipe* pipe) +{ + this->InitData(tiling_data); + headBlockLen = static_cast(this->head_size / ELE_NUM_FP32); + rotaryBlockLen = static_cast(this->rotary_dim / ELE_NUM_FP32); + calBlockLen = rotaryBlockLen / 2; + num_heads_max = (this->num_q_heads > this->num_kv_heads) ? this->num_q_heads : this->num_kv_heads; + + if (this->blockIdx_ < this->front_core) { + blockOffset = this->num_tokens_each_front_core * this->blockIdx_; + } else { + blockOffset = this->num_tokens_each_front_core * (this->front_core) + + (this->blockIdx_ - this->front_core) * this->num_tokens_each_tail_core; + } + + position_id_GM.SetGlobalBuffer((__gm__ uint64_t*)position_id + blockOffset); + query_in_GM.SetGlobalBuffer((__gm__ T*)query_in + blockOffset * this->num_q_heads * this->head_size); + key_in_GM.SetGlobalBuffer((__gm__ T*)key_in + blockOffset * this->num_kv_heads * this->head_size); + cos_sin_cache_GM.SetGlobalBuffer((__gm__ T*)cos_sin_cache); + + queryGM.SetGlobalBuffer((__gm__ T*)query_out + blockOffset * this->num_q_heads * this->head_size); + keyGM.SetGlobalBuffer((__gm__ T*)key_out + blockOffset * this->num_kv_heads * this->head_size); + + pipe->InitBuffer(copyBuf0, this->rotary_dim / 2 * sizeof(T)); + if(this->loop_for_one_token==0){ + pipe->InitBuffer( + inQQue, BUFFER_NUM, this->num_tokens_each_loop_current_core * num_heads_max * this->head_size * sizeof(T)); + pipe->InitBuffer( + inQueueCosSinCache, BUFFER_NUM, this->num_tokens_each_loop_current_core * this->rotary_dim * sizeof(T)); + pipe->InitBuffer( + outQue, BUFFER_NUM, this->num_tokens_each_loop_current_core * num_heads_max * this->head_size * sizeof(T)); + pipe->InitBuffer( + reverseBuf, this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(negOneBuf, this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(cosSinBuf, this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(T)); + pipe->InitBuffer( + inQueCalBuf, this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(T)); + + if (this->is_neox_style == 0) { + pipe->InitBuffer(temp1, this->num_tokens_each_loop_current_core * num_heads_max * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(offsetBuf, this->rotary_dim * sizeof(uint32_t)); + } else { +#ifndef __CCE_KT_TEST__ + pipe->InitBuffer(temp1, 0 * sizeof(T)); + pipe->InitBuffer(offsetBuf, 0 * sizeof(uint32_t)); +#else + pipe->InitBuffer(temp1, 1 * sizeof(T)); + pipe->InitBuffer(offsetBuf, 1 * sizeof(uint32_t)); +#endif + } + } else { + pipe->InitBuffer(inQQue, BUFFER_NUM, this->num_heads_each_loop * this->head_size * sizeof(T)); + pipe->InitBuffer(inQueueCosSinCache, BUFFER_NUM, this->rotary_dim * sizeof(T)); + pipe->InitBuffer(outQue, BUFFER_NUM, this->num_heads_each_loop * this->head_size * sizeof(T)); + pipe->InitBuffer(reverseBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(negOneBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(cosSinBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(inQueCalBuf, this->num_heads_each_loop * this->rotary_dim * sizeof(T)); + + if (this->is_neox_style == 0) { + pipe->InitBuffer(temp1, this->num_heads_each_loop * this->rotary_dim * sizeof(T)); + pipe->InitBuffer(offsetBuf, this->rotary_dim * sizeof(uint32_t)); + } else { +#ifndef __CCE_KT_TEST__ + pipe->InitBuffer(temp1, 0 * sizeof(T)); + pipe->InitBuffer(offsetBuf, 0 * sizeof(uint32_t)); +#else + pipe->InitBuffer(temp1, 1 * sizeof(T)); + pipe->InitBuffer(offsetBuf, 1 * sizeof(uint32_t)); +#endif + } + } +} + +template +__aicore__ inline void +RopeWithSinCosCacheF32::GetCosSinCache(LocalTensor copyBuf0Local, LocalTensor inCosSin, + LocalTensor cosSin, uint64_t offsetPos, uint64_t cosSinOffset, + uint64_t localStartAddr, uint32_t (&srcShape_)[2], uint32_t (&dstShape_)[2]) +{ + if (this->mrope_section0 > 0) { + uint64_t pos0 = position_id_GM.GetValue(offsetPos); + uint64_t pos1 = position_id_GM.GetValue(offsetPos + this->num_tokens); + uint64_t pos2 = position_id_GM.GetValue(offsetPos + 2 * this->num_tokens); + if (this->cacheMode == 0) { + if (this->mrope_section3 == 0) { + uint8_t padding2 = ((this->mrope_section0 + this->mrope_section1) * sizeof(T) % BLOCK_SIZE) / sizeof(T); + this->VToMTE2Sync(); + DataCopyPad(inCosSin[this->mrope_section0 + static_cast(this->mrope_section1) - padding2], + cos_sin_cache_GM[pos2 * this->rotary_dim + + static_cast(this->mrope_section0 + this->mrope_section1) + cosSinOffset], + {1, static_cast(this->mrope_section2 * sizeof(T)), 0, 0}, {true, padding2, 0, 0}); + } else if (this->mrope_section3 > 0) { + uint64_t pos3 = position_id_GM.GetValue(offsetPos + 3 * this->num_tokens); + uint8_t padding3 = ((this->mrope_section0 + this->mrope_section1 + this->mrope_section2) * sizeof(T) % BLOCK_SIZE) / sizeof(T); + this->VToMTE2Sync(); + DataCopyPad(inCosSin[this->mrope_section0 + this->mrope_section1 + this->mrope_section2 - padding3], + cos_sin_cache_GM[pos3 * this->rotary_dim + + static_cast(this->mrope_section0 + this->mrope_section1 + this->mrope_section2) + cosSinOffset], + {1, static_cast(this->mrope_section3 * sizeof(T)), 0, 0}, {true, padding3, 0, 0}); + + // DataCopyPad(inCosSin[起始地址] ; cos_sin_cache_GM[起始地址],(重复次数, 搬运数目),(PAD长度)) + uint8_t padding2 = ((this->mrope_section0 + this->mrope_section1) * sizeof(T) % BLOCK_SIZE) / sizeof(T); + if (this->mrope_section2 % MROPE_SECTION_BASE_SIZE == 0) { + DataCopyPad( + inCosSin[this->mrope_section0 + this->mrope_section1 - padding2], + cos_sin_cache_GM[pos2 * this->rotary_dim + static_cast(this->mrope_section0 + this->mrope_section1) + cosSinOffset], + {1, static_cast(this->mrope_section1 * sizeof(float)), 0, 0}, {true, padding2, 0, 0}); + } else { + DataCopyPad( + copyBuf0Local, + cos_sin_cache_GM[pos2 * this->rotary_dim + static_cast(this->mrope_section0 + this->mrope_section1) + cosSinOffset], + {1, static_cast(this->mrope_section2 * sizeof(T)), 0, 0}, {true, padding2, 0, 0}); + this->MTE2ToVSync(); + Copy(inCosSin[this->mrope_section0 + this->mrope_section1 - padding2], copyBuf0Local, this->mrope_section2 + padding2, 1, + {1, 1, 0, 0}); + } + } + // 如果mrope_section不是32B对齐,DataCopyPad接口会自动填充,同时为了兼容旧版16 24 24做法,避免该场景性能劣化 + uint8_t padding1 = (this->mrope_section0 * sizeof(T) % BLOCK_SIZE) / sizeof(T); + if (this->mrope_section1 % MROPE_SECTION_BASE_SIZE == 0) { + DataCopyPad( + inCosSin[this->mrope_section0 - padding1], + cos_sin_cache_GM[pos1 * this->rotary_dim + static_cast(this->mrope_section0) + cosSinOffset], + {1, static_cast(this->mrope_section1 * sizeof(float)), 0, 0}, {true, padding1, 0, 0}); + } else { + DataCopyPad( + copyBuf0Local, + cos_sin_cache_GM[pos1 * this->rotary_dim + static_cast(this->mrope_section0) + cosSinOffset], + {1, static_cast(this->mrope_section1 * sizeof(T)), 0, 0}, {true, padding1, 0, 0}); + this->MTE2ToVSync(); + Copy(inCosSin[this->mrope_section0 - padding1], copyBuf0Local, this->mrope_section1 + padding1, 1, + {1, 1, 0, 0}); + } + if (this->mrope_section0 % MROPE_SECTION_BASE_SIZE == 0) { + DataCopyPad(inCosSin, cos_sin_cache_GM[pos0 * this->rotary_dim + cosSinOffset], + {1, static_cast(this->mrope_section0 * sizeof(float)), 0, 0}, {false, 0, 0, 0}); + } else { + this->VToMTE2Sync(); + DataCopyPad(copyBuf0Local, cos_sin_cache_GM[pos0 * this->rotary_dim + cosSinOffset], + {1, static_cast(this->mrope_section0 * sizeof(T)), 0, 0}, {false, 0, 0, 0}); + this->MTE2ToVSync(); + Copy(inCosSin, copyBuf0Local, this->mrope_section0, 1, {1, 1, 0, 0}); + } + } else if (this->cacheMode == 1) { + // 新的处理方式 + this->VToMTE2Sync(); + DataCopyPad(inCosSin, + cos_sin_cache_GM[pos0 * this->rotary_dim + cosSinOffset], + {1, static_cast(this->rotary_dim / 2 * sizeof(T)), 0, 0}, {false, 0, 0, 0}); + float pos1Value = 0; + float pos2Value = 0; + uint32_t i = 0; + for (i = 0; i < this->rotary_dim / 2; i++) { + if (i < this->mrope_section1) { + pos1Value = cos_sin_cache_GM.GetValue(pos1 * this->rotary_dim + cosSinOffset + i * 3 + 1); + inCosSin.SetValue(i * 3 + 1, pos1Value); + } + if (i < this->mrope_section2) { + pos2Value = cos_sin_cache_GM.GetValue(pos2 * this->rotary_dim + cosSinOffset + i * 3 + 2); + inCosSin.SetValue(i * 3 + 2, pos2Value); + } + if (i > this->mrope_section1 && i > this->mrope_section2){ + break; + } + } + } + } else { + uint64_t pos = position_id_GM.GetValue(offsetPos); + this->VToMTE2Sync(); + DataCopy(inCosSin, cos_sin_cache_GM[pos * this->rotary_dim + cosSinOffset], {1, calBlockLen, 0, 0}); + } + this->MTE2ToVSync(); + DataCopy(inCosSin[this->rotary_dim / 2], inCosSin, {1, calBlockLen, 0, 0}); + Broadcast(cosSin[localStartAddr], inCosSin, dstShape_, srcShape_); +} + +template +__aicore__ inline void RopeWithSinCosCacheF32::Compute(uint64_t index, uint64_t loopN) +{ + q_size = this->num_q_heads * this->head_size; + k_size = this->num_kv_heads * this->head_size; + uint64_t offset = index * this->num_tokens_each_loop_current_core * q_size; + uint64_t offsetk = index * this->num_tokens_each_loop_current_core * k_size; + uint64_t offsetCosSin = index * loopN * this->rotary_dim; + + uint32_t dstShape_[2] = {static_cast(this->num_heads_max), static_cast(this->rotary_dim)}; + uint64_t negOneRows = loopN * this->num_heads_max; + uint32_t dstShape_4Negone_[2] = { + static_cast(negOneRows - 1), static_cast(this->rotary_dim)}; + uint32_t srcShape_[2] = {1, static_cast(this->rotary_dim)}; + + LocalTensor inLocal = inQQue.AllocTensor(); + LocalTensor inCosSin = inQueueCosSinCache.AllocTensor(); + LocalTensor outLocal = outQue.AllocTensor(); + LocalTensor reverseQ = reverseBuf.Get(); + LocalTensor negOne = negOneBuf.Get(); + LocalTensor cosSin = cosSinBuf.Get(); + LocalTensor offsetLocal = offsetBuf.Get(); + LocalTensor temp1Local = temp1.Get(); + LocalTensor inQueCalLocal = inQueCalBuf.Get(); + LocalTensor copyBuf0Local = copyBuf0.Get(); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < this->rotary_dim / 2; i++) { + offsetLocal.SetValue(i * 2, i * 4); + offsetLocal.SetValue(i * 2 + 1, (this->rotary_dim / 2 + i) * 4); + } + } + DataCopy( + inLocal, query_in_GM[offset], + {static_cast(loopN), static_cast(this->num_q_heads * headBlockLen), + static_cast(this->q_leading_dimension / ELE_NUM_FP32 - this->q_size / ELE_NUM_FP32), 0}); + this->MTE2ToVSync(); + + if (this->is_neox_style == 0) { + DataCopy( + temp1Local, inLocal, + {static_cast(loopN * this->num_q_heads), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopN * this->num_q_heads; i++) { + GatherMask( + inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], static_cast(1), true, + this->rotary_dim, {1, 1, 0, 0}, rsv); + GatherMask( + inQueCalLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + } + } else { + DataCopy( + inQueCalLocal, inLocal, + {static_cast(loopN * this->num_q_heads), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + } + + DataCopy( + reverseQ, inQueCalLocal[this->rotary_dim / 2], + {static_cast(loopN * this->num_q_heads), calBlockLen, calBlockLen, calBlockLen}); + DataCopy( + reverseQ[this->rotary_dim / 2], inQueCalLocal, + {static_cast(loopN * this->num_q_heads), calBlockLen, calBlockLen, calBlockLen}); + + float One = 1.0; + float None = -1.0; + Duplicate(negOne, None, this->rotary_dim / 2); + Duplicate(negOne[this->rotary_dim / 2], One, this->rotary_dim / 2); + + if (negOneRows > 1) { + Broadcast(negOne[this->rotary_dim], negOne, dstShape_4Negone_, srcShape_); + } + uint64_t localStartAddr = 0; + uint64_t cosSinOffset = 0; + for (uint32_t i = 0; i < loopN; ++i) { + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_q_heads * this->rotary_dim; + } + Mul(inQueCalLocal, cosSin, inQueCalLocal, loopN * this->num_q_heads * this->rotary_dim); + Mul(reverseQ, negOne, reverseQ, loopN * this->num_q_heads * this->rotary_dim); + localStartAddr = 0; + cosSinOffset = this->rotary_dim / 2; + for (uint32_t i = 0; i < loopN; ++i) { + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_q_heads * this->rotary_dim; + } + Mul(reverseQ, cosSin, reverseQ, loopN * this->num_q_heads * this->rotary_dim); + + if (this->is_neox_style == 0) { + Add(temp1Local, reverseQ, inQueCalLocal, loopN * this->num_q_heads * this->rotary_dim); + for (uint32_t i = 0; i < loopN * this->num_q_heads; i++) { + Gather( + inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + } + } else { + Add(inQueCalLocal, reverseQ, inQueCalLocal, loopN * this->num_q_heads * this->rotary_dim); + } + + if (this->head_size != this->rotary_dim) { + DataCopy( + outLocal, inQueCalLocal, + {static_cast(loopN * this->num_q_heads), static_cast(rotaryBlockLen), 0, + static_cast(headBlockLen - rotaryBlockLen)}); + DataCopy( + outLocal[this->rotary_dim], inLocal[this->rotary_dim], + {static_cast(loopN * this->num_q_heads), static_cast(headBlockLen - rotaryBlockLen), + static_cast(rotaryBlockLen), static_cast(rotaryBlockLen)}); + } else { + DataCopy( + outLocal, inQueCalLocal, + {static_cast(loopN), static_cast(this->num_q_heads * headBlockLen), 0, 0}); + } + this->VToMTE3Sync(); + DataCopy( + queryGM[offset], outLocal, + {static_cast(loopN), static_cast(this->num_q_heads * headBlockLen), 0, 0}); + // key的处理 + this->MTE3ToVSync(); + this->VToMTE2Sync(); + DataCopy( + inLocal, key_in_GM[offsetk], + {static_cast(loopN), static_cast(this->num_kv_heads * headBlockLen), + static_cast(this->k_leading_dimension / ELE_NUM_FP32 - this->k_size / ELE_NUM_FP32), 0}); + this->MTE2ToVSync(); + + if (this->is_neox_style == 0) { + DataCopy( + temp1Local, inLocal, + {static_cast(loopN * this->num_kv_heads), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopN * this->num_kv_heads; i++) { + GatherMask( + inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], static_cast(1), true, + this->rotary_dim, {1, 1, 0, 0}, rsv); + GatherMask( + inQueCalLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + } + } else { + DataCopy( + inQueCalLocal, inLocal, + {static_cast(loopN * this->num_kv_heads), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + } + DataCopy( + reverseQ, inQueCalLocal[this->rotary_dim / 2], + {static_cast(loopN * this->num_kv_heads), calBlockLen, calBlockLen, calBlockLen}); + DataCopy( + reverseQ[this->rotary_dim / 2], inQueCalLocal, + {static_cast(loopN * this->num_kv_heads), calBlockLen, calBlockLen, calBlockLen}); + + localStartAddr = 0; + cosSinOffset = 0; + for (uint32_t i = 0; i < loopN; ++i) { + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_kv_heads * this->rotary_dim; + } + + Mul(inQueCalLocal, cosSin, inQueCalLocal, loopN * this->num_kv_heads * this->rotary_dim); + Mul(reverseQ, negOne, reverseQ, loopN * this->num_kv_heads * this->rotary_dim); + + localStartAddr = 0; + cosSinOffset = this->rotary_dim / 2; + for (uint32_t i = 0; i < loopN; ++i) { + uint64_t offsetPos = this->num_tokens_each_loop_current_core * index + i; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + localStartAddr += this->num_kv_heads * this->rotary_dim; + } + + Mul(reverseQ, cosSin, reverseQ, loopN * this->num_kv_heads * this->rotary_dim); + + if (this->is_neox_style == 0) { + Add(temp1Local, reverseQ, inQueCalLocal, loopN * this->num_kv_heads * this->rotary_dim); + + for (uint32_t i = 0; i < loopN * this->num_kv_heads; i++) { + Gather( + inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + } + } else { + Add(inQueCalLocal, reverseQ, inQueCalLocal, loopN * this->num_kv_heads * this->rotary_dim); + } + + if (this->head_size != this->rotary_dim) { + DataCopy( + outLocal, inQueCalLocal, + {static_cast(loopN * this->num_kv_heads), static_cast(rotaryBlockLen), 0, + static_cast(headBlockLen - rotaryBlockLen)}); + + DataCopy( + outLocal[this->rotary_dim], inLocal[this->rotary_dim], + {static_cast(loopN * this->num_kv_heads), static_cast(headBlockLen - rotaryBlockLen), + static_cast(rotaryBlockLen), static_cast(rotaryBlockLen)}); + } else { + DataCopy( + outLocal, inQueCalLocal, + {static_cast(loopN), static_cast(this->num_kv_heads * headBlockLen), 0, 0}); + } + this->VToMTE3Sync(); + DataCopy( + keyGM[offsetk], outLocal, + {static_cast(loopN), static_cast(this->num_kv_heads * headBlockLen), 0, 0}); + + inQueueCosSinCache.FreeTensor(inCosSin); + inQQue.FreeTensor(inLocal); + outQue.FreeTensor(outLocal); +} + +template +__aicore__ inline void RopeWithSinCosCacheF32::ComputeAlongHeads(uint64_t indexToken, uint64_t indexHeads){ + q_size = this->num_q_heads * this->head_size; + k_size = this->num_kv_heads * this->head_size; + uint64_t offsetQHead = indexHeads * this->num_qheads_each_loop * this->head_size; + uint64_t offsetKHead = indexHeads * this->num_kheads_each_loop * this->head_size; + uint64_t offset = indexToken * q_size + offsetQHead;//非连续? + uint64_t offsetk = indexToken * k_size + offsetKHead; + + uint32_t dstShape_[2] = {static_cast(this->num_heads_each_loop), static_cast(this->rotary_dim)}; + uint32_t dstShape_4Negone_[2] = {static_cast(this->num_heads_each_loop - 1), + static_cast(this->rotary_dim)}; + uint32_t srcShape_[2] = {1, static_cast(this->rotary_dim)}; + + LocalTensor inLocal = inQQue.AllocTensor(); + LocalTensor inCosSin = inQueueCosSinCache.AllocTensor(); + LocalTensor outLocal = outQue.AllocTensor(); + LocalTensor reverseQ = reverseBuf.Get(); + LocalTensor negOne = negOneBuf.Get(); + LocalTensor cosSin = cosSinBuf.Get(); + LocalTensor offsetLocal = offsetBuf.Get(); + LocalTensor temp1Local = temp1.Get(); + LocalTensor inQueCalLocal = inQueCalBuf.Get(); + LocalTensor copyBuf0Local = copyBuf0.Get(); + + if (this->is_neox_style == 0) { + for (uint32_t i = 0; i < this->rotary_dim / 2; i++) { + offsetLocal.SetValue(i * 2, i * 4); + offsetLocal.SetValue(i * 2 + 1, (this->rotary_dim / 2 + i) * 4); + } + } + + if (indexHeads < this->loop_along_qheads) { + uint64_t loopNQhead = (indexHeads == this->loop_along_qheads - 1 && this->num_qheads_last_loop != 0) ? + this->num_qheads_last_loop : + this->num_qheads_each_loop; + DataCopy(inLocal, query_in_GM[offset], {1, static_cast(loopNQhead * headBlockLen), 0, 0}); + this->MTE2ToVSync(); + if (this->is_neox_style == 0) { + DataCopy(temp1Local, inLocal, + {static_cast(loopNQhead), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopNQhead; i++) { + GatherMask(inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], + static_cast(1), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + GatherMask(inQueCalLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + } + } else { + DataCopy(inQueCalLocal, inLocal, + {static_cast(loopNQhead), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + } + + DataCopy(reverseQ, inQueCalLocal[this->rotary_dim / 2], + {static_cast(loopNQhead), calBlockLen, calBlockLen, calBlockLen}); + DataCopy(reverseQ[this->rotary_dim / 2], inQueCalLocal, + {static_cast(loopNQhead), calBlockLen, calBlockLen, calBlockLen}); + + float One = 1.0; + float None = -1.0; + Duplicate(negOne, None, this->rotary_dim / 2); + Duplicate(negOne[this->rotary_dim / 2], One, this->rotary_dim / 2); + + if (this->num_heads_each_loop > 1) { + Broadcast(negOne[this->rotary_dim], negOne, dstShape_4Negone_, srcShape_); + } + + uint64_t offsetPos = indexToken; + uint64_t cosSinOffset = 0; + uint64_t localStartAddr = 0; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(inQueCalLocal, cosSin, inQueCalLocal, loopNQhead * this->rotary_dim); + Mul(reverseQ, negOne, reverseQ, loopNQhead * this->rotary_dim); + offsetPos = indexToken; + cosSinOffset = this->rotary_dim / 2; + localStartAddr = 0; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(reverseQ, cosSin, reverseQ, loopNQhead * this->rotary_dim); + + if (this->is_neox_style == 0) { + Add(temp1Local, reverseQ, inQueCalLocal, loopNQhead * this->rotary_dim); + for (uint32_t i = 0; i < loopNQhead; i++) { + Gather(inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + } + } else { + Add(inQueCalLocal, reverseQ, inQueCalLocal, loopNQhead * this->rotary_dim); + } + + if (this->head_size != this->rotary_dim) { + DataCopy(outLocal, inQueCalLocal, + {static_cast(loopNQhead), static_cast(rotaryBlockLen), 0, + static_cast(headBlockLen - rotaryBlockLen)}); + DataCopy(outLocal[this->rotary_dim], inLocal[this->rotary_dim], + {static_cast(loopNQhead), static_cast(headBlockLen - rotaryBlockLen), + static_cast(rotaryBlockLen), static_cast(rotaryBlockLen)}); + } else { + DataCopy(outLocal, inQueCalLocal, + {static_cast(loopNQhead), static_cast(headBlockLen), 0, 0}); + } + this->VToMTE3Sync(); + DataCopy(queryGM[offset], outLocal, + {static_cast(loopNQhead), static_cast(headBlockLen), 0, 0}); + } + //key + this->MTE3ToVSync(); + this->VToMTE2Sync(); + if (indexHeads < this->loop_along_kheads) { + uint64_t loopNKhead = (indexHeads == this->loop_along_kheads - 1 && this->num_kheads_last_loop != 0) ? + this->num_kheads_last_loop : + this->num_kheads_each_loop; + DataCopy(inLocal, key_in_GM[offsetk], {1, static_cast(loopNKhead * headBlockLen), 0, 0}); + this->MTE2ToVSync(); + if (this->is_neox_style == 0) { + DataCopy(temp1Local, inLocal, + {static_cast(loopNKhead), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + + uint64_t rsv = 0; + for (uint32_t i = 0; i < loopNKhead; i++) { + GatherMask(inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], + static_cast(1), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + GatherMask(inQueCalLocal[i * this->rotary_dim + this->rotary_dim / 2], temp1Local[i * this->rotary_dim], + static_cast(2), true, this->rotary_dim, {1, 1, 0, 0}, rsv); + } + } else { + DataCopy(inQueCalLocal, inLocal, + {static_cast(loopNKhead), static_cast(rotaryBlockLen), + static_cast(headBlockLen - rotaryBlockLen), 0}); + } + + DataCopy(reverseQ, inQueCalLocal[this->rotary_dim / 2], + {static_cast(loopNKhead), calBlockLen, calBlockLen, calBlockLen}); + DataCopy(reverseQ[this->rotary_dim / 2], inQueCalLocal, + {static_cast(loopNKhead), calBlockLen, calBlockLen, calBlockLen}); + + uint64_t offsetPos = indexToken; + uint64_t cosSinOffset = 0; + uint64_t localStartAddr = 0; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + + Mul(inQueCalLocal, cosSin, inQueCalLocal, loopNKhead * this->rotary_dim); + Mul(reverseQ, negOne, reverseQ, loopNKhead * this->rotary_dim); + offsetPos = indexToken; + cosSinOffset = this->rotary_dim / 2; + localStartAddr = 0; + GetCosSinCache(copyBuf0Local, inCosSin, cosSin, offsetPos, cosSinOffset, localStartAddr, srcShape_, dstShape_); + Mul(reverseQ, cosSin, reverseQ, loopNKhead * this->rotary_dim); + + if (this->is_neox_style == 0) { + Add(temp1Local, reverseQ, inQueCalLocal, loopNKhead * this->rotary_dim); + for (uint32_t i = 0; i < loopNKhead; i++) { + Gather(inQueCalLocal[i * this->rotary_dim], temp1Local[i * this->rotary_dim], offsetLocal, (uint32_t)0, + this->rotary_dim); + } + } else { + Add(inQueCalLocal, reverseQ, inQueCalLocal, loopNKhead * this->rotary_dim); + } + + if (this->head_size != this->rotary_dim) { + DataCopy(outLocal, inQueCalLocal, + {static_cast(loopNKhead), static_cast(rotaryBlockLen), 0, + static_cast(headBlockLen - rotaryBlockLen)}); + DataCopy(outLocal[this->rotary_dim], inLocal[this->rotary_dim], + {static_cast(loopNKhead), static_cast(headBlockLen - rotaryBlockLen), + static_cast(rotaryBlockLen), static_cast(rotaryBlockLen)}); + } else { + DataCopy(outLocal, inQueCalLocal, + {static_cast(loopNKhead), static_cast(headBlockLen), 0, 0}); + } + this->VToMTE3Sync(); + DataCopy(keyGM[offsetk], outLocal, + {static_cast(loopNKhead), static_cast(headBlockLen), 0, 0}); + } + + inQueueCosSinCache.FreeTensor(inCosSin); + inQQue.FreeTensor(inLocal); + outQue.FreeTensor(outLocal); +} + +template +__aicore__ inline void RopeWithSinCosCacheF32::Process() +{ + if(this->loop_for_one_token==0){ + for (uint64_t n = 0; n < this->loop_time_current_core - 1; n++) { + Compute(n, this->num_tokens_each_loop_current_core); + } + + if (this->num_tokens_last_loop_current_core == 0) { + Compute(this->loop_time_current_core - 1, this->num_tokens_each_loop_current_core); + } else { + Compute(this->loop_time_current_core - 1, this->num_tokens_last_loop_current_core); + } + } + else{ + uint64_t loop_along_heads = + this->loop_along_qheads > this->loop_along_kheads ? this->loop_along_qheads : this->loop_along_kheads; + for(uint64_t n=0;nnum_tokens_current_core;n++){ + for(uint64_t m=0;m 0): sum(mropeSection) * 2 == rotaryDim + -> rotaryDim = cosSinCache last dim = 2*sum(sections) + * headSize != 0, cacheMode ∈ {0, 1}; mrope-with-4-sections requires cacheMode == 0 + +TILING (from tiling.cpp) — headSize and rotaryDim must be 64-byte aligned: + * fp16/bf16 (2B): headSize, rotaryDim are multiples of 32 + * fp32 (4B): headSize, rotaryDim are multiples of 16 + * headSize >= rotaryDim + +BINDING NOTE — the aclnn takes ONLY (positions, queryIn, keyIn, cosSinCache, mropeSection, +headSize, isNeoxStyle) as inputs; numQHeads/numKHeads/qStride/kStride/cacheMode are computed +inside the aclnn wrapper from the tensor shapes and ignored. The autobind (aclnn_header.py) +reflects that, so the binding keeps them in the Python signature but does not pass them to the +aclnn call. PARAM_NAMES below matches the wrapper exactly; the values for the ignored attrs are +still supplied for clarity (qStride=kStride=0 => the wrapper computes strides from the tensors). + +CASE MATRIX — all mrope mode (rope mode is unreachable through this binding because it needs a +nullptr mropeSection which a vector parameter cannot express): + +# case_0: fp16 sections=[16,24,24] sum=64 rot=128 head=128 Q4 /K4 T=8 maxSeq=256 neox +# case_1: bf16 sections=[8,12,12] sum=32 rot=64 head=64 Q32/K8 T=16 maxSeq=256 neox (GQA) +# case_2: fp32 sections=[16,16,16,16] sum=64 rot=128 head=128 Q8/K8 T=64 maxSeq=512 neox (4-section) +# case_3: fp16 sections=[24,20,20] sum=64 rot=128 head=128 Q16/K4 T=512 maxSeq=1024 interleaved (large) +# case_4: bf16 sections=[11,11,10] sum=32 rot=64 head=64 Q8/K8 T=1 maxSeq=128 interleaved (tiny) +# case_5: fp16 sections=[16,24,24] sum=64 rot=128 head=128 Q32/K8 T=2048 maxSeq=4096 neox (very large) +# case_6: fp32 sections=[24,20,20] sum=64 rot=128 head=128 Q8/K1 T=32 maxSeq=512 neox (GQA) +# case_7: bf16 sections=[8,12,12] sum=32 rot=64 head=64 Q16/K16 T=128 maxSeq=1024 neox +# case_8: fp16 sections=[16,16,16,16] sum=64 rot=128 head=128 Q4/K4 T=256 maxSeq=2048 interleaved +# case_9: fp16 sections=[11,11,10] sum=32 rot=64 head=96 Q8/K8 T=16 maxSeq=256 neox (pass-through) +""" +import json, os, sys +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "rope_with_sin_cos_cache" +OP_CAMEL = "RopeWithSinCosCache" +DEVICE = "npu:0" +SEED = 2026 + +# Positional order of the generated wrapper (binding.py), excluding 'out'. +# The aclnn ignores numQHeads/numKHeads/qStride/kStride/cacheMode (computes them from shapes), +# but the wrapper signature includes them; check_signature() verifies PARAM_NAMES against it. +PARAM_NAMES = [ + "positions", "queryIn", "keyIn", "cosSinCache", + "numQHeads", "numKHeads", "headSize", + "mropeSection", "qStride", "kStride", "isNeoxStyle", "cacheMode", +] +OUTPUT_KEYS = ["queryOut", "keyOut"] + +# mropeSection lists accepted by aclnn (mropeSupportList in aclnn_rope_with_sin_cos_cache.cpp). +DEFAULT_CACHE_MODE = 0 +DEFAULT_QSTRIDE = 0 +DEFAULT_KSTRIDE = 0 + +CASES = [ + {"id": 0, "dtype": torch.float16, "sections": [16, 24, 24], "numQ": 4, "numK": 4, + "T": 8, "maxSeq": 256, "isNeoxStyle": True}, + {"id": 1, "dtype": torch.bfloat16, "sections": [8, 12, 12], "numQ": 32, "numK": 8, + "T": 16, "maxSeq": 256, "isNeoxStyle": True}, + {"id": 2, "dtype": torch.float32, "sections": [16, 16, 16, 16], "numQ": 8, "numK": 8, + "T": 64, "maxSeq": 512, "isNeoxStyle": True}, + {"id": 3, "dtype": torch.float16, "sections": [24, 20, 20], "numQ": 16, "numK": 4, + "T": 512, "maxSeq": 1024, "isNeoxStyle": False}, + {"id": 4, "dtype": torch.bfloat16, "sections": [11, 11, 10], "numQ": 8, "numK": 8, + "T": 1, "maxSeq": 128, "isNeoxStyle": False}, + {"id": 5, "dtype": torch.float16, "sections": [16, 24, 24], "numQ": 32, "numK": 8, + "T": 2048, "maxSeq": 4096, "isNeoxStyle": True}, + {"id": 6, "dtype": torch.float32, "sections": [24, 20, 20], "numQ": 8, "numK": 1, + "T": 32, "maxSeq": 512, "isNeoxStyle": True}, + {"id": 7, "dtype": torch.bfloat16, "sections": [8, 12, 12], "numQ": 16, "numK": 16, + "T": 128, "maxSeq": 1024, "isNeoxStyle": True}, + {"id": 8, "dtype": torch.float16, "sections": [16, 16, 16, 16], "numQ": 4, "numK": 4, + "T": 256, "maxSeq": 2048, "isNeoxStyle": False}, + {"id": 9, "dtype": torch.float16, "sections": [11, 11, 10], "numQ": 8, "numK": 8, + "T": 16, "maxSeq": 256, "isNeoxStyle": True, "headSize_override": 96}, +] + +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 rotary_and_head(case): + """rotaryDim (cosSinCache last dim) = 2*sum(sections); headSize >= rotaryDim and aligned.""" + rotary = 2 * sum(case["sections"]) + head = case.get("headSize_override", rotary) + type_len = 2 if case["dtype"] in (torch.float16, torch.bfloat16) else 4 + assert head % (64 // type_len) == 0, f"headSize {head} not 64B-aligned for {case['dtype']}" + assert rotary % (64 // type_len) == 0, f"rotaryDim {rotary} not 64B-aligned" + assert head >= rotary, "headSize < rotaryDim" + assert sum(case["sections"]) * 2 == rotary + assert 3 <= len(case["sections"]) <= 4 + return rotary, head + + +def make_inputs(case): + """Build every entry of PARAM_NAMES for this case.""" + torch.manual_seed(SEED + case["id"]) + dtype = case["dtype"] + rotary, head = rotary_and_head(case) + T = case["T"] + numS = len(case["sections"]) + maxSeq = case["maxSeq"] + + queryIn = torch.randn(T, case["numQ"] * head, dtype=torch.float32, device=DEVICE).to(dtype) + keyIn = torch.randn(T, case["numK"] * head, dtype=torch.float32, device=DEVICE).to(dtype) + # Real rope tables: cos on the first half, sin on the second half of each cache row, + # so values stay in [-1, 1] and the golden is meaningful. + freq = torch.arange(rotary // 2, dtype=torch.float32, device=DEVICE).unsqueeze(0) / max(rotary // 2, 1) + pos_rows = torch.arange(rotary // 2, dtype=torch.float32, device=DEVICE).unsqueeze(1) + ang = pos_rows * freq + cos = torch.cos(ang).to(dtype) + sin = torch.sin(ang).to(dtype) + cos_sin_cache = torch.cat([cos, sin], dim=1) # (rotary/2, rotary) -> repeat along rows below + + # cosSinCache rows >= num positions we need; tile the table to maxSeqLen rows. + reps = (maxSeq + cos_sin_cache.shape[0] - 1) // cos_sin_cache.shape[0] + cos_sin_cache = cos_sin_cache.repeat(reps, 1)[:maxSeq, :].contiguous() + + positions = torch.randint(0, maxSeq, (numS, T), dtype=torch.int64, device=DEVICE) + + return { + "positions": positions, + "queryIn": queryIn, + "keyIn": keyIn, + "cosSinCache": cos_sin_cache, + "numQHeads": int(case["numQ"]), + "numKHeads": int(case["numK"]), + "headSize": int(head), + "mropeSection": list(case["sections"]), + "qStride": DEFAULT_QSTRIDE, + "kStride": DEFAULT_KSTRIDE, + "isNeoxStyle": bool(case["isNeoxStyle"]), + "cacheMode": 0 if len(case["sections"]) == 4 else DEFAULT_CACHE_MODE, + } + + +def make_output_bufs(case): + """out_tmpl buffers in OUTPUT_KEYS order: (T, numHeads*headSize) for query and key.""" + _, head = rotary_and_head(case) + T = case["T"] + dtype = case["dtype"] + return [ + torch.empty(T, case["numQ"] * head, dtype=dtype, device=DEVICE), + torch.empty(T, case["numK"] * head, 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_rope_with_sin_cos_cache(*call_args, out_arg) + 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 describe_call(call_args): + """Compact argument summary for signature-mismatch diagnostics.""" + 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 check_signature(): + """Compare PARAM_NAMES against the generated wrapper's real signature.""" + import inspect + try: + params = list(inspect.signature(ops.npu_rope_with_sin_cos_cache).parameters) + except (TypeError, ValueError): + print("[WARN] cannot introspect the wrapper signature — skipping the arity check") + return + 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)) + missing = [p for p in expected if p not in PARAM_NAMES] + extra = [p for p in PARAM_NAMES if p not in expected] + if missing: + print(" missing here: %s" % ", ".join(missing)) + if extra: + print(" not in wrapper: %s" % ", ".join(extra)) + sys.exit(1) + if "out" not in params: + print("[WARN] the wrapper has no 'out' parameter — every output is in-place") + + +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_rope_with_sin_cos_cache.__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) + 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["T"], case["numQ"] * rotary_and_head(case)[1]], + "attrs": {k: (str(v).replace("torch.", "") if isinstance(v, torch.dtype) else v) + for k, v in case.items() if k not in ("id", "dtype")}, + }) + 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/rope_with_sin_cos_cache/rope_with_sin_cos_cache_test.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/rope_with_sin_cos_cache_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5c7e454882bf069f52f7d7d97e0266dad0e741b6 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/rope_with_sin_cos_cache_test.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +"""Regression test: NPU operator vs golden data collected from the same operator. + +This is the canonical test script for the sandbox workflow. 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. + +Naming: the operator is called as ops.npu_rope_with_sin_cos_cache verbatim. +Both queryOut and keyOut are template (buffered) outputs; the call passes a 2-element list +as `out` and receives (queryOut, keyOut). +""" +import json +import os +import sys + +import numpy as np +import torch +import torch_npu # noqa: F401 +import gtsrusops as ops + +OP_NAME = "rope_with_sin_cos_cache" +OP_CAMEL = "RopeWithSinCosCache" +DEVICE = "npu:0" + +# All parameters in the wrapper signature (binding.py generated), in order. +# numQHeads/numKHeads/qStride/kStride/cacheMode are accepted by the wrapper but computed +# inside the aclnn layer from tensor shapes; they are still required inputs here. +PARAM_NAMES = [ + "positions", "queryIn", "keyIn", "cosSinCache", + "numQHeads", "numKHeads", "headSize", + "mropeSection", "qStride", "kStride", "isNeoxStyle", "cacheMode", +] +# Order in which the operator returns its outputs. +OUTPUT_KEYS = ["queryOut", "keyOut"] + +# No intermediate-statistic outputs here: every output is in the same dtype as the input. +INTERMEDIATE_OUTPUT_KEYS = set() + +# Default tolerance. +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. {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).""" + 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(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. + 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)) + + if len(out_bufs) == 1: + out_arg = out_bufs[0] + else: + out_arg = out_bufs + positional = [call_kwargs[p] for p in PARAM_NAMES] + [out_arg] + outputs = ops.npu_rope_with_sin_cos_cache(*positional) + torch.npu.synchronize() + + outputs = [outputs] if isinstance(outputs, torch.Tensor) else list(outputs) + input_dtype = input_data[PARAM_NAMES[1]].dtype # queryIn + + 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/rope_with_sin_cos_cache/test_data/cases_manifest.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/test_data/cases_manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..8ba789ebc04b0b8d2c75cb3fd989a8234e1e4bdb --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/test_data/cases_manifest.json @@ -0,0 +1,213 @@ +{ + "op_name": "rope_with_sin_cos_cache", + "op_camel": "RopeWithSinCosCache", + "output_keys": [ + "queryOut", + "keyOut" + ], + "cases": [ + { + "id": 0, + "dtype": "float16", + "shape": [ + 8, + 512 + ], + "attrs": { + "sections": [ + 16, + 24, + 24 + ], + "numQ": 4, + "numK": 4, + "T": 8, + "maxSeq": 256, + "isNeoxStyle": true + } + }, + { + "id": 1, + "dtype": "bfloat16", + "shape": [ + 16, + 2048 + ], + "attrs": { + "sections": [ + 8, + 12, + 12 + ], + "numQ": 32, + "numK": 8, + "T": 16, + "maxSeq": 256, + "isNeoxStyle": true + } + }, + { + "id": 2, + "dtype": "float32", + "shape": [ + 64, + 1024 + ], + "attrs": { + "sections": [ + 16, + 16, + 16, + 16 + ], + "numQ": 8, + "numK": 8, + "T": 64, + "maxSeq": 512, + "isNeoxStyle": true + } + }, + { + "id": 3, + "dtype": "float16", + "shape": [ + 512, + 2048 + ], + "attrs": { + "sections": [ + 24, + 20, + 20 + ], + "numQ": 16, + "numK": 4, + "T": 512, + "maxSeq": 1024, + "isNeoxStyle": false + } + }, + { + "id": 4, + "dtype": "bfloat16", + "shape": [ + 1, + 512 + ], + "attrs": { + "sections": [ + 11, + 11, + 10 + ], + "numQ": 8, + "numK": 8, + "T": 1, + "maxSeq": 128, + "isNeoxStyle": false + } + }, + { + "id": 5, + "dtype": "float16", + "shape": [ + 2048, + 4096 + ], + "attrs": { + "sections": [ + 16, + 24, + 24 + ], + "numQ": 32, + "numK": 8, + "T": 2048, + "maxSeq": 4096, + "isNeoxStyle": true + } + }, + { + "id": 6, + "dtype": "float32", + "shape": [ + 32, + 1024 + ], + "attrs": { + "sections": [ + 24, + 20, + 20 + ], + "numQ": 8, + "numK": 1, + "T": 32, + "maxSeq": 512, + "isNeoxStyle": true + } + }, + { + "id": 7, + "dtype": "bfloat16", + "shape": [ + 128, + 1024 + ], + "attrs": { + "sections": [ + 8, + 12, + 12 + ], + "numQ": 16, + "numK": 16, + "T": 128, + "maxSeq": 1024, + "isNeoxStyle": true + } + }, + { + "id": 8, + "dtype": "float16", + "shape": [ + 256, + 512 + ], + "attrs": { + "sections": [ + 16, + 16, + 16, + 16 + ], + "numQ": 4, + "numK": 4, + "T": 256, + "maxSeq": 2048, + "isNeoxStyle": false + } + }, + { + "id": 9, + "dtype": "float16", + "shape": [ + 16, + 768 + ], + "attrs": { + "sections": [ + 11, + 11, + 10 + ], + "numQ": 8, + "numK": 8, + "T": 16, + "maxSeq": 256, + "isNeoxStyle": true, + "headSize_override": 96 + } + } + ] +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..6a2bf5d0a977280a0cbad893892692649b9894d2 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/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. +# ----------------------------------------------------------------------------------------------------------- + +message(STATUS "=== Debug: start ops.transformerrope_with_sin_cos_cache.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() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/st/aclnnRopeWithSinCosCache/atk_aclnnRopeWithSinCosCache.json b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/st/aclnnRopeWithSinCosCache/atk_aclnnRopeWithSinCosCache.json new file mode 100644 index 0000000000000000000000000000000000000000..3db21a482591fc5ed26dd5c922b12f268e8a3e3a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/st/aclnnRopeWithSinCosCache/atk_aclnnRopeWithSinCosCache.json @@ -0,0 +1 @@ +[{"id": 0, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 142], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 256], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 704], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [142, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 1, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 40], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 832], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 480], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [40, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 2, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 121], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 1056], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 1632], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [121, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 3, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 107], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 800], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 864], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [107, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 4, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 46], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 960], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 736], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [46, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 5, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 2], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 704], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [2, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 6, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 288], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 768], "range_values": ["-inf"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [288, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 7, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 369], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 800], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 224], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [369, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 8, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 155], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 256], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 1152], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [155, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 9, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 357], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 736], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 640], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [357, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 10, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 563], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [7, 480], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [7, 416], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [563, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 11, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 156], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [156, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 12, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 189], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 992], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 352], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [189, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 13, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 785], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 960], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 320], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [785, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 14, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 369], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 1792], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 1408], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [369, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 15, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 868], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [868, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 16, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 389], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [389, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 17, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 613], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 480], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 704], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [613, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 18, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 616], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 480], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 800], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [616, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 19, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 55], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 2784], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [55, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 20, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 12], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [17, 960], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [17, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [12, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 21, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 633], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 224], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 736], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [633, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 22, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 544], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 992], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 224], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [544, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 23, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 358], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 1344], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 1632], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [358, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 24, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 181], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 1440], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 1248], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [181, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 25, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 583], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 1472], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 896], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [583, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 26, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 764], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 928], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [764, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 27, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 1113], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [9, 448], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [9, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1113, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 28, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [82], "range_values": [-1, 242], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [82, 320], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [82, 96], "range_values": ["-inf"], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [242, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 29, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 39], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [17, 1280], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [17, 1216], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [39, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 30, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 493], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 1472], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [493, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 31, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 309], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 1792], "range_values": ["inf"], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [309, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 32, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 1285], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 416], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1285, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 33, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 1139], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 160], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 640], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1139, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 34, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 1545], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 512], "range_values": ["-inf"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 192], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1545, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 35, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 1324], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 160], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 352], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1324, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 36, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 1204], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [9, 1024], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [9, 704], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1204, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 37, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 321], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 1472], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [321, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 38, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 605], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 192], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 896], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [605, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 39, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 1751], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 672], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 352], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1751, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 40, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 559], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 960], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 1472], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [559, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 41, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 181], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 4096], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 256], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [181, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 42, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 1589], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 192], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1589, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 43, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 515], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 2048], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 1280], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [515, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 44, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 1384], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [17, 544], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [17, 416], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1384, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 45, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 1894], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 192], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1894, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 46, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 503], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 1920], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 192], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [503, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 47, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 956], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 1728], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 320], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [956, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 48, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 335], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 1152], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 2400], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [335, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 49, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 1840], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 224], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 576], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1840, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 50, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 479], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 1472], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [479, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 51, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 1914], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 672], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1914, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 52, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 1955], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 320], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1955, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 53, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 160], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 2976], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 576], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [160, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 54, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 1903], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 160], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 928], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1903, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 55, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 199], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [17, 192], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [17, 2880], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [199, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 56, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 342], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [9, 2688], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [9, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [342, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 57, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 1916], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 672], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1916, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 58, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 1030], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 256], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1030, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 59, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 1085], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1085, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 60, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 916], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 1088], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 256], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [916, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 61, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 177], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 3456], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [177, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 62, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 828], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 1024], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 832], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [828, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 63, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 500], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 2688], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 1632], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [500, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 64, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 873], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [17, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [17, 960], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [873, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 65, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 896], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 2112], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 2304], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [896, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 66, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 1405], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 1472], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1, 576], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1405, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 67, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 1483], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 832], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 640], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1483, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 68, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 493], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 2496], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 576], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [493, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 69, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 1460], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 1472], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 1664], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1460, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 70, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 709], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 2208], "range_values": ["-inf"], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [709, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 71, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 1457], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 960], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 192], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1457, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 72, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 753], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [17, 1056], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [17, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [753, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 73, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 1372], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 1792], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 832], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1372, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 74, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 1492], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 1600], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1492, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 75, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 1038], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 1152], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 480], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1038, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 76, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 83], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 3968], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 2048], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [83, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 77, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 839], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 2880], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [839, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 78, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 934], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 864], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 2880], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [934, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 79, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 964], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [9, 1632], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [9, 1440], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [964, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 80, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 705], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 1280], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 2304], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [705, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 81, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 871], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [8, 1408], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [871, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 82, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 1101], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 2400], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1101, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 83, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 1988], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 1024], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 1472], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1988, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 84, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 1353], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 1792], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 1152], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1353, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 85, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 988], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [16, 1344], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [16, 1344], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [988, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 86, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 1157], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 1440], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 3072], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1157, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 87, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 474], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 3456], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 1920], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [474, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 88, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 1255], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 672], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [8, 3072], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1255, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 89, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 1238], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 2400], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [9, 1152], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1238, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 90, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 1159], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 896], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1, 2944], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1159, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 91, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 1120], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [17, 672], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [17, 2016], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1120, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 92, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 1297], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 1632], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 2592], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1297, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 93, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 807], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [9, 3840], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [9, 2176], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [807, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 94, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 1472], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 1920], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1472, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 95, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 1907], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 640], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 2048], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1907, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 96, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 1864], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 1920], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 1024], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1864, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 97, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 1720], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 1792], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [15, 2048], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1720, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 98, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [1], "range_values": [-1, 1279], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 3712], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1279, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 99, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 1606], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 1824], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [7, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1606, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 100, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 1737], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [16, 1664], "range_values": ["nan"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [16, 2048], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1737, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 101, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 1068], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [16, 1920], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [16, 2592], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1068, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 102, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 1664], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 480], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1664, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 103, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [364], "range_values": [-1, 559], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [364, 288], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [364, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [559, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 104, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 1629], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [17, 480], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [17, 1920], "range_values": ["inf"], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1629, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 105, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 1464], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 2112], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1464, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 106, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 1457], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [7, 640], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [7, 1152], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1457, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 107, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 1487], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [7, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [7, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1487, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 108, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 1390], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 2560], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 1792], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1390, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 109, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 1054], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 2304], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 2048], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1054, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 110, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 1230], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 3456], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [15, 256], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1230, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 111, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 1651], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 2304], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [16, 1152], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1651, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 112, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [384], "range_values": [-1, 1866], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [384, 288], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [384, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1866, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 113, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [9], "range_values": [-1, 1349], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 2688], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [9, 3456], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1349, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 114, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 1916], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 1344], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 1728], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1916, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 115, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [15], "range_values": [-1, 1038], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 3456], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [15, 3328], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1038, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 116, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 1160], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 3200], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 1920], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1160, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 117, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [8], "range_values": [-1, 1577], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 4096], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [8, 1792], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1577, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 118, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 1991], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 2592], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [16, 1248], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1991, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 119, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 1591], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [17, 2816], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1591, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 120, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [7], "range_values": [-1, 1865], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 384], "range_values": ["inf"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [7, 3328], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1865, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 121, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [17], "range_values": [-1, 1714], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [17, 1664], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [17, 1280], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1714, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 122, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 945], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [320, 704], "range_values": ["nan"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [320, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [945, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 123, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [16], "range_values": [-1, 1745], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [16, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [16, 3968], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1745, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 124, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 1800], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 416], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1800, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 125, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 631], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [320, 320], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [320, 640], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [631, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 126, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [384], "range_values": [-1, 1543], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [384, 288], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [384, 448], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1543, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 127, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [256], "range_values": [-1, 1094], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256, 864], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1094, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 128, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [256], "range_values": [-1, 749], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256, 480], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256, 1024], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [749, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 129, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [218], "range_values": [-1, 324], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [218, 640], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [218, 1152], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [324, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 130, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [384], "range_values": [-1, 1214], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [384, 128], "range_values": ["-inf"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [384, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1214, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 131, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [610], "range_values": [-1, 1645], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [610, 160], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [610, 448], "range_values": ["nan"], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1645, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 132, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 1636], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [320, 896], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [320, 192], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1636, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 133, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 455], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 736], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 704], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [455, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 134, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [451], "range_values": [-1, 700], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [451, 448], "range_values": ["-inf"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [451, 640], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [700, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 135, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 145], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 672], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 1056], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [145, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 136, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [256], "range_values": [-1, 1816], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256, 1408], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1816, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 137, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 356], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [320, 704], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [320, 1280], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [356, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 138, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [224], "range_values": [-1, 458], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [224, 1152], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [224, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [458, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 139, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 1041], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [320, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [320, 1920], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1041, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 140, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [384], "range_values": [-1, 1529], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [384, 1280], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [384, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1529, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 141, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 844], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [320, 2048], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [320, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [844, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 142, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 1477], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [320, 2048], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [320, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1477, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 143, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [384], "range_values": [-1, 68], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [384, 1472], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [384, 576], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [68, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 144, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [256], "range_values": [-1, 1613], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256, 1408], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256, 1280], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1613, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 145, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [256], "range_values": [-1, 1864], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256, 1152], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1864, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 146, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [502], "range_values": [-1, 854], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [502, 960], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [502, 576], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [854, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 147, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 1810], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [320, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [320, 2016], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1810, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 148, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [384], "range_values": [-1, 1478], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [384, 1472], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [384, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1478, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 149, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [384], "range_values": [-1, 614], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [384, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [384, 1856], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [614, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 150, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 449], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [320, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [320, 1984], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [449, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 151, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [256], "range_values": [-1, 783], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256, 2880], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [783, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 152, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [384], "range_values": [-1, 338], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [384, 1824], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [384, 480], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [338, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 153, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 1520], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [320, 2176], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [320, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1520, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 154, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 944], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 2304], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 384], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [944, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 155, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [384], "range_values": [-1, 359], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [384, 1728], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [384, 672], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [359, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 156, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [256], "range_values": [-1, 1887], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256, 480], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256, 2592], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1887, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 157, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [241], "range_values": [-1, 1937], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [241, 2688], "range_values": ["-inf"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [241, 864], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1937, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 158, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 649], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 864], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [320, 2208], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [649, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 159, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [256], "range_values": [-1, 1607], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256, 2496], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [256, 1056], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1607, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 160, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [732], "range_values": [-1, 1889], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [732, 992], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [732, 448], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1889, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 161, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [637], "range_values": [-1, 447], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [637, 1664], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [637, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [447, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 162, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [256], "range_values": [-1, 1132], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256, 1024], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256, 3328], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1132, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 163, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [256], "range_values": [-1, 1245], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256, 3456], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [256, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1245, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 164, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [320], "range_values": [-1, 1371], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [320, 3072], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [320, 1280], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1371, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 165, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [256], "range_values": [-1, 1325], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256, 4096], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [256, 1664], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1325, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 166, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [384], "range_values": [-1, 242], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [384, 1632], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [384, 2976], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [242, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 167, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3584], "range_values": [-1, 1198], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3584, 288], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3584, 256], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1198, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 168, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [808], "range_values": [-1, 518], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [808, 896], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [808, 1664], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [518, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 169, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [622], "range_values": [-1, 259], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [622, 3968], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [622, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [259, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 170, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [615], "range_values": [-1, 1622], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [615, 2208], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [615, 2880], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1622, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 171, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 1723], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3696, 704], "range_values": ["-inf"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3696, 256], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1723, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 172, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3584], "range_values": [-1, 130], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3584, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3584, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [130, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 173, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3584], "range_values": [-1, 1288], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3584, 576], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3584, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1288, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 174, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [735], "range_values": [-1, 579], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [735, 3072], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [735, 2688], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [579, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 175, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 208], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3696, 832], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3696, 576], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [208, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 176, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3584], "range_values": [-1, 1944], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3584, 480], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3584, 992], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1944, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 177, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 46], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3696, 768], "range_values": ["nan"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3696, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [46, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 178, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 89], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3696, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3696, 1600], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [89, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 179, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 53], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3696, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3696, 640], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [53, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 180, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 1657], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3696, 1248], "range_values": ["-inf"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3696, 960], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1657, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 181, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 1034], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3696, 1792], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3696, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1034, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 182, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 673], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3696, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3696, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [673, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 183, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3584], "range_values": [-1, 1480], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3584, 1728], "range_values": ["nan"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3584, 1792], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1480, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 184, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3584], "range_values": [-1, 1131], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3584, 2400], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3584, 1248], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1131, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 185, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3584], "range_values": [-1, 341], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3584, 2048], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3584, 1920], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [341, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 186, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3584], "range_values": [-1, 1449], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3584, 2688], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3584, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1449, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 187, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 1517], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3696, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3696, 3840], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1517, 128], "range_values": ["-inf"], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 188, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 576], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3696, 1920], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3696, 2496], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [576, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 189, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 1687], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3696, 3200], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3696, 1280], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1687, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 190, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 1039], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3696, 3456], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3696, 1152], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1039, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 191, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3584], "range_values": [-1, 60], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3584, 2784], "range_values": ["nan"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [3584, 2016], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [60, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 192, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 1373], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3696, 1792], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [3696, 2944], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1373, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 193, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3696], "range_values": [-1, 1924], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3696, 2496], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3696, 2304], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1924, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 194, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3584], "range_values": [-1, 1819], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3584, 2208], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3584, 2976], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1819, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 195, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [3584], "range_values": [-1, 1532], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3584, 1920], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [3584, 4096], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1532, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 196, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 435], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [131073, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [131073, 224], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [435, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 197, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 692], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [131073, 384], "range_values": ["inf"], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [131073, 352], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [692, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 198, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 1982], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [131073, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [131073, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [1982, 64], "range_values": ["inf"], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 199, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 1328], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [131073, 768], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [131073, 320], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1328, 32], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [32], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 200, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 875], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [131073, 1088], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [131073, 1216], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [875, 64], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [64], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 201, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 408], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [131073, 2048], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [131073, 512], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [408, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 202, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 67], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [131073, 2304], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [131073, 1056], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [67, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 203, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 1262], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [131073, 1344], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [131073, 2016], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1262, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 204, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 757], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [131073, 3328], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [131073, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [757, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 205, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 840], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [131073, 1536], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp32", "shape": [131073, 2496], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp32", "shape": [840, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 206, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 1274], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [131073, 3840], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [131073, 640], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [1274, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 207, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 590], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [131073, 1152], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [131073, 3456], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [590, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 208, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 1817], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [131073, 1920], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "fp16", "shape": [131073, 2784], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "fp16", "shape": [1817, 96], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [96], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": true, "backward": false, "align_32B": null}], "is_boundary": true}, {"id": 209, "name": "aclnnRopeWithSinCosCache", "aclnn_name": "RopeWithSinCosCache", "api_type": "executor_function_ascend_rope_with_sin_cos_cache", "standard": {"acc": {"single_bm": {"type": "vector_fused"}}, "perf": "not_key"}, "inputs": [{"name": "positions", "type": "tensor", "required": true, "dtype": "int64", "shape": [131073], "range_values": [-1, 575], "backward": false, "align_32B": null}, {"name": "queryIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [131073, 3200], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "keyIn", "type": "tensor", "required": true, "dtype": "bf16", "shape": [131073, 1792], "range_values": [-5, 5], "backward": false, "align_32B": null}, {"name": "cosSinCache", "type": "tensor", "required": true, "dtype": "bf16", "shape": [575, 128], "range_values": [-5, 5], "backward": false, "align_32B": null}, [{"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}, {"name": "mropeSection", "type": "attrs", "required": false, "dtype": "int", "shape": null, "range_values": 0, "backward": false, "align_32B": null}], {"name": "headSize", "type": "attr", "required": false, "dtype": "int", "shape": null, "range_values": [128], "backward": false, "align_32B": null}, {"name": "isNeoxStyle", "type": "attr", "required": true, "dtype": "bool", "shape": null, "range_values": false, "backward": false, "align_32B": null}], "is_boundary": true}] \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/st/aclnnRopeWithSinCosCache/executor_aclnnRopeWithSinCosCache.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/st/aclnnRopeWithSinCosCache/executor_aclnnRopeWithSinCosCache.py new file mode 100644 index 0000000000000000000000000000000000000000..4ba0006a388cdaf70fc856db7d0f36dd7c8e2c69 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/st/aclnnRopeWithSinCosCache/executor_aclnnRopeWithSinCosCache.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# ---------------------------------------------------------------------------- +# 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. +# ---------------------------------------------------------------------------- + +import torch + +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 OutputData +from einops import rearrange + + +#下面为mrope实现,rope的positions为一维,不需要使用mrope_section; + +def mRopeNpu(positions, query, key, cos_sin_cache, mrope_section, head_size, num_q_heads, num_kv_heads, is_neox_style=True): + num_tokens = positions.shape[-1] + rotary_dim = cos_sin_cache.shape[-1] + + positions_flatten = positions.flatten() # [3, num_tokens] -> [3*num_tokens] + cos_sin = cos_sin_cache.index_select(0, positions_flatten) # cos_sin_cache: [num_tokens, rotary_dim] -> [3*num_tokens, rotary_dim] + cos_sin = cos_sin.reshape(-1, rotary_dim) + + cos, sin = cos_sin.chunk(2, dim=-1) # 1D: [num_tokens, rotary_dim // 2] 2D: [3 * num_tokens, rotary_dim // 2] + if positions.ndim == 2: + cos = cos.reshape(3, -1, rotary_dim // 2) # [3, num_tokens, rotary_dim // 2] + cos_0 = cos[0, :, :mrope_section[0]] + cos_1 = cos[1, :, mrope_section[0]:(mrope_section[0] + mrope_section[1])] + cos_2 = cos[2, :, (mrope_section[0] + mrope_section[1]):(mrope_section[0] + mrope_section[1] + mrope_section[2])] + cos = torch.concat((cos_0, cos_1, cos_2), dim=-1) + + sin = sin.reshape(3, -1, rotary_dim // 2) # [3, num_tokens, rotary_dim // 2] + sin_0 = sin[0, :, :mrope_section[0]] + sin_1 = sin[1, :, mrope_section[0]:(mrope_section[0] + mrope_section[1])] + sin_2 = sin[2, :, (mrope_section[0] + mrope_section[1]):(mrope_section[0] + mrope_section[1] + mrope_section[2])] + sin = torch.concat((sin_0, sin_1, sin_2), dim=-1) + + cos = cos.unsqueeze(-2) # [num_tokens, 1, rotary_dim // 2] + sin = sin.unsqueeze(-2) # [num_tokens, 1, rotary_dim // 2] + query_shape = query.shape + query = query.view(num_tokens, -1, head_size) # [num_tokens, num_heads, head_size] + query_rot = query[..., :rotary_dim] # [num_tokens, num_heads, rotary_dim] + query_pass = query[..., rotary_dim:] # [num_tokens, num_heads, head_size - rotary_dim] + if is_neox_style: + x1, x2 = torch.chunk(query_rot, 2, dim=-1) # [num_tokens, num_heads, rotary_dim // 2] + else: + x1 = query_rot[..., ::2] + x2 = query_rot[..., 1::2] + o1 = x1 * cos - x2 * sin + o2 = x2 * cos + x1 * sin + if is_neox_style: + query_rot = torch.cat((o1, o2), dim=-1) + else: + query_rot = torch.stack((o1, o2), dim=-1).flatten(-2) + query = torch.cat((query_rot, query_pass), dim=-1).reshape(query_shape) + + key_shape = key.shape + key = key.view(num_tokens, -1, head_size) # [num_tokens, num_kv_heads, head_size] + key_rot = key[..., :rotary_dim] # [num_tokens, num_kv_heads, rotary_dim] + key_pass = key[..., rotary_dim:] # [num_tokens, num_kv_heads, head_size - rotary_dim] + if is_neox_style: + x1, x2 = torch.chunk(key_rot, 2, dim=-1) + else: + x1 = key_rot[..., ::2] + x2 = key_rot[..., 1::2] + o1 = x1 * cos - x2 * sin + o2 = x2 * cos + x1 * sin + if is_neox_style: + key_rot = torch.cat((o1, o2), dim=-1) + else: + key_rot = torch.stack((o1, o2), dim=-1).flatten(-2) + key = torch.cat((key_rot, key_pass), dim=-1).reshape(key_shape) # [num_tokens, num_kv_heads * head_size] + return query, key + + +@register("executor_function_ascend_rope_with_sin_cos_cache") +class aclnnRopeWithSinCosCachesApi(BaseApi): + def __call__(self, input_data: InputDataset, with_output: bool = False): + positions = input_data.kwargs["positions"] + query = input_data.kwargs["queryIn"] + key = input_data.kwargs["keyIn"] + cos_sin_cache = input_data.kwargs["cosSinCache"] + mrope_section = input_data.kwargs["mropeSection"] + head_size = input_data.kwargs["headSize"] + num_q_heads = query.shape[1] / head_size + num_kv_heads = key.shape[1] / head_size + is_neox_style = input_data.kwargs["isNeoxStyle"] + if positions.ndim == 2: + mrope_section[0] = 16 + if self.device == 'cpu': + query = query.to(torch.float32) + key = key.to(torch.float32) + cos_sin_cache = cos_sin_cache.to(torch.float32) + output = mRopeNpu(positions, query, key, cos_sin_cache, mrope_section, head_size, num_q_heads, num_kv_heads, is_neox_style) + return output + + def init_by_input_data(self, input_data: InputDataset): + if self.device == 'pyaclnn': + if input_data.kwargs["positions"].ndim == 2: + input_data.kwargs["mropeSection"][0] = 16 + queryIn_input_dtype = input_data.kwargs["queryIn"].dtype + keyIn_input_dtype = input_data.kwargs["keyIn"].dtype + input_data.kwargs["positions"] = input_data.kwargs["positions"].npu() + input_data.kwargs["queryIn"] = input_data.kwargs["queryIn"].npu() + input_data.kwargs["keyIn"] = input_data.kwargs["keyIn"].npu() + input_data.kwargs["cosSinCache"] = input_data.kwargs["cosSinCache"].npu() + + self.task_result.output_info_list[0].dtype=str(queryIn_input_dtype) + self.task_result.output_info_list[1].dtype=str(keyIn_input_dtype) \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..d711fecbdd4a5c11ce9855daed6e736308d83a6a --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/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. +# ----------------------------------------------------------------------------------------------------------- + +message(STATUS "=== Debug: start ops.transformer.rope_with_sin_cos_cache.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() \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_host/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_host/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9947844423c100b61da61fe6a9cd60bcba6a5745 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/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/rope_with_sin_cos_cache/tests/ut/op_host/op_api/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_host/op_api/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..8a9a581e54bf50b478ac91eac8ec4de5bb62c0a5 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_host/op_api/CMakeLists.txt @@ -0,0 +1,13 @@ +# ----------------------------------------------------------------------------------------------------------- +# 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/rope_with_sin_cos_cache/tests/ut/op_host/op_api/test_aclnn_rope_with_sin_cos_cache.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_host/op_api/test_aclnn_rope_with_sin_cos_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf9518d041b7ab3142db3dc5e2c71328ca2ab204 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_host/op_api/test_aclnn_rope_with_sin_cos_cache.cpp @@ -0,0 +1,247 @@ +/** + * 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 "gtest/gtest.h" + +#include "../../../../op_host/op_api/aclnn_rope_with_sin_cos_cache.h" +#include "../../../../op_host/op_api/aclnn_rope_with_sin_cos_cache_v2.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 l2_rope_with_sin_cos_cache_test : public testing::Test +{ +protected: + static void SetUpTestCase() + { + cout << "rope_with_sin_cos_cache_test SetUp" << endl; + } + + static void TearDownTestCase() + { + cout << "rope_with_sin_cos_cache_test TearDown" << endl; + } +}; + +TEST_F(l2_rope_with_sin_cos_cache_test, Ascend910B_case_1) +{ + auto tensorPositions = + TensorDesc({4}, ACL_INT64, ACL_FORMAT_ND).ValueRange(0, 255).Value(vector{7, 6, 5, 4, 1, 0, 2, 3}); + + auto tensorQueryIn = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorKeyIn = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorCosSinCache = TensorDesc({20, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + vector mropeSectionContent = {16, 24, 24}; + aclIntArray* mropeSection = aclCreateIntArray(mropeSectionContent.data(), mropeSectionContent.size()); + + int64_t headSize = 64; + bool isNeoxStyle = true; + + auto tensorQueryOutDesc = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND); + auto tensorKeyOutDesc = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND); + + auto ut = OP_API_UT( + aclnnRopeWithSinCosCache, + INPUT(tensorPositions, tensorQueryIn, tensorKeyIn, tensorCosSinCache, mropeSection, headSize, isNeoxStyle), + OUTPUT(tensorQueryOutDesc, tensorKeyOutDesc)); + + uint64_t workspaceSize = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspaceSize); + EXPECT_EQ(aclRet, ACLNN_ERR_PARAM_INVALID); +} + +TEST_F(l2_rope_with_sin_cos_cache_test, Ascend910B_case_2) +{ + auto tensorPositions = + TensorDesc({8}, ACL_INT64, ACL_FORMAT_ND).ValueRange(0, 255).Value(vector{7, 6, 5, 4, 1, 0, 2, 3}); + + auto tensorQueryIn = TensorDesc({4, 64, 50}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorKeyIn = TensorDesc({4, 64, 51}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorCosSinCache = TensorDesc({20, 64, 51}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + vector mropeSectionContent = {16, 24, 24}; + aclIntArray* mropeSection = aclCreateIntArray(mropeSectionContent.data(), mropeSectionContent.size()); + + int64_t headSize = 64; + bool isNeoxStyle = true; + + auto tensorQueryOutDesc = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND); + auto tensorKeyOutDesc = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND); + + auto ut = OP_API_UT( + aclnnRopeWithSinCosCache, + INPUT(tensorPositions, tensorQueryIn, tensorKeyIn, tensorCosSinCache, mropeSection, headSize, isNeoxStyle), + OUTPUT(tensorQueryOutDesc, tensorKeyOutDesc)); + + uint64_t workspaceSize = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspaceSize); + EXPECT_EQ(aclRet, ACLNN_ERR_PARAM_INVALID); +} + +TEST_F(l2_rope_with_sin_cos_cache_test, Ascend910B_case_3) +{ + auto tensorPositions = + TensorDesc({8}, ACL_INT64, ACL_FORMAT_ND).ValueRange(0, 255).Value(vector{7, 6, 5, 4, 1, 0, 2, 3}); + + auto tensorQueryIn = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorKeyIn = TensorDesc({4, 64, 51}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorCosSinCache = TensorDesc({20, 64, 51}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + vector mropeSectionContent = {16, 24, 24}; + aclIntArray* mropeSection = aclCreateIntArray(mropeSectionContent.data(), mropeSectionContent.size()); + + int64_t headSize = 64; + bool isNeoxStyle = true; + + auto tensorQueryOutDesc = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND); + auto tensorKeyOutDesc = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND); + + auto ut = OP_API_UT( + aclnnRopeWithSinCosCache, + INPUT(tensorPositions, tensorQueryIn, tensorKeyIn, tensorCosSinCache, mropeSection, headSize, isNeoxStyle), + OUTPUT(tensorQueryOutDesc, tensorKeyOutDesc)); + + uint64_t workspaceSize = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspaceSize); + EXPECT_EQ(aclRet, ACLNN_ERR_PARAM_INVALID); +} + +TEST_F(l2_rope_with_sin_cos_cache_test, Ascend910B_case_4) +{ + auto tensorPositions = + TensorDesc({8}, ACL_INT64, ACL_FORMAT_ND).ValueRange(0, 255).Value(vector{7, 6, 5, 4, 1, 0, 2, 3}); + + auto tensorQueryIn = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorKeyIn = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorCosSinCache = TensorDesc({20, 64, 51}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + vector mropeSectionContent = {16, 24, 24}; + aclIntArray* mropeSection = aclCreateIntArray(mropeSectionContent.data(), mropeSectionContent.size()); + + int64_t headSize = 64; + bool isNeoxStyle = true; + + auto tensorQueryOutDesc = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND); + auto tensorKeyOutDesc = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND); + + auto ut = OP_API_UT( + aclnnRopeWithSinCosCache, + INPUT(tensorPositions, tensorQueryIn, tensorKeyIn, tensorCosSinCache, mropeSection, headSize, isNeoxStyle), + OUTPUT(tensorQueryOutDesc, tensorKeyOutDesc)); + + uint64_t workspaceSize = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspaceSize); + EXPECT_EQ(aclRet, ACLNN_ERR_PARAM_INVALID); +} + +TEST_F(l2_rope_with_sin_cos_cache_test, Ascend910B_case_5) +{ + auto tensorPositions = + TensorDesc({8}, ACL_INT64, ACL_FORMAT_ND).ValueRange(0, 255).Value(vector{7, 6, 5, 4, 1, 0, 2, 3}); + + auto tensorQueryIn = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorKeyIn = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorCosSinCache = TensorDesc({20, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + vector mropeSectionContent = {16, 24, 24}; + aclIntArray* mropeSection = aclCreateIntArray(mropeSectionContent.data(), mropeSectionContent.size()); + + int64_t headSize = 64; + bool isNeoxStyle = true; + + auto tensorQueryOutDesc = TensorDesc({4, 64, 5}, ACL_FLOAT, ACL_FORMAT_ND); + auto tensorKeyOutDesc = TensorDesc({4, 64, 5}, ACL_FLOAT, ACL_FORMAT_ND); + + auto ut = OP_API_UT( + aclnnRopeWithSinCosCache, + INPUT(tensorPositions, tensorQueryIn, tensorKeyIn, tensorCosSinCache, mropeSection, headSize, isNeoxStyle), + OUTPUT(tensorQueryOutDesc, tensorKeyOutDesc)); + + uint64_t workspaceSize = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspaceSize); + EXPECT_EQ(aclRet, ACLNN_ERR_PARAM_INVALID); +} + +TEST_F(l2_rope_with_sin_cos_cache_test, Ascend910B_case_6) +{ + auto tensorPositions = + TensorDesc({8}, ACL_INT64, ACL_FORMAT_ND).ValueRange(0, 255).Value(vector{7, 6, 5, 4, 1, 0, 2, 3}); + + auto tensorQueryIn = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorKeyIn = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorCosSinCache = TensorDesc({20, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + vector mropeSectionContent = {16, 24, 24}; + aclIntArray* mropeSection = aclCreateIntArray(mropeSectionContent.data(), mropeSectionContent.size()); + + int64_t headSize = 64; + bool isNeoxStyle = true; + + auto tensorQueryOutDesc = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND); + auto tensorKeyOutDesc = TensorDesc({4, 64, 5}, ACL_FLOAT, ACL_FORMAT_ND); + + auto ut = OP_API_UT( + aclnnRopeWithSinCosCache, + INPUT(tensorPositions, tensorQueryIn, tensorKeyIn, tensorCosSinCache, mropeSection, headSize, isNeoxStyle), + OUTPUT(tensorQueryOutDesc, tensorKeyOutDesc)); + + uint64_t workspaceSize = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspaceSize); + EXPECT_EQ(aclRet, ACLNN_ERR_PARAM_INVALID); +} + +TEST_F(l2_rope_with_sin_cos_cache_test, rope_v2_case_7) +{ + auto tensorPositions = + TensorDesc({8}, ACL_INT64, ACL_FORMAT_ND).ValueRange(0, 255).Value(vector{7, 6, 5, 4, 1, 0, 2, 3}); + + auto tensorQueryIn = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorKeyIn = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + auto tensorCosSinCache = TensorDesc({20, 64}, ACL_FLOAT, ACL_FORMAT_ND).ValueRange(0, 20); + + vector mropeSectionContent = {16, 24, 24}; + aclIntArray* mropeSection = aclCreateIntArray(mropeSectionContent.data(), mropeSectionContent.size()); + + int64_t headSize = 64; + bool isNeoxStyle = true; + int64_t cacheMode = 1; + + auto tensorQueryOutDesc = TensorDesc({4, 64}, ACL_FLOAT, ACL_FORMAT_ND); + auto tensorKeyOutDesc = TensorDesc({4, 64, 5}, ACL_FLOAT, ACL_FORMAT_ND); + + auto ut = OP_API_UT( + aclnnRopeWithSinCosCacheV2, + INPUT(tensorPositions, tensorQueryIn, tensorKeyIn, tensorCosSinCache, mropeSection, headSize, isNeoxStyle, cacheMode), + OUTPUT(tensorQueryOutDesc, tensorKeyOutDesc)); + + uint64_t workspaceSize = 0; + aclnnStatus aclRet = ut.TestGetWorkspaceSize(&workspaceSize); + EXPECT_EQ(aclRet, ACLNN_ERR_PARAM_INVALID); +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_host/test_rope_with_sin_cos_cache_infershape.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_host/test_rope_with_sin_cos_cache_infershape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e965a4106cac7a3525ba3c041c1e85959af55e1c --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_host/test_rope_with_sin_cos_cache_infershape.cpp @@ -0,0 +1,122 @@ +/** + * 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" + +class RopeWithSinCosCache : public testing::Test +{ +protected: + static void SetUpTestCase() + { + std::cout << "RopeWithSinCosCache Proto Test SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "RopeWithSinCosCache Proto Test TearDown" << std::endl; + } +}; + +TEST_F(RopeWithSinCosCache, rope_with_sin_cos_cache_bf16_true) +{ + std::vector mropeParams{0, 0, 0}; + gert::InfershapeContextPara infershapeContextPara( + "RopeWithSinCosCache", + { + // input info + {{{48}, {48}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{48, 256}, {48, 256}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{48, 128}, {48, 128}}, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + // attr + {"numQHeads", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"numKHeads", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"headSize", Ops::Transformer::AnyValue::CreateFrom(128)}, + {"mropeSection", Ops::Transformer::AnyValue::CreateFrom>(mropeParams)}, + {"qstride", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"kstride", Ops::Transformer::AnyValue::CreateFrom(512)}, + {"isNeoxStyle", Ops::Transformer::AnyValue::CreateFrom(1)}, + }); + std::vector> expectOutputShape = {{48, 256}, {48, 512}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(RopeWithSinCosCache, rope_with_sin_cos_cache_fp16_true) +{ + std::vector mropeParams{0, 0, 0}; + gert::InfershapeContextPara infershapeContextPara( + "RopeWithSinCosCache", + { + // input info + {{{48}, {48}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{48, 256}, {48, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 128}, {48, 128}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + // attr + {"numQHeads", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"numKHeads", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"headSize", Ops::Transformer::AnyValue::CreateFrom(128)}, + {"mropeSection", Ops::Transformer::AnyValue::CreateFrom>(mropeParams)}, + {"qstride", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"kstride", Ops::Transformer::AnyValue::CreateFrom(512)}, + {"isNeoxStyle", Ops::Transformer::AnyValue::CreateFrom(1)}, + }); + std::vector> expectOutputShape = {{48, 256}, {48, 512}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} + +TEST_F(RopeWithSinCosCache, rope_with_sin_cos_cache_fp32_true) +{ + std::vector mropeParams{0, 0, 0}; + gert::InfershapeContextPara infershapeContextPara( + "RopeWithSinCosCache", + { + // input info + {{{48}, {48}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{48, 256}, {48, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{48, 128}, {48, 128}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // output info + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{}, {}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + // attr + {"numQHeads", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"numKHeads", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"headSize", Ops::Transformer::AnyValue::CreateFrom(128)}, + {"mropeSection", Ops::Transformer::AnyValue::CreateFrom>(mropeParams)}, + {"qstride", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"kstride", Ops::Transformer::AnyValue::CreateFrom(512)}, + {"isNeoxStyle", Ops::Transformer::AnyValue::CreateFrom(1)}, + }); + std::vector> expectOutputShape = {{48, 256}, {48, 512}}; + ExecuteTestCase(infershapeContextPara, ge::GRAPH_SUCCESS, expectOutputShape); +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_host/test_rope_with_sin_cos_cache_tiling.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_host/test_rope_with_sin_cos_cache_tiling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..46871c838c8608140bcaf97043b7f78a861d8650 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_host/test_rope_with_sin_cos_cache_tiling.cpp @@ -0,0 +1,285 @@ +/** + * 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_cross_entropy_loss.cpp + * \brief + */ + +#include +#include +#include "tiling_context_faker.h" +#include "tiling_case_executor.h" +#include "../../../op_host/rope_with_sin_cos_cache_tiling.h" + + +using namespace std; + +struct RopeWithSinCosCacheCompileInfo {}; +class RopeWithSinCosCacheTiling : public testing::Test { +protected: + static void SetUpTestCase() + { + std::cout << "RopeWithSinCosCacheTiling SetUp" << std::endl; + } + + static void TearDownTestCase() + { + std::cout << "RopeWithSinCosCacheTiling TearDown" << std::endl; + } +}; + +TEST_F(RopeWithSinCosCacheTiling, test_tiling_bf16_true) +{ + RopeWithSinCosCacheCompileInfo compile_info = {}; + vector mropeParams{0, 0, 0}; + gert::TilingContextPara tilingContextPara( + "RopeWithSinCosCache", + { + {{{48, 48}, {48, 48}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{48, 256}, {48, 256}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{48, 128}, {48, 128}}, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {{{48, 256}, {48, 256}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + }, + {{"numQHeads", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"numKHeads", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"headSize", Ops::Transformer::AnyValue::CreateFrom(128)}, + {"mropeSection", Ops::Transformer::AnyValue::CreateFrom>(mropeParams)}, + {"qstride", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"kstride", Ops::Transformer::AnyValue::CreateFrom(512)}, + {"isNeoxStyle", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"cacheMode", Ops::Transformer::AnyValue::CreateFrom(0)}}, + &compile_info); + uint64_t expectTilingKey = 20; + string expectTilingData = "48 48 2 4 128 128 0 0 0 0 256 512 1 0 48 0 1 0 1 0 1 0 0 0 0 1 1 2 0 4 0 "; + std::vector expectWorkspaces = {16 * 1024 * 1024}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(RopeWithSinCosCacheTiling, test_tiling_fp16_true) +{ + RopeWithSinCosCacheCompileInfo compile_info = {}; + vector mropeParams{0, 0, 0}; + gert::TilingContextPara tilingContextPara( + "RopeWithSinCosCache", + { + {{{48, 48}, {48, 48}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{48, 256}, {48, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 128}, {48, 128}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{48, 256}, {48, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + {{"numQHeads", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"numKHeads", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"headSize", Ops::Transformer::AnyValue::CreateFrom(128)}, + {"mropeSection", Ops::Transformer::AnyValue::CreateFrom>(mropeParams)}, + {"qstride", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"kstride", Ops::Transformer::AnyValue::CreateFrom(512)}, + {"isNeoxStyle", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"cacheMode", Ops::Transformer::AnyValue::CreateFrom(0)}}, + &compile_info); + uint64_t expectTilingKey = 21; + string expectTilingData = "48 48 2 4 128 128 0 0 0 0 256 512 1 0 48 0 1 0 1 0 1 0 0 0 0 1 1 2 0 4 0 "; + std::vector expectWorkspaces = {16 * 1024 * 1024}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(RopeWithSinCosCacheTiling, test_tiling_fp32_true) +{ + RopeWithSinCosCacheCompileInfo compile_info = {}; + vector mropeParams{0, 0, 0}; + gert::TilingContextPara tilingContextPara( + "RopeWithSinCosCache", + { + {{{48, 48}, {48, 48}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{48, 256}, {48, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{48, 128}, {48, 128}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + { + {{{48, 256}, {48, 256}}, ge::DT_FLOAT, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT, ge::FORMAT_ND}, + }, + {{"numQHeads", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"numKHeads", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"headSize", Ops::Transformer::AnyValue::CreateFrom(128)}, + {"mropeSection", Ops::Transformer::AnyValue::CreateFrom>(mropeParams)}, + {"qstride", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"kstride", Ops::Transformer::AnyValue::CreateFrom(512)}, + {"isNeoxStyle", Ops::Transformer::AnyValue::CreateFrom(1)}, + {"cacheMode", Ops::Transformer::AnyValue::CreateFrom(0)}}, + &compile_info); + uint64_t expectTilingKey = 22; + string expectTilingData = "48 48 2 4 128 128 0 0 0 0 256 512 1 0 48 0 1 0 1 0 1 0 0 0 0 1 1 2 0 4 0 "; + std::vector expectWorkspaces = {16 * 1024 * 1024}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(RopeWithSinCosCacheTiling, test_tiling_bf16_false) +{ + RopeWithSinCosCacheCompileInfo compile_info = {}; + vector mropeParams{0, 0, 0}; + gert::TilingContextPara tilingContextPara( + "RopeWithSinCosCache", + { + {{{48, 48}, {48, 48}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{48, 256}, {48, 256}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{48, 128}, {48, 128}}, ge::DT_BF16, ge::FORMAT_ND}, + }, + { + {{{48, 256}, {48, 256}}, ge::DT_BF16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_BF16, ge::FORMAT_ND}, + }, + {{"numQHeads", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"numKHeads", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"headSize", Ops::Transformer::AnyValue::CreateFrom(128)}, + {"mropeSection", Ops::Transformer::AnyValue::CreateFrom>(mropeParams)}, + {"qstride", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"kstride", Ops::Transformer::AnyValue::CreateFrom(512)}, + {"isNeoxStyle", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"cacheMode", Ops::Transformer::AnyValue::CreateFrom(0)}}, + &compile_info); + uint64_t expectTilingKey = 20; + string expectTilingData = "48 48 2 4 128 128 0 0 0 0 256 512 0 0 48 0 1 0 1 0 1 0 0 0 0 1 1 2 0 4 0 "; + std::vector expectWorkspaces = {16 * 1024 * 1024}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(RopeWithSinCosCacheTiling, test_tiling_fp16_false) +{ + RopeWithSinCosCacheCompileInfo compile_info = {}; + vector mropeParams{0, 0, 0}; + gert::TilingContextPara tilingContextPara( + "RopeWithSinCosCache", + { + {{{48, 48}, {48, 48}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{48, 256}, {48, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 128}, {48, 128}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{48, 256}, {48, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + {{"numQHeads", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"numKHeads", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"headSize", Ops::Transformer::AnyValue::CreateFrom(128)}, + {"mropeSection", Ops::Transformer::AnyValue::CreateFrom>(mropeParams)}, + {"qstride", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"kstride", Ops::Transformer::AnyValue::CreateFrom(512)}, + {"isNeoxStyle", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"cacheMode", Ops::Transformer::AnyValue::CreateFrom(0)}}, + &compile_info); + uint64_t expectTilingKey = 21; + string expectTilingData = "48 48 2 4 128 128 0 0 0 0 256 512 0 0 48 0 1 0 1 0 1 0 0 0 0 1 1 2 0 4 0 "; + std::vector expectWorkspaces = {16 * 1024 * 1024}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(RopeWithSinCosCacheTiling, test_tiling_fp32_false) +{ + RopeWithSinCosCacheCompileInfo compile_info = {}; + vector mropeParams{0, 0, 0}; + gert::TilingContextPara tilingContextPara( + "RopeWithSinCosCache", + { + {{{48, 48}, {48, 48}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{48, 256}, {48, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 128}, {48, 128}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{48, 256}, {48, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + {{"numQHeads", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"numKHeads", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"headSize", Ops::Transformer::AnyValue::CreateFrom(128)}, + {"mropeSection", Ops::Transformer::AnyValue::CreateFrom>(mropeParams)}, + {"qstride", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"kstride", Ops::Transformer::AnyValue::CreateFrom(512)}, + {"isNeoxStyle", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"cacheMode", Ops::Transformer::AnyValue::CreateFrom(0)}}, + &compile_info); + uint64_t expectTilingKey = 21; + string expectTilingData = "48 48 2 4 128 128 0 0 0 0 256 512 0 0 48 0 1 0 1 0 1 0 0 0 0 1 1 2 0 4 0 "; + std::vector expectWorkspaces = {16 * 1024 * 1024}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(RopeWithSinCosCacheTiling, test_v2_tiling_fp32_false_cache1) +{ + RopeWithSinCosCacheCompileInfo compile_info = {}; + vector mropeParams{16, 24, 24}; + gert::TilingContextPara tilingContextPara( + "RopeWithSinCosCache", + { + {{{48, 48}, {48, 48}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{48, 256}, {48, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 128}, {48, 128}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{48, 256}, {48, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + {{"numQHeads", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"numKHeads", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"headSize", Ops::Transformer::AnyValue::CreateFrom(128)}, + {"mropeSection", Ops::Transformer::AnyValue::CreateFrom>(mropeParams)}, + {"qstride", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"kstride", Ops::Transformer::AnyValue::CreateFrom(512)}, + {"isNeoxStyle", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"cacheMode", Ops::Transformer::AnyValue::CreateFrom(1)}}, + &compile_info); + uint64_t expectTilingKey = 21; + string expectTilingData = "48 48 2 4 128 128 16 24 24 0 256 512 0 1 48 0 1 0 1 0 1 0 0 0 0 1 1 2 0 4 0 "; + std::vector expectWorkspaces = {16 * 1024 * 1024}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} + +TEST_F(RopeWithSinCosCacheTiling, test_v2_tiling_fp32_false_cache0_sectionsize4) +{ + RopeWithSinCosCacheCompileInfo compile_info = {}; + vector mropeParams{16, 16, 16, 16}; + gert::TilingContextPara tilingContextPara( + "RopeWithSinCosCache", + { + {{{48, 48}, {48, 48}}, ge::DT_INT64, ge::FORMAT_ND}, + {{{48, 256}, {48, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 128}, {48, 128}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + { + {{{48, 256}, {48, 256}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + {{{48, 512}, {48, 512}}, ge::DT_FLOAT16, ge::FORMAT_ND}, + }, + {{"numQHeads", Ops::Transformer::AnyValue::CreateFrom(2)}, + {"numKHeads", Ops::Transformer::AnyValue::CreateFrom(4)}, + {"headSize", Ops::Transformer::AnyValue::CreateFrom(128)}, + {"mropeSection", Ops::Transformer::AnyValue::CreateFrom>(mropeParams)}, + {"qstride", Ops::Transformer::AnyValue::CreateFrom(256)}, + {"kstride", Ops::Transformer::AnyValue::CreateFrom(512)}, + {"isNeoxStyle", Ops::Transformer::AnyValue::CreateFrom(0)}, + {"cacheMode", Ops::Transformer::AnyValue::CreateFrom(0)}}, + &compile_info); + uint64_t expectTilingKey = 21; + string expectTilingData = "48 48 2 4 128 128 16 16 16 16 256 512 0 0 48 0 1 0 1 0 1 0 0 0 0 1 1 2 0 4 0 "; + std::vector expectWorkspaces = {16 * 1024 * 1024}; + ExecuteTestCase(tilingContextPara, ge::GRAPH_SUCCESS, expectTilingKey, expectTilingData, expectWorkspaces); +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_kernel/CMakeLists.txt b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_kernel/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5d29805ce8dc1b502caa549ac375b266fbf5b29b --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_kernel/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_KERNEL_UT) + # 算子自己的tiling文件路径 + set(rope_with_sin_cos_cache_tiling_files + ${CMAKE_CURRENT_SOURCE_DIR}/../../../op_host/rope_with_sin_cos_cache_tiling.cpp + ) + # 使用AddOpTestCase + # param1:算子名称,以kernel方式命名 + # param2:soc版本,多个以分号分隔,例如:"Ascend950PR_9599;AscendB1" + # param3:自定义编译选项,一般填写测试的一种典型数据类型组合,不需要则传入空字符串,例如:"-DDTYPE_X=float",多个使用空格分隔,例如:"-DDTYPE_X=float -DDTYPE_Y=float" + # param4:该算子依赖的所有tiling源码文件 + AddOpTestCase(rope_with_sin_cos_cache "ascend910B1" "-DDTYPE_X=float" "${rope_with_sin_cos_cache_tiling_files}") +endif() diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_kernel/rope_with_sin_cos_cache_data/gen_data.py b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_kernel/rope_with_sin_cos_cache_data/gen_data.py new file mode 100644 index 0000000000000000000000000000000000000000..fa5c8e4b0a699576c7eac0b6b2012b8bd1c4bd3e --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_kernel/rope_with_sin_cos_cache_data/gen_data.py @@ -0,0 +1,49 @@ +#!/usr/bin/python3 +# -*- coding:utf-8 -*- +# ----------------------------------------------------------------------------------------------------------- +# 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. +# ----------------------------------------------------------------------------------------------------------- +import sys +import numpy as np +import torch +import tensorflow as tf +import os + +bf16 = tf.bfloat16.as_numpy_dtype +np.random.seed(0) + +def gen_golden_data_simple(numTokens, numQHeads, numKHeads, headSize, rotaryDim, dtype): + d_type_dict = { + "fp32": np.float32, + "fp16": np.float16, + "bf16": bf16 + } + + dtype = d_type_dict.get(dtype) + + data_position = np.random.uniform(1, int(numTokens), [int(numTokens)]).astype(np.int64) + data_query = np.random.uniform(-2, 2, [int(numTokens), int(numQHeads) * int(headSize)]).astype(dtype) + data_key = np.random.uniform(-2, 2, [int(numTokens), int(numKHeads) * int(headSize)]).astype(dtype) + data_cosSinCache = np.random.uniform(-2, 2, [int(numTokens), int(rotaryDim)]).astype(dtype) + + data_position.tofile("./input_position.bin") + data_query.tofile("./input_query.bin") + data_key.tofile("./input_key.bin") + data_cosSinCache.tofile("./input_cosSinCache.bin") + + data_queryOut = data_query + data_keyOut = data_key + + data_queryOut.tofile("./output_queryOut.bin") + data_keyOut.tofile("./output_keyOut.bin") + + +if __name__ == "__main__": + os.system("rm -rf *.bin") + gen_golden_data_simple(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5],sys.argv[6]) diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_kernel/test_rope_with_sin_cos_cache.cpp b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_kernel/test_rope_with_sin_cos_cache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3d0b1d5681cc142221c11fa213f891a5f0aabca3 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_kernel/test_rope_with_sin_cos_cache.cpp @@ -0,0 +1,436 @@ +/** + * 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 "tikicpulib.h" +#include "test_rope_with_sin_cos_cache.h" +#include "data_utils.h" + +#include + +using namespace std; + +extern "C" __global__ __aicore__ void rope_with_sin_cos_cache( + GM_ADDR positions, GM_ADDR queryIn, GM_ADDR keyIn, GM_ADDR cosSinCache, GM_ADDR queryOut, GM_ADDR keyOut, + GM_ADDR workspace, GM_ADDR tiling); + +class rope_with_sin_cos_cache_test : public testing::Test +{ +protected: + static void SetUpTestCase() + { + std::cout << "rope_with_sin_cos_cache_test SetUp\n" << std::endl; + } + static void TearDownTestCase() + { + std::cout << "rope_with_sin_cos_cache_test TearDown\n" << std::endl; + } +}; + +TEST_F(rope_with_sin_cos_cache_test, test_case_bf16) +{ + system( + "cp -rf " + "../../../../../posembedding/rope_with_sin_cos_cache/tests/ut/op_kernel/rope_with_sin_cos_cache_data ./"); + system("chmod -R 755 ./rope_with_sin_cos_cache_data/"); + system("cd ./rope_with_sin_cos_cache_data/ && python3 gen_data.py '48' '2' '4' '128' '128' 'bf16' "); + AscendC::SetKernelMode(KernelMode::AIV_MODE); + uint64_t numTokens = 48; + uint64_t numQHeads = 2; + uint64_t numKHeads = 4; + uint64_t headSize = 128; + uint64_t rotaryDim = 128; + + size_t positionSize = numTokens * sizeof(int64_t); + size_t querySize = numTokens * numQHeads * headSize * sizeof(half); + size_t keySize = numTokens * numKHeads * headSize * sizeof(half); + size_t cosSinCacheSize = numTokens * rotaryDim * sizeof(half); + size_t queryOutSize = numTokens * numQHeads * headSize * sizeof(half); + size_t keyOutSize = numTokens * numKHeads * headSize * sizeof(half); + + size_t tilingSize = sizeof(RopeWithSinCosCacheTilingData); + + uint8_t* position = (uint8_t*)AscendC::GmAlloc(positionSize); + uint8_t* query = (uint8_t*)AscendC::GmAlloc(querySize); + uint8_t* key = (uint8_t*)AscendC::GmAlloc(keySize); + uint8_t* cosSinCache = (uint8_t*)AscendC::GmAlloc(cosSinCacheSize); + uint8_t* queryOut = (uint8_t*)AscendC::GmAlloc(queryOutSize); + uint8_t* keyOut = (uint8_t*)AscendC::GmAlloc(keyOutSize); + + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(1024 * 1024 * 1024); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tilingSize); + uint32_t blockDim = 48; + + RopeWithSinCosCacheTilingData* tilingData = reinterpret_cast(tiling); + tilingData->core_num_use = 48; + tilingData->num_tokens = 48; + tilingData->num_q_heads = 2; + tilingData->num_kv_heads = 4; + tilingData->head_size = 128; + tilingData->rotary_dim = 128; + tilingData->mrope_section0 = 0; + tilingData->mrope_section1 = 0; + tilingData->mrope_section2 = 0; + tilingData->q_leading_dimension = 256; + tilingData->k_leading_dimension = 512; + tilingData->isNeoxStyle = 1; + tilingData->front_core = 48; + tilingData->tail_core = 0; + tilingData->num_tokens_each_front_core = 1; + tilingData->num_tokens_each_tail_core = 1; + tilingData->num_tokens_front_core_each_loop = 1; + tilingData->num_tokens_tail_core_each_loop = 1; + tilingData->loop_time_each_front_core = 1; + tilingData->loop_time_each_tail_core = 1; + tilingData->num_tokens_front_core_last_loop = 0; + tilingData->num_tokens_tail_core_last_loop = 0; + + ReadFile("./rope_with_sin_cos_cache_data/input_position.bin", positionSize, position, positionSize); + ReadFile("./rope_with_sin_cos_cache_data/input_query.bin", querySize, query, querySize); + ReadFile("./rope_with_sin_cos_cache_data/input_key.bin", keySize, key, keySize); + ReadFile("./rope_with_sin_cos_cache_data/input_cosSinCache.bin", cosSinCacheSize, cosSinCache, cosSinCacheSize); + ReadFile("./rope_with_sin_cos_cache_data/output_queryOut.bin", queryOutSize, queryOut, queryOutSize); + ReadFile("./rope_with_sin_cos_cache_data/output_keyOut.bin", keyOutSize, keyOut, keyOutSize); + + ICPU_SET_TILING_KEY(20); + ICPU_RUN_KF( + rope_with_sin_cos_cache, blockDim, position, query, key, cosSinCache, queryOut, keyOut, workspace, tiling); + + AscendC::GmFree(position); + AscendC::GmFree(query); + AscendC::GmFree(key); + AscendC::GmFree(cosSinCache); + AscendC::GmFree(queryOut); + AscendC::GmFree(keyOut); + AscendC::GmFree(workspace); + AscendC::GmFree(tiling); +} + +TEST_F(rope_with_sin_cos_cache_test, test_case_fp32) +{ + system( + "cp -rf " + "../../../../../posembedding/rope_with_sin_cos_cache/tests/ut/op_kernel/rope_with_sin_cos_cache_data ./"); + system("chmod -R 755 ./rope_with_sin_cos_cache_data/"); + system("cd ./rope_with_sin_cos_cache_data/ && python3 gen_data.py '48' '2' '4' '128' '128' 'fp32' "); + AscendC::SetKernelMode(KernelMode::AIV_MODE); + uint64_t numTokens = 48; + uint64_t numQHeads = 2; + uint64_t numKHeads = 4; + uint64_t headSize = 128; + uint64_t rotaryDim = 128; + + size_t positionSize = numTokens * sizeof(int64_t); + size_t querySize = numTokens * numQHeads * headSize * sizeof(float); + size_t keySize = numTokens * numKHeads * headSize * sizeof(float); + size_t cosSinCacheSize = numTokens * rotaryDim * sizeof(float); + size_t queryOutSize = numTokens * numQHeads * headSize * sizeof(float); + size_t keyOutSize = numTokens * numKHeads * headSize * sizeof(float); + + size_t tilingSize = sizeof(RopeWithSinCosCacheTilingData); + + uint8_t* position = (uint8_t*)AscendC::GmAlloc(positionSize); + uint8_t* query = (uint8_t*)AscendC::GmAlloc(querySize); + uint8_t* key = (uint8_t*)AscendC::GmAlloc(keySize); + uint8_t* cosSinCache = (uint8_t*)AscendC::GmAlloc(cosSinCacheSize); + uint8_t* queryOut = (uint8_t*)AscendC::GmAlloc(queryOutSize); + uint8_t* keyOut = (uint8_t*)AscendC::GmAlloc(keyOutSize); + + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(1024 * 1024 * 1024); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tilingSize); + uint32_t blockDim = 48; + + RopeWithSinCosCacheTilingData* tilingData = reinterpret_cast(tiling); + tilingData->core_num_use = 48; + tilingData->num_tokens = 48; + tilingData->num_q_heads = 2; + tilingData->num_kv_heads = 4; + tilingData->head_size = 128; + tilingData->rotary_dim = 128; + tilingData->mrope_section0 = 0; + tilingData->mrope_section1 = 0; + tilingData->mrope_section2 = 0; + tilingData->q_leading_dimension = 256; + tilingData->k_leading_dimension = 512; + tilingData->isNeoxStyle = 1; + tilingData->front_core = 48; + tilingData->tail_core = 0; + tilingData->num_tokens_each_front_core = 1; + tilingData->num_tokens_each_tail_core = 1; + tilingData->num_tokens_front_core_each_loop = 1; + tilingData->num_tokens_tail_core_each_loop = 1; + tilingData->loop_time_each_front_core = 1; + tilingData->loop_time_each_tail_core = 1; + tilingData->num_tokens_front_core_last_loop = 0; + tilingData->num_tokens_tail_core_last_loop = 0; + + ReadFile("./rope_with_sin_cos_cache_data/input_position.bin", positionSize, position, positionSize); + ReadFile("./rope_with_sin_cos_cache_data/input_query.bin", querySize, query, querySize); + ReadFile("./rope_with_sin_cos_cache_data/input_key.bin", keySize, key, keySize); + ReadFile("./rope_with_sin_cos_cache_data/input_cosSinCache.bin", cosSinCacheSize, cosSinCache, cosSinCacheSize); + ReadFile("./rope_with_sin_cos_cache_data/output_queryOut.bin", queryOutSize, queryOut, queryOutSize); + ReadFile("./rope_with_sin_cos_cache_data/output_keyOut.bin", keyOutSize, keyOut, keyOutSize); + + ICPU_SET_TILING_KEY(22); + ICPU_RUN_KF( + rope_with_sin_cos_cache, blockDim, position, query, key, cosSinCache, queryOut, keyOut, workspace, tiling); + + AscendC::GmFree(position); + AscendC::GmFree(query); + AscendC::GmFree(key); + AscendC::GmFree(cosSinCache); + AscendC::GmFree(queryOut); + AscendC::GmFree(keyOut); + AscendC::GmFree(workspace); + AscendC::GmFree(tiling); +} + +TEST_F(rope_with_sin_cos_cache_test, test_case_fp16) +{ + system( + "cp -rf " + "../../../../../posembedding/rope_with_sin_cos_cache/tests/ut/op_kernel/rope_with_sin_cos_cache_data ./"); + system("chmod -R 755 ./rope_with_sin_cos_cache_data/"); + system("cd ./rope_with_sin_cos_cache_data/ && python3 gen_data.py '48' '2' '4' '128' '128' 'fp16' "); + AscendC::SetKernelMode(KernelMode::AIV_MODE); + uint64_t numTokens = 48; + uint64_t numQHeads = 2; + uint64_t numKHeads = 4; + uint64_t headSize = 128; + uint64_t rotaryDim = 128; + + size_t positionSize = numTokens * sizeof(int64_t); + size_t querySize = numTokens * numQHeads * headSize * sizeof(half); + size_t keySize = numTokens * numKHeads * headSize * sizeof(half); + size_t cosSinCacheSize = numTokens * rotaryDim * sizeof(half); + size_t queryOutSize = numTokens * numQHeads * headSize * sizeof(half); + size_t keyOutSize = numTokens * numKHeads * headSize * sizeof(half); + + size_t tilingSize = sizeof(RopeWithSinCosCacheTilingData); + + uint8_t* position = (uint8_t*)AscendC::GmAlloc(positionSize); + uint8_t* query = (uint8_t*)AscendC::GmAlloc(querySize); + uint8_t* key = (uint8_t*)AscendC::GmAlloc(keySize); + uint8_t* cosSinCache = (uint8_t*)AscendC::GmAlloc(cosSinCacheSize); + uint8_t* queryOut = (uint8_t*)AscendC::GmAlloc(queryOutSize); + uint8_t* keyOut = (uint8_t*)AscendC::GmAlloc(keyOutSize); + + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(1024 * 1024 * 1024); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tilingSize); + uint32_t blockDim = 48; + + RopeWithSinCosCacheTilingData* tilingData = reinterpret_cast(tiling); + tilingData->core_num_use = 48; + tilingData->num_tokens = 48; + tilingData->num_q_heads = 2; + tilingData->num_kv_heads = 4; + tilingData->head_size = 128; + tilingData->rotary_dim = 128; + tilingData->mrope_section0 = 0; + tilingData->mrope_section1 = 0; + tilingData->mrope_section2 = 0; + tilingData->q_leading_dimension = 256; + tilingData->k_leading_dimension = 512; + tilingData->isNeoxStyle = 1; + tilingData->front_core = 48; + tilingData->tail_core = 0; + tilingData->num_tokens_each_front_core = 1; + tilingData->num_tokens_each_tail_core = 1; + tilingData->num_tokens_front_core_each_loop = 1; + tilingData->num_tokens_tail_core_each_loop = 1; + tilingData->loop_time_each_front_core = 1; + tilingData->loop_time_each_tail_core = 1; + tilingData->num_tokens_front_core_last_loop = 0; + tilingData->num_tokens_tail_core_last_loop = 0; + + ReadFile("./rope_with_sin_cos_cache_data/input_position.bin", positionSize, position, positionSize); + ReadFile("./rope_with_sin_cos_cache_data/input_query.bin", querySize, query, querySize); + ReadFile("./rope_with_sin_cos_cache_data/input_key.bin", keySize, key, keySize); + ReadFile("./rope_with_sin_cos_cache_data/input_cosSinCache.bin", cosSinCacheSize, cosSinCache, cosSinCacheSize); + ReadFile("./rope_with_sin_cos_cache_data/output_queryOut.bin", queryOutSize, queryOut, queryOutSize); + ReadFile("./rope_with_sin_cos_cache_data/output_keyOut.bin", keyOutSize, keyOut, keyOutSize); + + ICPU_SET_TILING_KEY(21); + ICPU_RUN_KF( + rope_with_sin_cos_cache, blockDim, position, query, key, cosSinCache, queryOut, keyOut, workspace, tiling); + + AscendC::GmFree(position); + AscendC::GmFree(query); + AscendC::GmFree(key); + AscendC::GmFree(cosSinCache); + AscendC::GmFree(queryOut); + AscendC::GmFree(keyOut); + AscendC::GmFree(workspace); + AscendC::GmFree(tiling); +} + +TEST_F(rope_with_sin_cos_cache_test, test_case_fp32_2) +{ + system( + "cp -rf " + "../../../../../posembedding/rope_with_sin_cos_cache/tests/ut/op_kernel/rope_with_sin_cos_cache_data ./"); + system("chmod -R 755 ./rope_with_sin_cos_cache_data/"); + system("cd ./rope_with_sin_cos_cache_data/ && python3 gen_data.py '48' '2' '4' '128' '128' 'fp32' "); + AscendC::SetKernelMode(KernelMode::AIV_MODE); + uint64_t numTokens = 48; + uint64_t numQHeads = 2; + uint64_t numKHeads = 4; + uint64_t headSize = 128; + uint64_t rotaryDim = 128; + + size_t positionSize = numTokens * sizeof(int64_t); + size_t querySize = numTokens * numQHeads * headSize * sizeof(float); + size_t keySize = numTokens * numKHeads * headSize * sizeof(float); + size_t cosSinCacheSize = numTokens * rotaryDim * sizeof(float); + size_t queryOutSize = numTokens * numQHeads * headSize * sizeof(float); + size_t keyOutSize = numTokens * numKHeads * headSize * sizeof(float); + + size_t tilingSize = sizeof(RopeWithSinCosCacheTilingData); + + uint8_t* position = (uint8_t*)AscendC::GmAlloc(positionSize); + uint8_t* query = (uint8_t*)AscendC::GmAlloc(querySize); + uint8_t* key = (uint8_t*)AscendC::GmAlloc(keySize); + uint8_t* cosSinCache = (uint8_t*)AscendC::GmAlloc(cosSinCacheSize); + uint8_t* queryOut = (uint8_t*)AscendC::GmAlloc(queryOutSize); + uint8_t* keyOut = (uint8_t*)AscendC::GmAlloc(keyOutSize); + + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(1024 * 1024 * 1024); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tilingSize); + uint32_t blockDim = 48; + + RopeWithSinCosCacheTilingData* tilingData = reinterpret_cast(tiling); + tilingData->core_num_use = 48; + tilingData->num_tokens = 48; + tilingData->num_q_heads = 2; + tilingData->num_kv_heads = 4; + tilingData->head_size = 128; + tilingData->rotary_dim = 128; + tilingData->mrope_section0 = 0; + tilingData->mrope_section1 = 0; + tilingData->mrope_section2 = 0; + tilingData->q_leading_dimension = 256; + tilingData->k_leading_dimension = 512; + tilingData->isNeoxStyle = 1; + tilingData->front_core = 48; + tilingData->tail_core = 0; + tilingData->num_tokens_each_front_core = 1; + tilingData->num_tokens_each_tail_core = 1; + tilingData->num_tokens_front_core_each_loop = 1; + tilingData->num_tokens_tail_core_each_loop = 1; + tilingData->loop_time_each_front_core = 1; + tilingData->loop_time_each_tail_core = 1; + tilingData->num_tokens_front_core_last_loop = 0; + tilingData->num_tokens_tail_core_last_loop = 0; + + ReadFile("./rope_with_sin_cos_cache_data/input_position.bin", positionSize, position, positionSize); + ReadFile("./rope_with_sin_cos_cache_data/input_query.bin", querySize, query, querySize); + ReadFile("./rope_with_sin_cos_cache_data/input_key.bin", keySize, key, keySize); + ReadFile("./rope_with_sin_cos_cache_data/input_cosSinCache.bin", cosSinCacheSize, cosSinCache, cosSinCacheSize); + ReadFile("./rope_with_sin_cos_cache_data/output_queryOut.bin", queryOutSize, queryOut, queryOutSize); + ReadFile("./rope_with_sin_cos_cache_data/output_keyOut.bin", keyOutSize, keyOut, keyOutSize); + + ICPU_SET_TILING_KEY(22); + ICPU_RUN_KF( + rope_with_sin_cos_cache, blockDim, position, query, key, cosSinCache, queryOut, keyOut, workspace, tiling); + + AscendC::GmFree(position); + AscendC::GmFree(query); + AscendC::GmFree(key); + AscendC::GmFree(cosSinCache); + AscendC::GmFree(queryOut); + AscendC::GmFree(keyOut); + AscendC::GmFree(workspace); + AscendC::GmFree(tiling); +} + +TEST_F(rope_with_sin_cos_cache_test, test_case_v2_fp32) +{ + system( + "cp -rf " + "../../../../../posembedding/rope_with_sin_cos_cache/tests/ut/op_kernel/rope_with_sin_cos_cache_data ./"); + system("chmod -R 755 ./rope_with_sin_cos_cache_data/"); + system("cd ./rope_with_sin_cos_cache_data/ && python3 gen_data.py '48' '2' '4' '128' '128' 'fp32' "); + AscendC::SetKernelMode(KernelMode::AIV_MODE); + uint64_t numTokens = 48; + uint64_t numQHeads = 2; + uint64_t numKHeads = 4; + uint64_t headSize = 128; + uint64_t rotaryDim = 128; + + size_t positionSize = numTokens * sizeof(int64_t); + size_t querySize = numTokens * numQHeads * headSize * sizeof(float); + size_t keySize = numTokens * numKHeads * headSize * sizeof(float); + size_t cosSinCacheSize = numTokens * rotaryDim * sizeof(float); + size_t queryOutSize = numTokens * numQHeads * headSize * sizeof(float); + size_t keyOutSize = numTokens * numKHeads * headSize * sizeof(float); + + size_t tilingSize = sizeof(RopeWithSinCosCacheTilingData); + + uint8_t* position = (uint8_t*)AscendC::GmAlloc(positionSize); + uint8_t* query = (uint8_t*)AscendC::GmAlloc(querySize); + uint8_t* key = (uint8_t*)AscendC::GmAlloc(keySize); + uint8_t* cosSinCache = (uint8_t*)AscendC::GmAlloc(cosSinCacheSize); + uint8_t* queryOut = (uint8_t*)AscendC::GmAlloc(queryOutSize); + uint8_t* keyOut = (uint8_t*)AscendC::GmAlloc(keyOutSize); + + uint8_t* workspace = (uint8_t*)AscendC::GmAlloc(1024 * 1024 * 1024); + uint8_t* tiling = (uint8_t*)AscendC::GmAlloc(tilingSize); + uint32_t blockDim = 48; + + RopeWithSinCosCacheTilingData* tilingData = reinterpret_cast(tiling); + tilingData->core_num_use = 48; + tilingData->num_tokens = 48; + tilingData->num_q_heads = 2; + tilingData->num_kv_heads = 4; + tilingData->head_size = 128; + tilingData->rotary_dim = 128; + tilingData->mrope_section0 = 0; + tilingData->mrope_section1 = 0; + tilingData->mrope_section2 = 0; + tilingData->q_leading_dimension = 256; + tilingData->k_leading_dimension = 512; + tilingData->isNeoxStyle = 1; + tilingData->cacheMode = 1; + tilingData->front_core = 48; + tilingData->tail_core = 0; + tilingData->num_tokens_each_front_core = 1; + tilingData->num_tokens_each_tail_core = 1; + tilingData->num_tokens_front_core_each_loop = 1; + tilingData->num_tokens_tail_core_each_loop = 1; + tilingData->loop_time_each_front_core = 1; + tilingData->loop_time_each_tail_core = 1; + tilingData->num_tokens_front_core_last_loop = 0; + tilingData->num_tokens_tail_core_last_loop = 0; + + ReadFile("./rope_with_sin_cos_cache_data/input_position.bin", positionSize, position, positionSize); + ReadFile("./rope_with_sin_cos_cache_data/input_query.bin", querySize, query, querySize); + ReadFile("./rope_with_sin_cos_cache_data/input_key.bin", keySize, key, keySize); + ReadFile("./rope_with_sin_cos_cache_data/input_cosSinCache.bin", cosSinCacheSize, cosSinCache, cosSinCacheSize); + ReadFile("./rope_with_sin_cos_cache_data/output_queryOut.bin", queryOutSize, queryOut, queryOutSize); + ReadFile("./rope_with_sin_cos_cache_data/output_keyOut.bin", keyOutSize, keyOut, keyOutSize); + + ICPU_SET_TILING_KEY(22); + ICPU_RUN_KF( + rope_with_sin_cos_cache, blockDim, position, query, key, cosSinCache, queryOut, keyOut, workspace, tiling); + + AscendC::GmFree(position); + AscendC::GmFree(query); + AscendC::GmFree(key); + AscendC::GmFree(cosSinCache); + AscendC::GmFree(queryOut); + AscendC::GmFree(keyOut); + AscendC::GmFree(workspace); + AscendC::GmFree(tiling); +} \ No newline at end of file diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_kernel/test_rope_with_sin_cos_cache.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_kernel/test_rope_with_sin_cos_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..4e55cda1e826632cb0738856cd78cac44e8799bb --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/rope_with_sin_cos_cache/tests/ut/op_kernel/test_rope_with_sin_cos_cache.h @@ -0,0 +1,32 @@ +/** + * 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 _ROPE_WITH_SIN_COS_CACHE_H +#define _ROPE_WITH_SIN_COS_CACHE_H + +#include "kernel_tiling/kernel_tiling.h" + +#include +#include + +#define DT_BF16 bfloat16_t +#define ORIG_DTYPE_START DT_BF16 +#define __CCE_UT_TEST__ +#define ORIG_DTYPE_QUERYIN DT_FLOAT + +inline void InitRopeWithSinCosCacheTilingData(uint8_t* tiling, RopeWithSinCosCacheTilingData* const_data) +{ + memcpy(const_data, tiling, sizeof(RopeWithSinCosCacheTilingData)); +} + +#define GET_TILING_DATA(tilingData, tilingPointer) \ + RopeWithSinCosCacheTilingData tilingData; \ + InitRopeWithSinCosCacheTilingData(tilingPointer, &tilingData) +#endif diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch22/sparse_flash_attention_kernel_mla.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch22/sparse_flash_attention_kernel_mla.h new file mode 100644 index 0000000000000000000000000000000000000000..8af849db05bc03c4b8093866528c9b5b16cbe223 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch22/sparse_flash_attention_kernel_mla.h @@ -0,0 +1,1031 @@ +/** + * 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_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_common.h" +#include "sparse_flash_attention_service_cube_mla.h" +#include "sparse_flash_attention_service_vector_mla.h" + +using namespace matmul; +using AscendC::CacheMode; +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +// 由于S2循环前,RunInfo还没有赋值,使用Bngs1Param临时存放B、N、S1轴相关的信息;同时减少重复计算 +struct TempLoopInfo { + uint32_t bn2IdxInCurCore = 0; + uint32_t bIdx = 0U; + uint32_t n2Idx = 0U; + uint32_t s2LoopTimes = 0U; // S2方向循环的总次数,无论TND还是BXXD都是等于实际次数,不用减1 + uint64_t s2BasicSizeTail = 0U; // S2方向循环的尾基本块大小 + uint64_t curActualSeqLen = 0ULL; + uint64_t curActualSeqLenOri = 0ULL; + uint64_t actS1Size = 1ULL; // TND场景下当前Batch循环处理的S1轴的大小 + int32_t nextTokensPerBatch = 0; + uint32_t tndCoreStartKVSplitPos; + uint64_t mBasicSizeTail = 0U; // gS1方向循环的尾基本块大小 + uint32_t gS1Idx = 0U; + bool curActSeqLenIsZero = false; + bool tndIsS2SplitCore; +}; + +template +class SparseFlashAttentionMla { +public: + // 中间计算数据类型为float,高精度模式 + using T = float; + using Q_T = typename SFAT::queryType; + using KV_T = typename SFAT::kvType; + using OUT_T = typename SFAT::outputType; + using Q_ROPE_T = Q_T; + using K_ROPE_T = KV_T; + using UPDATE_T = T; + using MM1_OUT_T = T; + using MM2_OUT_T = T; + + __aicore__ inline SparseFlashAttentionMla(){}; + __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 *workspace, + const SparseFlashAttentionTilingDataMla *__restrict tiling, __gm__ uint8_t *gmTiling, + TPipe *tPipe); + + __aicore__ inline void Process(); + +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 PRELOAD_NUM = 2; + static constexpr uint32_t N_BUFFER_M_BASIC_SIZE = 256; + static constexpr uint32_t SFA_PRELOAD_TASK_CACHE_SIZE = 3; + + static constexpr uint32_t SYNC_V0_C1_FLAG = 6; + static constexpr uint32_t SYNC_C1_V1_FLAG = 7; + static constexpr uint32_t SYNC_V1_C2_FLAG = 8; + static constexpr uint32_t SYNC_C2_V2_FLAG = 9; + static constexpr uint32_t SYNC_C2_V1_FLAG = 4; + static constexpr uint32_t SYNC_V1_NUPDATE_C2_FLAG = 5; + + static constexpr uint64_t SYNC_MM2RES_BUF1_FLAG = 10; + static constexpr uint64_t SYNC_MM2RES_BUF2_FLAG = 11; + static constexpr uint64_t SYNC_FDOUTPUT_BUF_FLAG = 12; + + static constexpr uint32_t BLOCK_ELEMENT_NUM = SFAVectorService::BYTE_BLOCK / sizeof(T); + + static constexpr uint64_t kvHeadNum = 1ULL; + static constexpr uint64_t headDim = 512ULL; + static constexpr uint64_t headDimAlign = 512ULL; + static constexpr uint64_t headDimRope = 64ULL; + static constexpr uint32_t msdIterNum = 2U; + + static constexpr uint32_t dbWorkspaceRatio = PRELOAD_NUM; + + const SparseFlashAttentionTilingDataMla *__restrict tilingData = nullptr; + + TPipe *pipe = nullptr; + + uint64_t mSizeVStart = 0ULL; + int64_t threshold = 0; + uint64_t topKBaseOffset = 0ULL; + uint64_t s2BatchBaseOffset = 0; + uint64_t tensorACoreOffset = 0ULL; + uint64_t tensorBCoreOffset = 0ULL; + uint64_t tensorARopeCoreOffset = 0ULL; + uint64_t tensorBRopeCoreOffset = 0ULL; + uint64_t tensorBOffset = 0ULL; + uint64_t attenOutOffset = 0ULL; + + uint32_t tmpBlockIdx = 0U; + uint32_t aiCoreIdx = 0U; + uint32_t usedCoreNum = 0U; + + __gm__ uint8_t *keyPtr = nullptr; + __gm__ uint8_t *valuePtr = nullptr; + + ConstInfo constInfo{}; + TempLoopInfo tempLoopInfo{}; + + SFAMatmulService matmulService; + SFAVectorService vectorService; + + GlobalTensor queryGm; + GlobalTensor keyGm; + GlobalTensor valueGm; + GlobalTensor qRopeGm; + GlobalTensor kRopeGm; + + GlobalTensor attentionOutGm; + GlobalTensor softmaxMaxGm; + GlobalTensor softmaxSumGm; + GlobalTensor blockTableGm; + GlobalTensor topKGm; + + GlobalTensor actualSeqLengthsQGm; + GlobalTensor actualSeqLengthsKVGm; + + // workspace + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor mm2ResGm; + GlobalTensor kvMergeGm_; + GlobalTensor kvValidSizeGm_; + + GlobalTensor mm2ResInt32Gm; + GlobalTensor vec2ResGm; + + GlobalTensor accumOutGm; + GlobalTensor lseSumFdGm; + GlobalTensor lseMaxFdGm; + + GlobalTensor lseSumFaGm; + GlobalTensor lseMaxFaGm; + + // ================================Init functions=================================== + __aicore__ inline void InitTilingData(); + __aicore__ inline void InitCalcParamsEach(); + __aicore__ inline void InitBuffers(); + __aicore__ inline void InitActualSeqLen(__gm__ uint8_t *actualSeqLengthsQ, __gm__ uint8_t *actualSeqLengths); + __aicore__ inline void InitOutputSingleCore(); + // ================================Process functions================================ + __aicore__ inline void ProcessBalance(); + __aicore__ inline void PreloadPipeline(uint32_t loop, uint64_t s2Start, uint64_t s2LoopIdx, + RunInfo extraInfo[SFA_PRELOAD_TASK_CACHE_SIZE], uint32_t &curTopKIdx, + uint64_t &curOffsetInSparseBlock); + // ================================Offset Calc===================================== + __aicore__ inline void GetActualSeqLen(uint32_t bIdx, uint32_t s1Idx = 0); + __aicore__ inline void GetSparseActualSeqLen(uint32_t bIdx, uint32_t s1Idx, uint32_t n2Idx); + __aicore__ inline void CalcSinnerTopKBegin(RunInfo &info, uint32_t &curTopKIdx, uint64_t &curOffsetInSparseBlock); + __aicore__ inline void UpdateInnerLoopCond(); + __aicore__ inline void DealActSeqLenIsZero(uint32_t bIdx, uint32_t s1Idx, uint32_t n2Idx); + __aicore__ inline void CalcParams(uint32_t loop, uint64_t s2Start, uint32_t s2LoopIdx, RunInfo &info); + __aicore__ inline void GetAxisStartIdx(uint32_t bN2EndPrev, uint32_t gS1EndPrev, uint32_t s2EndPrev); + __aicore__ inline uint64_t GetBalanceActualSeqLengths(GlobalTensor &actualSeqLengths, uint32_t bIdx); + __aicore__ inline uint32_t GetActualSeqLenKV(uint32_t bIdx); + __aicore__ inline void GetBN2Idx(uint32_t bN2Idx, uint32_t &bIdx, uint32_t &n2Idx); + __aicore__ inline void UpdateInner(uint32_t &s2End, uint32_t &curS2End, uint32_t s1Idx, bool isEnd); + __aicore__ inline void GetPreNextTokensLeftUp(); + // ================================Mm1============================================== + __aicore__ inline void ComputeMm1(const RunInfo &info); + // ================================Mm2============================================== + __aicore__ inline void ComputeMm2(const RunInfo &info); + __aicore__ inline void Bmm2DataCopyOut(uint64_t attenOutOffset, LocalTensor &attenOutUb, uint32_t startRow, + uint32_t dealRowCount, uint32_t columnCount, uint32_t actualColumnCount); + __aicore__ inline void InitAllZeroOutput(uint32_t bIdx, uint32_t s1Idx, uint32_t n2Idx); +}; + +template +__aicore__ inline void SparseFlashAttentionMla::InitTilingData() +{ + usedCoreNum = tilingData->singleCoreParams.usedCoreNum; + constInfo.splitKVNum = tilingData->splitKVParams.s2; + constInfo.mmResUbSize = tilingData->singleCoreTensorSize.mmResUbSize; + constInfo.bmm2ResUbSize = tilingData->singleCoreTensorSize.bmm2ResUbSize; + constInfo.vec1ResUbSize = constInfo.mmResUbSize * msdIterNum; + + constInfo.batchSize = tilingData->baseParams.batchSize; + constInfo.qHeadNum = constInfo.gSize = tilingData->baseParams.nNumOfQInOneGroup; + constInfo.kvSeqSize = tilingData->baseParams.seqSize; + constInfo.qSeqSize = tilingData->baseParams.qSeqSize; + constInfo.maxBlockNumPerBatch = tilingData->baseParams.maxBlockNumPerBatch; + constInfo.kvCacheBlockSize = tilingData->baseParams.blockSize; + constInfo.outputLayout = static_cast(tilingData->baseParams.outputLayout); + constInfo.mBaseSize = tilingData->innerSplitParams.mBaseSize; + constInfo.s2BaseSize = tilingData->innerSplitParams.s2BaseSize; + constInfo.kvHeadNum = kvHeadNum; + constInfo.headDim = headDim; + constInfo.headDimRope = headDimRope; + constInfo.sparseBlockSize = tilingData->baseParams.sparseBlockSize; + constInfo.sparseBlockCount = tilingData->baseParams.sparseBlockCount; + constInfo.sparseMode = tilingData->baseParams.sparseMode; + constInfo.preTokens = tilingData->baseParams.preTokens; + constInfo.nextTokens = tilingData->baseParams.nextTokens; + constInfo.attentionMode = tilingData->baseParams.attentionMode; + constInfo.returnSoftmaxLse = tilingData->baseParams.returnSoftmaxLse; + + constInfo.preLoadNum = PRELOAD_NUM; + constInfo.nBufferMBaseSize = N_BUFFER_M_BASIC_SIZE; + constInfo.syncV0C1 = SYNC_V0_C1_FLAG; + constInfo.syncC1V1 = SYNC_C1_V1_FLAG; + constInfo.syncV1C2 = SYNC_V1_C2_FLAG; + constInfo.syncC2V2 = SYNC_C2_V2_FLAG; + constInfo.syncC2V1 = SYNC_C2_V1_FLAG; + constInfo.syncV1NupdateC2 = SYNC_V1_NUPDATE_C2_FLAG; +} + +template +__aicore__ inline void SparseFlashAttentionMla::InitBuffers() +{ + if ASCEND_IS_AIV { + vectorService.InitBuffers(pipe); + } else { + matmulService.InitBuffers(pipe); + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::InitActualSeqLen(__gm__ uint8_t *actualSeqLengthsQ, + __gm__ uint8_t *actualSeqLengths) +{ + constInfo.actualLenDimsQ = tilingData->baseParams.actualLenDimsQ; + constInfo.actualLenDimsKV = tilingData->baseParams.actualLenDimsKV; + if (constInfo.actualLenDimsKV != 0) { + actualSeqLengthsKVGm.SetGlobalBuffer((__gm__ int32_t *)actualSeqLengths, constInfo.actualLenDimsKV); + } + if (constInfo.actualLenDimsQ != 0) { + actualSeqLengthsQGm.SetGlobalBuffer((__gm__ int32_t *)actualSeqLengthsQ, constInfo.actualLenDimsQ); + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::InitAllZeroOutput(uint32_t bIdx, uint32_t s1Idx, uint32_t n2Idx) +{ + if (constInfo.outputLayout == SFA_LAYOUT::TND) { + uint32_t tBase = bIdx == 0 ? 0 : actualSeqLengthsQGm.GetValue(bIdx - 1); + uint32_t s1Count = tempLoopInfo.actS1Size; + + uint64_t attenOutOffset = (tBase + s1Idx) * kvHeadNum * constInfo.gSize * headDim + // T轴、s1轴偏移 + n2Idx * constInfo.gSize * headDim; // N2轴偏移 + matmul::InitOutput(attentionOutGm[attenOutOffset], constInfo.gSize * headDim, 0); + if (constInfo.returnSoftmaxLse) { + uint64_t softmaxSumOffset = + n2Idx * actualSeqLengthsQGm.GetValue(constInfo.batchSize - 1) * constInfo.gSize + + (tBase + s1Idx) * constInfo.gSize; + uint64_t softmaxMaxOffset = softmaxSumOffset; + matmul::InitOutput(softmaxSumGm[softmaxSumOffset], constInfo.gSize, 0); + matmul::InitOutput(softmaxMaxGm[softmaxMaxOffset], constInfo.gSize, 0); + } + } else if (constInfo.outputLayout == SFA_LAYOUT::BSND) { + uint64_t attenOutOffset = bIdx * constInfo.qSeqSize * kvHeadNum * constInfo.gSize * headDim + + s1Idx * kvHeadNum * constInfo.gSize * headDim + // B轴、S1轴偏移 + n2Idx * constInfo.gSize * headDim; // N2轴偏移 + matmul::InitOutput(attentionOutGm[attenOutOffset], constInfo.gSize * headDim, 0); + if (constInfo.returnSoftmaxLse) { + uint64_t softmaxSumOffset = bIdx * kvHeadNum * constInfo.qSeqSize * constInfo.gSize + + n2Idx * constInfo.qSeqSize * constInfo.gSize + s1Idx * constInfo.gSize; + uint64_t softmaxMaxOffset = softmaxSumOffset; + matmul::InitOutput(softmaxSumGm[softmaxSumOffset], constInfo.gSize, 0); + matmul::InitOutput(softmaxMaxGm[softmaxMaxOffset], constInfo.gSize, 0); + } + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::InitOutputSingleCore() +{ + uint32_t coreNum = GetBlockNum(); + if (coreNum != 0) { + uint64_t totalOutputSize = constInfo.batchSize * constInfo.qHeadNum * constInfo.qSeqSize * constInfo.headDim; + uint64_t singleCoreSize = (totalOutputSize + (2 * coreNum) - 1) / (2 * coreNum); // 2 means c:v = 1:2 + uint64_t tailSize = totalOutputSize - tmpBlockIdx * singleCoreSize; + uint64_t singleInitOutputSize = tailSize < singleCoreSize ? tailSize : singleCoreSize; + if (tmpBlockIdx * singleCoreSize < totalOutputSize && singleInitOutputSize > 0) { + matmul::InitOutput(attentionOutGm[tmpBlockIdx * singleCoreSize], singleInitOutputSize, 0); + } + if (constInfo.returnSoftmaxLse) { + uint64_t totalReturnSoftmaxSize = + constInfo.batchSize * constInfo.kvHeadNum * constInfo.qSeqSize * constInfo.gSize; + uint64_t singleCoreReturnSoftmaxSize = (totalReturnSoftmaxSize + (2 * coreNum) - 1) / (2 * coreNum); + uint64_t tailReturnSoftmaxSize = totalReturnSoftmaxSize - tmpBlockIdx * singleCoreReturnSoftmaxSize; + uint64_t singleInitReturnSoftmaxSize = tailReturnSoftmaxSize < singleCoreReturnSoftmaxSize ? + tailReturnSoftmaxSize : + singleCoreReturnSoftmaxSize; + if (tmpBlockIdx * singleCoreReturnSoftmaxSize < totalReturnSoftmaxSize && singleInitReturnSoftmaxSize > 0) { + matmul::InitOutput(softmaxSumGm[tmpBlockIdx * singleCoreReturnSoftmaxSize], + singleInitReturnSoftmaxSize, 0); + matmul::InitOutput(softmaxMaxGm[tmpBlockIdx * singleCoreReturnSoftmaxSize], + singleInitReturnSoftmaxSize, 0); + } + } + SyncAll(); + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::GetActualSeqLen(uint32_t bIdx, uint32_t s1Idx) +{ + tempLoopInfo.curActualSeqLenOri = GetActualSeqLenKV(bIdx); + tempLoopInfo.actS1Size = GetBalanceActualSeqLengths(actualSeqLengthsQGm, bIdx); +} + +template +__aicore__ inline void SparseFlashAttentionMla::GetSparseActualSeqLen(uint32_t bIdx, uint32_t s1Idx, + uint32_t n2Idx) +{ + if (tempLoopInfo.nextTokensPerBatch < 0 && s1Idx < (-tempLoopInfo.nextTokensPerBatch)) { // 存在行无效 + tempLoopInfo.curActualSeqLen = 0; + return; + } + int64_t threshold = tempLoopInfo.curActualSeqLenOri; + if (constInfo.sparseMode == 3) { + threshold = static_cast(tempLoopInfo.nextTokensPerBatch) + s1Idx + 1; + } + tempLoopInfo.curActualSeqLen = (constInfo.sparseBlockCount * constInfo.sparseBlockSize > threshold) ? + threshold : + (constInfo.sparseBlockCount * constInfo.sparseBlockSize); +} + +template +__aicore__ inline uint32_t SparseFlashAttentionMla::GetActualSeqLenKV(uint32_t bIdx) +{ + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::TND) { + if (bIdx > 0) { + return actualSeqLengthsKVGm.GetValue(bIdx) - actualSeqLengthsKVGm.GetValue(bIdx - 1); + } else if (bIdx == 0) { + return actualSeqLengthsKVGm.GetValue(0); + } else { + return 0; + } + } else { + if (constInfo.actualLenDimsKV == 0) { + return constInfo.kvSeqSize; + } else if (constInfo.actualLenDimsKV == 1) { + return actualSeqLengthsKVGm.GetValue(0); + } else { + return actualSeqLengthsKVGm.GetValue(bIdx); + } + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::DealActSeqLenIsZero(uint32_t bIdx, uint32_t s1Idx, uint32_t n2Idx) +{ + if ASCEND_IS_AIV { + InitAllZeroOutput(bIdx, s1Idx, n2Idx); + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::GetPreNextTokensLeftUp() +{ + if (constInfo.sparseMode == 3) { + tempLoopInfo.nextTokensPerBatch = + static_cast(tempLoopInfo.curActualSeqLenOri) - static_cast(tempLoopInfo.actS1Size); + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::UpdateInnerLoopCond() +{ + if ((tempLoopInfo.curActualSeqLen == 0) || (tempLoopInfo.actS1Size == 0)) { + tempLoopInfo.curActSeqLenIsZero = true; + return; + } + tempLoopInfo.curActSeqLenIsZero = false; + tempLoopInfo.mBasicSizeTail = (tempLoopInfo.actS1Size * constInfo.gSize) % constInfo.mBaseSize; + tempLoopInfo.mBasicSizeTail = + (tempLoopInfo.mBasicSizeTail == 0) ? constInfo.mBaseSize : tempLoopInfo.mBasicSizeTail; + tempLoopInfo.s2LoopTimes = 0; +} + +template +__aicore__ inline void SparseFlashAttentionMla::UpdateInner(uint32_t &s2End, uint32_t &curS2End, uint32_t s1Idx, + bool isEnd) +{ + uint32_t s1BaseSize = 1; + int64_t s1Offset = s1BaseSize * s1Idx; + int64_t s2LastToken = Min(s1Offset + tempLoopInfo.nextTokensPerBatch + s1BaseSize, tempLoopInfo.curActualSeqLenOri); + s2LastToken = Min(constInfo.sparseBlockSize * constInfo.sparseBlockCount, s2LastToken); + curS2End = (s2LastToken + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; + tempLoopInfo.s2LoopTimes = isEnd ? constInfo.s2End + 1 : curS2End; +} + +template +__aicore__ inline void SparseFlashAttentionMla::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 *workspace, const SparseFlashAttentionTilingDataMla *__restrict tiling, + __gm__ uint8_t *gmTiling, TPipe *tPipe) +{ + if ASCEND_IS_AIV { + tmpBlockIdx = GetBlockIdx(); // vec:0-47 + aiCoreIdx = tmpBlockIdx / 2; + } else { + tmpBlockIdx = GetBlockIdx(); // cube:0-23 + aiCoreIdx = tmpBlockIdx; + } + + // init tiling data + tilingData = tiling; + + InitTilingData(); + InitActualSeqLen(actualSeqLengthsQ, actualSeqLengths); + + // 初始化计算参数 + InitCalcParamsEach(); + pipe = tPipe; + keyPtr = key; + valuePtr = value; + + // init global buffer + queryGm.SetGlobalBuffer((__gm__ Q_T *)query); + keyGm.SetGlobalBuffer((__gm__ KV_T *)keyPtr); + valueGm.SetGlobalBuffer((__gm__ KV_T *)valuePtr); + qRopeGm.SetGlobalBuffer((__gm__ Q_ROPE_T *)queryRope); + kRopeGm.SetGlobalBuffer((__gm__ K_ROPE_T *)keyRope); + + attentionOutGm.SetGlobalBuffer((__gm__ OUT_T *)attentionOut); + softmaxMaxGm.SetGlobalBuffer((__gm__ T *)softmaxMax); + softmaxSumGm.SetGlobalBuffer((__gm__ T *)softmaxSum); + if ASCEND_IS_AIV { + if (constInfo.needInit && LAYOUT_T != SFA_LAYOUT::TND) { + InitOutputSingleCore(); + } + } + + if constexpr (PAGE_ATTENTION) { + blockTableGm.SetGlobalBuffer((__gm__ int32_t *)blockTable); + } + topKGm.SetGlobalBuffer((__gm__ int32_t *)sparseIndices); + + // workspace 内存排布 + // |Q--|mm1ResGm(存S)|vec1ResGm(存A1,A2)|mm2ResGm(存O)|vec2ResGm + // |Core0_Q1-Core0_Q2-Core1_Q1-Core1_Q2....Core32_Q1-Core32_Q2|Core0_mmRes + uint64_t offset = 0; + mm1ResGm.SetGlobalBuffer( + (__gm__ MM1_OUT_T *)(workspace + offset + + aiCoreIdx * dbWorkspaceRatio * constInfo.mmResUbSize * sizeof(MM1_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.mmResUbSize * sizeof(MM1_OUT_T); + + vec1ResGm.SetGlobalBuffer( + (__gm__ KV_T *)(workspace + offset + aiCoreIdx * dbWorkspaceRatio * constInfo.mmResUbSize * sizeof(KV_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.mmResUbSize * sizeof(KV_T); + + mm2ResGm.SetGlobalBuffer( + (__gm__ MM2_OUT_T *)(workspace + offset + + aiCoreIdx * dbWorkspaceRatio * constInfo.bmm2ResUbSize * sizeof(MM2_OUT_T))); + offset += GetBlockNum() * dbWorkspaceRatio * constInfo.bmm2ResUbSize * sizeof(MM2_OUT_T); + mm2ResInt32Gm.SetGlobalBuffer(reinterpret_cast<__gm__ int32_t *>(mm2ResGm.GetPhyAddr(0))); + + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + // s2 d+rope bufNum + kvMergeGm_.SetGlobalBuffer((__gm__ KV_T *)(workspace + offset + aiCoreIdx * 512 * 576 * 4 * sizeof(KV_T))); + offset += GetBlockNum() * 512 * 576 * 4 * sizeof(KV_T); + + kvValidSizeGm_.SetGlobalBuffer( + (__gm__ int32_t *)(workspace + offset + (aiCoreIdx * 2) * 128 * 4 * sizeof(int32_t))); + } + + if constexpr (FLASH_DECODE) { + accumOutGm.SetGlobalBuffer((__gm__ float *)(workspace + offset)); + offset = offset + tilingData->splitKVParams.accumOutSize * sizeof(float); + lseSumFdGm.SetGlobalBuffer((__gm__ float *)(workspace + offset)); + lseMaxFdGm.SetGlobalBuffer((__gm__ float *)(workspace + offset) + tilingData->splitKVParams.logSumExpSize / 2); + offset = offset + tilingData->splitKVParams.logSumExpSize * sizeof(float); + } + + if ASCEND_IS_AIV { + vectorService.InitParams(constInfo, tilingData); + vectorService.InitMm2ResInt32GmGlobalTensor(mm2ResInt32Gm); + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + vectorService.InitVec0GlobalTensor(kvValidSizeGm_, kvMergeGm_, kRopeGm, keyGm, blockTableGm); + } + vectorService.InitVec1GlobalTensor(mm1ResGm, vec1ResGm, actualSeqLengthsQGm, actualSeqLengthsKVGm, lseMaxFdGm, + lseSumFdGm, topKGm, softmaxMaxGm, softmaxSumGm); + vectorService.InitVec2GlobalTensor(accumOutGm, vec2ResGm, mm2ResGm, attentionOutGm); + } + + if ASCEND_IS_AIC { + matmulService.InitParams(constInfo); + matmulService.InitMm1GlobalTensor(queryGm, qRopeGm, keyGm, kRopeGm, mm1ResGm); + matmulService.InitMm2GlobalTensor(vec1ResGm, valueGm, mm2ResGm, attentionOutGm); + matmulService.InitPageAttentionInfo(kvMergeGm_, blockTableGm, topKGm, constInfo.kvCacheBlockSize, + constInfo.maxBlockNumPerBatch); + } + // 要在InitParams之后执行 + if (pipe != nullptr) { + InitBuffers(); + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::InitCalcParamsEach() +{ + // 计算总的基本块 + uint32_t actBatchS2 = 1; + uint32_t totalBaseNum = 0; + uint32_t s1GBaseSize = constInfo.gSize; + uint32_t coreNum = GetBlockNum(); + uint32_t currCoreIdx = aiCoreIdx; + uint32_t actBatchS1 = 1; + for (uint32_t bIdx = 0; bIdx < constInfo.batchSize; bIdx++) { + uint32_t actBatchS1 = GetBalanceActualSeqLengths(actualSeqLengthsQGm, bIdx); + if (actBatchS1 < constInfo.qSeqSize) { + constInfo.needInit = true; + } + totalBaseNum += actBatchS1 * actBatchS2; + } + uint32_t avgBaseNum = 1; + if (totalBaseNum > coreNum) { + avgBaseNum = (totalBaseNum + coreNum - 1) / coreNum; + } else { + usedCoreNum = totalBaseNum; + } + if (aiCoreIdx >= usedCoreNum) { + return; + } + // 计算当前核的基本块 + uint32_t accumBaseNum = 0; // 当前累积的基本块数 + uint32_t targetBaseNum = 0; + uint32_t lastValidBIdx = 0; + uint32_t lastValidactBatchS1 = 0; + bool setStart = false; + targetBaseNum = (currCoreIdx + 1) * avgBaseNum; // 计算当前的目标权重 + uint32_t targetStartBaseNum = targetBaseNum - avgBaseNum; + for (uint32_t bN2Idx = 0; bN2Idx < constInfo.batchSize * constInfo.kvHeadNum; bN2Idx++) { + uint32_t bIdx = bN2Idx / constInfo.kvHeadNum; + actBatchS1 = GetBalanceActualSeqLengths(actualSeqLengthsQGm, bIdx); + for (uint32_t s1GIdx = 0; s1GIdx < actBatchS1; s1GIdx++) { + accumBaseNum += 1; + if (!setStart && accumBaseNum >= targetStartBaseNum) { + constInfo.bN2Start = bN2Idx; + constInfo.gS1Start = s1GIdx; + setStart = true; + } + if (accumBaseNum >= targetBaseNum) { + // 更新当前核的End分核信息 + constInfo.bN2End = bN2Idx; + constInfo.gS1End = s1GIdx; + constInfo.s2End = 0; + constInfo.coreStartKVSplitPos = 0; + if (aiCoreIdx != 0) { + GetAxisStartIdx(constInfo.bN2Start, constInfo.gS1Start, 0); + } + return; + } + } + if ((actBatchS1 > 0) && (actBatchS2 > 0)) { + lastValidBIdx = bIdx; + lastValidactBatchS1 = actBatchS1; + } + } + if (!setStart) { + constInfo.bN2Start = lastValidBIdx; + constInfo.gS1Start = lastValidactBatchS1 - 1; + } + if (accumBaseNum < targetBaseNum) { + // 更新最后一个核的End分核信息 + constInfo.coreStartKVSplitPos = 0; + constInfo.bN2End = lastValidBIdx; + constInfo.gS1End = lastValidactBatchS1 - 1; + constInfo.s2End = 0; + if (aiCoreIdx != 0) { + GetAxisStartIdx(constInfo.bN2Start, constInfo.gS1Start, 0); + } + return; + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::Bmm2DataCopyOut(uint64_t attenOutOffset, + LocalTensor &attenOutUb, uint32_t startRow, + uint32_t dealRowCount, uint32_t columnCount, + uint32_t actualColumnCount) +{ + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = dealRowCount; + dataCopyParams.blockLen = actualColumnCount * sizeof(OUT_T); + dataCopyParams.srcStride = (columnCount - actualColumnCount) / (SFAVectorService::BYTE_BLOCK / sizeof(OUT_T)); + dataCopyParams.dstStride = 0; + DataCopyPad(attentionOutGm[attenOutOffset + (mSizeVStart + startRow) * actualColumnCount], attenOutUb, + dataCopyParams); +} + +template +__aicore__ inline void SparseFlashAttentionMla::CalcParams(uint32_t loop, uint64_t s2Start, uint32_t s2LoopIdx, + RunInfo &info) +{ + info.bIdx = tempLoopInfo.bIdx; + info.gS1Idx = tempLoopInfo.gS1Idx; + info.loop = loop; + info.s2Idx = s2LoopIdx; + info.curSInnerLoopTimes = tempLoopInfo.s2LoopTimes; + + info.tndIsS2SplitCore = tempLoopInfo.tndIsS2SplitCore; + info.tndCoreStartKVSplitPos = tempLoopInfo.tndCoreStartKVSplitPos; + info.isBmm2Output = false; + + info.actS1Size = tempLoopInfo.actS1Size; + + info.actMBaseSize = constInfo.mBaseSize; + uint32_t remainedGS1Size = tempLoopInfo.actS1Size * constInfo.gSize - tempLoopInfo.gS1Idx; + if (remainedGS1Size <= constInfo.mBaseSize && remainedGS1Size > 0) { + info.actMBaseSize = tempLoopInfo.mBasicSizeTail; + } + + info.isValid = s2LoopIdx < tempLoopInfo.s2LoopTimes; + + if ASCEND_IS_AIV { + info.mSize = info.actMBaseSize; + info.mSizeV = (info.mSize <= 16) ? info.mSize : (((info.mSize + 15) / 16 + 1) / 2 * 16); + info.mSizeVStart = 0; + if (tmpBlockIdx % 2 == 1) { + info.mSizeVStart = info.mSizeV; + info.mSizeV = info.mSize - info.mSizeV; + } + } + + info.isChangeBatch = false; + + info.isFirstSInnerLoop = s2LoopIdx == s2Start; + if (info.isFirstSInnerLoop) { + tempLoopInfo.bn2IdxInCurCore++; + } + info.isLastS2Loop = s2LoopIdx == tempLoopInfo.s2LoopTimes - 1; + info.bn2IdxInCurCore = tempLoopInfo.bn2IdxInCurCore - 1; + uint64_t actualSeqQPrefixSum; + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + actualSeqQPrefixSum = (info.bIdx <= 0) ? 0 : actualSeqLengthsQGm.GetValue(info.bIdx - 1); + } else { + actualSeqQPrefixSum = (info.bIdx <= 0) ? 0 : info.bIdx * constInfo.qSeqSize; + } + info.tndBIdxOffsetForQ = actualSeqQPrefixSum * constInfo.qHeadNum * headDim; + + uint64_t actualSeqKVPrefixSum; + if constexpr (KV_LAYOUT_T == SFA_LAYOUT::TND) { + actualSeqKVPrefixSum = (info.bIdx <= 0) ? 0 : actualSeqLengthsKVGm.GetValue(info.bIdx - 1); + } else { + actualSeqKVPrefixSum = (info.bIdx <= 0) ? 0 : info.bIdx * constInfo.kvSeqSize; + } + info.tndBIdxOffsetForKV = actualSeqKVPrefixSum * constInfo.kvHeadNum * headDim; + + if (info.isFirstSInnerLoop) { + uint64_t tndBIdxRopeOffsetForQ = actualSeqQPrefixSum * constInfo.qHeadNum * headDimRope; + tensorACoreOffset = info.tndBIdxOffsetForQ + info.gS1Idx * headDim; + tensorARopeCoreOffset = tndBIdxRopeOffsetForQ + info.gS1Idx * headDimRope; + + uint64_t tndBIdxRopeOffsetForK = actualSeqKVPrefixSum * constInfo.kvHeadNum * headDimRope; + tensorBCoreOffset = info.tndBIdxOffsetForKV + info.n2Idx * headDim; + tensorBRopeCoreOffset = tndBIdxRopeOffsetForK + info.n2Idx * headDimRope; + if (constInfo.sparseMode == 3) { + threshold = static_cast(tempLoopInfo.nextTokensPerBatch) + info.gS1Idx / constInfo.gSize + 1; + } else { + threshold = tempLoopInfo.curActualSeqLenOri; + } + if constexpr (LAYOUT_T == SFA_LAYOUT::BSND) { // B,S1,N2 K + topKBaseOffset = info.bIdx * constInfo.qSeqSize * constInfo.kvHeadNum * constInfo.sparseBlockCount + + info.gS1Idx / constInfo.gSize * constInfo.kvHeadNum * constInfo.sparseBlockCount + + info.n2Idx * constInfo.sparseBlockCount; + } else if (LAYOUT_T == SFA_LAYOUT::TND) { // T N2 K + topKBaseOffset = info.tndBIdxOffsetForQ / constInfo.gSize / constInfo.headDim * constInfo.kvHeadNum * + constInfo.sparseBlockCount + + info.n2Idx * constInfo.sparseBlockCount + + info.gS1Idx / constInfo.gSize * constInfo.kvHeadNum * constInfo.sparseBlockCount; + } else { // B N2 S1 K + topKBaseOffset = info.bIdx * constInfo.kvHeadNum * constInfo.qSeqSize * constInfo.sparseBlockCount + + info.n2Idx * constInfo.qSeqSize * constInfo.sparseBlockCount + + info.gS1Idx / constInfo.gSize * constInfo.sparseBlockCount; + } + } + info.threshold = threshold; + info.topKBaseOffset = topKBaseOffset; + info.tensorAOffset = tensorACoreOffset; + info.tensorARopeOffset = tensorARopeCoreOffset; + info.attenOutOffset = tensorACoreOffset; + info.tensorBOffset = tensorBCoreOffset; + info.tensorBRopeOffset = tensorBRopeCoreOffset; + + uint64_t sInnerOffsetDataSize = info.s2Idx * constInfo.s2BaseSize; + info.s2BatchOffset = s2BatchBaseOffset + sInnerOffsetDataSize; + + info.curActualSeqLenOri = tempLoopInfo.curActualSeqLenOri; + // 计算实际基本块size + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + if (tempLoopInfo.curActualSeqLen > sInnerOffsetDataSize) { + info.actualSingleProcessSInnerSize = tempLoopInfo.curActualSeqLen - sInnerOffsetDataSize; + info.actualSingleProcessSInnerSize = info.actualSingleProcessSInnerSize > constInfo.s2BaseSize ? + constInfo.s2BaseSize : + info.actualSingleProcessSInnerSize; + } else { + info.actualSingleProcessSInnerSize = 0; + } + info.actualSingleProcessSInnerSizeAlign = + SFAAlign((uint32_t)info.actualSingleProcessSInnerSize, (uint32_t)SFAVectorService::BYTE_BLOCK); + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::ComputeMm1(const RunInfo &info) +{ + uint32_t nBufferLoopTimes = (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / constInfo.nBufferMBaseSize; + uint32_t nBufferTail = info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; + for (uint32_t i = 0; i < nBufferLoopTimes; i++) { + MSplitInfo mSplitInfo; + mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; + mSplitInfo.nBufferDealM = (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; + matmulService.ComputeMm1(info, mSplitInfo); + CrossCoreSetFlag(constInfo.syncC1V1); + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::ComputeMm2(const RunInfo &info) +{ + uint32_t nBufferLoopTimes = (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / constInfo.nBufferMBaseSize; + uint32_t nBufferTail = info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; + for (uint32_t i = 0; i < nBufferLoopTimes; i++) { + MSplitInfo mSplitInfo; + mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; + mSplitInfo.nBufferDealM = (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; + CrossCoreWaitFlag(constInfo.syncV1C2); + matmulService.ComputeMm2(info, mSplitInfo); + CrossCoreSetFlag(constInfo.syncC2V2); + CrossCoreSetFlag(constInfo.syncC2V1); + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::Process() +{ + if (aiCoreIdx < usedCoreNum) { + if ASCEND_IS_AIV { + vectorService.AllocEventID(); + vectorService.InitSoftmaxDefaultBuffer(); + } else { + matmulService.AllocEventID(); + } + ProcessBalance(); + + if ASCEND_IS_AIV { + vectorService.FreeEventID(); + } else { + matmulService.FreeEventID(); + } + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::GetBN2Idx(uint32_t bN2Idx, uint32_t &bIdx, uint32_t &n2Idx) +{ + bIdx = bN2Idx / kvHeadNum; + n2Idx = bN2Idx % kvHeadNum; +} + +template +__aicore__ inline void SparseFlashAttentionMla::ProcessBalance() +{ + RunInfo extraInfo[SFA_PRELOAD_TASK_CACHE_SIZE]; + uint32_t gloop = 0; + int gS1LoopEnd; + bool globalLoopStart = true; + if ASCEND_IS_AIC { + CrossCoreSetFlag(constInfo.syncC2V1); + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + CrossCoreSetFlag(3); + CrossCoreSetFlag(3); + CrossCoreSetFlag(3); + CrossCoreSetFlag(3); + } + } + for (uint32_t bN2LoopIdx = constInfo.bN2Start; bN2LoopIdx <= constInfo.bN2End; bN2LoopIdx++) { + GetBN2Idx(bN2LoopIdx, tempLoopInfo.bIdx, tempLoopInfo.n2Idx); + GetActualSeqLen(tempLoopInfo.bIdx); // 获取actualSeqLength及ActualSeqLengthKV + GetPreNextTokensLeftUp(); + if (tempLoopInfo.actS1Size == 0) { + continue; + } + int gS1SplitNum = (tempLoopInfo.actS1Size * constInfo.gSize + constInfo.mBaseSize - 1) / constInfo.mBaseSize; + gS1LoopEnd = (bN2LoopIdx == constInfo.bN2End) ? constInfo.gS1End : gS1SplitNum - 1; + for (uint32_t gS1LoopIdx = constInfo.gS1Start; gS1LoopIdx <= gS1LoopEnd; gS1LoopIdx++) { + tempLoopInfo.gS1Idx = gS1LoopIdx * constInfo.mBaseSize; + GetSparseActualSeqLen(tempLoopInfo.bIdx, gS1LoopIdx, + tempLoopInfo.n2Idx); // TopK值sparse完后的ActualSeqLengthKV + UpdateInnerLoopCond(); + + if (tempLoopInfo.curActSeqLenIsZero) { + DealActSeqLenIsZero(tempLoopInfo.bIdx, gS1LoopIdx, tempLoopInfo.n2Idx); + } + int s2SplitNum = + (tempLoopInfo.curActualSeqLen + constInfo.s2BaseSize - 1) / constInfo.s2BaseSize; // S2切分份数 + bool isEnd = (bN2LoopIdx == constInfo.bN2End) && (gS1LoopIdx == constInfo.gS1End); + tempLoopInfo.s2LoopTimes = s2SplitNum; + // 分核修改后需要打开 + // 当前s2是否被切,决定了输出是否要写到attenOut上 + tempLoopInfo.tndIsS2SplitCore = + ((constInfo.s2Start == 0) && (tempLoopInfo.s2LoopTimes == s2SplitNum)) ? false : true; + tempLoopInfo.tndCoreStartKVSplitPos = globalLoopStart ? constInfo.coreStartKVSplitPos : 0; + uint32_t extraLoop = isEnd ? 2 : 0; + + uint32_t curTopKIdx = 0; + uint64_t curOffsetInSparseBlock = 0; + for (int s2LoopIdx = constInfo.s2Start; s2LoopIdx < (tempLoopInfo.s2LoopTimes + extraLoop); s2LoopIdx++) { + // PreloadPipeline loop初始值要求为 PRELOAD_NUM + PreloadPipeline(gloop, constInfo.s2Start, s2LoopIdx, extraInfo, curTopKIdx, curOffsetInSparseBlock); + ++gloop; + } + globalLoopStart = false; + constInfo.s2Start = 0; + } + constInfo.gS1Start = 0; + } + if ASCEND_IS_AIV { + CrossCoreWaitFlag(constInfo.syncC2V1); + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + CrossCoreWaitFlag(3); + CrossCoreWaitFlag(3); + CrossCoreWaitFlag(3); + CrossCoreWaitFlag(3); + } + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::PreloadPipeline(uint32_t loop, uint64_t s2Start, + uint64_t s2LoopIdx, + RunInfo extraInfo[SFA_PRELOAD_TASK_CACHE_SIZE], + uint32_t &curTopKIdx, + uint64_t &curOffsetInSparseBlock) +{ + RunInfo &extraInfo0 = extraInfo[loop % SFA_PRELOAD_TASK_CACHE_SIZE]; // 本轮任务 + RunInfo &extraInfo2 = extraInfo[(loop + 2) % SFA_PRELOAD_TASK_CACHE_SIZE]; // 上一轮任务 + RunInfo &extraInfo1 = extraInfo[(loop + 1) % SFA_PRELOAD_TASK_CACHE_SIZE]; // 上两轮任务 + + CalcParams(loop, s2Start, s2LoopIdx, extraInfo0); + CalcSinnerTopKBegin(extraInfo0, curTopKIdx, curOffsetInSparseBlock); + + if (extraInfo0.isValid) { + if ASCEND_IS_AIC { + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + CrossCoreWaitFlag(constInfo.syncV0C1); + } + ComputeMm1(extraInfo0); + } else { + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + CrossCoreWaitFlag(3); + vectorService.MergeKv(extraInfo0); + CrossCoreSetFlag(constInfo.syncV0C1); + } + } + } + if (extraInfo2.isValid) { + if ASCEND_IS_AIV { + vectorService.ProcessVec1L(extraInfo2); + } + if ASCEND_IS_AIC { + ComputeMm2(extraInfo2); + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + CrossCoreSetFlag(3); + } + } + } + if (extraInfo1.isValid) { + if ASCEND_IS_AIV { + vectorService.ProcessVec2L(extraInfo1); + } + extraInfo1.isValid = false; + } +} + +template +__aicore__ inline uint64_t SparseFlashAttentionMla::GetBalanceActualSeqLengths( + GlobalTensor &actualSeqLengths, uint32_t bIdx) +{ + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + if (bIdx > 0) { + return actualSeqLengths.GetValue(bIdx) - actualSeqLengths.GetValue(bIdx - 1); + } else if (bIdx == 0) { + return actualSeqLengths.GetValue(0); + } else { + return 0; + } + } else { + if (constInfo.actualLenDimsQ == 0) { + return constInfo.qSeqSize; + } else if (constInfo.actualLenDimsQ == 1) { + return actualSeqLengths.GetValue(0); + } else { + return actualSeqLengths.GetValue(bIdx); + } + } +} + +template +__aicore__ inline void SparseFlashAttentionMla::GetAxisStartIdx(uint32_t bN2EndPrev, uint32_t s1GEndPrev, + uint32_t s2EndPrev) +{ + uint32_t bEndPrev = bN2EndPrev / kvHeadNum; + uint32_t actualSeqQPrev = GetBalanceActualSeqLengths(actualSeqLengthsQGm, bEndPrev); + uint32_t s1GPrevBaseNum = (actualSeqQPrev * constInfo.gSize + constInfo.mBaseSize - 1) / constInfo.mBaseSize; + 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 SparseFlashAttentionMla::CalcSinnerTopKBegin(RunInfo &info, uint32_t &curTopKIdx, + uint64_t &curOffsetInSparseBlock) + +{ + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + return; + } + + uint64_t thresholdSparseCount = (info.threshold + constInfo.sparseBlockSize - 1) / constInfo.sparseBlockSize; + uint64_t validCount = + (constInfo.sparseBlockCount > thresholdSparseCount) ? thresholdSparseCount : constInfo.sparseBlockCount; + + int32_t sparseIndices = topKGm.GetValue(info.topKBaseOffset + curTopKIdx); + if (sparseIndices == -1 || curTopKIdx == validCount) { + info.actualSingleProcessSInnerSize = 0; + info.actualSingleProcessSInnerSizeAlign = 0; + tempLoopInfo.s2BasicSizeTail = 0; + if (curTopKIdx == 0) { + DealActSeqLenIsZero(info.bIdx, info.gS1Idx / constInfo.gSize, tempLoopInfo.n2Idx); + } + return; + } + + uint32_t sparseLen = 0; + uint64_t blockBegin = sparseIndices * constInfo.sparseBlockSize; + uint64_t blockEnd = (blockBegin + constInfo.sparseBlockSize > info.threshold) ? + info.threshold : + blockBegin + constInfo.sparseBlockSize; + int32_t blockLen = blockEnd - blockBegin; + sparseLen += (blockLen > static_cast(curOffsetInSparseBlock)) ? blockLen - curOffsetInSparseBlock : 0; + + bool firstVaildFlag = false; + if (curTopKIdx > 0) { + info.curTopKIdx = curTopKIdx; + info.curOffsetInSparseBlock = curOffsetInSparseBlock; + } else if (curTopKIdx == 0 && sparseLen > 0) { + info.curTopKIdx = curTopKIdx; + info.curOffsetInSparseBlock = 0; + firstVaildFlag = true; + } + + for (uint64_t topkIdx = curTopKIdx + 1; topkIdx < validCount; topkIdx++) { + int32_t sparseIndices = topKGm.GetValue(info.topKBaseOffset + topkIdx); + if (sparseIndices == -1) { + curTopKIdx = topkIdx; + curOffsetInSparseBlock = 0; + break; + } + uint64_t blockBegin = sparseIndices * constInfo.sparseBlockSize; + if (blockBegin >= info.threshold) { + continue; + } + if (firstVaildFlag == false && curTopKIdx == 0) { + info.curTopKIdx = topkIdx; + info.curOffsetInSparseBlock = 0; + firstVaildFlag = true; + } + uint64_t blockEnd = (blockBegin + constInfo.sparseBlockSize > info.threshold) ? + info.threshold : + blockBegin + constInfo.sparseBlockSize; + uint64_t blockLen = blockEnd - blockBegin; + sparseLen += blockLen; + if (sparseLen >= constInfo.s2BaseSize) { + curTopKIdx = topkIdx; + curOffsetInSparseBlock = blockLen - (sparseLen - constInfo.s2BaseSize); + sparseLen = constInfo.s2BaseSize; + break; + } + + if (topkIdx == validCount - 1) { + curTopKIdx = validCount; + curOffsetInSparseBlock = 0; + } + } + + info.actualSingleProcessSInnerSize = sparseLen; + info.actualSingleProcessSInnerSizeAlign = + SFAAlign((uint32_t)info.actualSingleProcessSInnerSize, (uint32_t)SFAVectorService::BYTE_BLOCK); + tempLoopInfo.s2BasicSizeTail = (sparseLen == constInfo.s2BaseSize) ? 0 : sparseLen; + if (curTopKIdx == 0 && sparseLen == 0) { + DealActSeqLenIsZero(info.bIdx, info.gS1Idx / constInfo.gSize, tempLoopInfo.n2Idx); + } +} + +#endif // SPARSE_FLASH_ATTENTION_KERNEL_MLA_H diff --git a/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch22/sparse_flash_attention_service_vector_mla.h b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch22/sparse_flash_attention_service_vector_mla.h new file mode 100644 index 0000000000000000000000000000000000000000..4b96aea18beb415b3a8177da3f191c4efa097958 --- /dev/null +++ b/datasets/ops_src/ops_transformer/test_kernels/kernels/sparse_flash_attention/op_kernel/arch22/sparse_flash_attention_service_vector_mla.h @@ -0,0 +1,1468 @@ +/** + * 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_vector_mla.h + * \brief + */ +#ifndef SPARSE_FLASH_ATTENTION_SERVICE_VECTOR_MLA_H +#define SPARSE_FLASH_ATTENTION_SERVICE_VECTOR_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" + +using AscendC::CrossCoreSetFlag; +using AscendC::CrossCoreWaitFlag; + +template +class SFAVectorService { +public: + // 中间计算数据类型为float,高精度模式 + using T = float; + using KV_T = typename SFAT::kvType; + using OUT_T = typename SFAT::outputType; + using UPDATE_T = T; + using MM1_OUT_T = float; + using MM2_OUT_T = float; + + __aicore__ inline SFAVectorService(){}; + __aicore__ inline void ProcessVec1L(const RunInfo &info); + __aicore__ inline void ProcessVec2L(const RunInfo &info); + __aicore__ inline void InitBuffers(TPipe *pipe); + __aicore__ inline void InitParams(const struct ConstInfo &constInfo, + const SparseFlashAttentionTilingDataMla *__restrict tilingData); + __aicore__ inline void InitMm2ResInt32GmGlobalTensor(GlobalTensor mm2ResInt32Gm); + __aicore__ inline void InitVec0GlobalTensor(const GlobalTensor &kvValidSizeGm, + const GlobalTensor &kvMergeGm, + const GlobalTensor &keyRopeGm, const GlobalTensor &keyGm, + const GlobalTensor &blkTableGm); + __aicore__ inline void InitVec1GlobalTensor(GlobalTensor mm1ResGm, GlobalTensor vec1ResGm, + GlobalTensor actualSeqLengthsQGm, + GlobalTensor actualSeqLengthsKVGm, GlobalTensor lseMaxFdGm, + GlobalTensor lseSumFdGm, GlobalTensor topKGm, + GlobalTensor softmaxMaxGm, GlobalTensor softmaxSumGm); + __aicore__ inline void InitVec2GlobalTensor(GlobalTensor accumOutGm, GlobalTensor vec2ResGm, + GlobalTensor mm2ResGm, GlobalTensor attentionOutGm); + __aicore__ inline void InitSoftmaxDefaultBuffer(); + __aicore__ inline void AllocEventID(); + __aicore__ inline void FreeEventID(); + // ================================Base Vector========================================== + __aicore__ inline void RowDivs(LocalTensor dstUb, LocalTensor src0Ub, LocalTensor src1Ub, + uint32_t dealRowCount, uint32_t columnCount, uint32_t actualColumnCount); + __aicore__ inline void RowMuls(LocalTensor dstUb, LocalTensor src0Ub, LocalTensor src1Ub, + uint32_t dealRowCount, uint32_t columnCount, uint32_t actualColumnCount); + // ================================Vector0========================================== + __aicore__ inline void MergeKv(const RunInfo &runInfo); + __aicore__ inline int64_t GetKeyGmOffset(int64_t realS2Idx, const RunInfo &runInfo, int64_t s2IdLimit); + __aicore__ inline int64_t GetKeyRopeGmOffset(int64_t realS2Idx, const RunInfo &runInfo, int64_t s2IdLimit); + __aicore__ inline void GetRealS2Idx(int64_t s2GmOffset, int64_t &realS2Idx, int64_t topkGmBaseOffset, + const RunInfo &runInfo); + __aicore__ inline void CopyInKv(int64_t &mte2Size, int64_t mte3Size, int64_t mergeMte3Idx, int64_t realS2Idx1, + int64_t realS2Idx2, const RunInfo &runInfo); + __aicore__ inline void CopyOutMrgeResult(int64_t mte2Size, int64_t mte3Size, int64_t s2StartGmOffset, + int64_t mergeMte3Idx, const RunInfo &runInfo); + __aicore__ inline void CopyInSingleKv(int64_t &mte2Size, int64_t mte3Size, int64_t mergeMte3Idx, int64_t realS2Idx, + int64_t keyBNBOffset, int64_t s2IdLimit, const RunInfo &runInfo); + __aicore__ inline void SetInfInBlk(const LocalTensor &mmResUb, uint32_t dealRowCount, uint32_t columnCount, + uint64_t startId, uint64_t endId); + __aicore__ inline void SetMidInf(const LocalTensor &mmResUb, uint32_t dealRowCount, uint32_t columnCount, + uint64_t startId, uint64_t endId); + // ================================Vector1========================================== + __aicore__ inline void ProcessVec1SingleBuf(const RunInfo &info, const MSplitInfo &mSplitInfo); + __aicore__ inline void DealBmm1ResBaseBlock(const RunInfo &info, const MSplitInfo &mSplitInfo, uint32_t startRow, + uint32_t dealRowCount, uint32_t columnCount, uint32_t loopId); + __aicore__ inline void SoftmaxFlashV2Compute(const RunInfo &info, const MSplitInfo &mSplitInfo, + LocalTensor &mmResUb, LocalTensor &softmaxTmpUb, + uint32_t startRow, uint32_t dealRowCount, uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void AmlaVecCompute(const RunInfo &info, const MSplitInfo &mSplitInfo, LocalTensor &mmResUb, + LocalTensor &softmaxTmpUb, uint32_t startRow, uint32_t dealRowCount, + uint32_t columnCount, uint32_t actualColumnCount); + __aicore__ inline void ElewiseCompute(const RunInfo &info, const LocalTensor &mmResUb, uint32_t dealRowCount, + uint32_t columnCount); + __aicore__ inline void ProcessAmlaNupdate(const RunInfo &info, const MSplitInfo &mSplitInfo); + __aicore__ inline void ComputeLogSumExpAndCopyToGm(const RunInfo &info, const MSplitInfo &mSplitInfo, + LocalTensor &softmaxSumUb, LocalTensor &softmaxMaxUb); + __aicore__ inline void CopyFALseToGm(const RunInfo &info, const MSplitInfo &mSplitInfo, + LocalTensor &softmaxSumUb, LocalTensor &softmaxMaxUb); + __aicore__ inline void SetBmm2FirstSInnerBias(const RunInfo &info, const MSplitInfo &mSplitInfo); + // ================================Vecotr2========================================== + __aicore__ inline void ProcessVec2SingleBuf(const RunInfo &info, const MSplitInfo &mSplitInfo); + __aicore__ inline void DealBmm2ResBaseBlock(const RunInfo &info, const MSplitInfo &mSplitInfo, uint32_t startRow, + uint32_t dealRowCount, uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void ProcessVec2Inner(const RunInfo &info, const MSplitInfo &mSplitInfo, uint32_t mStartRow, + uint32_t mDealSize); + __aicore__ inline void Bmm2DataCopyOutTrans(const RunInfo &info, LocalTensor &attenOutUb, uint32_t wsMStart, + uint32_t dealRowCount, uint32_t columnCount, + uint32_t actualColumnCount); + __aicore__ inline void Bmm2ResCopyOut(const RunInfo &info, LocalTensor &bmm2ResUb, uint32_t wsMStart, + uint32_t dealRowCount, uint32_t columnCount, uint32_t actualColumnCount); + __aicore__ inline void Bmm2CastAndCopyOut(const RunInfo &info, LocalTensor &bmm2ResUb, uint32_t wsMStart, + uint32_t dealRowCount, uint32_t columnCount, uint32_t actualColumnCount); + __aicore__ inline void Bmm2FDDataCopyOut(const RunInfo &info, LocalTensor &bmm2ResUb, uint32_t wsMStart, + uint32_t dealRowCount, uint32_t columnCount, uint32_t actualColumnCount); + __aicore__ inline uint64_t CalcAccumOffset(uint32_t bN2Idx, uint32_t gS1Idx); + __aicore__ inline void GetConfusionTransposeTiling(int64_t numR, int64_t numC, const uint32_t stackBufferSize, + const uint32_t typeSize, ConfusionTransposeTiling &tiling); + + // BLOCK和REPEAT的字节数 + static constexpr uint64_t BYTE_BLOCK = 32UL; + static constexpr uint32_t REPEAT_BLOCK_BYTE = 256U; + // BLOCK和REPEAT的FP32元素数 + static constexpr uint32_t FP32_BLOCK_ELEMENT_NUM = BYTE_BLOCK / sizeof(float); + static constexpr uint32_t FP32_REPEAT_ELEMENT_NUM = REPEAT_BLOCK_BYTE / sizeof(float); + // repeat stride不能超过256 + static constexpr uint32_t REPEATE_STRIDE_UP_BOUND = 256; + +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 uint64_t MERGE_CACHE_GM_BUF_NUM = 4; + static constexpr uint64_t SYNC_INPUT_BUF1_FLAG = 2; + static constexpr uint64_t SYNC_INPUT_BUF1_PONG_FLAG = 3; + static constexpr uint64_t SYNC_INPUT_BUF2_FLAG = 4; + static constexpr uint64_t SYNC_INPUT_BUF2_PONG_FLAG = 5; + static constexpr uint64_t SYNC_OUTPUT_BUF1_FLAG = 4; + static constexpr uint64_t SYNC_OUTPUT_BUF2_FLAG = 5; + static constexpr uint64_t SYNC_INPUT_V0BUF_FLAG = 6; + static constexpr uint32_t INPUT1_BUFFER_OFFSET = ConstInfo::BUFFER_SIZE_BYTE_32K; + static constexpr uint32_t SOFTMAX_TMP_BUFFER_OFFSET = ConstInfo::BUFFER_SIZE_BYTE_1K; + static constexpr uint32_t BASE_BLOCK_MAX_ELEMENT_NUM = ConstInfo::BUFFER_SIZE_BYTE_32K / sizeof(T); // 32768/4=8096 + static constexpr uint32_t BLOCK_ELEMENT_NUM = BYTE_BLOCK / sizeof(T); // 32/4=8 + static constexpr T FLOAT_E_SCALAR = 8388608; + static constexpr T LN2 = 0.6931471805599453094172; + static constexpr T RECIP_OF_LN2 = 1 / LN2; + static constexpr T SOFTMAX_MIN_NUM = -2e38; + + const SparseFlashAttentionTilingDataMla *__restrict tilingData; + + uint32_t pingpongFlag = 0U; + ConstInfo constInfo = {}; + + GlobalTensor mm2ResInt32Gm; + GlobalTensor mm1ResGm; + GlobalTensor vec1ResGm; + GlobalTensor lseSumFdGm; + GlobalTensor lseMaxFdGm; + GlobalTensor softmaxMaxGm; + GlobalTensor softmaxSumGm; + + GlobalTensor actualSeqLengthsQGm; + GlobalTensor actualSeqLengthsKVGm; + GlobalTensor vec2ResGm; + GlobalTensor mm2ResGm; + GlobalTensor accumOutGm; + GlobalTensor attentionOutGm; + GlobalTensor blkTableGm_; + + GlobalTensor kvMergeGm_; + GlobalTensor keyRopeGm_; + GlobalTensor keyGm_; + GlobalTensor topkGm_; + GlobalTensor kvValidSizeGm_; + + // ================================Local Buffer区==================================== + TBuf<> inputBuff1; // 32K + TBuf<> inputBuff2; // 16K + TBuf<> outputBuff1; // 32K + TBuf<> outputBuff2; // 4K + + TBuf<> tmpBuff1; // 32K + TBuf<> v0ValidSizeBuff; // 8K + + TBuf<> nValueBuff; + TBuf<> cofValueBuff; + TBuf<> aMlaSumBuff; + TBuf<> softmaxMaxBuff; // PRE_LOAD_NUM * 2K + TBuf<> softmaxExpBuff; // PRE_LOAD_NUM * 2K + TBuf<> softmaxSumBuff; // PRE_LOAD_NUM * 2K + TBuf<> softmaxMaxDefaultBuff; // 2K + TBuf<> softmaxSumDefaultBuff; // 2K + + LocalTensor softmaxMaxDefaultUb; + LocalTensor softmaxSumDefaultUb; + + LocalTensor nValueUb; + LocalTensor cofValueUb; + LocalTensor aMlaSumUb; + LocalTensor softmaxMaxUb; + LocalTensor softmaxSumUb; + LocalTensor softmaxExpUb; + LocalTensor kvMergUb_; + LocalTensor ropeMergUb_; + LocalTensor v0ValidSizeUb_; +}; + +template +__aicore__ inline void SFAVectorService::InitBuffers(TPipe *pipe) +{ + pipe->InitBuffer(inputBuff1, ConstInfo::BUFFER_SIZE_BYTE_32K * 2); // 2:pingpong + pipe->InitBuffer(inputBuff2, ConstInfo::BUFFER_SIZE_BYTE_8K * 2); // 2:pingpong + pipe->InitBuffer(outputBuff1, ConstInfo::BUFFER_SIZE_BYTE_32K); + pipe->InitBuffer(outputBuff2, ConstInfo::BUFFER_SIZE_BYTE_4K); + + pipe->InitBuffer(tmpBuff1, ConstInfo::BUFFER_SIZE_BYTE_32K); + pipe->InitBuffer(v0ValidSizeBuff, ConstInfo::BUFFER_SIZE_BYTE_8K); + + // M_MAX = 512/2vector = 256, 256 * sizeof(T) * N_Buffer + pipe->InitBuffer(nValueBuff, ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + pipe->InitBuffer(cofValueBuff, ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + pipe->InitBuffer(aMlaSumBuff, ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + + pipe->InitBuffer(softmaxMaxBuff, ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + pipe->InitBuffer(softmaxExpBuff, ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + pipe->InitBuffer(softmaxSumBuff, ConstInfo::BUFFER_SIZE_BYTE_1K * constInfo.preLoadNum); + + pipe->InitBuffer(softmaxMaxDefaultBuff, ConstInfo::BUFFER_SIZE_BYTE_1K); + pipe->InitBuffer(softmaxSumDefaultBuff, ConstInfo::BUFFER_SIZE_BYTE_1K); + + nValueUb = nValueBuff.Get(); + cofValueUb = cofValueBuff.Get(); + aMlaSumUb = aMlaSumBuff.Get(); + + softmaxMaxUb = softmaxMaxBuff.Get(); + softmaxSumUb = softmaxSumBuff.Get(); + softmaxExpUb = softmaxExpBuff.Get(); + + softmaxMaxDefaultUb = softmaxMaxDefaultBuff.Get(); + softmaxSumDefaultUb = softmaxSumDefaultBuff.Get(); + + kvMergUb_ = inputBuff1.Get(); + ropeMergUb_ = inputBuff2.Get(); + + v0ValidSizeUb_ = v0ValidSizeBuff.Get(); +} + +template +__aicore__ inline void SFAVectorService::InitParams( + const struct ConstInfo &constInfo, const SparseFlashAttentionTilingDataMla *__restrict tilingData) +{ + this->constInfo = constInfo; + this->tilingData = tilingData; +} + +template +__aicore__ inline void SFAVectorService::InitMm2ResInt32GmGlobalTensor(GlobalTensor mm2ResInt32Gm) +{ + this->mm2ResInt32Gm = mm2ResInt32Gm; +} + +template +__aicore__ inline void SFAVectorService::InitVec0GlobalTensor(const GlobalTensor &kvValidSizeGm, + const GlobalTensor &kvMergeGm, + const GlobalTensor &keyRopeGm, + const GlobalTensor &keyGm, + const GlobalTensor &blkTableGm) +{ + this->kvMergeGm_ = kvMergeGm; + this->keyRopeGm_ = keyRopeGm; + this->keyGm_ = keyGm; + this->blkTableGm_ = blkTableGm; + this->kvValidSizeGm_ = kvValidSizeGm; +} + +template +__aicore__ inline void SFAVectorService::InitVec1GlobalTensor( + GlobalTensor mm1ResGm, GlobalTensor vec1ResGm, GlobalTensor actualSeqLengthsQGm, + GlobalTensor actualSeqLengthsKVGm, GlobalTensor lseMaxFdGm, GlobalTensor lseSumFdGm, + GlobalTensor topKGm, GlobalTensor softmaxMaxGm, GlobalTensor softmaxSumGm) +{ + this->mm1ResGm = mm1ResGm; + this->vec1ResGm = vec1ResGm; + this->actualSeqLengthsQGm = actualSeqLengthsQGm; + this->actualSeqLengthsKVGm = actualSeqLengthsKVGm; + this->lseMaxFdGm = lseMaxFdGm; + this->lseSumFdGm = lseSumFdGm; + this->topkGm_ = topKGm; + this->softmaxMaxGm = softmaxMaxGm; + this->softmaxSumGm = softmaxSumGm; +} + +template +__aicore__ inline void SFAVectorService::InitVec2GlobalTensor(GlobalTensor accumOutGm, + GlobalTensor vec2ResGm, + GlobalTensor mm2ResGm, + GlobalTensor attentionOutGm) +{ + this->accumOutGm = accumOutGm; + this->vec2ResGm = vec2ResGm; + this->mm2ResGm = mm2ResGm; + this->attentionOutGm = attentionOutGm; +} + +template +__aicore__ inline void SFAVectorService::AllocEventID() +{ + SetFlag(SYNC_INPUT_BUF1_FLAG); + SetFlag(SYNC_INPUT_BUF1_PONG_FLAG); + SetFlag(SYNC_INPUT_BUF2_FLAG); + SetFlag(SYNC_INPUT_BUF2_PONG_FLAG); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); +} + +template +__aicore__ inline void SFAVectorService::FreeEventID() +{ + WaitFlag(SYNC_INPUT_BUF1_FLAG); + WaitFlag(SYNC_INPUT_BUF1_PONG_FLAG); + WaitFlag(SYNC_INPUT_BUF2_FLAG); + WaitFlag(SYNC_INPUT_BUF2_PONG_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); +} + +template +__aicore__ inline void SFAVectorService::InitSoftmaxDefaultBuffer() +{ + Duplicate(softmaxMaxDefaultUb, SOFTMAX_MIN_NUM, SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)); + Duplicate(softmaxSumDefaultUb, ConstInfo::FLOAT_ZERO, SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)); +} + +template +__aicore__ inline void SFAVectorService::CopyFALseToGm(const RunInfo &info, const MSplitInfo &mSplitInfo, + LocalTensor &softmaxSumUb, LocalTensor &softmaxMaxUb) + +{ + if (mSplitInfo.vecDealM == 0) { + return; + } + uint64_t baseOffset = mSplitInfo.nBufferStartM / 2; + size_t size = mSplitInfo.vecDealM; + + int64_t offset = 0; + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { // lse layout为N2 T G + uint64_t actualSeqQTotal = (info.bIdx <= 0) ? 0 : actualSeqLengthsQGm.GetValue(constInfo.batchSize - 1); + uint64_t actualSeqQPrefixSum = (info.bIdx <= 0) ? 0 : actualSeqLengthsQGm.GetValue(info.bIdx - 1); + offset += info.n2Idx * actualSeqQTotal * constInfo.gSize + + (actualSeqQPrefixSum + info.gS1Idx / constInfo.gSize) * constInfo.gSize + mSplitInfo.nBufferStartM + + mSplitInfo.vecStartM; + } else { + offset += info.bIdx * constInfo.kvHeadNum * constInfo.qSeqSize * constInfo.gSize + + info.n2Idx * constInfo.qSeqSize * constInfo.gSize + info.gS1Idx / constInfo.gSize * constInfo.gSize + + mSplitInfo.nBufferStartM + mSplitInfo.vecStartM; + } + + if (info.actualSingleProcessSInnerSize != 0) { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1; + dataCopyParams.blockLen = sizeof(T) * size; + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + size_t alignedSize = (sizeof(T) * size + 31) / 32 * 32 / sizeof(T); + LocalTensor tmp = outputBuff2.Get(); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + DataCopy(tmp, softmaxMaxUb[baseOffset], alignedSize); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + DataCopyPad(softmaxMaxGm[offset], tmp, dataCopyParams); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + + tmp = outputBuff2.Get(); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + DataCopy(tmp, softmaxSumUb[baseOffset], alignedSize); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + DataCopyPad(softmaxSumGm[offset], tmp, dataCopyParams); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + } else { + matmul::InitOutput(softmaxSumGm[offset], size, ConstInfo::FLOAT_ZERO); + matmul::InitOutput(softmaxMaxGm[offset], size, SOFTMAX_MIN_NUM); + } +} + +template +__aicore__ inline void SFAVectorService::ComputeLogSumExpAndCopyToGm(const RunInfo &info, + const MSplitInfo &mSplitInfo, + LocalTensor &softmaxSumUb, + LocalTensor &softmaxMaxUb) +{ + if (mSplitInfo.vecDealM == 0) { + return; + } + uint64_t baseOffset = mSplitInfo.nBufferStartM / 2; + size_t size = mSplitInfo.vecDealM * FP32_BLOCK_ELEMENT_NUM; + uint64_t accumTmpOutNum = CalcAccumOffset(info.bIdx, info.gS1Idx); + uint64_t offset = (accumTmpOutNum * constInfo.kvHeadNum * constInfo.mBaseSize + // taskoffset + info.tndCoreStartKVSplitPos * constInfo.kvHeadNum * constInfo.mBaseSize + // 份数offset + mSplitInfo.nBufferStartM + mSplitInfo.vecStartM) * + FP32_BLOCK_ELEMENT_NUM; // m轴offset + if (info.actualSingleProcessSInnerSize != 0) { + LocalTensor tmp = outputBuff2.Get(); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + Brcb(tmp, softmaxSumUb[baseOffset], (mSplitInfo.vecDealM + 7) / 8, {1, 8}); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + DataCopy(lseSumFdGm[offset], tmp, size); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + + tmp = outputBuff2.Get(); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + Brcb(tmp, softmaxMaxUb[baseOffset], (mSplitInfo.vecDealM + 7) / 8, {1, 8}); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + DataCopy(lseMaxFdGm[offset], tmp, size); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + } else { + matmul::InitOutput(lseSumFdGm[offset], size, ConstInfo::FLOAT_ZERO); + matmul::InitOutput(lseMaxFdGm[offset], size, SOFTMAX_MIN_NUM); + } +} + +template +__aicore__ inline void SFAVectorService::ElewiseCompute(const RunInfo &info, const LocalTensor &mmResUb, + uint32_t dealRowCount, uint32_t columnCount) +{ + Muls(mmResUb, mmResUb, static_cast(tilingData->baseParams.scaleValue), dealRowCount * columnCount); + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + // v0的无效值判断 + uint64_t s2ValidSizeFirstPart = v0ValidSizeUb_.GetValue(128 + info.loop % MERGE_CACHE_GM_BUF_NUM); + uint64_t s2ValidSizeSecondPart = v0ValidSizeUb_.GetValue(256 + info.loop % MERGE_CACHE_GM_BUF_NUM); + + int64_t s2ProcessSize = info.actualSingleProcessSInnerSize; + int64_t s2Pair = CeilDiv(s2ProcessSize, 2L * constInfo.sparseBlockSize); + int64_t s2Mid = CeilDiv(s2Pair, 2L) * 2 * constInfo.sparseBlockSize; + if (s2Mid > s2ProcessSize) { + s2Mid = s2ProcessSize; + } + if (unlikely(s2ValidSizeFirstPart < s2Mid)) { + int64_t s2StartCeilAlign = CeilAlign(s2ValidSizeFirstPart, 8); + int64_t s2MidFloorAlign = s2Mid / 8 * 8; + // 场景一 s2Mid > s2ValidSizeFirstPart + oneBlk + // 可以推导出s2StartCeilAlign < s2Mid 第一阶段取到s2StartCeilAlign + // s2StartCeilAlign <= s2MidFloorAlign 第二阶段取到s2MidFloorAlign + // 场景二 s2Mid <= s2ValidSizeFirstPart + oneBlk + // 可以推导出 s2StartCeilAlign >= s2Mid 第一阶段取到mid + // s2StartCeilAlign > s2MidFloorAlign 第二阶段取到s2StartCeilAlign + SetInfInBlk(mmResUb, dealRowCount, columnCount, s2ValidSizeFirstPart, + s2StartCeilAlign >= s2Mid ? s2Mid : s2StartCeilAlign); + SetMidInf(mmResUb, dealRowCount, columnCount, s2StartCeilAlign, s2MidFloorAlign); + SetInfInBlk(mmResUb, dealRowCount, columnCount, + s2StartCeilAlign <= s2MidFloorAlign ? s2MidFloorAlign : s2StartCeilAlign, s2Mid); + } + if (unlikely(s2ValidSizeSecondPart < s2ProcessSize - s2Mid)) { + // 场景一 s2Mid + s2ValidSizeSecondPart > s2ProcessSize + oneBlk + // 可以推导出 s2StartCeilAlign < s2ProcessSize 第一阶段取到s2StartCeilAlign + // s2StartCeilAlign <= s2EndFloorAlign 第二阶段取到s2EndFloorAlign + // 场景二 s2Mid + s2ValidSizeSecondPart <= s2ProcessSize + oneBlk + // 可以推导出 s2StartCeilAlign >= s2ProcessSize 第一阶段取到s2ProcessSize + // s2StartCeilAlign > s2EndFloorAlign 第二阶段取到s2StartCeilAlign + int64_t s2StartCeilAlign = CeilAlign(s2Mid + s2ValidSizeSecondPart, 8); + int64_t s2EndFloorAlign = s2ProcessSize / 8 * 8; + SetInfInBlk(mmResUb, dealRowCount, columnCount, s2Mid + s2ValidSizeSecondPart, + s2StartCeilAlign >= s2ProcessSize ? s2ProcessSize : s2StartCeilAlign); + SetMidInf(mmResUb, dealRowCount, columnCount, s2StartCeilAlign, s2EndFloorAlign); + SetInfInBlk(mmResUb, dealRowCount, columnCount, + s2StartCeilAlign <= s2EndFloorAlign ? s2EndFloorAlign : s2StartCeilAlign, s2ProcessSize); + } + } +} + +template +__aicore__ inline void SFAVectorService::SetInfInBlk(const LocalTensor &mmResUb, uint32_t dealRowCount, + uint32_t columnCount, uint64_t startId, uint64_t endId) +{ + // startId endId + // x x x 0 0 0 x x x + // 从startId到endId部分置-inf, endId、startId为endId一个blk内部的下标 + if (startId >= endId) { + return; + } + + uint64_t startFloorAlignSize = startId / BLOCK_ELEMENT_NUM * BLOCK_ELEMENT_NUM; + uint64_t notComputePreMaskOneBlk = (1 << (startId - startFloorAlignSize)) - 1; + uint64_t notComputePostMaskOneBlk = ~((1 << (endId - startFloorAlignSize)) - 1); + uint64_t notComputeMaskOneBlk = notComputePreMaskOneBlk ^ notComputePostMaskOneBlk; + + uint64_t maskOneBlk = ~notComputeMaskOneBlk; + uint64_t mask[1] = {maskOneBlk}; + for (int i = 1; i < 8; i++) { + mask[0] = mask[0] | (maskOneBlk << (i * 8)); + } + for (uint64_t rowId = 0; rowId < dealRowCount; rowId += 8) { + Duplicate(mmResUb[rowId * columnCount + startFloorAlignSize], SOFTMAX_MIN_NUM, mask, 1, CeilDiv(columnCount, 8), + 0); + } +} + +template +__aicore__ inline void SFAVectorService::SetMidInf(const LocalTensor &mmResUb, uint32_t dealRowCount, + uint32_t columnCount, uint64_t startId, uint64_t endId) +{ + if (startId >= endId) { + return; + } + // startId endId + // 0 ... 0 + // 从startId到endId部分置-inf, startId、endId为32B对齐的下标 + for (uint64_t rowId = 0; rowId < dealRowCount; rowId++) { + Duplicate(mmResUb[rowId * columnCount + startId], SOFTMAX_MIN_NUM, endId - startId); + } +} + +template +__aicore__ inline void SFAVectorService::SoftmaxFlashV2Compute(const RunInfo &info, const MSplitInfo &mSplitInfo, + LocalTensor &mmResUb, + LocalTensor &softmaxTmpUb, + uint32_t startRow, uint32_t dealRowCount, + uint32_t columnCount, uint32_t actualColumnCount) +{ + LocalTensor inSumTensor; + LocalTensor inMaxTensor; + uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; + uint32_t outIdx = info.loop % (constInfo.preLoadNum); + uint32_t softmaxOutOffset = outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; + if (info.isFirstSInnerLoop) { + inMaxTensor = softmaxMaxDefaultUb; + inSumTensor = softmaxSumDefaultUb; + } else { + uint32_t inIdx = (info.loop - 1) % (constInfo.preLoadNum); + inMaxTensor = softmaxMaxUb[inIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset]; + inSumTensor = softmaxSumUb[inIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset]; + } + if (actualColumnCount != 0) { + SoftMaxShapeInfo srcShape{dealRowCount, columnCount, dealRowCount, actualColumnCount}; + SoftMaxTiling newTiling = + SoftMaxFlashV2TilingFunc(srcShape, sizeof(T), sizeof(T), softmaxTmpUb.GetSize(), true, false); + SoftmaxFlashV2( + mmResUb, softmaxSumUb[softmaxOutOffset], softmaxMaxUb[softmaxOutOffset], mmResUb, + softmaxExpUb[softmaxOutOffset], inSumTensor, inMaxTensor, softmaxTmpUb, newTiling, srcShape); + } else { + uint32_t dealRowCountAlign = SFAAlign(dealRowCount, FP32_BLOCK_ELEMENT_NUM); + DataCopy(softmaxSumUb[softmaxOutOffset], inSumTensor, dealRowCountAlign); + PipeBarrier(); + DataCopy(softmaxMaxUb[softmaxOutOffset], inMaxTensor, dealRowCountAlign); + } +} + +template +__aicore__ inline void SFAVectorService::AmlaVecCompute(const RunInfo &info, const MSplitInfo &mSplitInfo, + LocalTensor &mmResUb, + LocalTensor &softmaxTmpUb, uint32_t startRow, + uint32_t dealRowCount, uint32_t columnCount, + uint32_t actualColumnCount) +{ + uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; + uint32_t calCount = dealRowCount; + uint32_t outIdx = info.loop % (constInfo.preLoadNum); + uint32_t softmaxOutOffset = outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; + // compute n(i) + LocalTensor nTmp = softmaxTmpUb.template ReinterpretCast(); + LocalTensor nUpdateTmp = nTmp[SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + Muls(nTmp, softmaxMaxUb[softmaxOutOffset], ((T)(-1.0)) * RECIP_OF_LN2, calCount); + + PipeBarrier(); + Cast(nTmp, nTmp, RoundMode::CAST_ROUND, calCount); + PipeBarrier(); + + uint32_t prOutIdx = (info.loop - 1) % (constInfo.preLoadNum); + uint32_t PreSoftmaxOutOffset = prOutIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset; + // n(i) - n(i-1) + if (info.isFirstSInnerLoop) { + Duplicate(nUpdateTmp, ConstInfo::FLOAT_ZERO, calCount); // n1=n0 + } else { + Sub(nUpdateTmp, nTmp, nValueUb[PreSoftmaxOutOffset], calCount); + } + PipeBarrier(); + // update n(i), DataCopy not support when calCount is not align 32B, so use Adds + Adds(nValueUb[softmaxOutOffset], nTmp, ConstInfo::FLOAT_ZERO, calCount); + PipeBarrier(); + + // update softmax res + LocalTensor nUpdateTmp2 = nTmp[2 * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + LocalTensor nTmp_KvT = nTmp[3 * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)].template ReinterpretCast(); + LocalTensor tmpCofUb = nTmp[4 * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + LocalTensor epsUb = nTmp[5 * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + Muls(nUpdateTmp2, softmaxMaxUb[softmaxOutOffset], RECIP_OF_LN2, calCount); + PipeBarrier(); + Add(nTmp, nUpdateTmp2, nTmp, calCount); + PipeBarrier(); + Muls(nTmp, nTmp, LN2, calCount); + PipeBarrier(); + Exp(nTmp, nTmp, calCount); + PipeBarrier(); + Cast(nTmp_KvT, nTmp, RoundMode::CAST_ROUND, calCount); // fp32->fp16/bf16 + PipeBarrier(); + Cast(nUpdateTmp2, nTmp_KvT, RoundMode::CAST_NONE, calCount); // fp16/bf16->fp32 + PipeBarrier(); + if (info.s2Idx + 1 == info.curSInnerLoopTimes) { + Mul(aMlaSumUb[softmaxOutOffset], softmaxSumUb[softmaxOutOffset], nUpdateTmp2, calCount); + } + if (actualColumnCount == 0) { + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + return; + } + LocalTensor nTmp3 = nTmp[6 * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + Brcb(nTmp3, nUpdateTmp2, (dealRowCount + 7) / 8, {1, 8}); + PipeBarrier(); + RowMuls(mmResUb, mmResUb, nTmp3, dealRowCount, columnCount, actualColumnCount); + + Div(tmpCofUb, nTmp, nUpdateTmp2, calCount); // cof(i)=tmpS32/tmpS16 + if (info.isFirstSInnerLoop) { + Duplicate(cofValueUb[softmaxOutOffset], (T)1.0, calCount); // cof_0=1 + PipeBarrier(); + Div(epsUb, cofValueUb[softmaxOutOffset], tmpCofUb, calCount); // 1 / cof(i) + } else { + PipeBarrier(); + Div(epsUb, cofValueUb[PreSoftmaxOutOffset], tmpCofUb, calCount); // cof(i - 1) / cof(i) + } + PipeBarrier(); + + Adds(cofValueUb[softmaxOutOffset], tmpCofUb, ConstInfo::FLOAT_ZERO, calCount); // store cof(i) + Adds(epsUb, epsUb, (T)(-1.0), calCount); // cof(i - 1) / cof(i) - 1 + PipeBarrier(); + Muls(epsUb, epsUb, (T)1.5, calCount); // (cof(i - 1) - cof(i)) / cof(i) * 1.5 + + Maxs(nUpdateTmp, nUpdateTmp, (T)(-30.0), calCount); // N = max(n(i) - n(i-1), -30) + PipeBarrier(); + Adds(epsUb, epsUb, (T)(0.000001), calCount); + PipeBarrier(); + Add(nUpdateTmp, nUpdateTmp, epsUb, calCount); + PipeBarrier(); + Muls(nUpdateTmp, nUpdateTmp, FLOAT_E_SCALAR, calCount); // N = N * pow(2, 23) + PipeBarrier(); + + // nUpdate int32 out + LocalTensor tmQue = outputBuff2.Get(); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + LocalTensor nInt32Out = tmQue[startRow]; // 缓存nUpdate + + Cast(nInt32Out, nUpdateTmp, RoundMode::CAST_ROUND, dealRowCount); + PipeBarrier(); + + SetFlag(SYNC_OUTPUT_BUF2_FLAG); +} + +template +__aicore__ inline void SFAVectorService::DealBmm1ResBaseBlock(const RunInfo &info, const MSplitInfo &mSplitInfo, + uint32_t startRow, uint32_t dealRowCount, + uint32_t columnCount, uint32_t loopId) +{ + uint32_t computeSize = dealRowCount * columnCount; + uint64_t inOutGmOffset = (info.loop % constInfo.preLoadNum) * constInfo.mmResUbSize + + (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + startRow) * columnCount; + LocalTensor mmResUb = inputBuff1.Get(); + mmResUb = mmResUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM1_OUT_T)]; + WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + + DataCopy(mmResUb, mm1ResGm[inOutGmOffset], computeSize); + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + if (loopId == 0) { + WaitFlag(0); + } + } + SetFlag(SYNC_INPUT_BUF1_FLAG); + WaitFlag(SYNC_INPUT_BUF1_FLAG); + + ElewiseCompute(info, mmResUb, dealRowCount, columnCount); + + PipeBarrier(); + LocalTensor tmpAFloorUb = tmpBuff1.Get(); + LocalTensor softmaxTmpUb = tmpAFloorUb.template ReinterpretCast(); + + SoftmaxFlashV2Compute(info, mSplitInfo, mmResUb, softmaxTmpUb, startRow, dealRowCount, columnCount, + info.actualSingleProcessSInnerSize); + + PipeBarrier(); + AmlaVecCompute(info, mSplitInfo, mmResUb, softmaxTmpUb, startRow, dealRowCount, columnCount, + info.actualSingleProcessSInnerSize); + + PipeBarrier(); + LocalTensor tmpMMResCastTensor = outputBuff1.Get(); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + + Cast(tmpMMResCastTensor, mmResUb, AscendC::RoundMode::CAST_ROUND, computeSize); + SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + DataCopy(vec1ResGm[inOutGmOffset], tmpMMResCastTensor, computeSize); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); +} + +template +__aicore__ inline void SFAVectorService::SetBmm2FirstSInnerBias(const RunInfo &info, const MSplitInfo &mSplitInfo) +{ + uint32_t mSplitSize = 16U; + uint64_t baseoffset = (info.bn2IdxInCurCore % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + + (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM) * constInfo.headDim; + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + LocalTensor tmpTensor = outputBuff1.Get(); + Duplicate(tmpTensor, static_cast(394264576), + mSplitSize * constInfo.headDim); // 394264576 : fp32下2^(-80)的二进制表示对应的int32数值 + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + uint32_t loopCount = (mSplitInfo.vecDealM + mSplitSize - 1) / mSplitSize; + for (uint32_t loop = 0; loop < loopCount; loop++) { + DataCopy(mm2ResInt32Gm[baseoffset + loop * mSplitSize * constInfo.headDim], tmpTensor, + mSplitSize * constInfo.headDim); + } + SetFlag(SYNC_OUTPUT_BUF1_FLAG); +} + +template +__aicore__ inline void SFAVectorService::ProcessAmlaNupdate(const RunInfo &info, const MSplitInfo &mSplitInfo) +{ + if (mSplitInfo.vecDealM == 0) { + return; + } + if (info.isFirstSInnerLoop) { + SetBmm2FirstSInnerBias(info, mSplitInfo); + return; + } + + LocalTensor nUpdateTensor = outputBuff2.Get(); // shape:1/2*s1*g + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + SetFlag(SYNC_OUTPUT_BUF2_FLAG); + WaitFlag(SYNC_OUTPUT_BUF2_FLAG); + + constexpr uint32_t dGroupSize = 128U; + constexpr uint32_t mSplitSize = + 64U; // tmpQue size 32KB,一次只能处理64个N,最大保存的数据大小:64*128*sizeof(int32) + constexpr uint32_t ONE_BLOCK_SIZE = 32U; // 32B + + uint32_t subMSize = SFAAlign(mSplitInfo.vecDealM, 16U); + uint16_t elementPerBlock = ONE_BLOCK_SIZE / sizeof(int32_t); // 单个datablock的元素数,int32_t类型的为32/4=8 + uint32_t loopCount = (subMSize + mSplitSize - 1) / mSplitSize; + uint32_t tailSplitSize = subMSize - (loopCount - 1) * mSplitSize; // 尾块 + + for (uint32_t loop = 0, processMSize = mSplitSize; loop < loopCount; loop++) { + if (loop == (loopCount - 1)) { + processMSize = tailSplitSize; + } + LocalTensor tmpQue = outputBuff1.Get(); + + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + // (m,1)单次brcb扩充成(m,8), 重复16次, 扩充为(m,128) + for (uint32_t i = 0; i < dGroupSize / elementPerBlock; i++) { + Brcb(tmpQue[i * elementPerBlock], nUpdateTensor[loop * mSplitSize], + static_cast((processMSize + elementPerBlock - 1) / elementPerBlock), + {static_cast( + dGroupSize / elementPerBlock), // 单次迭代内,目的操作数不同datablock间地址步长,单位为datablock + static_cast(dGroupSize)}); // 相邻迭代间,目的操作数相同datablock地址步长 + } + + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + + uint64_t baseoffset = (info.bn2IdxInCurCore % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + + (mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + loop * mSplitSize) * constInfo.headDim; + + SetAtomicAdd(); + DataCopyParams dataCopyParams; + dataCopyParams.blockCount = static_cast(processMSize); + dataCopyParams.blockLen = dGroupSize * sizeof(int32_t) / ONE_BLOCK_SIZE; // 每个block是128个元素,单位为32B + dataCopyParams.srcStride = 0; // 前面一个数据块的尾与后面数据块的头的间隔 + dataCopyParams.dstStride = + static_cast((constInfo.headDim - dGroupSize) * sizeof(int32_t) / ONE_BLOCK_SIZE); // 单位为32B + for (uint32_t i = 0; i < constInfo.headDim / dGroupSize; i++) { // 4=512/128 + DataCopy(mm2ResInt32Gm[baseoffset + i * dGroupSize], tmpQue, dataCopyParams); + } + SetAtomicNone(); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + } + SetFlag(SYNC_OUTPUT_BUF2_FLAG); +} + +template +__aicore__ inline void SFAVectorService::ProcessVec1SingleBuf(const RunInfo &info, const MSplitInfo &mSplitInfo) +{ + if (mSplitInfo.vecDealM == 0) { + return; + } + uint32_t mSplitSize = info.actualSingleProcessSInnerSize == 0 ? + 16 : + BASE_BLOCK_MAX_ELEMENT_NUM / info.actualSingleProcessSInnerSizeAlign; + // 1. 向下8对齐是因为UB操作至少32B + // 2. info.actualSingleProcessSInnerSizeAlign最大512, mSplitSize可以确保最小为16 + mSplitSize = mSplitSize / 8 * 8; + + if (mSplitSize > mSplitInfo.vecDealM) { + mSplitSize = mSplitInfo.vecDealM; + } + uint32_t loopCount = (mSplitInfo.vecDealM + mSplitSize - 1) / mSplitSize; + uint32_t tailSplitSize = mSplitInfo.vecDealM - (loopCount - 1) * mSplitSize; + + if constexpr (TEMPLATE_MODE == V_TEMPLATE) { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1; + dataCopyParams.blockLen = 256 * sizeof(int32_t); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + DataCopyPadExtParams padParams; + // 额外偏移128个元素,避免不同loop下v0和v1互相影响 + DataCopyPad(v0ValidSizeUb_[128], kvValidSizeGm_[info.loop % MERGE_CACHE_GM_BUF_NUM * (128 * 2)], dataCopyParams, + padParams); + SetFlag(0); + if (unlikely(loopCount == 0)) { + // scalar同步影响较大,挪到循环内部进行 + WaitFlag(0); + } + } + for (uint32_t i = 0, dealSize = mSplitSize; i < loopCount; i++) { + if (i == (loopCount - 1)) { + dealSize = tailSplitSize; + } + DealBmm1ResBaseBlock(info, mSplitInfo, i * mSplitSize, dealSize, info.actualSingleProcessSInnerSizeAlign, i); + pingpongFlag ^= 1; // pingpong 0 1切换 + } +} + +template +__aicore__ inline void SFAVectorService::GetRealS2Idx(int64_t s2GmOffset, int64_t &realS2Idx, + int64_t topkGmBaseOffset, const RunInfo &runInfo) +{ + int64_t topkGmIdx = (s2GmOffset + runInfo.s2Idx * constInfo.s2BaseSize) / constInfo.sparseBlockSize; + if (unlikely(topkGmIdx >= constInfo.sparseBlockCount)) { + realS2Idx = -1; + return; + } + realS2Idx = topkGm_.GetValue(topkGmBaseOffset + topkGmIdx) * static_cast(constInfo.sparseBlockSize) + + static_cast((s2GmOffset + runInfo.s2Idx * constInfo.s2BaseSize) % constInfo.sparseBlockSize); +} + +template +__aicore__ inline int64_t SFAVectorService::GetKeyGmOffset(int64_t realS2Idx, const RunInfo &runInfo, + int64_t s2IdLimit) +{ + if (realS2Idx < 0 || realS2Idx >= s2IdLimit) { + return -1; + } + int64_t realKeyGmOffset = 0; + if constexpr (PAGE_ATTENTION) { + int64_t blkTableIdx = realS2Idx / constInfo.kvCacheBlockSize; + int64_t blkTableOffset = realS2Idx % constInfo.kvCacheBlockSize; + realKeyGmOffset = blkTableGm_.GetValue(runInfo.bIdx * constInfo.maxBlockNumPerBatch + blkTableIdx) * + static_cast(constInfo.kvCacheBlockSize) * + static_cast(constInfo.kvHeadNum) + + blkTableOffset; + } else { + realKeyGmOffset = + (runInfo.tensorBOffset + realS2Idx * constInfo.kvHeadNum * constInfo.headDim) / constInfo.headDim; + } + return realKeyGmOffset; +} + +template +__aicore__ inline int64_t SFAVectorService::GetKeyRopeGmOffset(int64_t realS2Idx, const RunInfo &runInfo, + int64_t s2IdLimit) +{ + if (realS2Idx < 0 || realS2Idx >= s2IdLimit) { + return -1; + } + int64_t realKeyRopeGmOffset = 0; + realKeyRopeGmOffset = + (runInfo.tensorBRopeOffset + realS2Idx * constInfo.kvHeadNum * constInfo.headDimRope) / constInfo.headDimRope; + return realKeyRopeGmOffset; +} + +template +__aicore__ inline void SFAVectorService::CopyInSingleKv(int64_t &mte2Size, int64_t mte3Size, int64_t mergeMte3Idx, + int64_t realS2Idx, int64_t keyBNBOffset, + int64_t s2IdLimit, const RunInfo &runInfo) +{ + if (keyBNBOffset < 0) { + return; + } + int64_t validS2Count = + (realS2Idx + constInfo.sparseBlockSize > s2IdLimit ? s2IdLimit - realS2Idx : constInfo.sparseBlockSize); + DataCopyExtParams intriParams; + intriParams.blockLen = validS2Count * constInfo.headDim * sizeof(KV_T); + intriParams.blockCount = 1; + intriParams.dstStride = 0; + intriParams.srcStride = 0; + DataCopyPadExtParams padParams; + DataCopyPad(kvMergUb_[mergeMte3Idx % 2 * 32 * 512 + (mte2Size - mte3Size) * constInfo.headDim], + keyGm_[keyBNBOffset * constInfo.headDim], intriParams, padParams); + intriParams.blockLen = validS2Count * constInfo.headDimRope * sizeof(KV_T); + + DataCopyPad(ropeMergUb_[mergeMte3Idx % 2 * 32 * 64 + (mte2Size - mte3Size) * constInfo.headDimRope], + keyRopeGm_[keyBNBOffset * constInfo.headDimRope], intriParams, padParams); + mte2Size += validS2Count; +} + +template +__aicore__ inline void SFAVectorService::CopyInKv(int64_t &mte2Size, int64_t mte3Size, int64_t mergeMte3Idx, + int64_t realS2Idx1, int64_t realS2Idx2, const RunInfo &runInfo) +{ + int64_t s2IdLimit = runInfo.curActualSeqLenOri; + if (constInfo.sparseMode == 3) { + s2IdLimit = runInfo.curActualSeqLenOri - runInfo.actS1Size + runInfo.gS1Idx / constInfo.gSize + 1; + } + + int64_t keyOffset1 = GetKeyGmOffset(realS2Idx1, runInfo, s2IdLimit); + int64_t keyOffset2 = GetKeyGmOffset(realS2Idx2, runInfo, s2IdLimit); + if (unlikely(keyOffset1 < 0 && keyOffset2 < 0)) { + return; + } + + int64_t keySrcStride = 0; + int64_t keyRopeSrcStride = 0; + if constexpr (PAGE_ATTENTION) { + int64_t blkTableSrcStride = ((keyOffset1 > keyOffset2 ? (keyOffset1 - keyOffset2) : (keyOffset2 - keyOffset1)) - + constInfo.sparseBlockSize); + keySrcStride = blkTableSrcStride * constInfo.headDim * sizeof(KV_T); + keyRopeSrcStride = blkTableSrcStride * constInfo.headDimRope * sizeof(KV_T); + } else { + int64_t keyRopeOffset1 = GetKeyRopeGmOffset(realS2Idx1, runInfo, s2IdLimit); + int64_t keyRopeOffset2 = GetKeyRopeGmOffset(realS2Idx2, runInfo, s2IdLimit); + keySrcStride = ((keyOffset1 > keyOffset2 ? (keyOffset1 - keyOffset2) : (keyOffset2 - keyOffset1)) - + constInfo.sparseBlockSize) * + constInfo.headDim * sizeof(KV_T); + keyRopeSrcStride = + ((keyRopeOffset1 > keyRopeOffset2 ? (keyRopeOffset1 - keyRopeOffset2) : (keyRopeOffset2 - keyRopeOffset1)) - + constInfo.sparseBlockSize) * + constInfo.headDimRope * sizeof(KV_T); + } + + if (unlikely(keySrcStride >= INT32_MAX || keySrcStride < 0 || + (!PAGE_ATTENTION && (keyRopeSrcStride >= INT32_MAX || keyRopeSrcStride < 0)) || + realS2Idx1 + constInfo.sparseBlockSize >= s2IdLimit || + realS2Idx2 + constInfo.sparseBlockSize >= s2IdLimit)) { + // stride溢出、stride为负数、s2超长等异常场景,还原成2条搬运指令 + CopyInSingleKv(mte2Size, mte3Size, mergeMte3Idx, realS2Idx1, keyOffset1, s2IdLimit, runInfo); + CopyInSingleKv(mte2Size, mte3Size, mergeMte3Idx, realS2Idx2, keyOffset2, s2IdLimit, runInfo); + } else { + DataCopyExtParams intriParams; + intriParams.blockLen = constInfo.sparseBlockSize * constInfo.headDim * sizeof(KV_T); + intriParams.blockCount = (keyOffset1 >= 0) + (keyOffset2 >= 0); + intriParams.dstStride = 0; + intriParams.srcStride = keySrcStride; + DataCopyPadExtParams padParams; + + int64_t startGmOffset = keyOffset1 > -1 ? keyOffset1 : keyOffset2; + if (keyOffset2 > -1 && keyOffset2 < keyOffset1) { + startGmOffset = keyOffset2; + } + DataCopyPad(kvMergUb_[mergeMte3Idx % 2 * 32 * 512 + (mte2Size - mte3Size) * constInfo.headDim], + keyGm_[startGmOffset * constInfo.headDim], intriParams, padParams); + + intriParams.blockLen = constInfo.sparseBlockSize * constInfo.headDimRope * sizeof(KV_T); + intriParams.dstStride = 0; + intriParams.srcStride = keyRopeSrcStride; + DataCopyPad(ropeMergUb_[mergeMte3Idx % 2 * 32 * 64 + (mte2Size - mte3Size) * constInfo.headDimRope], + keyRopeGm_[startGmOffset * constInfo.headDimRope], intriParams, padParams); + mte2Size += ((keyOffset1 > -1) + (keyOffset2 > -1)) * constInfo.sparseBlockSize; + } +} + +template +__aicore__ inline void SFAVectorService::CopyOutMrgeResult(int64_t mte2Size, int64_t mte3Size, + int64_t s2GmStartOffset, int64_t mergeMte3Idx, + const RunInfo &runInfo) +{ + if (mte2Size <= mte3Size) { + return; + } + SetFlag(0); + WaitFlag(0); + + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = mte2Size - mte3Size; + dataCopyParams.blockLen = constInfo.headDim * sizeof(KV_T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + + DataCopyPad(kvMergeGm_[runInfo.loop % 4 * 512 * 576 + (s2GmStartOffset + mte3Size) * constInfo.headDim], + kvMergUb_[mergeMte3Idx % 2 * 32 * 512], dataCopyParams); + + dataCopyParams.blockLen = constInfo.headDimRope * sizeof(KV_T); + DataCopyPad( + kvMergeGm_[runInfo.loop % 4 * 512 * 576 + 512 * 512 + (s2GmStartOffset + mte3Size) * constInfo.headDimRope], + ropeMergUb_[mergeMte3Idx % 2 * 32 * 64], dataCopyParams); +} + +// b s1 k +template +__aicore__ inline void SFAVectorService::MergeKv(const RunInfo &runInfo) +{ + int64_t s2ProcessSize = runInfo.actualSingleProcessSInnerSize; + int64_t s2Pair = CeilDiv(s2ProcessSize, 2L * constInfo.sparseBlockSize); + int64_t topkGmBaseOffset = 0; + + if constexpr (LAYOUT_T == SFA_LAYOUT::TND) { + uint64_t actualSeqQPrefixSum = (runInfo.bIdx <= 0) ? 0 : actualSeqLengthsQGm.GetValue(runInfo.bIdx - 1); + topkGmBaseOffset += (actualSeqQPrefixSum + runInfo.gS1Idx / constInfo.gSize) * constInfo.kvHeadNum * + constInfo.sparseBlockCount + + runInfo.n2Idx * constInfo.sparseBlockCount; + } else { + topkGmBaseOffset += runInfo.bIdx * constInfo.qSeqSize * constInfo.sparseBlockCount + + runInfo.gS1Idx / constInfo.gSize * constInfo.sparseBlockCount; + } + int64_t mergeMte3Idx = 0; + int64_t mte2Size = 0; + int64_t mte3Size = 0; + int64_t s2IdxArray0 = -1; + int64_t s2IdxArray1 = -1; + bool needWaitMte3ToMte2 = true; + SetFlag(0); + SetFlag(1); + int64_t s2GmStartOffset = GetSubBlockIdx() == 0 ? 0 : CeilDiv(s2Pair, 2L) * 2 * constInfo.sparseBlockSize; + int64_t s2GmLimit = GetSubBlockIdx() == 0 ? CeilDiv(s2Pair, 2L) * 2 * constInfo.sparseBlockSize : s2ProcessSize; + if (s2GmLimit > s2ProcessSize) { + s2GmLimit = s2ProcessSize; + } + for (int64_t s2GmOffsetArray = s2GmStartOffset; s2GmOffsetArray < s2GmLimit; + s2GmOffsetArray += 2 * constInfo.sparseBlockSize) { + if (needWaitMte3ToMte2) { + WaitFlag(mergeMte3Idx % 2); + needWaitMte3ToMte2 = false; + } + GetRealS2Idx(s2GmOffsetArray, s2IdxArray0, topkGmBaseOffset, runInfo); + if (unlikely(s2IdxArray0 < 0)) { + CopyOutMrgeResult(mte2Size, mte3Size, s2GmStartOffset, mergeMte3Idx, runInfo); + SetFlag(mergeMte3Idx % 2); + mergeMte3Idx++; + break; + } + GetRealS2Idx(s2GmOffsetArray + constInfo.sparseBlockSize, s2IdxArray1, topkGmBaseOffset, runInfo); + CopyInKv(mte2Size, mte3Size, mergeMte3Idx, s2IdxArray0, s2IdxArray1, runInfo); + if ((mte2Size - mte3Size + 2 * constInfo.sparseBlockSize > 32) || + s2GmOffsetArray + 2 * constInfo.sparseBlockSize >= s2GmLimit) { + CopyOutMrgeResult(mte2Size, mte3Size, s2GmStartOffset, mergeMte3Idx, runInfo); + mte3Size = mte2Size; + SetFlag(mergeMte3Idx % 2); + mergeMte3Idx++; + needWaitMte3ToMte2 = true; + } + } + + if (unlikely(s2GmStartOffset + mte2Size < s2GmLimit)) { + SetFlag(0); + WaitFlag(0); + WaitFlag(mergeMte3Idx & 1); + Duplicate(kvMergUb_, static_cast(0.0), constInfo.headDim); + SetFlag(0); + WaitFlag(0); + + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1; + dataCopyParams.blockLen = constInfo.headDim * sizeof(KV_T); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + for (int64_t s2GmOffset = s2GmStartOffset + mte2Size; s2GmOffset < s2GmLimit; s2GmOffset++) { + DataCopyPad(kvMergeGm_[runInfo.loop % MERGE_CACHE_GM_BUF_NUM * 512 * 576 + s2GmOffset * constInfo.headDim], + kvMergUb_, dataCopyParams); + } + dataCopyParams.blockLen = constInfo.headDimRope * sizeof(KV_T); + for (int64_t s2GmOffset = s2GmStartOffset + mte2Size; s2GmOffset < s2GmLimit; s2GmOffset++) { + DataCopyPad(kvMergeGm_[runInfo.loop % MERGE_CACHE_GM_BUF_NUM * 512 * 576 + 512 * constInfo.headDim + + s2GmOffset * constInfo.headDimRope], + kvMergUb_, dataCopyParams); + } + SetFlag(mergeMte3Idx & 1); + mergeMte3Idx++; + } + WaitFlag(0); + WaitFlag(1); + v0ValidSizeUb_.SetValue(runInfo.loop % MERGE_CACHE_GM_BUF_NUM, mte2Size); + SetFlag(1); + WaitFlag(1); + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = 1; + dataCopyParams.blockLen = 128 * sizeof(int32_t); + dataCopyParams.srcStride = 0; + dataCopyParams.dstStride = 0; + DataCopyPad(kvValidSizeGm_[runInfo.loop % MERGE_CACHE_GM_BUF_NUM * (128 * 2) + GetSubBlockIdx() * 128], + v0ValidSizeUb_, dataCopyParams); + SetFlag(SYNC_INPUT_V0BUF_FLAG); + WaitFlag(SYNC_INPUT_V0BUF_FLAG); + return; +} + +template +__aicore__ inline void SFAVectorService::ProcessVec1L(const RunInfo &info) +{ + uint32_t nBufferLoopTimes = (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / constInfo.nBufferMBaseSize; + uint32_t nBufferTail = info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; + for (uint32_t i = 0; i < nBufferLoopTimes; i++) { + MSplitInfo mSplitInfo; + mSplitInfo.nBufferIdx = i; + mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; + mSplitInfo.nBufferDealM = (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; + + mSplitInfo.vecDealM = (mSplitInfo.nBufferDealM <= 16) ? mSplitInfo.nBufferDealM : + (((mSplitInfo.nBufferDealM + 15) / 16 + 1) / 2 * 16); + mSplitInfo.vecStartM = 0; + if (GetBlockIdx() % 2 == 1) { + mSplitInfo.vecStartM = mSplitInfo.vecDealM; + mSplitInfo.vecDealM = mSplitInfo.nBufferDealM - mSplitInfo.vecDealM; + } + + CrossCoreWaitFlag(constInfo.syncC1V1); + // vec1 compute + ProcessVec1SingleBuf(info, mSplitInfo); + CrossCoreSetFlag(constInfo.syncV1C2); + CrossCoreWaitFlag(constInfo.syncC2V1); + // add nUpdate to mm2ResGm + if (info.actualSingleProcessSInnerSize != 0) { + ProcessAmlaNupdate(info, mSplitInfo); + CrossCoreSetFlag(constInfo.syncV1NupdateC2); + } + // move lse for flash decode or FA + if (info.s2Idx == info.curSInnerLoopTimes - 1 && (constInfo.returnSoftmaxLse || info.tndIsS2SplitCore)) { + uint32_t outIdx = info.loop % (constInfo.preLoadNum); + auto sumTensor = softmaxSumUb[outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + auto maxTensor = softmaxMaxUb[outIdx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T)]; + if (constInfo.returnSoftmaxLse) { + CopyFALseToGm(info, mSplitInfo, sumTensor, maxTensor); + } + if (info.tndIsS2SplitCore) { + if constexpr (FLASH_DECODE) { + ComputeLogSumExpAndCopyToGm(info, mSplitInfo, sumTensor, maxTensor); + } + } + } + } +} + +template +__aicore__ inline uint64_t SFAVectorService::CalcAccumOffset(uint32_t bN2Idx, uint32_t gS1Idx) +{ + return 0; +} + +template +__aicore__ inline void SFAVectorService::ProcessVec2SingleBuf(const RunInfo &info, const MSplitInfo &mSplitInfo) +{ + if (info.s2Idx + 1 != info.curSInnerLoopTimes) { + return; + } + if (mSplitInfo.vecDealM == 0) { + return; + } + + ProcessVec2Inner(info, mSplitInfo, 0, mSplitInfo.vecDealM); +} + +template +__aicore__ inline void SFAVectorService::ProcessVec2L(const RunInfo &info) +{ + uint32_t nBufferLoopTimes = (info.actMBaseSize + constInfo.nBufferMBaseSize - 1) / constInfo.nBufferMBaseSize; + uint32_t nBufferTail = info.actMBaseSize - (nBufferLoopTimes - 1) * constInfo.nBufferMBaseSize; + for (uint32_t i = 0; i < nBufferLoopTimes; i++) { + MSplitInfo mSplitInfo; + mSplitInfo.nBufferIdx = i; + mSplitInfo.nBufferStartM = i * constInfo.nBufferMBaseSize; + mSplitInfo.nBufferDealM = (i + 1 != nBufferLoopTimes) ? constInfo.nBufferMBaseSize : nBufferTail; + + mSplitInfo.vecStartM = 0; + mSplitInfo.vecDealM = (mSplitInfo.nBufferDealM <= 16) ? mSplitInfo.nBufferDealM : + (((mSplitInfo.nBufferDealM + 15) / 16 + 1) / 2 * 16); + if (GetBlockIdx() % 2 == 1) { + mSplitInfo.vecStartM = mSplitInfo.vecDealM; + mSplitInfo.vecDealM = mSplitInfo.nBufferDealM - mSplitInfo.vecDealM; + } + CrossCoreWaitFlag(constInfo.syncC2V2); + ProcessVec2SingleBuf(info, mSplitInfo); + } +} + +template +__aicore__ inline void SFAVectorService::ProcessVec2Inner(const RunInfo &info, const MSplitInfo &mSplitInfo, + uint32_t mStartRow, uint32_t mDealSize) +{ + uint32_t mSplitSize = BASE_BLOCK_MAX_ELEMENT_NUM / constInfo.headDim; + if (mSplitSize > mDealSize) { + mSplitSize = mDealSize; + } + + uint32_t loopCount = (mDealSize + mSplitSize - 1) / mSplitSize; + uint32_t tailSplitSize = mDealSize - (loopCount - 1) * mSplitSize; + for (uint32_t i = 0, dealSize = mSplitSize; i < loopCount; i++) { + if (i == (loopCount - 1)) { + dealSize = tailSplitSize; + } + DealBmm2ResBaseBlock(info, mSplitInfo, i * mSplitSize + mStartRow, dealSize, constInfo.headDim, + constInfo.headDim); + pingpongFlag ^= 1; // pingpong 0 1切换 + } +} + +template +__aicore__ inline void SFAVectorService::GetConfusionTransposeTiling(int64_t numR, int64_t numC, + const uint32_t stackBufferSize, + const uint32_t typeSize, + ConfusionTransposeTiling &tiling) +{ + (void)stackBufferSize; + uint32_t blockSize = ONE_BLK_SIZE / typeSize; + uint32_t height = numC; + uint32_t width = numR; + uint32_t highBlock = height / BLOCK_CUBE; + uint32_t stride = height * blockSize * typeSize / ONE_BLK_SIZE; + uint32_t repeat = width / blockSize; + + tiling.param0 = blockSize; + tiling.param1 = height; + tiling.param2 = width; + tiling.param3 = highBlock; + tiling.param4 = stride; + tiling.param5 = repeat; +} + +template +__aicore__ inline void SFAVectorService::Bmm2FDDataCopyOut(const RunInfo &info, LocalTensor &bmm2ResUb, + uint32_t wsMStart, uint32_t dealRowCount, + uint32_t columnCount, uint32_t actualColumnCount) +{ + LocalTensor tmp = outputBuff1.Get(); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + DataCopy(tmp, bmm2ResUb, columnCount * dealRowCount); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + uint64_t accumTmpOutNum = CalcAccumOffset(info.bIdx, info.gS1Idx); + uint64_t offset = + accumTmpOutNum * constInfo.kvHeadNum * constInfo.mBaseSize * constInfo.headDim + // taskoffset + info.tndCoreStartKVSplitPos * constInfo.kvHeadNum * constInfo.mBaseSize * constInfo.headDim + // 份数offset + wsMStart * actualColumnCount; // m轴offset + GlobalTensor dst = accumOutGm[offset]; + if (info.actualSingleProcessSInnerSize == 0) { + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = dealRowCount; + dataCopyParams.blockLen = actualColumnCount * sizeof(T); + dataCopyParams.dstStride = 0; + dataCopyParams.srcStride = (columnCount - actualColumnCount) / (BYTE_BLOCK / sizeof(T)); + DataCopyPad(dst, tmp, dataCopyParams); + } else { + matmul::InitOutput(dst, dealRowCount * actualColumnCount, ConstInfo::FLOAT_ZERO); + } + SetFlag(SYNC_OUTPUT_BUF1_FLAG); +} + +template +__aicore__ inline void SFAVectorService::Bmm2DataCopyOutTrans(const RunInfo &info, LocalTensor &attenOutUb, + uint32_t wsMStart, uint32_t dealRowCount, + uint32_t columnCount, uint32_t actualColumnCount) +{ + DataCopyExtParams dataCopyParams; + dataCopyParams.blockCount = dealRowCount; + dataCopyParams.blockLen = actualColumnCount * sizeof(OUT_T); + dataCopyParams.srcStride = (columnCount - actualColumnCount) / (BYTE_BLOCK / sizeof(OUT_T)); + dataCopyParams.dstStride = 0; + DataCopyPad(attentionOutGm[info.attenOutOffset + wsMStart * actualColumnCount], attenOutUb, dataCopyParams); + return; +} + +template +__aicore__ inline void SFAVectorService::Bmm2CastAndCopyOut(const RunInfo &info, LocalTensor &bmm2ResUb, + uint32_t wsMStart, uint32_t dealRowCount, + uint32_t columnCount, uint32_t actualColumnCount) +{ + LocalTensor tmpBmm2ResCastTensor = outputBuff1.Get(); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + if constexpr (IsSameType::value) { // bf16 采取四舍六入五成双模式 + Cast(tmpBmm2ResCastTensor, bmm2ResUb, AscendC::RoundMode::CAST_RINT, dealRowCount * columnCount); + } else { + Cast(tmpBmm2ResCastTensor, bmm2ResUb, AscendC::RoundMode::CAST_ROUND, dealRowCount * columnCount); + } + + SetFlag(SYNC_OUTPUT_BUF1_FLAG); + WaitFlag(SYNC_OUTPUT_BUF1_FLAG); + Bmm2DataCopyOutTrans(info, tmpBmm2ResCastTensor, wsMStart, dealRowCount, columnCount, actualColumnCount); + SetFlag(SYNC_OUTPUT_BUF1_FLAG); +} + +template +__aicore__ inline void SFAVectorService::Bmm2ResCopyOut(const RunInfo &info, LocalTensor &bmm2ResUb, + uint32_t wsMStart, uint32_t dealRowCount, + uint32_t columnCount, uint32_t actualColumnCount) +{ + if constexpr (FLASH_DECODE) { + if (info.tndIsS2SplitCore) { + Bmm2FDDataCopyOut(info, bmm2ResUb, wsMStart, dealRowCount, columnCount, actualColumnCount); + } else { + Bmm2CastAndCopyOut(info, bmm2ResUb, wsMStart, dealRowCount, columnCount, actualColumnCount); + } + } else { + Bmm2CastAndCopyOut(info, bmm2ResUb, wsMStart, dealRowCount, columnCount, actualColumnCount); + } +} + +template +__aicore__ inline void SFAVectorService::DealBmm2ResBaseBlock(const RunInfo &info, const MSplitInfo &mSplitInfo, + uint32_t startRow, uint32_t dealRowCount, + uint32_t columnCount, uint32_t actualColumnCount) +{ + uint32_t vec2ComputeSize = dealRowCount * columnCount; + uint32_t mStart = mSplitInfo.nBufferStartM + mSplitInfo.vecStartM + startRow; + uint64_t srcGmOffset = + (info.bn2IdxInCurCore % constInfo.preLoadNum) * constInfo.bmm2ResUbSize + mStart * columnCount; + LocalTensor tmpBmm2ResUb = inputBuff1.Get(); + tmpBmm2ResUb = tmpBmm2ResUb[pingpongFlag * INPUT1_BUFFER_OFFSET / sizeof(MM2_OUT_T)]; + WaitFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + DataCopy(tmpBmm2ResUb, mm2ResGm[srcGmOffset], vec2ComputeSize); + + SetFlag(SYNC_INPUT_BUF1_FLAG); + WaitFlag(SYNC_INPUT_BUF1_FLAG); + + // 将绝对值大于1e10的数置为0 + LocalTensor bmm2ResUb = tmpBuff1.Get(); + bmm2ResUb.SetSize(vec2ComputeSize); + LocalTensor absBmm2ResUb = bmm2ResUb.template ReinterpretCast(); + Abs(absBmm2ResUb, tmpBmm2ResUb, vec2ComputeSize); + PipeBarrier(); + LocalTensor cmpMaskUb = absBmm2ResUb.template ReinterpretCast(); + CompareScalar(cmpMaskUb, absBmm2ResUb, (T)1e10, CMPMODE::LE, vec2ComputeSize); + PipeBarrier(); + Select(tmpBmm2ResUb, cmpMaskUb, tmpBmm2ResUb, ConstInfo::FLOAT_ZERO, SELMODE::VSEL_TENSOR_SCALAR_MODE, + vec2ComputeSize); + PipeBarrier(); + uint32_t baseOffset = mSplitInfo.nBufferStartM / 2 + startRow; + uint32_t idx = info.loop % (constInfo.preLoadNum); + LocalTensor tmpSumUb = v0ValidSizeBuff.Get()[384]; // sumUb用临时内存 16 * 32B = 512B + Brcb(tmpSumUb, aMlaSumUb[idx * SOFTMAX_TMP_BUFFER_OFFSET / sizeof(T) + baseOffset], (dealRowCount + 7) / 8, {1, 8}); + PipeBarrier(); + RowDivs(bmm2ResUb, tmpBmm2ResUb, tmpSumUb, dealRowCount, columnCount, actualColumnCount); + PipeBarrier(); + SetFlag(SYNC_INPUT_BUF1_FLAG + pingpongFlag); + Bmm2ResCopyOut(info, bmm2ResUb, mStart, dealRowCount, columnCount, actualColumnCount); +} + +template +__aicore__ inline void SFAVectorService::RowDivs(LocalTensor dstUb, LocalTensor src0Ub, + LocalTensor src1Ub, uint32_t dealRowCount, + uint32_t columnCount, uint32_t actualColumnCount) +{ + // divs by row, 每行的元素除以相同的元素 + // dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] / src1Ub[i, 0 : 7] + // src0Ub:[dealRowCount, columnCount], src1Ub:[dealRowCount, FP32_BLOCK_ELEMENT_NUM] dstUb:[dealRowCount, + // columnCount] + uint32_t dtypeMask = FP32_REPEAT_ELEMENT_NUM; + uint32_t dLoop = actualColumnCount / dtypeMask; + uint32_t dRemain = actualColumnCount % dtypeMask; + + BinaryRepeatParams repeatParamsDiv; + repeatParamsDiv.src0BlkStride = 1; + repeatParamsDiv.src1BlkStride = 0; + repeatParamsDiv.dstBlkStride = 1; + repeatParamsDiv.src0RepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; + repeatParamsDiv.src1RepStride = 1; + repeatParamsDiv.dstRepStride = columnCount / FP32_BLOCK_ELEMENT_NUM; + uint32_t columnRepeatCount = dLoop; + if (columnRepeatCount <= dealRowCount) { + uint32_t offset = 0; + for (uint32_t i = 0; i < dLoop; i++) { + Div(dstUb[offset], src0Ub[offset], src1Ub, dtypeMask, dealRowCount, repeatParamsDiv); + offset += dtypeMask; + } + } else { + BinaryRepeatParams columnRepeatParams; + columnRepeatParams.dstBlkStride = 1; + columnRepeatParams.src0BlkStride = 1; + columnRepeatParams.src1BlkStride = 0; + columnRepeatParams.src0RepStride = 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + columnRepeatParams.src1RepStride = 0; + columnRepeatParams.dstRepStride = 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + uint32_t offset = 0; + for (uint32_t i = 0; i < dealRowCount; i++) { + Div(dstUb[offset], src0Ub[offset], src1Ub[i * FP32_BLOCK_ELEMENT_NUM], dtypeMask, columnRepeatCount, + columnRepeatParams); + offset += columnCount; + } + } + if (dRemain > 0) { + Div(dstUb[dLoop * dtypeMask], src0Ub[dLoop * dtypeMask], src1Ub, dRemain, dealRowCount, repeatParamsDiv); + } +} + +template +__aicore__ inline void SFAVectorService::RowMuls(LocalTensor dstUb, LocalTensor src0Ub, + LocalTensor src1Ub, uint32_t dealRowCount, + uint32_t columnCount, uint32_t actualColumnCount) +{ + // muls by row, 每行的元素乘以相同的元素 + // dstUb[i, (j * 8) : (j * 8 + 7)] = src0Ub[i, (j * 8) : (j * 8 + 7)] * src1Ub[i, 0 : 7] + // src0Ub:[dealRowCount, columnCount] src1Ub:[dealRowCount, FP32_BLOCK_ELEMENT_NUM] dstUb:[dealRowCount, + // columnCount] + // dealRowCount is repeat times, must be less 256 + uint32_t repeatElementNum = FP32_REPEAT_ELEMENT_NUM; + uint32_t blockElementNum = FP32_BLOCK_ELEMENT_NUM; + + if constexpr (std::is_same::value) { + // 此限制由于每个repeat至多连续读取256B数据 + repeatElementNum = FP32_REPEAT_ELEMENT_NUM * 2; // 256/4 * 2=128 + blockElementNum = FP32_BLOCK_ELEMENT_NUM * 2; // 32/4 * 2 = 16 + } + + // 每次只能连续读取256B的数据进行计算,故每次只能处理256B/sizeof(dType)= + // 列方向分dLoop次,每次处理8列数据 + uint32_t dRemain = actualColumnCount % repeatElementNum; + uint32_t dLoop = actualColumnCount / repeatElementNum; + // REPEATE_STRIDE_UP_BOUND=256, 此限制由于src0RepStride数据类型为uint8之多256个datablock间距 + if (columnCount < REPEATE_STRIDE_UP_BOUND * blockElementNum) { + BinaryRepeatParams repeatParams; + repeatParams.dstBlkStride = 1; + repeatParams.src0BlkStride = 1; + repeatParams.src1BlkStride = 0; + repeatParams.dstRepStride = columnCount / blockElementNum; + repeatParams.src0RepStride = columnCount / blockElementNum; + repeatParams.src1RepStride = 1; + + // 如果以列为repeat所处理的次数小于行处理次数,则以列方式处理。反之则以行进行repeat处理 + if (dLoop <= dealRowCount) { + uint32_t offset = 0; + for (uint32_t i = 0; i < dLoop; i++) { + Mul(dstUb[offset], src0Ub[offset], src1Ub, repeatElementNum, dealRowCount, repeatParams); + offset += repeatElementNum; + } + } else { + BinaryRepeatParams columnRepeatParams; + columnRepeatParams.dstBlkStride = 1; + columnRepeatParams.src0BlkStride = 1; + columnRepeatParams.src1BlkStride = 0; + columnRepeatParams.dstRepStride = 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + columnRepeatParams.src0RepStride = 8; // 列方向上两次repeat起始地址间隔dtypeMask=64个元素,即8个block + columnRepeatParams.src1RepStride = 0; + for (uint32_t i = 0; i < dealRowCount; i++) { + Mul(dstUb[i * columnCount], src0Ub[i * columnCount], src1Ub[i * blockElementNum], repeatElementNum, + dLoop, columnRepeatParams); + } + } + + // 最后一次完成[dealRowCount, dRemain] * [dealRowCount, blockElementNum] 只计算有效部分 + if (dRemain > 0) { + Mul(dstUb[dLoop * repeatElementNum], src0Ub[dLoop * repeatElementNum], src1Ub, dRemain, dealRowCount, + repeatParams); + } + } else { + BinaryRepeatParams repeatParams; + repeatParams.dstRepStride = 8; + repeatParams.src0RepStride = 8; // 每个repeat为256B数据,正好8个datablock + repeatParams.src0BlkStride = 1; + repeatParams.dstBlkStride = 1; + repeatParams.src1RepStride = 0; + repeatParams.src1BlkStride = 0; + // 每次计算一行,共计算dealRowCount行 + for (uint32_t i = 0; i < dealRowCount; i++) { + // 计算一行中的dLoop个repeat, 每个repeat计算256/block_size 个data_block + Mul(dstUb[i * columnCount], src0Ub[i * columnCount], src1Ub[i * blockElementNum], repeatElementNum, dLoop, + repeatParams); + // 计算一行中的尾块 + if (dRemain > 0) { + Mul(dstUb[i * columnCount + dLoop * repeatElementNum], + src0Ub[i * columnCount + dLoop * repeatElementNum], src1Ub[i * blockElementNum], dRemain, 1, + repeatParams); + } + } + } +} + +#endif // SPARSE_FLASH_ATTENTION_SERVICE_VECTOR_MLA_H