Merged
feat(experimental): 新增 attention 与 moe 系列 10 个算子 #14792
weili_zjuAdd on Oct 28
feat(experimental): 新增 attention 与 moe 系列 10 个算子 #14792
Merged
Total: 216 files changed+34287-0
| @@ -0,0 +1,19 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 12 | +if(NOT ENABLE_TEST AND NOT BENCHMARK) | ||
| 13 | + list(REMOVE_ITEM CURRENT_DIRS tests) | ||
| 14 | +endif() | ||
| 15 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 16 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 17 | + add_subdirectory(${SUB_DIR}) | ||
| 18 | + endif() | ||
| 19 | +endforeach() | ||
| @@ -0,0 +1,82 @@ | |||
| 1 | +# BlockIndexerRearrange | ||
| 2 | + | ||
| 3 | +## 产品支持情况 | ||
| 4 | + | ||
| 5 | +| 产品 | 是否支持 | | ||
| 6 | +| ------------------------------- | :------: | | ||
| 7 | +| <term>Atlas A3系列产品</term> | √ | | ||
| 8 | +| <term>Atlas A2系列产品</term> | √ | | ||
| 9 | + | ||
| 10 | +## 功能说明 | ||
| 11 | + | ||
| 12 | +- API功能:`BlockIndexerRearrange`算子将稀疏注意力前处理阶段选取的 TopK block 索引(block 级索引)展开为逐 token 的索引。对每个 query token、每个 head,将选中的 block 索引乘以 `block_size` 并加上块内偏移 `[0, 1, ..., block_size-1]`,从而得到连续的 token 级索引;无效位置填充为 `-1`。常用于变长(TND/varlen)场景下稀疏 Attention 的索引重排。 | ||
| 13 | + | ||
| 14 | +- 计算公式: | ||
| 15 | + | ||
| 16 | + 对于第 $t$ 个 query token、第 $n$ 个 head 的第 $j$ 个 block 索引 $\text{idx}[t, n, j]$($\text{idx} \ge 0$): | ||
| 17 | + | ||
| 18 | + $$ | ||
| 19 | + \text{topk\_output}[t, n, j \cdot bs + i] = \text{idx}[t, n, j] \cdot bs + i,\quad i \in [0, bs) | ||
| 20 | + $$ | ||
| 21 | + | ||
| 22 | + 其中 $bs$ 为 `block_size`。当 $\text{idx}[t, n, j] < 0$(无效 block)或块内 token 超出实际有效 KV 长度时,对应输出填充为 `-1`。 | ||
| 23 | + | ||
| 24 | +## 参数说明 | ||
| 25 | + | ||
| 26 | +| 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 数据格式 | | ||
| 27 | +| -------------- | -------------- | -------------------------------------------------------------------- | -------- | :------: | | ||
| 28 | +| topk_indices | 输入 | block 级稀疏索引,shape 为 `[T1, N2, blockCount]`,值为 `-1` 表示无效 | INT32 | ND | | ||
| 29 | +| acc_seq_qlen | 输入 | query 累积序列长度(前缀和,首元素为 0),shape 为 `[B+1]` | INT64 | ND | | ||
| 30 | +| acc_seq_kvlen | 输入 | KV 累积序列长度(前缀和,首元素为 0),shape 为 `[B+1]` | INT64 | ND | | ||
| 31 | +| causal | 可选属性 | 是否按因果(下三角)方式计算有效 KV 长度,默认值为 `False` | BOOL | - | | ||
| 32 | +| block_size | 可选属性 | 每个 block 对应的连续 token 数,默认值为 `1` | INT64 | - | | ||
| 33 | +| topk_output | 输出 | token 级稀疏索引,shape 为 `[T1, N2, blockCount * block_size]` | INT32 | ND | | ||
| 34 | + | ||
| 35 | +## 约束说明 | ||
| 36 | + | ||
| 37 | +- 仅支持变长(TND)场景。 | ||
| 38 | +- `topk_indices` 与 `topk_output` 均为 INT32。 | ||
| 39 | +- `acc_seq_qlen`、`acc_seq_kvlen` 为累积序列长度(前缀和形式,首元素为 0)。 | ||
| 40 | +- 有效 KV 长度由 `acc_seq_kvlen` 与 `acc_seq_qlen` 之差、当前 token 在其 batch 内的偏移及 `causal` 共同决定,超出有效范围的位置填充 `-1`。 | ||
| 41 | + | ||
| 42 | +## 调用说明 | ||
| 43 | + | ||
| 44 | +本算子 Host 层通过代码仓库标准入口编译生成 `aclnnBlockIndexerRearrange` 单算子 API。编译示例: | ||
| 45 | + | ||
| 46 | +```bash | ||
| 47 | +source /usr/local/Ascend/cann/set_env.sh | ||
| 48 | +bash build.sh --pkg --experimental --soc=ascend910b --ops=block_indexer_rearrange -j8 | ||
| 49 | +``` | ||
| 50 | + | ||
| 51 | +`--soc` 可选 `ascend910b`(Atlas A2 系列)或 `ascend910_93`(Atlas A3 系列)。 | ||
| 52 | + | ||
| 53 | +## 目录结构 | ||
| 54 | + | ||
| 55 | +```text | ||
| 56 | +block_indexer_rearrange/ | ||
| 57 | + CMakeLists.txt # 算子接入仓库构建 | ||
| 58 | + op_host/ | ||
| 59 | + CMakeLists.txt | ||
| 60 | + block_indexer_rearrange_def.cpp # OpDef 定义(输入/输出/属性/平台配置) | ||
| 61 | + block_indexer_rearrange_infershape.cpp # InferShape / InferDataType | ||
| 62 | + block_indexer_rearrange_tiling.h # TilingData 定义 | ||
| 63 | + block_indexer_rearrange_tiling.cpp # Tiling 与注册 | ||
| 64 | + op_kernel/ | ||
| 65 | + block_indexer_rearrange.cpp # Ascend C 内核入口与实现 | ||
| 66 | + tests/ | ||
| 67 | + pytest/ # pytest 功能验证(CPU golden + NPU 直调) | ||
| 68 | + test_block_indexer_rearrange_single.py # 单用例测试主程序 | ||
| 69 | + block_indexer_rearrange_golden.py # CPU 侧 golden | ||
| 70 | + block_indexer_rearrange_process.py # NPU 侧算子调用 | ||
| 71 | + block_indexer_rearrange_paramset.py # 用例参数配置 | ||
| 72 | + result_compare_method.py # 结果精度对比 | ||
| 73 | + test_run.sh # 执行脚本 | ||
| 74 | +``` | ||
| 75 | + | ||
| 76 | +## 测试 | ||
| 77 | + | ||
| 78 | +参考 [tests/pytest/README.md](./tests/pytest/README.md)。在 `tests/pytest` 目录下激活自定义算子包后执行: | ||
| 79 | + | ||
| 80 | +```bash | ||
| 81 | +bash test_run.sh single | ||
| 82 | +``` | ||
| @@ -0,0 +1,18 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +add_op_to_compiled_list() | ||
| 11 | + | ||
| 12 | +if (BUILD_OPEN_PROJECT) | ||
| 13 | + target_sources(op_host_aclnn PRIVATE | ||
| 14 | + block_indexer_rearrange_def.cpp | ||
| 15 | + ) | ||
| 16 | +endif() | ||
| 17 | + | ||
| 18 | +add_modules_sources(OPTYPE block_indexer_rearrange ACLNNTYPE aclnn) | ||
| @@ -0,0 +1,62 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file block_indexer_rearrange_def.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "register/op_def_registry.h" | ||
| 17 | + | ||
| 18 | +namespace ops { | ||
| 19 | +class BlockIndexerRearrange : public OpDef { | ||
| 20 | +public: | ||
| 21 | + explicit BlockIndexerRearrange(const char *name) : OpDef(name) | ||
| 22 | + { | ||
| 23 | + this->Input("topk_indices") | ||
| 24 | + .ParamType(REQUIRED) | ||
| 25 | + .DataType({ge::DT_INT32}) | ||
| 26 | + .Format({ge::FORMAT_ND}) | ||
| 27 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 28 | + .AutoContiguous(); | ||
| 29 | + this->Input("acc_seq_qlen") | ||
| 30 | + .ParamType(REQUIRED) | ||
| 31 | + .DataType({ge::DT_INT64}) | ||
| 32 | + .Format({ge::FORMAT_ND}) | ||
| 33 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 34 | + .AutoContiguous(); | ||
| 35 | + this->Input("acc_seq_kvlen") | ||
| 36 | + .ParamType(REQUIRED) | ||
| 37 | + .DataType({ge::DT_INT64}) | ||
| 38 | + .Format({ge::FORMAT_ND}) | ||
| 39 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 40 | + .AutoContiguous(); | ||
| 41 | + this->Output("topk_output") | ||
| 42 | + .ParamType(REQUIRED) | ||
| 43 | + .DataType({ge::DT_INT32}) | ||
| 44 | + .Format({ge::FORMAT_ND}) | ||
| 45 | + .UnknownShapeFormat({ge::FORMAT_ND}); | ||
| 46 | + | ||
| 47 | + this->Attr("causal").AttrType(OPTIONAL).Bool(false); | ||
| 48 | + this->Attr("block_size").AttrType(OPTIONAL).Int(1); | ||
| 49 | + | ||
| 50 | + OpAICoreConfig aicore_config; | ||
| 51 | + aicore_config.DynamicCompileStaticFlag(true) | ||
| 52 | + .DynamicFormatFlag(true) | ||
| 53 | + .DynamicRankSupportFlag(true) | ||
| 54 | + .DynamicShapeSupportFlag(true) | ||
| 55 | + .NeedCheckSupportFlag(false) | ||
| 56 | + .PrecisionReduceFlag(true); | ||
| 57 | + this->AICore().AddConfig("ascend910b", aicore_config); | ||
| 58 | + this->AICore().AddConfig("ascend910_93", aicore_config); | ||
| 59 | + } | ||
| 60 | +}; | ||
| 61 | +OP_ADD(BlockIndexerRearrange); | ||
| 62 | +} // namespace ops | ||
| @@ -0,0 +1,63 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file block_indexer_rearrange_infershape.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include <register/op_impl_registry.h> | ||
| 17 | +#include "log/log.h" | ||
| 18 | +#include "err/ops_err.h" | ||
| 19 | + | ||
| 20 | +using namespace ge; | ||
| 21 | + | ||
| 22 | +namespace ops { | ||
| 23 | +constexpr uint32_t TOPK_INPUT_INDEX = 0; | ||
| 24 | +constexpr uint32_t TOPK_OUTPUT_INDEX = 0; | ||
| 25 | +constexpr size_t BLOCK_SIZE_ATTR_INDEX = 1; | ||
| 26 | + | ||
| 27 | +static ge::graphStatus InferShapeBlockIndexerRearrange(gert::InferShapeContext* context) | ||
| 28 | +{ | ||
| 29 | + OP_CHECK_IF(context == nullptr, OP_LOGE("BlockIndexerRearrange", "InferShapeContext is nullptr!"), | ||
| 30 | + return ge::GRAPH_FAILED); | ||
| 31 | + | ||
| 32 | + const gert::Shape* topkShape = context->GetInputShape(TOPK_INPUT_INDEX); | ||
| 33 | + OP_CHECK_NULL_WITH_CONTEXT(context, topkShape); | ||
| 34 | + gert::Shape* outShape = context->GetOutputShape(TOPK_OUTPUT_INDEX); | ||
| 35 | + OP_CHECK_NULL_WITH_CONTEXT(context, outShape); | ||
| 36 | + | ||
| 37 | + auto attrs = context->GetAttrs(); | ||
| 38 | + OP_CHECK_NULL_WITH_CONTEXT(context, attrs); | ||
| 39 | + const int64_t* blockSizePtr = attrs->GetInt(BLOCK_SIZE_ATTR_INDEX); | ||
| 40 | + OP_CHECK_NULL_WITH_CONTEXT(context, blockSizePtr); | ||
| 41 | + | ||
| 42 | + // topk_output: [T1, N2, blockCount * blockSize] | ||
| 43 | + outShape->SetDimNum(topkShape->GetDimNum()); | ||
| 44 | + outShape->SetDim(0, topkShape->GetDim(0)); | ||
| 45 | + outShape->SetDim(1, topkShape->GetDim(1)); | ||
| 46 | + outShape->SetDim(2, topkShape->GetDim(2) * (*blockSizePtr)); | ||
| 47 | + | ||
| 48 | + OP_LOGD(context->GetNodeName(), "BlockIndexerRearrange InferShape end."); | ||
| 49 | + return ge::GRAPH_SUCCESS; | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +static ge::graphStatus InferDataTypeBlockIndexerRearrange(gert::InferDataTypeContext* context) | ||
| 53 | +{ | ||
| 54 | + OP_CHECK_IF(context == nullptr, OP_LOGE("BlockIndexerRearrange", "InferDataTypeContext is nullptr!"), | ||
| 55 | + return ge::GRAPH_FAILED); | ||
| 56 | + context->SetOutputDataType(TOPK_OUTPUT_INDEX, ge::DT_INT32); | ||
| 57 | + return ge::GRAPH_SUCCESS; | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +IMPL_OP_INFERSHAPE(BlockIndexerRearrange) | ||
| 61 | + .InferShape(InferShapeBlockIndexerRearrange) | ||
| 62 | + .InferDataType(InferDataTypeBlockIndexerRearrange); | ||
| 63 | +} // namespace ops | ||
| @@ -0,0 +1,254 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file block_indexer_rearrange_tiling.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include <string> | ||
| 17 | +#include <cmath> | ||
| 18 | +#include <numeric> | ||
| 19 | +#include <sstream> | ||
| 20 | +#include "block_indexer_rearrange_tiling.h" | ||
| 21 | + | ||
| 22 | +using namespace ge; | ||
| 23 | +using namespace AscendC; | ||
| 24 | + | ||
| 25 | +namespace optiling { | ||
| 26 | + | ||
| 27 | +// tensor inputs | ||
| 28 | +constexpr size_t TOPK_INPUT_INDEX = 0; | ||
| 29 | +constexpr size_t SEQ_LENQ_INDEX = 1; | ||
| 30 | +constexpr size_t SEQ_LENKV_INDEX = 2; | ||
| 31 | + | ||
| 32 | +// attrs inputs | ||
| 33 | +constexpr size_t CAUSAL_ATTR_INDEX = 0; | ||
| 34 | +constexpr size_t BLOCK_SIZE_ATTR_INDEX = 1; | ||
| 35 | + | ||
| 36 | +class BlockIndexerRearrangeTiling { | ||
| 37 | +public: | ||
| 38 | + explicit BlockIndexerRearrangeTiling(gert::TilingContext* context) | ||
| 39 | + : context_(context) | ||
| 40 | + {} | ||
| 41 | + ~BlockIndexerRearrangeTiling() = default; | ||
| 42 | + ge::graphStatus RunTiling(); | ||
| 43 | + | ||
| 44 | +protected: | ||
| 45 | + ge::graphStatus GetPlatformInfo(); | ||
| 46 | + ge::graphStatus ProcessInput(); | ||
| 47 | + ge::graphStatus DoBlockTiling(); | ||
| 48 | + ge::graphStatus CalcWorkSpace(); | ||
| 49 | + ge::graphStatus CalcBlockDim(); | ||
| 50 | + ge::graphStatus GenTilingKey(); | ||
| 51 | + ge::graphStatus FillTiling(); | ||
| 52 | + | ||
| 53 | +protected: | ||
| 54 | + // platform info | ||
| 55 | + uint32_t sysWorkspaceSize_; | ||
| 56 | + uint32_t aicNum_; | ||
| 57 | + uint32_t aivNum_; | ||
| 58 | + uint32_t coreNum_; | ||
| 59 | + size_t ubSize_ = 0; | ||
| 60 | + size_t l1Size_ = 0; | ||
| 61 | + size_t l0bSize_ = 0; | ||
| 62 | + size_t l0cSize_ = 0; | ||
| 63 | + | ||
| 64 | + // input info | ||
| 65 | + bool causal_ = false; | ||
| 66 | + int32_t blockSize_ = 1; | ||
| 67 | + int32_t totalSeqlen_; | ||
| 68 | + int32_t headNum_; | ||
| 69 | + int32_t blockCount_; | ||
| 70 | + | ||
| 71 | + // split info | ||
| 72 | + uint32_t usedCoreNum_ = 0; | ||
| 73 | + uint32_t formerCoreProcessNums_ = 0; | ||
| 74 | + uint32_t remainCoreNum_ = 0; | ||
| 75 | + uint32_t workspaceSize_ = 0; | ||
| 76 | + | ||
| 77 | + gert::TilingContext* context_ = nullptr; | ||
| 78 | + const char* opName_ = nullptr; | ||
| 79 | + BlockIndexerRearrangeTilingData tilingData_; | ||
| 80 | +}; | ||
| 81 | + | ||
| 82 | +ge::graphStatus BlockIndexerRearrangeTiling::GetPlatformInfo() | ||
| 83 | +{ | ||
| 84 | + if (context_->GetNodeName() == nullptr) { | ||
| 85 | + OP_LOGE("BlockIndexerRearrange", "opName got from TilingContext is nullptr"); | ||
| 86 | + return ge::GRAPH_FAILED; | ||
| 87 | + } | ||
| 88 | + opName_ = context_->GetNodeName(); | ||
| 89 | + | ||
| 90 | + OP_CHECK_IF(context_->GetPlatformInfo() == nullptr, OP_LOGE(opName_, "GetPlatformInfo is nullptr."), | ||
| 91 | + return ge::GRAPH_FAILED); | ||
| 92 | + | ||
| 93 | + auto ascendcPlatform = platform_ascendc::PlatformAscendC(context_->GetPlatformInfo()); | ||
| 94 | + sysWorkspaceSize_ = ascendcPlatform.GetLibApiWorkSpaceSize(); | ||
| 95 | + | ||
| 96 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ubSize_); | ||
| 97 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L1, l1Size_); | ||
| 98 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_C, l0cSize_); | ||
| 99 | + ascendcPlatform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_B, l0bSize_); | ||
| 100 | + | ||
| 101 | + aicNum_ = ascendcPlatform.GetCoreNumAic(); | ||
| 102 | + aivNum_ = ascendcPlatform.GetCoreNumAiv(); | ||
| 103 | + coreNum_ = aivNum_; // default aiv num | ||
| 104 | + OP_LOGD(opName_, "BlockIndexerRearrange, total vector core num is %u", coreNum_); | ||
| 105 | + OP_CHECK_IF(aicNum_ == 0 || aivNum_ == 0, OP_LOGE(opName_, "num of core obtained is 0."), return ge::GRAPH_FAILED); | ||
| 106 | + | ||
| 107 | + return ge::GRAPH_SUCCESS; | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +ge::graphStatus BlockIndexerRearrangeTiling::ProcessInput() | ||
| 111 | +{ | ||
| 112 | + auto topkShape = context_->GetInputShape(TOPK_INPUT_INDEX); | ||
| 113 | + auto topkDesc = context_->GetInputDesc(TOPK_INPUT_INDEX); | ||
| 114 | + auto seqlenQShape = context_->GetInputShape(SEQ_LENQ_INDEX); | ||
| 115 | + auto seqlenQDesc = context_->GetInputDesc(SEQ_LENQ_INDEX); | ||
| 116 | + auto seqlenKvShape = context_->GetInputShape(SEQ_LENKV_INDEX); | ||
| 117 | + auto seqlenKvDesc = context_->GetInputDesc(SEQ_LENKV_INDEX); | ||
| 118 | + | ||
| 119 | + OP_CHECK_IF(topkShape == nullptr, OP_LOGE(opName_, "Shape of tensor topk is nullptr"), return ge::GRAPH_FAILED); | ||
| 120 | + OP_CHECK_IF(topkDesc == nullptr, OP_LOGE(opName_, "Desc of tensor topk is nullptr"), return ge::GRAPH_FAILED); | ||
| 121 | + OP_CHECK_IF(seqlenQShape == nullptr, OP_LOGE(opName_, "Shape of tensor seqlenQ is nullptr"), | ||
| 122 | + return ge::GRAPH_FAILED); | ||
| 123 | + OP_CHECK_IF(seqlenQDesc == nullptr, OP_LOGE(opName_, "Desc of tensor seqlenQ is nullptr"), return ge::GRAPH_FAILED); | ||
| 124 | + OP_CHECK_IF(seqlenKvShape == nullptr, OP_LOGE(opName_, "Shape of tensor seqlenKV is nullptr"), | ||
| 125 | + return ge::GRAPH_FAILED); | ||
| 126 | + OP_CHECK_IF(seqlenKvDesc == nullptr, OP_LOGE(opName_, "Desc of tensor seqlenKV is nullptr"), | ||
| 127 | + return ge::GRAPH_FAILED); | ||
| 128 | + | ||
| 129 | + auto attrs = context_->GetAttrs(); | ||
| 130 | + OP_CHECK_IF(attrs == nullptr, OP_LOGE(opName_, "attrs got from TilingContext is nullptr"), return ge::GRAPH_FAILED); | ||
| 131 | + auto causalPtr = attrs->GetAttrPointer<bool>(CAUSAL_ATTR_INDEX); | ||
| 132 | + auto blockSizePtr = attrs->GetAttrPointer<int>(BLOCK_SIZE_ATTR_INDEX); | ||
| 133 | + OP_CHECK_IF(causalPtr == nullptr, OP_LOGE(opName_, "Attr causal is nullptr"), return ge::GRAPH_FAILED); | ||
| 134 | + OP_CHECK_IF(blockSizePtr == nullptr, OP_LOGE(opName_, "Attr block_size is nullptr"), return ge::GRAPH_FAILED); | ||
| 135 | + | ||
| 136 | + causal_ = *causalPtr; | ||
| 137 | + blockSize_ = *blockSizePtr; | ||
| 138 | + | ||
| 139 | + // only support varlen now | ||
| 140 | + totalSeqlen_ = topkShape->GetStorageShape().GetDim(0); | ||
| 141 | + headNum_ = topkShape->GetStorageShape().GetDim(1); | ||
| 142 | + blockCount_ = topkShape->GetStorageShape().GetDim(2); | ||
| 143 | + return ge::GRAPH_SUCCESS; | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +ge::graphStatus BlockIndexerRearrangeTiling::DoBlockTiling() | ||
| 147 | +{ | ||
| 148 | + int32_t totalBlocks = totalSeqlen_; | ||
| 149 | + int32_t aivNum = static_cast<int32_t>(aivNum_); | ||
| 150 | + usedCoreNum_ = static_cast<uint32_t>(totalBlocks < aivNum ? totalBlocks : aivNum); | ||
| 151 | + | ||
| 152 | + formerCoreProcessNums_ = (totalBlocks + aivNum_ - 1) / aivNum_; | ||
| 153 | + remainCoreNum_ = formerCoreProcessNums_ * aivNum_ - totalBlocks; | ||
| 154 | + | ||
| 155 | + return ge::GRAPH_SUCCESS; | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +ge::graphStatus BlockIndexerRearrangeTiling::CalcWorkSpace() | ||
| 159 | +{ | ||
| 160 | + workspaceSize_ = sysWorkspaceSize_; | ||
| 161 | + | ||
| 162 | + size_t* workSpaces = context_->GetWorkspaceSizes(1); | ||
| 163 | + workSpaces[0] = workspaceSize_; | ||
| 164 | + | ||
| 165 | + FillTiling(); | ||
| 166 | + | ||
| 167 | + return ge::GRAPH_SUCCESS; | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +ge::graphStatus BlockIndexerRearrangeTiling::CalcBlockDim() | ||
| 171 | +{ | ||
| 172 | + context_->SetBlockDim(aivNum_); | ||
| 173 | + OP_LOGD(opName_, "BlockIndexerRearrange tiling block dim: %u", aivNum_); | ||
| 174 | + | ||
| 175 | + return ge::GRAPH_SUCCESS; | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +ge::graphStatus BlockIndexerRearrangeTiling::GenTilingKey() | ||
| 179 | +{ | ||
| 180 | + uint64_t tilingKey = 1; // only support int32 index | ||
| 181 | + OP_LOGD(opName_, "BlockIndexerRearrange tilingKey:%lu", tilingKey); | ||
| 182 | + context_->SetTilingKey(tilingKey); | ||
| 183 | + | ||
| 184 | + return ge::GRAPH_SUCCESS; | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +ge::graphStatus BlockIndexerRearrangeTiling::FillTiling() | ||
| 188 | +{ | ||
| 189 | + // fill base params | ||
| 190 | + tilingData_.baseParams.set_totalSeqlen(totalSeqlen_); | ||
| 191 | + tilingData_.baseParams.set_headNum(headNum_); | ||
| 192 | + tilingData_.baseParams.set_blockCount(blockCount_); | ||
| 193 | + tilingData_.baseParams.set_blockSize(blockSize_); | ||
| 194 | + tilingData_.baseParams.set_causal(causal_); | ||
| 195 | + | ||
| 196 | + OP_LOGD(opName_, "totalSeqlen is: %ld", tilingData_.baseParams.get_totalSeqlen()); | ||
| 197 | + OP_LOGD(opName_, "headNum is: %ld", tilingData_.baseParams.get_headNum()); | ||
| 198 | + OP_LOGD(opName_, "blockCount is: %ld", tilingData_.baseParams.get_blockCount()); | ||
| 199 | + OP_LOGD(opName_, "blockSize is: %ld", tilingData_.baseParams.get_blockSize()); | ||
| 200 | + OP_LOGD(opName_, "causal is: %ld", tilingData_.baseParams.get_causal()); | ||
| 201 | + | ||
| 202 | + // fill tiling params | ||
| 203 | + tilingData_.coreParams.set_usedCoreNum(usedCoreNum_); | ||
| 204 | + tilingData_.coreParams.set_formerCoreNum(aivNum_ - remainCoreNum_); | ||
| 205 | + tilingData_.coreParams.set_formerCoreProcessNums(formerCoreProcessNums_); | ||
| 206 | + tilingData_.coreParams.set_remainCoreProcessNums(formerCoreProcessNums_ - 1); | ||
| 207 | + | ||
| 208 | + OP_LOGD(opName_, "usedCoreNum is: %u", tilingData_.coreParams.get_usedCoreNum()); | ||
| 209 | + OP_LOGD(opName_, "formerCoreNum is: %d", tilingData_.coreParams.get_formerCoreNum()); | ||
| 210 | + OP_LOGD(opName_, "formerCoreProcessNums is: %u", tilingData_.coreParams.get_formerCoreProcessNums()); | ||
| 211 | + OP_LOGD(opName_, "remainCoreProcessNums is: %d", tilingData_.coreParams.get_remainCoreProcessNums()); | ||
| 212 | + | ||
| 213 | + return ge::GRAPH_SUCCESS; | ||
| 214 | +} | ||
| 215 | + | ||
| 216 | +ge::graphStatus BlockIndexerRearrangeTiling::RunTiling() | ||
| 217 | +{ | ||
| 218 | + if (GetPlatformInfo() != ge::GRAPH_SUCCESS) { | ||
| 219 | + return ge::GRAPH_FAILED; | ||
| 220 | + } | ||
| 221 | + if (ProcessInput() != ge::GRAPH_SUCCESS) { | ||
| 222 | + return ge::GRAPH_FAILED; | ||
| 223 | + } | ||
| 224 | + if (DoBlockTiling() != ge::GRAPH_SUCCESS) { | ||
| 225 | + return ge::GRAPH_FAILED; | ||
| 226 | + } | ||
| 227 | + if (CalcWorkSpace() != ge::GRAPH_SUCCESS) { | ||
| 228 | + return ge::GRAPH_FAILED; | ||
| 229 | + } | ||
| 230 | + if (CalcBlockDim() != ge::GRAPH_SUCCESS) { | ||
| 231 | + return ge::GRAPH_FAILED; | ||
| 232 | + } | ||
| 233 | + if (GenTilingKey() != ge::GRAPH_SUCCESS) { | ||
| 234 | + return ge::GRAPH_FAILED; | ||
| 235 | + } | ||
| 236 | + | ||
| 237 | + OP_CHECK_IF(context_->GetRawTilingData() == nullptr, | ||
| 238 | + OP_LOGE(opName_, "RawTilingData got from ge context is nullptr."), return ge::GRAPH_FAILED); | ||
| 239 | + tilingData_.SaveToBuffer(context_->GetRawTilingData()->GetData(), context_->GetRawTilingData()->GetCapacity()); | ||
| 240 | + context_->GetRawTilingData()->SetDataSize(tilingData_.GetDataSize()); | ||
| 241 | + | ||
| 242 | + return ge::GRAPH_SUCCESS; | ||
| 243 | +} | ||
| 244 | + | ||
| 245 | +ge::graphStatus BlockIndexerRearrangeTilingFunc(gert::TilingContext* context) | ||
| 246 | +{ | ||
| 247 | + OP_CHECK_IF(context == nullptr, OP_LOGE("BlockIndexerRearrange", "Context is nullptr."), return ge::GRAPH_FAILED); | ||
| 248 | + BlockIndexerRearrangeTiling tilingFunc(context); | ||
| 249 | + return tilingFunc.RunTiling(); | ||
| 250 | +} | ||
| 251 | + | ||
| 252 | +IMPL_OP_OPTILING(BlockIndexerRearrange).Tiling(BlockIndexerRearrangeTilingFunc); | ||
| 253 | + | ||
| 254 | +} // namespace optiling | ||
| @@ -0,0 +1,55 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file block_indexer_rearrange_tiling.h | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef BLOCK_INDEXER_REARRANGE_TILING_H | ||
| 17 | +#define BLOCK_INDEXER_REARRANGE_TILING_H | ||
| 18 | + | ||
| 19 | +#include <register/tilingdata_base.h> | ||
| 20 | +#include <tiling/tiling_api.h> | ||
| 21 | +#include <tiling/platform/platform_ascendc.h> | ||
| 22 | +#include "register/op_def_registry.h" | ||
| 23 | +#include "log/log.h" | ||
| 24 | +#include "err/ops_err.h" | ||
| 25 | + | ||
| 26 | +namespace optiling { | ||
| 27 | + | ||
| 28 | +ge::graphStatus BlockIndexerRearrangeTilingFunc(gert::TilingContext* context); | ||
| 29 | + | ||
| 30 | +BEGIN_TILING_DATA_DEF(BlockIndexerRearrangeBaseParams) | ||
| 31 | +TILING_DATA_FIELD_DEF(int64_t, totalSeqlen); | ||
| 32 | +TILING_DATA_FIELD_DEF(int64_t, headNum); | ||
| 33 | +TILING_DATA_FIELD_DEF(int64_t, blockCount); | ||
| 34 | +TILING_DATA_FIELD_DEF(int64_t, blockSize); | ||
| 35 | +TILING_DATA_FIELD_DEF(int64_t, causal); | ||
| 36 | +END_TILING_DATA_DEF; | ||
| 37 | +REGISTER_TILING_DATA_CLASS(BlockIndexerRearrangeBaseParamsOp, BlockIndexerRearrangeBaseParams) | ||
| 38 | + | ||
| 39 | +BEGIN_TILING_DATA_DEF(BlockIndexerRearrangeCoreParams) | ||
| 40 | +TILING_DATA_FIELD_DEF(int32_t, usedCoreNum); | ||
| 41 | +TILING_DATA_FIELD_DEF(int32_t, formerCoreNum); | ||
| 42 | +TILING_DATA_FIELD_DEF(int32_t, formerCoreProcessNums); | ||
| 43 | +TILING_DATA_FIELD_DEF(int32_t, remainCoreProcessNums); | ||
| 44 | +END_TILING_DATA_DEF; | ||
| 45 | +REGISTER_TILING_DATA_CLASS(BlockIndexerRearrangeCoreParamsOp, BlockIndexerRearrangeCoreParams) | ||
| 46 | + | ||
| 47 | +BEGIN_TILING_DATA_DEF(BlockIndexerRearrangeTilingData) | ||
| 48 | +TILING_DATA_FIELD_DEF_STRUCT(BlockIndexerRearrangeBaseParams, baseParams); | ||
| 49 | +TILING_DATA_FIELD_DEF_STRUCT(BlockIndexerRearrangeCoreParams, coreParams); | ||
| 50 | +END_TILING_DATA_DEF; | ||
| 51 | + | ||
| 52 | +REGISTER_TILING_DATA_CLASS(BlockIndexerRearrange, BlockIndexerRearrangeTilingData) | ||
| 53 | + | ||
| 54 | +} // namespace optiling | ||
| 55 | +#endif // BLOCK_INDEXER_REARRANGE_TILING_H | ||
| @@ -0,0 +1,300 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file block_indexer_rearrange.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "kernel_operator.h" | ||
| 17 | +#include "kernel_operator_list_tensor_intf.h" | ||
| 18 | +#include "kernel_tiling/kernel_tiling.h" | ||
| 19 | + | ||
| 20 | +using namespace AscendC; | ||
| 21 | + | ||
| 22 | +#define SET_FLAG(trigger, waiter, e) AscendC::SetFlag<AscendC::HardEvent::trigger##_##waiter>((e)) | ||
| 23 | +#define WAIT_FLAG(trigger, waiter, e) AscendC::WaitFlag<AscendC::HardEvent::trigger##_##waiter>((e)) | ||
| 24 | + | ||
| 25 | +constexpr static int32_t REPEAT_MAX_BYTES = 256; | ||
| 26 | +constexpr static int32_t BLOCK_BYTES = 32; | ||
| 27 | +constexpr static int32_t REPEAT_MAX_BLOCKS = 255; | ||
| 28 | + | ||
| 29 | +template <typename INPUT_T> | ||
| 30 | +class BlockIndexerRearrange { | ||
| 31 | +public: | ||
| 32 | + __aicore__ inline BlockIndexerRearrange(){}; | ||
| 33 | + | ||
| 34 | + __aicore__ inline void Init(__gm__ uint8_t* topk_indices, __gm__ uint8_t* acc_seqlen_q, | ||
| 35 | + __gm__ uint8_t* acc_seqlen_kv, __gm__ uint8_t* topk_output, __gm__ uint8_t* workspace, | ||
| 36 | + const BlockIndexerRearrangeTilingData* __restrict tiling, TPipe* tPipe); | ||
| 37 | + | ||
| 38 | + __aicore__ inline void Process(); | ||
| 39 | + | ||
| 40 | +protected: | ||
| 41 | + int32_t blockIdx; | ||
| 42 | + TPipe* pipe; | ||
| 43 | + const BlockIndexerRearrangeTilingData* __restrict tilingData; | ||
| 44 | + | ||
| 45 | + // host base info | ||
| 46 | + int32_t batchSize; | ||
| 47 | + int32_t Tq; | ||
| 48 | + int32_t Tk; | ||
| 49 | + int32_t headNum; | ||
| 50 | + int32_t blockCount; | ||
| 51 | + int32_t blockSize; | ||
| 52 | + bool causal; | ||
| 53 | + int64_t actualS1Len = 0; | ||
| 54 | + int64_t actualS2Len = 0; | ||
| 55 | + | ||
| 56 | + // host tiling info | ||
| 57 | + int32_t usedCoreNum; | ||
| 58 | + int32_t formerCoreNum; | ||
| 59 | + int32_t formerCoreProcessNums; | ||
| 60 | + int32_t remainCoreProcessNums; | ||
| 61 | + | ||
| 62 | + // device block info | ||
| 63 | + int32_t actualProcessNums; | ||
| 64 | + int32_t t1Offset{0}; | ||
| 65 | + int32_t t2Offset{0}; | ||
| 66 | + int32_t curS1{0}; | ||
| 67 | + int32_t curS2{0}; | ||
| 68 | + | ||
| 69 | + // device indexe | ||
| 70 | + int64_t bIndex{0}; | ||
| 71 | + int64_t n2Index{0}; | ||
| 72 | + int64_t s1Index{0}; | ||
| 73 | + | ||
| 74 | + // input & output | ||
| 75 | + GlobalTensor<INPUT_T> topkInputGm; | ||
| 76 | + GlobalTensor<INPUT_T> topkOutputGm; | ||
| 77 | + GM_ADDR seqQlenAddr; | ||
| 78 | + GM_ADDR seqKlenAddr; | ||
| 79 | + | ||
| 80 | + // tbuf | ||
| 81 | + TBuf<> topkInputBuf; | ||
| 82 | + TBuf<> brcbBuf; | ||
| 83 | + TBuf<> helpBuf; | ||
| 84 | + | ||
| 85 | +private: | ||
| 86 | + __aicore__ inline void GetTndSeqLen(const GM_ADDR actual_seq_qlen_addr, const GM_ADDR actual_seq_kvlen_addr, | ||
| 87 | + const int64_t t1Idx, int64_t& bIdx); | ||
| 88 | + __aicore__ inline void VecCompute(); | ||
| 89 | +}; | ||
| 90 | + | ||
| 91 | +template <typename INPUT_T> | ||
| 92 | +__aicore__ inline void BlockIndexerRearrange<INPUT_T>::Init(__gm__ uint8_t* topk_indices, __gm__ uint8_t* acc_seqlen_q, | ||
| 93 | + __gm__ uint8_t* acc_seqlen_kv, __gm__ uint8_t* topk_output, | ||
| 94 | + __gm__ uint8_t* workspace, | ||
| 95 | + const BlockIndexerRearrangeTilingData* __restrict tiling, | ||
| 96 | + TPipe* tPipe) | ||
| 97 | +{ | ||
| 98 | + blockIdx = GetBlockIdx(); | ||
| 99 | + pipe = tPipe; | ||
| 100 | + tilingData = tiling; | ||
| 101 | + | ||
| 102 | + // base info | ||
| 103 | + Tq = tilingData->baseParams.totalSeqlen; | ||
| 104 | + headNum = tilingData->baseParams.headNum; | ||
| 105 | + blockCount = tilingData->baseParams.blockCount; | ||
| 106 | + blockSize = tilingData->baseParams.blockSize; | ||
| 107 | + causal = tilingData->baseParams.causal; | ||
| 108 | + | ||
| 109 | + // tiling info | ||
| 110 | + usedCoreNum = tilingData->coreParams.usedCoreNum; | ||
| 111 | + formerCoreNum = tilingData->coreParams.formerCoreNum; | ||
| 112 | + formerCoreProcessNums = tilingData->coreParams.formerCoreProcessNums; | ||
| 113 | + remainCoreProcessNums = tilingData->coreParams.remainCoreProcessNums; | ||
| 114 | + | ||
| 115 | + topkInputGm.SetGlobalBuffer((__gm__ INPUT_T*)topk_indices); | ||
| 116 | + seqQlenAddr = acc_seqlen_q; | ||
| 117 | + seqKlenAddr = acc_seqlen_kv; | ||
| 118 | + topkOutputGm.SetGlobalBuffer((__gm__ INPUT_T*)topk_output); | ||
| 119 | + | ||
| 120 | + // init buffer | ||
| 121 | + pipe->InitBuffer(topkInputBuf, 32 * 1024); // 32k | ||
| 122 | + pipe->InitBuffer(brcbBuf, 128 * 1024); | ||
| 123 | + pipe->InitBuffer(helpBuf, 1024); | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +template <typename INPUT_T> | ||
| 127 | +__aicore__ inline void BlockIndexerRearrange<INPUT_T>::Process() | ||
| 128 | +{ | ||
| 129 | + if (blockIdx < formerCoreNum) { | ||
| 130 | + actualProcessNums = formerCoreProcessNums; | ||
| 131 | + } else { | ||
| 132 | + actualProcessNums = remainCoreProcessNums; | ||
| 133 | + } | ||
| 134 | + | ||
| 135 | + for (int32_t i = 0; i < actualProcessNums; i++) { | ||
| 136 | + int32_t t1Index = blockIdx + usedCoreNum * i; | ||
| 137 | + GetTndSeqLen(seqQlenAddr, seqKlenAddr, t1Index, bIndex); | ||
| 138 | + for (n2Index = 0; n2Index < headNum; n2Index++) { | ||
| 139 | + VecCompute(); | ||
| 140 | + } | ||
| 141 | + } | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +template <typename INPUT_T> | ||
| 145 | +__aicore__ inline void BlockIndexerRearrange<INPUT_T>::GetTndSeqLen(const GM_ADDR actual_seq_qlen_addr, | ||
| 146 | + const GM_ADDR actual_seq_kvlen_addr, | ||
| 147 | + const int64_t t1Idx, int64_t& bIdx) | ||
| 148 | +{ | ||
| 149 | + int64_t curT1 = ((__gm__ int64_t*)actual_seq_qlen_addr)[bIndex]; | ||
| 150 | + while (t1Idx >= curT1) { | ||
| 151 | + curT1 = ((__gm__ int64_t*)actual_seq_qlen_addr)[++bIndex]; | ||
| 152 | + } | ||
| 153 | + | ||
| 154 | + if (unlikely(bIndex == 0)) { | ||
| 155 | + t1Offset = 0; | ||
| 156 | + t2Offset = 0; | ||
| 157 | + curS1 = ((__gm__ int64_t*)actual_seq_qlen_addr)[bIndex]; | ||
| 158 | + curS2 = ((__gm__ int64_t*)actual_seq_kvlen_addr)[bIndex]; | ||
| 159 | + } else { | ||
| 160 | + t1Offset = ((__gm__ int64_t*)actual_seq_qlen_addr)[bIndex - 1]; | ||
| 161 | + t2Offset = ((__gm__ int64_t*)actual_seq_kvlen_addr)[bIndex - 1]; | ||
| 162 | + curS1 = ((__gm__ int64_t*)actual_seq_qlen_addr)[bIndex] - ((__gm__ int64_t*)actual_seq_qlen_addr)[bIndex - 1]; | ||
| 163 | + curS2 = ((__gm__ int64_t*)actual_seq_kvlen_addr)[bIndex] - ((__gm__ int64_t*)actual_seq_kvlen_addr)[bIndex - 1]; | ||
| 164 | + } | ||
| 165 | + s1Index = t1Idx - t1Offset; | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +template <typename INPUT_T> | ||
| 169 | +__aicore__ inline void BlockIndexerRearrange<INPUT_T>::VecCompute() | ||
| 170 | +{ | ||
| 171 | + event_t Mte2WaitMte3 = static_cast<event_t>(GetTPipePtr()->AllocEventID<HardEvent::MTE3_MTE2>()); | ||
| 172 | + event_t vWaitMte2 = static_cast<event_t>(GetTPipePtr()->AllocEventID<HardEvent::MTE2_V>()); | ||
| 173 | + event_t Mte3WaitS = static_cast<event_t>(GetTPipePtr()->AllocEventID<HardEvent::S_MTE3>()); | ||
| 174 | + event_t Mte3WaitV = static_cast<event_t>(GetTPipePtr()->AllocEventID<HardEvent::V_MTE3>()); | ||
| 175 | + | ||
| 176 | + uint64_t s1Offset = (t1Offset + s1Index) * headNum * blockCount; | ||
| 177 | + uint64_t nOffset = n2Index * blockCount; | ||
| 178 | + uint64_t gmOffset = s1Offset + nOffset; | ||
| 179 | + int32_t blockEleNums = BLOCK_BYTES / sizeof(INPUT_T); | ||
| 180 | + | ||
| 181 | + LocalTensor<INPUT_T> topkInputTensor = topkInputBuf.template Get<INPUT_T>(); | ||
| 182 | + LocalTensor<INPUT_T> brcbTensor = brcbBuf.template Get<INPUT_T>(); | ||
| 183 | + LocalTensor<INPUT_T> helpTensor = helpBuf.template Get<INPUT_T>(); | ||
| 184 | + DataCopyExtParams dataCopyParams; | ||
| 185 | + DataCopyPadExtParams<INPUT_T> padParams; | ||
| 186 | + dataCopyParams.blockCount = 1; | ||
| 187 | + dataCopyParams.blockLen = blockCount * sizeof(INPUT_T); | ||
| 188 | + dataCopyParams.srcStride = 0; | ||
| 189 | + dataCopyParams.dstStride = 0; | ||
| 190 | + | ||
| 191 | + SET_FLAG(MTE3, MTE2, Mte2WaitMte3); | ||
| 192 | + WAIT_FLAG(MTE3, MTE2, Mte2WaitMte3); | ||
| 193 | + | ||
| 194 | + DataCopyPad(topkInputTensor, topkInputGm[gmOffset], dataCopyParams, padParams); | ||
| 195 | + | ||
| 196 | + SET_FLAG(MTE2, V, vWaitMte2); | ||
| 197 | + WAIT_FLAG(MTE2, V, vWaitMte2); | ||
| 198 | + | ||
| 199 | + // brcb parms | ||
| 200 | + int32_t repeatTims = (blockCount + 8 - 1) / 8; // 每次固定处理8个 | ||
| 201 | + int32_t maxRepeatOffset = REPEAT_MAX_BLOCKS * 8; // src 一次最大offset,对应dst offset 需要 * blockEleNums | ||
| 202 | + int32_t loop = repeatTims / REPEAT_MAX_BLOCKS; | ||
| 203 | + int32_t remain = repeatTims % REPEAT_MAX_BLOCKS; | ||
| 204 | + for (int32_t i = 0; i < loop; i++) { | ||
| 205 | + Brcb(brcbTensor[i * maxRepeatOffset * blockEleNums], topkInputTensor[i * maxRepeatOffset], REPEAT_MAX_BLOCKS, | ||
| 206 | + {1, 8}); | ||
| 207 | + } | ||
| 208 | + if (likely(remain)) { | ||
| 209 | + Brcb(brcbTensor[loop * maxRepeatOffset * blockEleNums], topkInputTensor[loop * maxRepeatOffset], remain, | ||
| 210 | + {1, 8}); | ||
| 211 | + } | ||
| 212 | + | ||
| 213 | + PipeBarrier<PIPE_V>(); | ||
| 214 | + // creat offset vector [0, 1, 2, ...] | ||
| 215 | + CreateVecIndex(helpTensor, (INPUT_T)0, blockEleNums); | ||
| 216 | + PipeBarrier<PIPE_V>(); | ||
| 217 | + | ||
| 218 | + int32_t validS2Len = s1Index + curS2 - curS1 + 1; | ||
| 219 | + int32_t validTopkSize = (validS2Len + blockSize - 1) / blockSize; | ||
| 220 | + validTopkSize = validTopkSize > blockCount ? blockCount : validTopkSize; | ||
| 221 | + | ||
| 222 | + int32_t totalEle = validTopkSize * blockEleNums; | ||
| 223 | + int32_t maxProcessOnce = REPEAT_MAX_BYTES / sizeof(INPUT_T); | ||
| 224 | + loop = totalEle / maxProcessOnce; | ||
| 225 | + remain = totalEle % maxProcessOnce; | ||
| 226 | + Muls(brcbTensor, brcbTensor, blockSize, totalEle); | ||
| 227 | + PipeBarrier<PIPE_V>(); | ||
| 228 | + | ||
| 229 | + if (unlikely(loop > REPEAT_MAX_BLOCKS)) { | ||
| 230 | + int32_t max_repeat_loops = loop / REPEAT_MAX_BLOCKS; | ||
| 231 | + int32_t max_repeat_remains = loop % REPEAT_MAX_BLOCKS; | ||
| 232 | + | ||
| 233 | + for (int32_t idx = 0; idx < max_repeat_loops; idx++) { | ||
| 234 | + Add(brcbTensor[idx * REPEAT_MAX_BLOCKS * maxProcessOnce], | ||
| 235 | + brcbTensor[idx * REPEAT_MAX_BLOCKS * maxProcessOnce], helpTensor, maxProcessOnce, REPEAT_MAX_BLOCKS, | ||
| 236 | + {1, 1, 0, /*block stride*/ | ||
| 237 | + 8, 8, 0 /*dst rep stride*/}); | ||
| 238 | + } | ||
| 239 | + if (likely(max_repeat_remains)) { | ||
| 240 | + Add(brcbTensor[max_repeat_loops * REPEAT_MAX_BLOCKS * maxProcessOnce], | ||
| 241 | + brcbTensor[max_repeat_loops * REPEAT_MAX_BLOCKS * maxProcessOnce], helpTensor, maxProcessOnce, | ||
| 242 | + REPEAT_MAX_BLOCKS, | ||
| 243 | + {1, 1, 0, /*block stride*/ | ||
| 244 | + 8, 8, 0 /*dst rep stride*/}); | ||
| 245 | + } | ||
| 246 | + } else { | ||
| 247 | + Add(brcbTensor, brcbTensor, helpTensor, maxProcessOnce, loop, | ||
| 248 | + {1, 1, 0, /*block stride*/ | ||
| 249 | + 8, 8, 0 /*dst rep stride*/}); | ||
| 250 | + } | ||
| 251 | + if (likely(remain)) { | ||
| 252 | + Add(brcbTensor[loop * maxProcessOnce], brcbTensor[loop * maxProcessOnce], helpTensor, remain, 1, | ||
| 253 | + {1, 1, 0, /*block stride*/ | ||
| 254 | + 8, 8, 0 /*dst rep stride*/}); | ||
| 255 | + } | ||
| 256 | + PipeBarrier<PIPE_V>(); | ||
| 257 | + | ||
| 258 | + int32_t validTail = validS2Len % blockSize; | ||
| 259 | + int32_t maskLen = blockEleNums - validTail; | ||
| 260 | + if (validTail > 0) { | ||
| 261 | + for (int i = 0; i < maskLen; i++) { | ||
| 262 | + brcbTensor.SetValue((validTopkSize - 1) * blockEleNums + validTail + i, (INPUT_T)-1); | ||
| 263 | + } | ||
| 264 | + SET_FLAG(S, MTE3, Mte3WaitS); | ||
| 265 | + WAIT_FLAG(S, MTE3, Mte3WaitS); | ||
| 266 | + } | ||
| 267 | + | ||
| 268 | + SET_FLAG(V, MTE3, Mte3WaitV); | ||
| 269 | + WAIT_FLAG(V, MTE3, Mte3WaitV); | ||
| 270 | + | ||
| 271 | + dataCopyParams.blockCount = blockCount; | ||
| 272 | + dataCopyParams.blockLen = blockSize * sizeof(INPUT_T); | ||
| 273 | + dataCopyParams.srcStride = 0; | ||
| 274 | + dataCopyParams.dstStride = 0; | ||
| 275 | + int64_t outOffset = (t1Offset + s1Index) * headNum * blockCount * blockSize + n2Index * blockCount * blockSize; | ||
| 276 | + DataCopyPad(topkOutputGm[outOffset], brcbTensor, dataCopyParams); | ||
| 277 | +} | ||
| 278 | + | ||
| 279 | +extern "C" __global__ __aicore__ void block_indexer_rearrange(__gm__ uint8_t* topk_indices, | ||
| 280 | + __gm__ uint8_t* acc_seqlen_q, | ||
| 281 | + __gm__ uint8_t* acc_seqlen_kv, | ||
| 282 | + __gm__ uint8_t* topk_output, __gm__ uint8_t* workspace, | ||
| 283 | + __gm__ uint8_t* tiling) | ||
| 284 | +{ | ||
| 285 | + TPipe tPipe; | ||
| 286 | + set_mask_norm(); | ||
| 287 | + SetSysWorkspace(workspace); | ||
| 288 | + __gm__ uint8_t* user = GetUserWorkspace(workspace); | ||
| 289 | + | ||
| 290 | + GET_TILING_DATA_WITH_STRUCT(BlockIndexerRearrangeTilingData, tiling_data_in, tiling); | ||
| 291 | + const BlockIndexerRearrangeTilingData* __restrict tilingData = &tiling_data_in; | ||
| 292 | + | ||
| 293 | + if (TILING_KEY_IS(1)) { | ||
| 294 | + BlockIndexerRearrange<int32_t> op; | ||
| 295 | + op.Init(topk_indices, acc_seqlen_q, acc_seqlen_kv, topk_output, user, tilingData, &tPipe); | ||
| 296 | + op.Process(); | ||
| 297 | + } | ||
| 298 | + | ||
| 299 | + return; | ||
| 300 | +} | ||
| @@ -0,0 +1,43 @@ | |||
| 1 | +# block_indexer_rearrange算子测试框架 | ||
| 2 | + | ||
| 3 | +## 功能说明 | ||
| 4 | +基于pytest测试框架,实现block_indexer_rearrange算子的功能验证: | ||
| 5 | +- **CPU侧**:复现算子功能用以生成golden数据 | ||
| 6 | +- **NPU侧**:通过TorchNPU进行算子直调获取实际数据 | ||
| 7 | +- **精度对比**:进行CPU与NPU结果的精确对比验证算子功能 | ||
| 8 | + | ||
| 9 | +## 当前实现范围 | ||
| 10 | + | ||
| 11 | +### 参数限制 | ||
| 12 | +- **数据格式:** TND(变长) | ||
| 13 | +- **数据类型:** INT32(索引)、INT64(序列长度) | ||
| 14 | + | ||
| 15 | +### 环境配置 | ||
| 16 | +#### 前置要求 | ||
| 17 | +1. 确认TorchNPU为最新版本 | ||
| 18 | +2. 参考[Attention融合算子Experimental使用说明](../../../Attention融合算子Experimental使用说明.md)激活CANN包和自定义算子包 | ||
| 19 | + | ||
| 20 | +## 文件结构 | ||
| 21 | +- test_run.sh # 执行脚本 | ||
| 22 | +- block_indexer_rearrange_golden.py # cpu侧算子golden实现 | ||
| 23 | +- result_compare_method.py # cpu golden与npu输出精度对比 | ||
| 24 | +- block_indexer_rearrange_process.py # 调用算子获取npu输出 | ||
| 25 | +- block_indexer_rearrange_paramset.py # 用例入参配置 | ||
| 26 | +- test_block_indexer_rearrange_single.py # pytest测试单用例运行主程序 | ||
| 27 | +- utils.py # 结果保存工具 | ||
| 28 | +- pytest.ini # 创建测试标记 | ||
| 29 | + | ||
| 30 | +## 使用方法 | ||
| 31 | + | ||
| 32 | +在pytest文件夹路径下执行: | ||
| 33 | + | ||
| 34 | +1. 手动配置`block_indexer_rearrange_paramset.py`的参数 | ||
| 35 | +2. 执行指令: | ||
| 36 | +```bash | ||
| 37 | +bash test_run.sh single | ||
| 38 | +``` | ||
| 39 | + | ||
| 40 | +支持自定义结果保存路径: | ||
| 41 | +```bash | ||
| 42 | +bash test_run.sh single -R "./result/bir_result.xlsx" | ||
| 43 | +``` | ||
| @@ -0,0 +1,150 @@ | |||
| 1 | +#!/usr/bin/python | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +"""直接调用 CANN aclnn C 接口(ctypes),不依赖 torch_npu 的算子 op-plugin 绑定。 | ||
| 14 | + | ||
| 15 | +依赖:libcust_opapi.so(算子自带 aclnn)、libnnopbase.so(aclCreateTensor/aclCreateIntArray)、 | ||
| 16 | +libascendcl(aclrt*)。torch/torch_npu 仅用于申请 NPU 显存和获取 aclrtStream。 | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +import ctypes | ||
| 20 | +from ctypes import ( | ||
| 21 | + c_void_p, | ||
| 22 | + c_int64, | ||
| 23 | + c_uint64, | ||
| 24 | + c_int, | ||
| 25 | + c_char_p, | ||
| 26 | + c_double, | ||
| 27 | + c_bool, | ||
| 28 | + byref, | ||
| 29 | + POINTER, | ||
| 30 | +) | ||
| 31 | + | ||
| 32 | +import torch | ||
| 33 | +import torch_npu | ||
| 34 | + | ||
| 35 | +_OPAPI = ctypes.CDLL("libcust_opapi.so") | ||
| 36 | +_NNOP = ctypes.CDLL("libnnopbase.so") | ||
| 37 | + | ||
| 38 | +_DTYPE = { | ||
| 39 | + torch.float32: 0, | ||
| 40 | + torch.float16: 1, | ||
| 41 | + torch.int8: 2, | ||
| 42 | + torch.int32: 3, | ||
| 43 | + torch.uint8: 4, | ||
| 44 | + torch.int16: 6, | ||
| 45 | + torch.uint16: 7, | ||
| 46 | + torch.uint32: 8, | ||
| 47 | + torch.uint64: 10, | ||
| 48 | + torch.int64: 9, | ||
| 49 | + torch.float64: 11, | ||
| 50 | + torch.bool: 12, | ||
| 51 | + torch.bfloat16: 27, | ||
| 52 | +} | ||
| 53 | +_FORMAT_ND = 2 | ||
| 54 | + | ||
| 55 | +_NNOP.aclCreateTensor.restype = c_void_p | ||
| 56 | +_NNOP.aclCreateTensor.argtypes = [ | ||
| 57 | + POINTER(c_int64), | ||
| 58 | + c_uint64, | ||
| 59 | + c_int, | ||
| 60 | + POINTER(c_int64), | ||
| 61 | + c_int64, | ||
| 62 | + c_int, | ||
| 63 | + POINTER(c_int64), | ||
| 64 | + c_uint64, | ||
| 65 | + c_void_p, | ||
| 66 | +] | ||
| 67 | +_NNOP.aclCreateIntArray.restype = c_void_p | ||
| 68 | +_NNOP.aclCreateIntArray.argtypes = [POINTER(c_int64), c_uint64] | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def to_acl(tensor): | ||
| 72 | + """把 torch NPU tensor 包装成 aclTensor(None -> 空指针,用于可选输入)。""" | ||
| 73 | + if tensor is None: | ||
| 74 | + return c_void_p(None) | ||
| 75 | + shape = list(tensor.shape) | ||
| 76 | + n = len(shape) | ||
| 77 | + dims = (c_int64 * n)(*shape) | ||
| 78 | + strides, s = [], 1 | ||
| 79 | + for d in reversed(shape): | ||
| 80 | + strides.insert(0, s) | ||
| 81 | + s *= d | ||
| 82 | + strd = (c_int64 * n)(*strides) | ||
| 83 | + return _NNOP.aclCreateTensor( | ||
| 84 | + dims, | ||
| 85 | + n, | ||
| 86 | + _DTYPE[tensor.dtype], | ||
| 87 | + strd, | ||
| 88 | + 0, | ||
| 89 | + _FORMAT_ND, | ||
| 90 | + dims, | ||
| 91 | + n, | ||
| 92 | + c_void_p(tensor.data_ptr()), | ||
| 93 | + ) | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +def int_array(values): | ||
| 97 | + if values is None: | ||
| 98 | + return c_void_p(None) | ||
| 99 | + arr = (c_int64 * len(values))(*values) | ||
| 100 | + return _NNOP.aclCreateIntArray(arr, len(values)) | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +_CTYPE = { | ||
| 104 | + "tensor": c_void_p, | ||
| 105 | + "int64": c_int64, | ||
| 106 | + "double": c_double, | ||
| 107 | + "bool": c_bool, | ||
| 108 | + "str": c_char_p, | ||
| 109 | + "intarray": c_void_p, | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +def call(get_ws_name, op_name, spec): | ||
| 114 | + """spec: [(kind, value), ...],按 aclnn GetWorkspaceSize 的形参顺序(含输出)。 | ||
| 115 | + | ||
| 116 | + kind ∈ {tensor, int64, double, bool, str, intarray} | ||
| 117 | + """ | ||
| 118 | + fn = getattr(_OPAPI, get_ws_name) | ||
| 119 | + fn.restype = c_int | ||
| 120 | + argtypes, cargs = [], [] | ||
| 121 | + for kind, value in spec: | ||
| 122 | + argtypes.append(_CTYPE[kind]) | ||
| 123 | + if kind == "tensor": | ||
| 124 | + cargs.append(to_acl(value)) | ||
| 125 | + elif kind == "intarray": | ||
| 126 | + cargs.append(int_array(value)) | ||
| 127 | + elif kind == "str": | ||
| 128 | + cargs.append(c_char_p(None) if value is None else c_char_p(value.encode())) | ||
| 129 | + else: | ||
| 130 | + cargs.append(value) | ||
| 131 | + | ||
| 132 | + ws = c_uint64(0) | ||
| 133 | + executor = c_void_p() | ||
| 134 | + fn.argtypes = argtypes + [POINTER(c_uint64), POINTER(c_void_p)] | ||
| 135 | + st = fn(*(cargs + [byref(ws), byref(executor)])) | ||
| 136 | + if st != 0: | ||
| 137 | + raise RuntimeError("%s failed, status=%d" % (get_ws_name, st)) | ||
| 138 | + | ||
| 139 | + run = getattr(_OPAPI, op_name) | ||
| 140 | + run.restype = c_int | ||
| 141 | + run.argtypes = [c_void_p, c_uint64, c_void_p, c_void_p] | ||
| 142 | + dev = torch.npu.current_device() | ||
| 143 | + ws_tensor = torch.empty( | ||
| 144 | + max(int(ws.value), 1), dtype=torch.uint8, device="npu:%d" % dev | ||
| 145 | + ) | ||
| 146 | + stream = c_void_p(torch_npu.npu.current_stream().npu_stream) | ||
| 147 | + st = run(c_void_p(ws_tensor.data_ptr()), ws.value, executor, stream) | ||
| 148 | + if st != 0: | ||
| 149 | + raise RuntimeError("%s failed, status=%d" % (op_name, st)) | ||
| 150 | + torch.npu.synchronize() | ||
Aexperimental/attention/block_indexer_rearrange/tests/pytest/block_indexer_rearrange_golden.py+132-0
| @@ -0,0 +1,132 @@ | |||
| 1 | +#!/usr/bin/python | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +import math | ||
| 14 | + | ||
| 15 | +import numpy as np | ||
| 16 | +import torch | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def _get_tnd_idx(acc_q_len, t_idx): | ||
| 20 | + b_idx = 0 | ||
| 21 | + while t_idx >= acc_q_len[b_idx + 1]: | ||
| 22 | + b_idx += 1 | ||
| 23 | + s1_idx = t_idx - acc_q_len[b_idx] | ||
| 24 | + return b_idx, s1_idx | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def _randperm(n, device): | ||
| 28 | + if n <= 0: | ||
| 29 | + return torch.empty(0, dtype=torch.int32, device=device) | ||
| 30 | + return torch.randperm(n, device=device).to(torch.int32) | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +def _gen_topk_indices( | ||
| 34 | + acc_seqlen_q, | ||
| 35 | + cur_seqlen_q, | ||
| 36 | + cur_seqlen_kv, | ||
| 37 | + block_size, | ||
| 38 | + block_count, | ||
| 39 | + n2, | ||
| 40 | + device, | ||
| 41 | + seed=42, | ||
| 42 | +): | ||
| 43 | + """按 TND 变长规则生成随机的 block 级 topk 索引(无效位置为 -1)。""" | ||
| 44 | + torch.manual_seed(seed) | ||
| 45 | + t1 = int(acc_seqlen_q[-1]) | ||
| 46 | + topk_indices = torch.full( | ||
| 47 | + (t1, n2, block_count), -1, dtype=torch.int32, device=device | ||
| 48 | + ) | ||
| 49 | + for t in range(t1): | ||
| 50 | + b_idx, s1_idx = _get_tnd_idx(acc_seqlen_q, t) | ||
| 51 | + cur_s1 = cur_seqlen_q[b_idx] | ||
| 52 | + cur_s2 = cur_seqlen_kv[b_idx] | ||
| 53 | + delta_s = cur_s2 - cur_s1 | ||
| 54 | + threshold = delta_s + s1_idx + 1 | ||
| 55 | + threshold = threshold if threshold >= 0 else 0 | ||
| 56 | + valid_block_count = math.ceil(threshold / block_size) | ||
| 57 | + for j in range(n2): | ||
| 58 | + if valid_block_count >= block_count: | ||
| 59 | + topk_indices[t][j][-1] = valid_block_count - 1 | ||
| 60 | + topk_indices[t][j][0:-1] = _randperm(valid_block_count - 1, device)[ | ||
| 61 | + : block_count - 1 | ||
| 62 | + ] | ||
| 63 | + else: | ||
| 64 | + topk_indices[t][j][valid_block_count - 1] = valid_block_count - 1 | ||
| 65 | + topk_indices[t][j][0 : valid_block_count - 1] = _randperm( | ||
| 66 | + valid_block_count - 1, device | ||
| 67 | + ) | ||
| 68 | + return topk_indices | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def _cpu_golden( | ||
| 72 | + topk_indices, acc_seqlen_q, cur_seqlen_q, cur_seqlen_kv, block_size, block_count | ||
| 73 | +): | ||
| 74 | + """CPU 侧 golden:将 block 级索引展开为逐 token 索引,并处理尾块与无效位置(-1)。""" | ||
| 75 | + t1, n2, _ = topk_indices.shape | ||
| 76 | + expanded = topk_indices.unsqueeze(-1) * block_size + torch.arange( | ||
| 77 | + block_size, dtype=torch.int32, device=topk_indices.device | ||
| 78 | + ) | ||
| 79 | + mask = (topk_indices <= -1).unsqueeze(-1) | ||
| 80 | + fill_value = torch.full_like(expanded, -1) | ||
| 81 | + golden = torch.where(mask, fill_value, expanded).view(t1, n2, -1) | ||
| 82 | + | ||
| 83 | + for t in range(t1): | ||
| 84 | + b_idx, s1_idx = _get_tnd_idx(acc_seqlen_q, t) | ||
| 85 | + cur_s1 = cur_seqlen_q[b_idx] | ||
| 86 | + cur_s2 = cur_seqlen_kv[b_idx] | ||
| 87 | + threshold = cur_s2 - cur_s1 + 1 + s1_idx | ||
| 88 | + valid_block_count = math.ceil(threshold / block_size) | ||
| 89 | + mask_size = valid_block_count * block_size - threshold | ||
| 90 | + if valid_block_count > block_count: | ||
| 91 | + if mask_size != 0: | ||
| 92 | + golden[t, :, -mask_size:] = -1 | ||
| 93 | + else: | ||
| 94 | + if mask_size != 0: | ||
| 95 | + end_pos = valid_block_count * block_size | ||
| 96 | + golden[t, :, end_pos - mask_size : end_pos] = -1 | ||
| 97 | + return golden | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +def gen_data(params): | ||
| 101 | + """根据参数生成算子输入、属性与 CPU golden 结果。""" | ||
| 102 | + n2, cur_seqlen_q, cur_seqlen_kv, block_size, block_count, causal, case_name = params | ||
| 103 | + device = torch.device("cpu") | ||
| 104 | + | ||
| 105 | + acc_seqlen_q = np.cumsum([0] + list(cur_seqlen_q)).tolist() | ||
| 106 | + acc_seqlen_kv = np.cumsum([0] + list(cur_seqlen_kv)).tolist() | ||
| 107 | + | ||
| 108 | + topk_indices = _gen_topk_indices( | ||
| 109 | + acc_seqlen_q, cur_seqlen_q, cur_seqlen_kv, block_size, block_count, n2, device | ||
| 110 | + ) | ||
| 111 | + cpu_output = _cpu_golden( | ||
| 112 | + topk_indices, acc_seqlen_q, cur_seqlen_q, cur_seqlen_kv, block_size, block_count | ||
| 113 | + ) | ||
| 114 | + | ||
| 115 | + input_data = { | ||
| 116 | + "input": { | ||
| 117 | + "topk_indices": topk_indices, | ||
| 118 | + "acc_seqlen_q": torch.tensor( | ||
| 119 | + acc_seqlen_q, dtype=torch.int64, device=device | ||
| 120 | + ), | ||
| 121 | + "acc_seqlen_kv": torch.tensor( | ||
| 122 | + acc_seqlen_kv, dtype=torch.int64, device=device | ||
| 123 | + ), | ||
| 124 | + }, | ||
| 125 | + "attr": { | ||
| 126 | + "causal": causal, | ||
| 127 | + "block_size": block_size, | ||
| 128 | + }, | ||
| 129 | + "cpu_output": cpu_output, | ||
| 130 | + "case_name": case_name, | ||
| 131 | + } | ||
| 132 | + return input_data | ||
Aexperimental/attention/block_indexer_rearrange/tests/pytest/block_indexer_rearrange_paramset.py+71-0
| @@ -0,0 +1,71 @@ | |||
| 1 | +#!/usr/bin/python | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +# 定义测试参数组合 | ||
| 14 | +# params 结构: | ||
| 15 | +# (n2, cur_seqlen_q, cur_seqlen_kv, block_size, block_count, causal, case_name) | ||
| 16 | +TEST_PARAMS = { | ||
| 17 | + "tnd_b1_bs4_bc512": { | ||
| 18 | + "n2": [1], | ||
| 19 | + "cur_seqlen_q": [[200]], | ||
| 20 | + "cur_seqlen_kv": [[200]], | ||
| 21 | + "block_size": [4], | ||
| 22 | + "block_count": [512], | ||
| 23 | + "causal": [True], | ||
| 24 | + }, | ||
| 25 | + "tnd_b2_bs4_bc512": { | ||
| 26 | + "n2": [1], | ||
| 27 | + "cur_seqlen_q": [[200, 300]], | ||
| 28 | + "cur_seqlen_kv": [[400, 900]], | ||
| 29 | + "block_size": [4], | ||
| 30 | + "block_count": [512], | ||
| 31 | + "causal": [True], | ||
| 32 | + }, | ||
| 33 | + "tnd_b2_bs2_bc1024": { | ||
| 34 | + "n2": [1], | ||
| 35 | + "cur_seqlen_q": [[512, 512]], | ||
| 36 | + "cur_seqlen_kv": [[1024, 2048]], | ||
| 37 | + "block_size": [2], | ||
| 38 | + "block_count": [1024], | ||
| 39 | + "causal": [True], | ||
| 40 | + }, | ||
| 41 | + "tnd_b2_bs8_bc2048": { | ||
| 42 | + "n2": [1], | ||
| 43 | + "cur_seqlen_q": [[1024, 2048]], | ||
| 44 | + "cur_seqlen_kv": [[2048, 8192]], | ||
| 45 | + "block_size": [8], | ||
| 46 | + "block_count": [2048], | ||
| 47 | + "causal": [True], | ||
| 48 | + }, | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +# 按需选择要启用的测试参数(默认启用所有) | ||
| 52 | +ENABLED_PARAMS = [] | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +def build_params(): | ||
| 56 | + for key in TEST_PARAMS.keys(): | ||
| 57 | + params = TEST_PARAMS[key] | ||
| 58 | + ENABLED_PARAMS.append( | ||
| 59 | + ( | ||
| 60 | + params["n2"][0], | ||
| 61 | + params["cur_seqlen_q"][0], | ||
| 62 | + params["cur_seqlen_kv"][0], | ||
| 63 | + params["block_size"][0], | ||
| 64 | + params["block_count"][0], | ||
| 65 | + params["causal"][0], | ||
| 66 | + key, | ||
| 67 | + ) | ||
| 68 | + ) | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +build_params() | ||
Aexperimental/attention/block_indexer_rearrange/tests/pytest/block_indexer_rearrange_process.py+33-0
| @@ -0,0 +1,33 @@ | |||
| 1 | +#!/usr/bin/python | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 | ||
| 5 | + | ||
| 6 | +import torch | ||
| 7 | +import torch_npu | ||
| 8 | +import aclnn_runner | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +def call_npu(input_data): | ||
| 12 | + """直接调用 aclnnBlockIndexerRearrange。""" | ||
| 13 | + ti = input_data["input"] | ||
| 14 | + topk = ti["topk_indices"].npu() | ||
| 15 | + acc_q = ti["acc_seqlen_q"].npu() | ||
| 16 | + acc_kv = ti["acc_seqlen_kv"].npu() | ||
| 17 | + causal = input_data["attr"]["causal"] | ||
| 18 | + block_size = input_data["attr"]["block_size"] | ||
| 19 | + t1, n2, kcnt = topk.shape | ||
| 20 | + out = torch.empty(t1, n2, kcnt * block_size, dtype=torch.int32, device=topk.device) | ||
| 21 | + aclnn_runner.call( | ||
| 22 | + "aclnnBlockIndexerRearrangeGetWorkspaceSize", | ||
| 23 | + "aclnnBlockIndexerRearrange", | ||
| 24 | + [ | ||
| 25 | + ("tensor", topk), | ||
| 26 | + ("tensor", acc_q), | ||
| 27 | + ("tensor", acc_kv), | ||
| 28 | + ("bool", bool(causal)), | ||
| 29 | + ("int64", int(block_size)), | ||
| 30 | + ("tensor", out), | ||
| 31 | + ], | ||
| 32 | + ) | ||
| 33 | + return out | ||
| @@ -0,0 +1,4 @@ | |||
| 1 | +[pytest] | ||
| 2 | +markers = | ||
| 3 | + ci: mark a test as a CI test | ||
| 4 | + graph: marks tests as graph mode compilation tests | ||
| @@ -0,0 +1,70 @@ | |||
| 1 | +#!/usr/bin/python | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +import datetime | ||
| 14 | +import logging | ||
| 15 | +import os | ||
| 16 | +import sys | ||
| 17 | + | ||
| 18 | +import numpy as np | ||
| 19 | +import torch | ||
| 20 | + | ||
| 21 | +logging.basicConfig(level=logging.INFO, format="%(message)s", force=True) | ||
| 22 | +logger = logging.getLogger(__name__) | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def print_log(data=None, level="INFO"): | ||
| 26 | + print( | ||
| 27 | + "[%s] [%s]-%s:%s - %s" | ||
| 28 | + % ( | ||
| 29 | + datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), | ||
| 30 | + level, | ||
| 31 | + os.path.basename(sys._getframe().f_back.f_code.co_filename), | ||
| 32 | + str(sys._getframe().f_back.f_lineno).zfill(4), | ||
| 33 | + data, | ||
| 34 | + ) | ||
| 35 | + ) | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def check_result(expect, npu_result): | ||
| 39 | + """逐元素精确比较 NPU 输出与 CPU golden(索引为整数,要求完全一致)。""" | ||
| 40 | + real_data = npu_result.cpu().to(torch.int64).numpy().flatten() | ||
| 41 | + data_compe = expect.cpu().to(torch.int64).numpy().flatten() | ||
| 42 | + | ||
| 43 | + if real_data.size != data_compe.size: | ||
| 44 | + print_log( | ||
| 45 | + "Error,the size of npu output[%s] and benchmark[%s] is not equal." | ||
| 46 | + % (real_data.size, data_compe.size) | ||
| 47 | + ) | ||
| 48 | + return "Failed", 0.0 | ||
| 49 | + | ||
| 50 | + total = real_data.size | ||
| 51 | + if total == 0: | ||
| 52 | + print_log('The output is empty, the result of data_compare is "Pass"') | ||
| 53 | + return "Pass", 100.0 | ||
| 54 | + | ||
| 55 | + err_idx = np.where(real_data != data_compe)[0] | ||
| 56 | + fulfill_percent = float(total - err_idx.size) / float(total) * 100.0 | ||
| 57 | + result = "Pass" if err_idx.size == 0 else "Failed" | ||
| 58 | + | ||
| 59 | + print_log( | ||
| 60 | + "---------------------------------------------------------------------------------------" | ||
| 61 | + ) | ||
| 62 | + print_log("Total \t Mismatch \t MatchPct \t Result") | ||
| 63 | + print_log( | ||
| 64 | + "%d \t %d \t %.6f%% \t %s" % (total, err_idx.size, fulfill_percent, result) | ||
| 65 | + ) | ||
| 66 | + if err_idx.size > 0: | ||
| 67 | + print_log("First 10 mismatch (idx: golden vs npu):") | ||
| 68 | + for i in err_idx[:10]: | ||
| 69 | + print_log(" %d: %d vs %d" % (i, data_compe[i], real_data[i])) | ||
| 70 | + return result, fulfill_percent | ||
Aexperimental/attention/block_indexer_rearrange/tests/pytest/test_block_indexer_rearrange_single.py+40-0
| @@ -0,0 +1,40 @@ | |||
| 1 | +#!/usr/bin/python | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +import os | ||
| 14 | + | ||
| 15 | +import pytest | ||
| 16 | +import torch_npu | ||
| 17 | + | ||
| 18 | +import block_indexer_rearrange_golden | ||
| 19 | +import block_indexer_rearrange_process | ||
| 20 | +import result_compare_method | ||
| 21 | +import utils | ||
| 22 | +from block_indexer_rearrange_paramset import ENABLED_PARAMS | ||
| 23 | + | ||
| 24 | +result_path = os.getenv("BIR_RESULT_SAVE_PATH", "./result/bir_result.xlsx") | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +@pytest.mark.ci | ||
| 28 | +@pytest.mark.parametrize("params", ENABLED_PARAMS) | ||
| 29 | +def test_block_indexer_rearrange(params): | ||
| 30 | + torch_npu.npu.set_device(0) | ||
| 31 | + case_name = params[6] | ||
| 32 | + | ||
| 33 | + input_data = block_indexer_rearrange_golden.gen_data(params) | ||
| 34 | + npu_result = block_indexer_rearrange_process.call_npu(input_data) | ||
| 35 | + | ||
| 36 | + result, fulfill_percent = result_compare_method.check_result( | ||
| 37 | + input_data["cpu_output"], npu_result | ||
| 38 | + ) | ||
| 39 | + utils.save_result(result, fulfill_percent, input_data, result_path) | ||
| 40 | + assert result == "Pass", f"test case {case_name} failed" | ||
| @@ -0,0 +1,95 @@ | |||
| 1 | +#!/bin/bash | ||
| 2 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | + | ||
| 12 | +# 显示帮助信息 | ||
| 13 | +show_help() { | ||
| 14 | + cat << EOF | ||
| 15 | +使用方法: $0 {single} [参数] | ||
| 16 | + | ||
| 17 | +脚本选项: | ||
| 18 | + single 执行单跑功能 | ||
| 19 | + -R 结果保存路径 | ||
| 20 | + 示例1: bash $0 single | ||
| 21 | + 示例2: bash $0 single -R "./result/bir_result.xlsx" | ||
| 22 | + | ||
| 23 | +通用选项: | ||
| 24 | + -h, --help 显示此帮助信息 | ||
| 25 | +EOF | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +# 检查参数数量 | ||
| 29 | +if [ $# -lt 1 ]; then | ||
| 30 | + echo "错误: 需要至少一个参数" | ||
| 31 | + show_help | ||
| 32 | + exit 1 | ||
| 33 | +fi | ||
| 34 | + | ||
| 35 | +SCRIPT_TYPE=$1 | ||
| 36 | +shift | ||
| 37 | + | ||
| 38 | +if [[ "$SCRIPT_TYPE" == "-h" ]] || [[ "$SCRIPT_TYPE" == "--help" ]]; then | ||
| 39 | + show_help | ||
| 40 | + exit 0 | ||
| 41 | +fi | ||
| 42 | + | ||
| 43 | +run_script_single() { | ||
| 44 | + echo "准备运行 单跑 脚本..." | ||
| 45 | + | ||
| 46 | + while [[ $# -gt 0 ]]; do | ||
| 47 | + case $1 in | ||
| 48 | + -R) | ||
| 49 | + if [ -z "$2" ] || [[ "$2" == -* ]]; then | ||
| 50 | + echo "错误: -R 参数需要值" | ||
| 51 | + exit 1 | ||
| 52 | + fi | ||
| 53 | + R_VALUE="$2" | ||
| 54 | + shift 2 | ||
| 55 | + ;; | ||
| 56 | + *) | ||
| 57 | + echo "错误: 未知参数 '$1'" | ||
| 58 | + exit 1 | ||
| 59 | + ;; | ||
| 60 | + esac | ||
| 61 | + done | ||
| 62 | + | ||
| 63 | + echo "===============================" | ||
| 64 | + echo "参数配置:" | ||
| 65 | + | ||
| 66 | + if [ -n "$R_VALUE" ]; then | ||
| 67 | + echo " 结果存储至文件 $R_VALUE" | ||
| 68 | + export BIR_RESULT_SAVE_PATH="$R_VALUE" | ||
| 69 | + else | ||
| 70 | + echo " 结果存储至文件 ./result/bir_result.xlsx" | ||
| 71 | + fi | ||
| 72 | + | ||
| 73 | + echo "===============================" | ||
| 74 | + | ||
| 75 | + if [ ! -f "test_block_indexer_rearrange_single.py" ]; then | ||
| 76 | + echo "错误: 找不到 test_block_indexer_rearrange_single.py 脚本" | ||
| 77 | + exit 1 | ||
| 78 | + fi | ||
| 79 | + python3 -m pytest -rA -s test_block_indexer_rearrange_single.py -v -m ci | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +case "$SCRIPT_TYPE" in | ||
| 83 | + single) | ||
| 84 | + run_script_single "$@" | ||
| 85 | + ;; | ||
| 86 | + *) | ||
| 87 | + echo "错误: 未知的脚本类型 '$SCRIPT_TYPE'" | ||
| 88 | + echo "可用类型: single" | ||
| 89 | + show_help | ||
| 90 | + exit 1 | ||
| 91 | + ;; | ||
| 92 | +esac | ||
| 93 | + | ||
| 94 | +echo "===============================" | ||
| 95 | +echo "所有任务完成" | ||
| @@ -0,0 +1,43 @@ | |||
| 1 | +#!/usr/bin/python | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +from pathlib import Path | ||
| 14 | + | ||
| 15 | +import pandas as pd | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def save_result( | ||
| 19 | + result, fulfill_percent, input_data, result_path="./result/bir_result.xlsx" | ||
| 20 | +): | ||
| 21 | + result_path = Path(result_path) | ||
| 22 | + row_data = { | ||
| 23 | + "case_name": input_data["case_name"], | ||
| 24 | + "block_size": input_data["attr"]["block_size"], | ||
| 25 | + "causal": input_data["attr"]["causal"], | ||
| 26 | + "result": result, | ||
| 27 | + "fulfill_percent": fulfill_percent, | ||
| 28 | + } | ||
| 29 | + result_path.parent.mkdir(parents=True, exist_ok=True) | ||
| 30 | + if result_path.exists(): | ||
| 31 | + df = pd.read_excel(result_path) | ||
| 32 | + if set(df.columns) != set(row_data.keys()): | ||
| 33 | + print("警告:变量名与Excel列名不匹配!") | ||
| 34 | + print(f"Excel列名: {list(df.columns)}") | ||
| 35 | + print(f"变量名: {list(row_data.keys())}") | ||
| 36 | + return False | ||
| 37 | + new_df = pd.DataFrame([row_data]) | ||
| 38 | + df = pd.concat([df, new_df], ignore_index=True) | ||
| 39 | + else: | ||
| 40 | + df = pd.DataFrame([row_data]) | ||
| 41 | + | ||
| 42 | + df.to_excel(result_path, index=False) | ||
| 43 | + return True | ||
| @@ -0,0 +1,19 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | + | ||
| 11 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 12 | +if(NOT ENABLE_TEST AND NOT BENCHMARK) | ||
| 13 | + list(REMOVE_ITEM CURRENT_DIRS tests) | ||
| 14 | +endif() | ||
| 15 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 16 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 17 | + add_subdirectory(${SUB_DIR}) | ||
| 18 | + endif() | ||
| 19 | +endforeach() | ||
| @@ -0,0 +1,89 @@ | |||
| 1 | +# DsaDense(Experimental) | ||
| 2 | + | ||
| 3 | +## 产品支持情况 | ||
| 4 | + | ||
| 5 | +| 产品 | 是否支持 | | ||
| 6 | +| ----------------------------- | :------: | | ||
| 7 | +| <term>Atlas A3系列产品</term> | √ | | ||
| 8 | +| <term>Atlas A2系列产品</term> | √ | | ||
| 9 | + | ||
| 10 | +## 功能说明 | ||
| 11 | + | ||
| 12 | +`DsaDense` 是 DSA(DeepSeek Sparse Attention)类结构的前向 dense 注意力前处理反向算子。 | ||
| 13 | +基于主注意力(main attention)与 indexer 两条通路的 softmax `max`/`sum` 统计量,计算: | ||
| 14 | + | ||
| 15 | +- `loss`:main 分布 `P` 与 indexer 分布 `Y` 的 KL 散度(每 batch 求和后累加); | ||
| 16 | +- `dq` / `dk`:indexer query/key 的梯度; | ||
| 17 | +- `dw`:indexer 逐 head 权重的梯度。 | ||
| 18 | + | ||
| 19 | +输入采用变长 TND 布局。 | ||
| 20 | + | ||
| 21 | +## 参数说明 | ||
| 22 | + | ||
| 23 | +| 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 格式 | | ||
| 24 | +| ---------- | -------------- | ------------------------------------------------- | -------- | :--: | | ||
| 25 | +| query | 输入 | `[T1, N, D]` | BF16 | ND | | ||
| 26 | +| key | 输入 | `[T2, N, D]` | BF16 | ND | | ||
| 27 | +| max | 输入 | main 注意力 softmax 行最大值,`[N, T1]` | FLOAT | ND | | ||
| 28 | +| sum | 输入 | main 注意力 softmax 行求和,`[N, T1]` | FLOAT | ND | | ||
| 29 | +| qLen | 输入 | query 累积序列长度(前缀和),`[B+1]` | INT64 | ND | | ||
| 30 | +| kvLen | 输入 | KV 累积序列长度(前缀和),`[B+1]` | INT64 | ND | | ||
| 31 | +| mask | 输入 | 因果掩码,`[128, 128]` | BOOL | ND | | ||
| 32 | +| queryIndex | 输入 | indexer query,`[T1, NI, DI]` | BF16 | ND | | ||
| 33 | +| keyIndex | 输入 | indexer key,`[T2, DI]` | BF16 | ND | | ||
| 34 | +| weights | 输入 | indexer 逐 head 权重,`[T1, NI]` | FLOAT | ND | | ||
| 35 | +| maxIndex | 输入 | indexer softmax 行最大值,`[T1]` | FLOAT | ND | | ||
| 36 | +| sumIndex | 输入 | indexer softmax 行求和,`[T1]` | FLOAT | ND | | ||
| 37 | +| sparse_mode| 属性 | 稀疏模式,仅支持 `1`(causal) | INT | - | | ||
| 38 | +| scale | 属性 | 缩放因子,`1/sqrt(D)` | FLOAT | - | | ||
| 39 | +| loss | 输出 | KL loss,`[1]` | FLOAT | ND | | ||
| 40 | +| dq | 输出 | indexer query 梯度,`[T1, NI, DI]` | BF16 | ND | | ||
| 41 | +| dk | 输出 | indexer key 梯度,`[T2, DI]` | BF16 | ND | | ||
| 42 | +| dw | 输出 | indexer weights 梯度,`[NI, T1]` | FLOAT | ND | | ||
| 43 | + | ||
| 44 | +## 约束说明 | ||
| 45 | + | ||
| 46 | +- 仅支持变长(TND)布局与因果(causal)模式(`sparse_mode=1`)。 | ||
| 47 | +- `mask` 形状固定为 `[128, 128]`。 | ||
| 48 | +- `NI <= 128`。 | ||
| 49 | + | ||
| 50 | +## 构建 | ||
| 51 | + | ||
| 52 | +```bash | ||
| 53 | +source /usr/local/Ascend/cann/set_env.sh | ||
| 54 | +bash build.sh --pkg --experimental --soc=ascend910b --ops=dsa_dense -j8 | ||
| 55 | +``` | ||
| 56 | + | ||
| 57 | +`--soc` 可选 `ascend910b`(Atlas A2 系列)或 `ascend910_93`(Atlas A3 系列)。 | ||
| 58 | + | ||
| 59 | +## 目录结构 | ||
| 60 | + | ||
| 61 | +```text | ||
| 62 | +dsa_dense/ | ||
| 63 | + CMakeLists.txt | ||
| 64 | + op_host/ | ||
| 65 | + CMakeLists.txt | ||
| 66 | + dsa_dense_def.cpp # OpDef | ||
| 67 | + dsa_dense_infershape.cpp # InferShape / InferDataType | ||
| 68 | + dsa_dense_tiling.h # TilingData 定义 | ||
| 69 | + dsa_dense_tiling.cpp # Tiling 与注册(含 matmul lib tiling) | ||
| 70 | + op_kernel/ | ||
| 71 | + dsa_dense.cpp # Ascend C 内核入口 | ||
| 72 | + dsa_dense.h # 内核实现 | ||
| 73 | + tests/ | ||
| 74 | + pytest/ # pytest 功能验证(CPU golden + NPU 直调) | ||
| 75 | + test_dsa_dense_single.py | ||
| 76 | + dsa_dense_golden.py | ||
| 77 | + dsa_dense_process.py | ||
| 78 | + dsa_dense_paramset.py | ||
| 79 | + result_compare_method.py | ||
| 80 | + test_run.sh | ||
| 81 | +``` | ||
| 82 | + | ||
| 83 | +## 测试 | ||
| 84 | + | ||
| 85 | +参考 [tests/pytest/README.md](./tests/pytest/README.md)。在 `tests/pytest` 目录下激活自定义算子包后执行: | ||
| 86 | + | ||
| 87 | +```bash | ||
| 88 | +bash test_run.sh single | ||
| 89 | +``` | ||
| @@ -0,0 +1,18 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +add_op_to_compiled_list() | ||
| 11 | + | ||
| 12 | +if (BUILD_OPEN_PROJECT) | ||
| 13 | + target_sources(op_host_aclnn PRIVATE | ||
| 14 | + dsa_dense_def.cpp | ||
| 15 | + ) | ||
| 16 | +endif() | ||
| 17 | + | ||
| 18 | +add_modules_sources(OPTYPE dsa_dense ACLNNTYPE aclnn) | ||
| @@ -0,0 +1,139 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file dsa_dense_def.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "register/op_def_registry.h" | ||
| 17 | + | ||
| 18 | +namespace ops { | ||
| 19 | +class DsaDense : public OpDef { | ||
| 20 | +public: | ||
| 21 | + explicit DsaDense(const char *name) : OpDef(name) | ||
| 22 | + { | ||
| 23 | + //// inputs //// | ||
| 24 | + // inputs for main model | ||
| 25 | + this->Input("query") // [T1 N D] | ||
| 26 | + .ParamType(REQUIRED) | ||
| 27 | + .DataType({ge::DT_BF16}) | ||
| 28 | + .Format({ge::FORMAT_ND}) | ||
| 29 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 30 | + .AutoContiguous(); | ||
| 31 | + this->Input("key") // [T2 N D] | ||
| 32 | + .ParamType(REQUIRED) | ||
| 33 | + .DataType({ge::DT_BF16}) | ||
| 34 | + .Format({ge::FORMAT_ND}) | ||
| 35 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 36 | + .AutoContiguous(); | ||
| 37 | + this->Input("max") // [N T1]: 对loop N更友好 | ||
| 38 | + .ParamType(REQUIRED) | ||
| 39 | + .DataType({ge::DT_FLOAT}) | ||
| 40 | + .Format({ge::FORMAT_ND}) | ||
| 41 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 42 | + .AutoContiguous(); | ||
| 43 | + this->Input("sum") | ||
| 44 | + .ParamType(REQUIRED) | ||
| 45 | + .DataType({ge::DT_FLOAT}) | ||
| 46 | + .Format({ge::FORMAT_ND}) | ||
| 47 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 48 | + .AutoContiguous(); | ||
| 49 | + this->Input("qLen") // cumulative format | ||
| 50 | + .ParamType(REQUIRED) | ||
| 51 | + .DataType({ge::DT_INT64}) | ||
| 52 | + .Format({ge::FORMAT_ND}) | ||
| 53 | + .UnknownShapeFormat({ge::FORMAT_ND}); | ||
| 54 | + this->Input("kvLen") | ||
| 55 | + .ParamType(REQUIRED) | ||
| 56 | + .DataType({ge::DT_INT64}) | ||
| 57 | + .Format({ge::FORMAT_ND}) | ||
| 58 | + .UnknownShapeFormat({ge::FORMAT_ND}); | ||
| 59 | + this->Input("mask") // CUBE_S1_TILE x CUBE_S2_TILE | ||
| 60 | + .ParamType(REQUIRED) | ||
| 61 | + .DataType({ge::DT_BOOL}) | ||
| 62 | + .Format({ge::FORMAT_ND}) | ||
| 63 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 64 | + .AutoContiguous(); | ||
| 65 | + // inputs for lightning indexer | ||
| 66 | + this->Input("queryIndex") // [T1 NI DI] | ||
| 67 | + .ParamType(REQUIRED) | ||
| 68 | + .DataType({ge::DT_BF16}) | ||
| 69 | + .Format({ge::FORMAT_ND}) | ||
| 70 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 71 | + .AutoContiguous(); | ||
| 72 | + this->Input("keyIndex") // [T2 DI] | ||
| 73 | + .ParamType(REQUIRED) | ||
| 74 | + .DataType({ge::DT_BF16}) | ||
| 75 | + .Format({ge::FORMAT_ND}) | ||
| 76 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 77 | + .AutoContiguous(); | ||
| 78 | + this->Input("weights") // [T1 N1] | ||
| 79 | + .ParamType(REQUIRED) | ||
| 80 | + .DataType({ge::DT_FLOAT}) | ||
| 81 | + .Format({ge::FORMAT_ND}) | ||
| 82 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 83 | + .AutoContiguous(); | ||
| 84 | + this->Input("maxIndex") // [T1] | ||
| 85 | + .ParamType(REQUIRED) | ||
| 86 | + .DataType({ge::DT_FLOAT}) | ||
| 87 | + .Format({ge::FORMAT_ND}) | ||
| 88 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 89 | + .AutoContiguous(); | ||
| 90 | + this->Input("sumIndex") | ||
| 91 | + .ParamType(REQUIRED) | ||
| 92 | + .DataType({ge::DT_FLOAT}) | ||
| 93 | + .Format({ge::FORMAT_ND}) | ||
| 94 | + .UnknownShapeFormat({ge::FORMAT_ND}) | ||
| 95 | + .AutoContiguous(); | ||
| 96 | + //// outputs //// | ||
| 97 | + // loss output | ||
| 98 | + this->Output("loss") | ||
| 99 | + .ParamType(REQUIRED) | ||
| 100 | + .DataType({ge::DT_FLOAT}) | ||
| 101 | + .Format({ge::FORMAT_ND}) | ||
| 102 | + .UnknownShapeFormat({ge::FORMAT_ND}); | ||
| 103 | + // grad outputs | ||
| 104 | + this->Output("dq") // [T1 NI DI] | ||
| 105 | + .ParamType(REQUIRED) | ||
| 106 | + .DataType({ge::DT_BF16}) | ||
| 107 | + .Format({ge::FORMAT_ND}) | ||
| 108 | + .UnknownShapeFormat({ge::FORMAT_ND}); | ||
| 109 | + this->Output("dk") // [T2 DI] | ||
| 110 | + .ParamType(REQUIRED) | ||
| 111 | + .DataType({ge::DT_BF16}) | ||
| 112 | + .Format({ge::FORMAT_ND}) | ||
| 113 | + .UnknownShapeFormat({ge::FORMAT_ND}); | ||
| 114 | + this->Output("dw") // [NI T1] | ||
| 115 | + .ParamType(REQUIRED) | ||
| 116 | + .DataType({ge::DT_FLOAT}) | ||
| 117 | + .Format({ge::FORMAT_ND}) | ||
| 118 | + .UnknownShapeFormat({ge::FORMAT_ND}); | ||
| 119 | + //// attrs //// | ||
| 120 | + this->Attr("sparse_mode").AttrType(REQUIRED).Int(1); // only support causal | ||
| 121 | + this->Attr("scale").AttrType(REQUIRED).Float(1.0); | ||
| 122 | + | ||
| 123 | + OpAICoreConfig aicore_config; | ||
| 124 | + aicore_config.DynamicCompileStaticFlag(true) | ||
| 125 | + .DynamicFormatFlag(true) | ||
| 126 | + .DynamicRankSupportFlag(true) | ||
| 127 | + .DynamicShapeSupportFlag(true) | ||
| 128 | + .NeedCheckSupportFlag(false) | ||
| 129 | + .PrecisionReduceFlag(true) | ||
| 130 | + .ExtendCfgInfo("prebuildPattern.value", "Opaque") | ||
| 131 | + .ExtendCfgInfo("coreType.value", "AiCore") | ||
| 132 | + .ExtendCfgInfo("aclnnSupport.value", "aclnn_only") | ||
| 133 | + .ExtendCfgInfo("jitCompile.flag", "false"); | ||
| 134 | + this->AICore().AddConfig("ascend910b", aicore_config); | ||
| 135 | + this->AICore().AddConfig("ascend910_93", aicore_config); | ||
| 136 | + } | ||
| 137 | +}; | ||
| 138 | +OP_ADD(DsaDense); | ||
| 139 | +} // namespace ops | ||
| @@ -0,0 +1,89 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file dsa_dense_infershape.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include <register/op_impl_registry.h> | ||
| 17 | +#include "log/log.h" | ||
| 18 | +#include "err/ops_err.h" | ||
| 19 | + | ||
| 20 | +using namespace ge; | ||
| 21 | + | ||
| 22 | +namespace ops { | ||
| 23 | +constexpr uint32_t QUERY_INDEX_POS = 7; | ||
| 24 | +constexpr uint32_t KEY_INDEX_POS = 8; | ||
| 25 | + | ||
| 26 | +constexpr uint32_t LOSS_POS = 0; | ||
| 27 | +constexpr uint32_t DQ_POS = 1; | ||
| 28 | +constexpr uint32_t DK_POS = 2; | ||
| 29 | +constexpr uint32_t DW_POS = 3; | ||
| 30 | + | ||
| 31 | +static ge::graphStatus InferShapeDsaDense(gert::InferShapeContext* context) | ||
| 32 | +{ | ||
| 33 | + OP_CHECK_IF(context == nullptr, OP_LOGE("DsaDense", "InferShapeContext is nullptr!"), return ge::GRAPH_FAILED); | ||
| 34 | + | ||
| 35 | + const gert::Shape* qIndexShape = context->GetInputShape(QUERY_INDEX_POS); // [T1 NI DI] | ||
| 36 | + OP_CHECK_NULL_WITH_CONTEXT(context, qIndexShape); | ||
| 37 | + const gert::Shape* kIndexShape = context->GetInputShape(KEY_INDEX_POS); // [T2 DI] | ||
| 38 | + OP_CHECK_NULL_WITH_CONTEXT(context, kIndexShape); | ||
| 39 | + | ||
| 40 | + gert::Shape* lossShape = context->GetOutputShape(LOSS_POS); | ||
| 41 | + OP_CHECK_NULL_WITH_CONTEXT(context, lossShape); | ||
| 42 | + gert::Shape* dqShape = context->GetOutputShape(DQ_POS); | ||
| 43 | + OP_CHECK_NULL_WITH_CONTEXT(context, dqShape); | ||
| 44 | + gert::Shape* dkShape = context->GetOutputShape(DK_POS); | ||
| 45 | + OP_CHECK_NULL_WITH_CONTEXT(context, dkShape); | ||
| 46 | + gert::Shape* dwShape = context->GetOutputShape(DW_POS); | ||
| 47 | + OP_CHECK_NULL_WITH_CONTEXT(context, dwShape); | ||
| 48 | + | ||
| 49 | + OP_CHECK_IF(qIndexShape->GetDimNum() != 3, OP_LOGE(context->GetNodeName(), "queryIndex dims must be 3!"), | ||
| 50 | + return ge::GRAPH_FAILED); | ||
| 51 | + OP_CHECK_IF(kIndexShape->GetDimNum() != 2, OP_LOGE(context->GetNodeName(), "keyIndex dims must be 2!"), | ||
| 52 | + return ge::GRAPH_FAILED); | ||
| 53 | + | ||
| 54 | + // loss: [1] | ||
| 55 | + lossShape->SetDimNum(1); | ||
| 56 | + lossShape->SetDim(0, 1); | ||
| 57 | + | ||
| 58 | + // dq: [T1 NI DI] | ||
| 59 | + dqShape->SetDimNum(3); | ||
| 60 | + dqShape->SetDim(0, qIndexShape->GetDim(0)); | ||
| 61 | + dqShape->SetDim(1, qIndexShape->GetDim(1)); | ||
| 62 | + dqShape->SetDim(2, qIndexShape->GetDim(2)); | ||
| 63 | + | ||
| 64 | + // dk: [T2 DI] | ||
| 65 | + dkShape->SetDimNum(2); | ||
| 66 | + dkShape->SetDim(0, kIndexShape->GetDim(0)); | ||
| 67 | + dkShape->SetDim(1, kIndexShape->GetDim(1)); | ||
| 68 | + | ||
| 69 | + // dw: [NI T1] | ||
| 70 | + dwShape->SetDimNum(2); | ||
| 71 | + dwShape->SetDim(0, qIndexShape->GetDim(1)); | ||
| 72 | + dwShape->SetDim(1, qIndexShape->GetDim(0)); | ||
| 73 | + | ||
| 74 | + OP_LOGD(context->GetNodeName(), "DsaDense InferShape end."); | ||
| 75 | + return ge::GRAPH_SUCCESS; | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +static ge::graphStatus InferDataTypeDsaDense(gert::InferDataTypeContext* context) | ||
| 79 | +{ | ||
| 80 | + OP_CHECK_IF(context == nullptr, OP_LOGE("DsaDense", "InferDataTypeContext is nullptr!"), return ge::GRAPH_FAILED); | ||
| 81 | + context->SetOutputDataType(LOSS_POS, ge::DT_FLOAT); | ||
| 82 | + context->SetOutputDataType(DQ_POS, context->GetInputDataType(QUERY_INDEX_POS)); | ||
| 83 | + context->SetOutputDataType(DK_POS, context->GetInputDataType(KEY_INDEX_POS)); | ||
| 84 | + context->SetOutputDataType(DW_POS, ge::DT_FLOAT); | ||
| 85 | + return ge::GRAPH_SUCCESS; | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +IMPL_OP_INFERSHAPE(DsaDense).InferShape(InferShapeDsaDense).InferDataType(InferDataTypeDsaDense); | ||
| 89 | +} // namespace ops | ||
| @@ -0,0 +1,451 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file dsa_dense_tiling.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "dsa_dense_tiling.h" | ||
| 17 | +#include "register/op_def_registry.h" | ||
| 18 | +#include "register/op_impl_registry.h" | ||
| 19 | +#include "tiling/platform/platform_ascendc.h" | ||
| 20 | +#include "log/log.h" | ||
| 21 | +#include "err/ops_err.h" | ||
| 22 | + | ||
| 23 | +#include <cmath> | ||
| 24 | +#include <algorithm> | ||
| 25 | + | ||
| 26 | +using namespace ge; | ||
| 27 | +using namespace AscendC; | ||
| 28 | + | ||
| 29 | +namespace optiling { | ||
| 30 | +namespace { | ||
| 31 | +//// constants //// | ||
| 32 | +constexpr uint32_t SYS_WORKSPACE_SIZE = 16 * 1024 * 1024; | ||
| 33 | +constexpr uint32_t DB = 2; | ||
| 34 | +constexpr uint32_t CAUSAL_MODE = 1; | ||
| 35 | +constexpr uint32_t CORE_LIST_NUM = 50; | ||
| 36 | + | ||
| 37 | +// cv切块size | ||
| 38 | +constexpr uint32_t CUBE_S1_TILE = 128; | ||
| 39 | +constexpr uint32_t CUBE_S2_TILE = 1024; | ||
| 40 | +constexpr uint32_t VEC_S1_TILE = 8; | ||
| 41 | +constexpr uint32_t VEC_S2_TILE = 1024; | ||
| 42 | + | ||
| 43 | +// input index | ||
| 44 | +constexpr uint32_t Q_POS = 0; | ||
| 45 | +constexpr uint32_t K_POS = 1; | ||
| 46 | +constexpr uint32_t MAX_POS = 2; | ||
| 47 | +constexpr uint32_t SUM_POS = 3; | ||
| 48 | +constexpr uint32_t Q_LEN_POS = 4; | ||
| 49 | +constexpr uint32_t KV_LEN_POS = 5; | ||
| 50 | +constexpr uint32_t MASK_POS = 6; | ||
| 51 | + | ||
| 52 | +constexpr uint32_t Q_INDEX_POS = 7; | ||
| 53 | +constexpr uint32_t K_INDEX_POS = 8; | ||
| 54 | +constexpr uint32_t WEIGHTS_POS = 9; | ||
| 55 | +constexpr uint32_t MAX_INDEX_POS = 10; | ||
| 56 | +constexpr uint32_t SUM_INDEX_POS = 11; | ||
| 57 | + | ||
| 58 | +// output index | ||
| 59 | +constexpr uint32_t LOSS_POS = 0; | ||
| 60 | +constexpr uint32_t GRAD_Q_POS = 1; | ||
| 61 | +constexpr uint32_t GRAD_K_POS = 2; | ||
| 62 | +constexpr uint32_t GRAD_WEIGHTS_POS = 3; | ||
| 63 | + | ||
| 64 | +// attr index | ||
| 65 | +constexpr uint32_t ATTR_SPARSE_MODE_POS = 0; | ||
| 66 | +constexpr uint32_t ATTR_SCALE_POS = 1; | ||
| 67 | + | ||
| 68 | +// func tools | ||
| 69 | +template <typename T1, typename T2> | ||
| 70 | +static T2 CeilDivide(const T1 a, const T2 b) | ||
| 71 | +{ | ||
| 72 | + return static_cast<T2>((a + static_cast<T1>(b) - 1) / static_cast<T1>(b)); | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +uint64_t GetSizePlatForm(const platform_ascendc::CoreMemType memType, platform_ascendc::PlatformAscendC ascendcPlatform) | ||
| 76 | +{ | ||
| 77 | + uint64_t size; | ||
| 78 | + ascendcPlatform.GetCoreMemSize(memType, size); | ||
| 79 | + return size; | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +struct PlatFormInfo { | ||
| 83 | + uint64_t ubSize; | ||
| 84 | + uint64_t l1Size; | ||
| 85 | + uint64_t l0CSize; | ||
| 86 | + uint64_t l0ASize; | ||
| 87 | + uint64_t l0BSize; | ||
| 88 | + uint32_t aicNum; | ||
| 89 | + uint32_t aivNum; | ||
| 90 | + | ||
| 91 | + PlatFormInfo() = default; | ||
| 92 | + | ||
| 93 | + explicit PlatFormInfo(platform_ascendc::PlatformAscendC ascendcPlatform) | ||
| 94 | + : ubSize(GetSizePlatForm(platform_ascendc::CoreMemType::UB, ascendcPlatform)), | ||
| 95 | + l1Size(GetSizePlatForm(platform_ascendc::CoreMemType::L1, ascendcPlatform)), | ||
| 96 | + l0CSize(GetSizePlatForm(platform_ascendc::CoreMemType::L0_C, ascendcPlatform)), | ||
| 97 | + l0ASize(GetSizePlatForm(platform_ascendc::CoreMemType::L0_A, ascendcPlatform)), | ||
| 98 | + l0BSize(GetSizePlatForm(platform_ascendc::CoreMemType::L0_B, ascendcPlatform)), | ||
| 99 | + aicNum(ascendcPlatform.GetCoreNumAic()), | ||
| 100 | + aivNum(ascendcPlatform.GetCoreNumAiv()) | ||
| 101 | + {} | ||
| 102 | +}; | ||
| 103 | +} // namespace | ||
| 104 | + | ||
| 105 | +class DsaDenseTiling { | ||
| 106 | +public: | ||
| 107 | + DsaDenseTiling() {} | ||
| 108 | + ge::graphStatus Init(const gert::TilingContext* context, const platform_ascendc::PlatformAscendC& ascendcPlatform); | ||
| 109 | + ge::graphStatus DoTiling(gert::TilingContext* context); | ||
| 110 | + | ||
| 111 | + DsaDenseTilingData tilingData; | ||
| 112 | + | ||
| 113 | +protected: | ||
| 114 | + ge::graphStatus DoLibTiling(const gert::TilingContext* context); | ||
| 115 | + void SetWorkspace(gert::TilingContext* context); | ||
| 116 | + void SaveTilingInfo(gert::TilingContext* context); | ||
| 117 | + | ||
| 118 | +private: | ||
| 119 | + PlatFormInfo ascInfo_; | ||
| 120 | + | ||
| 121 | + uint32_t B_; | ||
| 122 | + uint32_t N_; | ||
| 123 | + uint32_t NI_; | ||
| 124 | + uint32_t D_; | ||
| 125 | + uint32_t DI_; | ||
| 126 | + uint64_t T1_; | ||
| 127 | + uint64_t T2_; | ||
| 128 | + uint64_t maxS1_ = 0; | ||
| 129 | + uint64_t maxS2_ = 0; | ||
| 130 | + float scale_; | ||
| 131 | +}; | ||
| 132 | + | ||
| 133 | +ge::graphStatus DsaDenseTiling::Init(const gert::TilingContext* context, | ||
| 134 | + const platform_ascendc::PlatformAscendC& ascendcPlatform) | ||
| 135 | +{ | ||
| 136 | + // parse ascendc platform information | ||
| 137 | + static const PlatFormInfo ascInfo(ascendcPlatform); | ||
| 138 | + ascInfo_ = ascInfo; | ||
| 139 | + | ||
| 140 | + // parse shape | ||
| 141 | + const gert::Shape& qShape = context->GetInputShape(Q_POS)->GetStorageShape(); | ||
| 142 | + const gert::Shape& kShape = context->GetInputShape(K_POS)->GetStorageShape(); | ||
| 143 | + const gert::Shape& maxShape = context->GetInputShape(MAX_POS)->GetStorageShape(); | ||
| 144 | + const gert::Shape& sumShape = context->GetInputShape(SUM_POS)->GetStorageShape(); | ||
| 145 | + const gert::Shape& qLenShape = context->GetInputShape(Q_LEN_POS)->GetStorageShape(); | ||
| 146 | + const gert::Shape& kvLenShape = context->GetInputShape(KV_LEN_POS)->GetStorageShape(); | ||
| 147 | + const gert::Shape& maskShape = context->GetInputShape(MASK_POS)->GetStorageShape(); | ||
| 148 | + | ||
| 149 | + const gert::Shape& qIndexShape = context->GetInputShape(Q_INDEX_POS)->GetStorageShape(); | ||
| 150 | + const gert::Shape& kIndexShape = context->GetInputShape(K_INDEX_POS)->GetStorageShape(); | ||
| 151 | + const gert::Shape& weightsShape = context->GetInputShape(WEIGHTS_POS)->GetStorageShape(); | ||
| 152 | + const gert::Shape& maxIndexShape = context->GetInputShape(MAX_INDEX_POS)->GetStorageShape(); | ||
| 153 | + const gert::Shape& sumIndexShape = context->GetInputShape(SUM_INDEX_POS)->GetStorageShape(); | ||
| 154 | + | ||
| 155 | + const gert::Shape& lossShape = context->GetOutputShape(LOSS_POS)->GetStorageShape(); | ||
| 156 | + const gert::Shape& gradQShape = context->GetOutputShape(GRAD_Q_POS)->GetStorageShape(); | ||
| 157 | + const gert::Shape& gradKShape = context->GetOutputShape(GRAD_K_POS)->GetStorageShape(); | ||
| 158 | + const gert::Shape& gradWeightsShape = context->GetOutputShape(GRAD_WEIGHTS_POS)->GetStorageShape(); | ||
| 159 | + | ||
| 160 | + // check dim | ||
| 161 | + if (qShape.GetDimNum() != 3) { | ||
| 162 | + OP_LOGE(context->GetNodeName(), "Layout of q is not TND"); | ||
| 163 | + return ge::GRAPH_FAILED; | ||
| 164 | + } | ||
| 165 | + if (kShape.GetDimNum() != 3) { | ||
| 166 | + OP_LOGE(context->GetNodeName(), "Layout of k is not TND"); | ||
| 167 | + return ge::GRAPH_FAILED; | ||
| 168 | + } | ||
| 169 | + if (maxShape.GetDimNum() != 2) { | ||
| 170 | + OP_LOGE(context->GetNodeName(), "Layout of max is not NT"); | ||
| 171 | + return ge::GRAPH_FAILED; | ||
| 172 | + } | ||
| 173 | + if (sumShape.GetDimNum() != 2) { | ||
| 174 | + OP_LOGE(context->GetNodeName(), "Layout of sum is not NT"); | ||
| 175 | + return ge::GRAPH_FAILED; | ||
| 176 | + } | ||
| 177 | + if (qLenShape.GetDimNum() != 1) { | ||
| 178 | + OP_LOGE(context->GetNodeName(), "Dim of q_len is not 1"); | ||
| 179 | + return ge::GRAPH_FAILED; | ||
| 180 | + } | ||
| 181 | + if (kvLenShape.GetDimNum() != 1) { | ||
| 182 | + OP_LOGE(context->GetNodeName(), "Dim of kv_len is not 1"); | ||
| 183 | + return ge::GRAPH_FAILED; | ||
| 184 | + } | ||
| 185 | + if (maskShape.GetDimNum() != 2) { | ||
| 186 | + OP_LOGE(context->GetNodeName(), "Dim of mask is not 2"); | ||
| 187 | + return ge::GRAPH_FAILED; | ||
| 188 | + } | ||
| 189 | + if (qIndexShape.GetDimNum() != 3) { | ||
| 190 | + OP_LOGE(context->GetNodeName(), "Layout of q_index is not TND"); | ||
| 191 | + return ge::GRAPH_FAILED; | ||
| 192 | + } | ||
| 193 | + if (kIndexShape.GetDimNum() != 2) { | ||
| 194 | + OP_LOGE(context->GetNodeName(), "Layout of k_index is not TD"); | ||
| 195 | + return ge::GRAPH_FAILED; | ||
| 196 | + } | ||
| 197 | + if (weightsShape.GetDimNum() != 2) { | ||
| 198 | + OP_LOGE(context->GetNodeName(), "Layout of weights is not TN"); | ||
| 199 | + return ge::GRAPH_FAILED; | ||
| 200 | + } | ||
| 201 | + if (maxIndexShape.GetDimNum() != 1) { | ||
| 202 | + OP_LOGE(context->GetNodeName(), "Layout of max_index is not T"); | ||
| 203 | + return ge::GRAPH_FAILED; | ||
| 204 | + } | ||
| 205 | + if (sumIndexShape.GetDimNum() != 1) { | ||
| 206 | + OP_LOGE(context->GetNodeName(), "Layout of sum_index is not T"); | ||
| 207 | + return ge::GRAPH_FAILED; | ||
| 208 | + } | ||
| 209 | + | ||
| 210 | + if (lossShape.GetDimNum() != 1) { | ||
| 211 | + OP_LOGE(context->GetNodeName(), "Dim of loss is not 1"); | ||
| 212 | + return ge::GRAPH_FAILED; | ||
| 213 | + } | ||
| 214 | + if (gradQShape.GetDimNum() != 3) { | ||
| 215 | + OP_LOGE(context->GetNodeName(), "Layout of grad q is not TND"); | ||
| 216 | + return ge::GRAPH_FAILED; | ||
| 217 | + } | ||
| 218 | + if (gradKShape.GetDimNum() != 2) { | ||
| 219 | + OP_LOGE(context->GetNodeName(), "Layout of grad k is not TD"); | ||
| 220 | + return ge::GRAPH_FAILED; | ||
| 221 | + } | ||
| 222 | + if (gradWeightsShape.GetDimNum() != 2) { | ||
| 223 | + OP_LOGE(context->GetNodeName(), "Layout of grad weights is not NT"); | ||
| 224 | + return ge::GRAPH_FAILED; | ||
| 225 | + } | ||
| 226 | + B_ = qLenShape.GetDim(0) - 1; | ||
| 227 | + T1_ = qShape.GetDim(0); | ||
| 228 | + N_ = qShape.GetDim(1); | ||
| 229 | + D_ = qShape.GetDim(2); | ||
| 230 | + T2_ = kShape.GetDim(0); | ||
| 231 | + NI_ = qIndexShape.GetDim(1); | ||
| 232 | + DI_ = qIndexShape.GetDim(2); | ||
| 233 | + | ||
| 234 | + // parse attrs | ||
| 235 | + auto attrs = context->GetAttrs(); | ||
| 236 | + int sparseMode = *(attrs->GetAttrPointer<int>(ATTR_SPARSE_MODE_POS)); | ||
| 237 | + if (sparseMode != CAUSAL_MODE) { | ||
| 238 | + OP_LOGE(context->GetNodeName(), "Only support causal mode."); | ||
| 239 | + return ge::GRAPH_PARAM_INVALID; | ||
| 240 | + } | ||
| 241 | + scale_ = *(attrs->GetAttrPointer<float>(ATTR_SCALE_POS)); | ||
| 242 | + | ||
| 243 | + // shape value check | ||
| 244 | + if (kShape.GetDim(1) != N_ || kShape.GetDim(2) != D_) { | ||
| 245 | + OP_LOGE(context->GetNodeName(), "Shape mismatch: k and q have incompatible dimensions"); | ||
| 246 | + return ge::GRAPH_FAILED; | ||
| 247 | + } | ||
| 248 | + if (maxShape.GetDim(0) != N_ || maxShape.GetDim(1) != T1_) { | ||
| 249 | + OP_LOGE(context->GetNodeName(), "Shape of max tensor is not [N T1]"); | ||
| 250 | + return ge::GRAPH_FAILED; | ||
| 251 | + } | ||
| 252 | + if (sumShape.GetDim(0) != N_ || sumShape.GetDim(1) != T1_) { | ||
| 253 | + OP_LOGE(context->GetNodeName(), "Shape of sum tensor is not [N T1]"); | ||
| 254 | + return ge::GRAPH_FAILED; | ||
| 255 | + } | ||
| 256 | + if (kvLenShape.GetDim(0) != (B_ + 1)) { | ||
| 257 | + OP_LOGE(context->GetNodeName(), "Shape of kv_len tensor is not [B+1,]"); | ||
| 258 | + return ge::GRAPH_FAILED; | ||
| 259 | + } | ||
| 260 | + if (maskShape.GetDim(0) != CUBE_S1_TILE || maskShape.GetDim(1) != CUBE_S1_TILE) { | ||
| 261 | + OP_LOGE(context->GetNodeName(), "Shape of mask tensor is not [CUBE_S1_TILE CUBE_S1_TILE]"); | ||
| 262 | + return ge::GRAPH_FAILED; | ||
| 263 | + } | ||
| 264 | + | ||
| 265 | + if (kIndexShape.GetDim(0) != T2_ || kIndexShape.GetDim(1) != DI_) { | ||
| 266 | + OP_LOGE(context->GetNodeName(), "Shape of k_index tensor is not [T2 DI]"); | ||
| 267 | + return ge::GRAPH_FAILED; | ||
| 268 | + } | ||
| 269 | + if (weightsShape.GetDim(0) != T1_ || weightsShape.GetDim(1) != NI_) { | ||
| 270 | + OP_LOGE(context->GetNodeName(), "Shape of weights tensor is not [T1 NI]"); | ||
| 271 | + return ge::GRAPH_FAILED; | ||
| 272 | + } | ||
| 273 | + if (maxIndexShape.GetDim(0) != T1_) { | ||
| 274 | + OP_LOGE(context->GetNodeName(), "Shape of max_index tensor is not [T1]"); | ||
| 275 | + return ge::GRAPH_FAILED; | ||
| 276 | + } | ||
| 277 | + if (sumIndexShape.GetDim(0) != T1_) { | ||
| 278 | + OP_LOGE(context->GetNodeName(), "Shape of sum_index tensor is not [T1]"); | ||
| 279 | + return ge::GRAPH_FAILED; | ||
| 280 | + } | ||
| 281 | + | ||
| 282 | + if (lossShape.GetDim(0) != 1) { | ||
| 283 | + OP_LOGE(context->GetNodeName(), "Shape of loss tensor is not [1]"); | ||
| 284 | + return ge::GRAPH_FAILED; | ||
| 285 | + } | ||
| 286 | + if (gradQShape.GetDim(0) != T1_ || gradQShape.GetDim(1) != NI_ || gradQShape.GetDim(2) != DI_) { | ||
| 287 | + OP_LOGE(context->GetNodeName(), "Shape mismatch: grad_q and q_index have incompatible dimensions"); | ||
| 288 | + return ge::GRAPH_FAILED; | ||
| 289 | + } | ||
| 290 | + if (gradKShape.GetDim(0) != T2_ || gradKShape.GetDim(1) != DI_) { | ||
| 291 | + OP_LOGE(context->GetNodeName(), "Shape mismatch: grad_k and k_index have incompatible dimensions"); | ||
| 292 | + return ge::GRAPH_FAILED; | ||
| 293 | + } | ||
| 294 | + if (gradWeightsShape.GetDim(0) != NI_ || gradWeightsShape.GetDim(1) != T1_) { | ||
| 295 | + OP_LOGE(context->GetNodeName(), "Shape mismatch: grad_weights and weights have incompatible dimensions"); | ||
| 296 | + return ge::GRAPH_FAILED; | ||
| 297 | + } | ||
| 298 | + | ||
| 299 | + // check head num | ||
| 300 | + if (NI_ > CUBE_S1_TILE) { | ||
| 301 | + OP_LOGE(context->GetNodeName(), "Not support NI > CUBE_S1_TILE currently"); | ||
| 302 | + return ge::GRAPH_FAILED; | ||
| 303 | + } | ||
| 304 | + | ||
| 305 | + return ge::GRAPH_SUCCESS; | ||
| 306 | +} | ||
| 307 | + | ||
| 308 | +// TODO: 考虑db? depth等信息? | ||
| 309 | +ge::graphStatus DsaDenseTiling::DoLibTiling(const gert::TilingContext* context) | ||
| 310 | +{ | ||
| 311 | + matmul_tiling::MatmulApiTiling mm1; | ||
| 312 | + matmul_tiling::MatmulApiTiling mm2; | ||
| 313 | + matmul_tiling::MatmulApiTiling mm3; | ||
| 314 | + | ||
| 315 | + // setting mm1 | ||
| 316 | + mm1.SetAType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_BFLOAT16, | ||
| 317 | + false); | ||
| 318 | + mm1.SetBType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_BFLOAT16, | ||
| 319 | + true); | ||
| 320 | + mm1.SetCType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_FLOAT); | ||
| 321 | + mm1.SetOrgShape(maxS1_, maxS2_, D_); // tiling阶段随意设置,kernel运行时再设置为准确值 | ||
| 322 | + mm1.SetShape(CUBE_S1_TILE, CUBE_S2_TILE, D_); | ||
| 323 | + mm1.SetBias(false); | ||
| 324 | + mm1.SetFixSplit(CUBE_S1_TILE, 128, -1); // TODO: 这里是影响应能的关键,可参考FAG | ||
| 325 | + if (mm1.GetTiling(tilingData.mm1TilingData) == -1) { | ||
| 326 | + OP_LOGE(context->GetNodeName(), "mm1 getTiling failed."); | ||
| 327 | + return ge::GRAPH_FAILED; | ||
| 328 | + } | ||
| 329 | + tilingData.mm1TilingData.set_shareMode(0); | ||
| 330 | + tilingData.mm1TilingData.set_shareL1Size(ascInfo_.l1Size); | ||
| 331 | + tilingData.mm1TilingData.set_shareL0CSize(ascInfo_.l0CSize); | ||
| 332 | + | ||
| 333 | + // setting mm2 | ||
| 334 | + mm2.SetAType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_BFLOAT16, | ||
| 335 | + true); | ||
| 336 | + mm2.SetBType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_BFLOAT16, | ||
| 337 | + false); | ||
| 338 | + mm2.SetCType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_FLOAT); | ||
| 339 | + mm2.SetOrgShape(maxS2_, DI_, maxS1_); // tiling阶段随意设置,kernel运行时再设置为准确值 | ||
| 340 | + mm2.SetShape(CUBE_S2_TILE, DI_, CUBE_S1_TILE); | ||
| 341 | + mm2.SetBias(false); | ||
| 342 | + mm2.SetFixSplit(-1, -1, -1); | ||
| 343 | + if (mm2.GetTiling(tilingData.mm2TilingData) == -1) { | ||
| 344 | + OP_LOGE(context->GetNodeName(), "mm2 getTiling failed."); | ||
| 345 | + return ge::GRAPH_FAILED; | ||
| 346 | + } | ||
| 347 | + tilingData.mm2TilingData.set_shareMode(0); | ||
| 348 | + tilingData.mm2TilingData.set_shareL1Size(ascInfo_.l1Size); | ||
| 349 | + tilingData.mm2TilingData.set_shareL0CSize(ascInfo_.l0CSize); | ||
| 350 | + | ||
| 351 | + // setting mm3 | ||
| 352 | + mm3.SetAType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_BFLOAT16, | ||
| 353 | + false); | ||
| 354 | + mm3.SetBType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_BFLOAT16, | ||
| 355 | + false); | ||
| 356 | + mm3.SetCType(matmul_tiling::TPosition::GM, matmul_tiling::CubeFormat::ND, matmul_tiling::DataType::DT_FLOAT); | ||
| 357 | + mm3.SetOrgShape(maxS1_, DI_, maxS2_); // tiling阶段随意设置,kernel运行时再设置为准确值 | ||
| 358 | + mm3.SetShape(CUBE_S1_TILE, DI_, CUBE_S2_TILE); | ||
| 359 | + mm3.SetBias(false); | ||
| 360 | + mm3.SetFixSplit(-1, -1, -1); | ||
| 361 | + if (mm3.GetTiling(tilingData.mm3TilingData) == -1) { | ||
| 362 | + OP_LOGE(context->GetNodeName(), "mm3 getTiling failed."); | ||
| 363 | + return ge::GRAPH_FAILED; | ||
| 364 | + } | ||
| 365 | + tilingData.mm3TilingData.set_shareMode(0); | ||
| 366 | + tilingData.mm3TilingData.set_shareL1Size(ascInfo_.l1Size); | ||
| 367 | + tilingData.mm3TilingData.set_shareL0CSize(ascInfo_.l0CSize); | ||
| 368 | + | ||
| 369 | + return ge::GRAPH_SUCCESS; | ||
| 370 | +} | ||
| 371 | + | ||
| 372 | +void DsaDenseTiling::SetWorkspace(gert::TilingContext* context) | ||
| 373 | +{ | ||
| 374 | + size_t* workspaces = context->GetWorkspaceSizes(1); | ||
| 375 | + uint64_t qkSpace = CUBE_S1_TILE * CUBE_S2_TILE * sizeof(float) * DB; // P、Y两个计算图复用 | ||
| 376 | + uint64_t pSpace = CUBE_S1_TILE * CUBE_S2_TILE * sizeof(float); // 保存P | ||
| 377 | + uint64_t ySpace = CUBE_S1_TILE * CUBE_S2_TILE * sizeof(float); // 保存Y | ||
| 378 | + uint64_t reluSpace = CUBE_S1_TILE * CUBE_S2_TILE * sizeof(float) * NI_; // 保存S' | ||
| 379 | + // uint64_t reluGradSpace = CUBE_S1_TILE * CUBE_S2_TILE * sizeof(float) * DB; // 复用qkSpace | ||
| 380 | + uint64_t dwSpace = T1_ * NI_ * sizeof(float); | ||
| 381 | + // kl loss workspace复用qkSpace | ||
| 382 | + uint64_t dkSpace = T2_ * DI_ * sizeof(float); | ||
| 383 | + uint64_t dqSpace = T1_ * NI_ * DI_ * sizeof(float); | ||
| 384 | + | ||
| 385 | + workspaces[0] = | ||
| 386 | + SYS_WORKSPACE_SIZE + ascInfo_.aivNum * (qkSpace + pSpace + ySpace + reluSpace + dkSpace) + dwSpace + dqSpace; | ||
| 387 | + | ||
| 388 | + tilingData.baseParams.set_qkSpaceBytes(qkSpace); | ||
| 389 | + tilingData.baseParams.set_pSpaceBytes(pSpace); | ||
| 390 | + tilingData.baseParams.set_ySpaceBytes(ySpace); | ||
| 391 | + tilingData.baseParams.set_reluSpaceBytes(reluSpace); | ||
| 392 | + tilingData.baseParams.set_dwSpaceBytes(dwSpace); | ||
| 393 | + tilingData.baseParams.set_dkSpaceBytes(dkSpace); | ||
| 394 | + tilingData.baseParams.set_dqSpaceBytes(dqSpace); | ||
| 395 | +} | ||
| 396 | + | ||
| 397 | +void DsaDenseTiling::SaveTilingInfo(gert::TilingContext* context) | ||
| 398 | +{ | ||
| 399 | + context->SetBlockDim(ascInfo_.aicNum); // mix算子按aic num发射《aicore》 | ||
| 400 | + context->SetTilingKey(0); | ||
| 401 | + context->SetScheduleMode(1); // 1: batchmode模式 | ||
| 402 | + | ||
| 403 | + tilingData.baseParams.set_B(B_); | ||
| 404 | + tilingData.baseParams.set_N(N_); | ||
| 405 | + tilingData.baseParams.set_NI(NI_); | ||
| 406 | + tilingData.baseParams.set_D(D_); | ||
| 407 | + tilingData.baseParams.set_DI(DI_); | ||
| 408 | + tilingData.baseParams.set_T1(T1_); | ||
| 409 | + tilingData.baseParams.set_T2(T2_); | ||
| 410 | + tilingData.baseParams.set_maxS1(maxS1_); | ||
| 411 | + tilingData.baseParams.set_maxS2(maxS2_); | ||
| 412 | + tilingData.baseParams.set_scale(scale_); | ||
| 413 | + tilingData.baseParams.set_cubeS1Tile(CUBE_S1_TILE); | ||
| 414 | + tilingData.baseParams.set_cubeS2Tile(CUBE_S2_TILE); | ||
| 415 | + tilingData.baseParams.set_vecS1Tile(VEC_S1_TILE); | ||
| 416 | + tilingData.baseParams.set_vecS2Tile(VEC_S2_TILE); | ||
| 417 | + tilingData.baseParams.set_aivNum(ascInfo_.aivNum); | ||
| 418 | + | ||
| 419 | + tilingData.SaveToBuffer(context->GetRawTilingData()->GetData(), context->GetRawTilingData()->GetCapacity()); | ||
| 420 | + context->GetRawTilingData()->SetDataSize(tilingData.GetDataSize()); | ||
| 421 | +} | ||
| 422 | + | ||
| 423 | +ge::graphStatus DsaDenseTiling::DoTiling(gert::TilingContext* context) | ||
| 424 | +{ | ||
| 425 | + if (DoLibTiling(context) != ge::GRAPH_SUCCESS) { | ||
| 426 | + OP_LOGE(context->GetNodeName(), "DoLibTiling failed"); | ||
| 427 | + return ge::GRAPH_FAILED; | ||
| 428 | + } | ||
| 429 | + | ||
| 430 | + SetWorkspace(context); | ||
| 431 | + | ||
| 432 | + SaveTilingInfo(context); | ||
| 433 | + | ||
| 434 | + return ge::GRAPH_SUCCESS; | ||
| 435 | +} | ||
| 436 | + | ||
| 437 | +ge::graphStatus TilingDsaDense(gert::TilingContext* context) | ||
| 438 | +{ | ||
| 439 | + OP_CHECK_IF(context == nullptr, OP_LOGE("DsaDense", "Context is nullptr."), return ge::GRAPH_FAILED); | ||
| 440 | + DsaDenseTiling tilingObj; | ||
| 441 | + platform_ascendc::PlatformAscendC ascendcPlatform(context->GetPlatformInfo()); | ||
| 442 | + if (tilingObj.Init(context, ascendcPlatform) != ge::GRAPH_SUCCESS) { | ||
| 443 | + OP_LOGE(context->GetNodeName(), "Tiling Init() failed."); | ||
| 444 | + return ge::GRAPH_FAILED; | ||
| 445 | + } | ||
| 446 | + return tilingObj.DoTiling(context); | ||
| 447 | +} | ||
| 448 | + | ||
| 449 | +IMPL_OP_OPTILING(DsaDense).Tiling(TilingDsaDense); | ||
| 450 | + | ||
| 451 | +} // namespace optiling | ||
| @@ -0,0 +1,64 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file dsa_dense_tiling.h | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#ifndef _DSA_DENSE_TILING_H_ | ||
| 17 | +#define _DSA_DENSE_TILING_H_ | ||
| 18 | + | ||
| 19 | +#include "register/tilingdata_base.h" | ||
| 20 | +#include "tiling/tiling_api.h" | ||
| 21 | + | ||
| 22 | +namespace optiling { | ||
| 23 | + | ||
| 24 | +BEGIN_TILING_DATA_DEF(DsaDenseBaseParams) | ||
| 25 | +// base shape | ||
| 26 | +TILING_DATA_FIELD_DEF(uint32_t, B); | ||
| 27 | +TILING_DATA_FIELD_DEF(uint32_t, N); | ||
| 28 | +TILING_DATA_FIELD_DEF(uint32_t, NI); | ||
| 29 | +TILING_DATA_FIELD_DEF(uint32_t, D); | ||
| 30 | +TILING_DATA_FIELD_DEF(uint32_t, DI); | ||
| 31 | +TILING_DATA_FIELD_DEF(uint64_t, T1); | ||
| 32 | +TILING_DATA_FIELD_DEF(uint64_t, T2); | ||
| 33 | +TILING_DATA_FIELD_DEF(uint64_t, maxS1); | ||
| 34 | +TILING_DATA_FIELD_DEF(uint64_t, maxS2); | ||
| 35 | +TILING_DATA_FIELD_DEF(float, scale); // 1 / sqrt(D) | ||
| 36 | +TILING_DATA_FIELD_DEF(uint32_t, cubeS1Tile); | ||
| 37 | +TILING_DATA_FIELD_DEF(uint32_t, cubeS2Tile); | ||
| 38 | +TILING_DATA_FIELD_DEF(uint32_t, vecS1Tile); | ||
| 39 | +TILING_DATA_FIELD_DEF(uint32_t, vecS2Tile); | ||
| 40 | +// workspace offset | ||
| 41 | +TILING_DATA_FIELD_DEF(uint64_t, qkSpaceBytes); | ||
| 42 | +TILING_DATA_FIELD_DEF(uint64_t, pSpaceBytes); | ||
| 43 | +TILING_DATA_FIELD_DEF(uint64_t, ySpaceBytes); | ||
| 44 | +TILING_DATA_FIELD_DEF(uint64_t, reluSpaceBytes); | ||
| 45 | +TILING_DATA_FIELD_DEF(uint64_t, dwSpaceBytes); | ||
| 46 | +TILING_DATA_FIELD_DEF(uint64_t, dkSpaceBytes); | ||
| 47 | +TILING_DATA_FIELD_DEF(uint64_t, dqSpaceBytes); | ||
| 48 | +// AIV num | ||
| 49 | +TILING_DATA_FIELD_DEF(uint32_t, aivNum); | ||
| 50 | +END_TILING_DATA_DEF; | ||
| 51 | + | ||
| 52 | +REGISTER_TILING_DATA_CLASS(DsaDenseBaseParamsOp, DsaDenseBaseParams) | ||
| 53 | + | ||
| 54 | +BEGIN_TILING_DATA_DEF(DsaDenseTilingData) | ||
| 55 | +TILING_DATA_FIELD_DEF_STRUCT(DsaDenseBaseParams, baseParams); | ||
| 56 | +TILING_DATA_FIELD_DEF_STRUCT(TCubeTiling, mm1TilingData); | ||
| 57 | +TILING_DATA_FIELD_DEF_STRUCT(TCubeTiling, mm2TilingData); | ||
| 58 | +TILING_DATA_FIELD_DEF_STRUCT(TCubeTiling, mm3TilingData); | ||
| 59 | +END_TILING_DATA_DEF; | ||
| 60 | + | ||
| 61 | +REGISTER_TILING_DATA_CLASS(DsaDense, DsaDenseTilingData) | ||
| 62 | +} // namespace optiling | ||
| 63 | + | ||
| 64 | +#endif | ||
| @@ -0,0 +1,52 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file dsa_dense.cpp | ||
| 13 | + * \brief | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "kernel_operator.h" | ||
| 17 | +#include "dsa_dense.h" | ||
| 18 | + | ||
| 19 | +using namespace AscendC; | ||
| 20 | +using namespace matmul; | ||
| 21 | + | ||
| 22 | +extern "C" __global__ __aicore__ void dsa_dense(__gm__ uint8_t* query, __gm__ uint8_t* key, __gm__ uint8_t* max, | ||
| 23 | + __gm__ uint8_t* sum, __gm__ uint8_t* qLen, __gm__ uint8_t* kvLen, | ||
| 24 | + __gm__ uint8_t* mask, __gm__ uint8_t* queryIndex, | ||
| 25 | + __gm__ uint8_t* keyIndex, __gm__ uint8_t* weights, | ||
| 26 | + __gm__ uint8_t* maxIndex, __gm__ uint8_t* sumIndex, | ||
| 27 | + __gm__ uint8_t* loss, __gm__ uint8_t* dq, __gm__ uint8_t* dk, | ||
| 28 | + __gm__ uint8_t* dw, __gm__ uint8_t* workspace, __gm__ uint8_t* tiling) | ||
| 29 | +{ | ||
| 30 | + // global TPipe obj | ||
| 31 | + TPipe tPipe; | ||
| 32 | + AscendCUtils::SetOverflow(1); | ||
| 33 | + | ||
| 34 | + // user worksapce | ||
| 35 | + SetSysWorkspace(workspace); | ||
| 36 | + __gm__ uint8_t* user = GetUserWorkspace(workspace); | ||
| 37 | + | ||
| 38 | + // tiling obj | ||
| 39 | + GET_TILING_DATA(tiling_data, tiling); | ||
| 40 | + | ||
| 41 | + if (TILING_KEY_IS(0)) { | ||
| 42 | + const TCubeTiling* __restrict mm1Tiling = &(tiling_data.mm1TilingData); | ||
| 43 | + const TCubeTiling* __restrict mm2Tiling = &(tiling_data.mm2TilingData); | ||
| 44 | + const TCubeTiling* __restrict mm3Tiling = &(tiling_data.mm3TilingData); | ||
| 45 | + | ||
| 46 | + ops_dsa_dense::DsaDense<bfloat16_t, float> op; | ||
| 47 | + REGIST_MATMUL_OBJ(&tPipe, GetSysWorkSpacePtr(), op.mm1, mm1Tiling, op.mm2, mm2Tiling, op.mm3, mm3Tiling); | ||
| 48 | + op.Init(query, key, max, sum, qLen, kvLen, mask, queryIndex, keyIndex, weights, maxIndex, sumIndex, loss, dq, | ||
| 49 | + dk, dw, user, &tiling_data, &tPipe); | ||
| 50 | + op.Process(); | ||
| 51 | + } | ||
| 52 | +} | ||
| @@ -0,0 +1,42 @@ | |||
| 1 | +# dsa_dense算子测试框架 | ||
| 2 | + | ||
| 3 | +## 功能说明 | ||
| 4 | +基于pytest测试框架,实现dsa_dense算子的功能验证: | ||
| 5 | +- **CPU侧**:复现算子功能(DSA dense 反向的 loss/dq/dk/dw)生成 golden 数据 | ||
| 6 | +- **NPU侧**:通过 `torch_npu.dsa_dense` 直调获取实际数据 | ||
| 7 | +- **精度对比**:按浮点误差(mean(abs diff) <= 阈值)比较 CPU 与 NPU 结果 | ||
| 8 | + | ||
| 9 | +## 当前实现范围 | ||
| 10 | + | ||
| 11 | +### 参数限制 | ||
| 12 | +- 布局:TND(变长) | ||
| 13 | +- 数据类型:BF16(query/key/queryIndex/keyIndex)、FLOAT(weights/max/sum/maxIndex/sumIndex) | ||
| 14 | +- `sparse_mode` 仅支持 1(causal);`D=192`、`DI=128`、`NI=N//2` | ||
| 15 | + | ||
| 16 | +### 环境配置 | ||
| 17 | +1. 确认 TorchNPU 为最新版本 | ||
| 18 | +2. 参考[Attention融合算子Experimental使用说明](../../../Attention融合算子Experimental使用说明.md)激活 CANN 包和自定义算子包 | ||
| 19 | + | ||
| 20 | +## 文件结构 | ||
| 21 | +- test_run.sh # 执行脚本 | ||
| 22 | +- dsa_dense_golden.py # cpu侧算子golden实现 | ||
| 23 | +- dsa_dense_process.py # 调用算子获取npu输出 | ||
| 24 | +- dsa_dense_paramset.py # 用例入参配置 | ||
| 25 | +- result_compare_method.py # 精度对比 | ||
| 26 | +- test_dsa_dense_single.py # pytest测试单用例运行主程序 | ||
| 27 | +- utils.py # 结果保存工具 | ||
| 28 | +- pytest.ini # 创建测试标记 | ||
| 29 | + | ||
| 30 | +## 使用方法 | ||
| 31 | + | ||
| 32 | +在 pytest 文件夹路径下执行: | ||
| 33 | + | ||
| 34 | +1. 手动配置 `dsa_dense_paramset.py` 的参数 | ||
| 35 | +2. 执行指令: | ||
| 36 | +```bash | ||
| 37 | +bash test_run.sh single | ||
| 38 | +``` | ||
| 39 | +支持自定义结果保存路径: | ||
| 40 | +```bash | ||
| 41 | +bash test_run.sh single -R "./result/dsa_result.xlsx" | ||
| 42 | +``` | ||
| @@ -0,0 +1,150 @@ | |||
| 1 | +#!/usr/bin/python | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +"""直接调用 CANN aclnn C 接口(ctypes),不依赖 torch_npu 的算子 op-plugin 绑定。 | ||
| 14 | + | ||
| 15 | +依赖:libcust_opapi.so(算子自带 aclnn)、libnnopbase.so(aclCreateTensor/aclCreateIntArray)、 | ||
| 16 | +libascendcl(aclrt*)。torch/torch_npu 仅用于申请 NPU 显存和获取 aclrtStream。 | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +import ctypes | ||
| 20 | +from ctypes import ( | ||
| 21 | + c_void_p, | ||
| 22 | + c_int64, | ||
| 23 | + c_uint64, | ||
| 24 | + c_int, | ||
| 25 | + c_char_p, | ||
| 26 | + c_double, | ||
| 27 | + c_bool, | ||
| 28 | + byref, | ||
| 29 | + POINTER, | ||
| 30 | +) | ||
| 31 | + | ||
| 32 | +import torch | ||
| 33 | +import torch_npu | ||
| 34 | + | ||
| 35 | +_OPAPI = ctypes.CDLL("libcust_opapi.so") | ||
| 36 | +_NNOP = ctypes.CDLL("libnnopbase.so") | ||
| 37 | + | ||
| 38 | +_DTYPE = { | ||
| 39 | + torch.float32: 0, | ||
| 40 | + torch.float16: 1, | ||
| 41 | + torch.int8: 2, | ||
| 42 | + torch.int32: 3, | ||
| 43 | + torch.uint8: 4, | ||
| 44 | + torch.int16: 6, | ||
| 45 | + torch.uint16: 7, | ||
| 46 | + torch.uint32: 8, | ||
| 47 | + torch.uint64: 10, | ||
| 48 | + torch.int64: 9, | ||
| 49 | + torch.float64: 11, | ||
| 50 | + torch.bool: 12, | ||
| 51 | + torch.bfloat16: 27, | ||
| 52 | +} | ||
| 53 | +_FORMAT_ND = 2 | ||
| 54 | + | ||
| 55 | +_NNOP.aclCreateTensor.restype = c_void_p | ||
| 56 | +_NNOP.aclCreateTensor.argtypes = [ | ||
| 57 | + POINTER(c_int64), | ||
| 58 | + c_uint64, | ||
| 59 | + c_int, | ||
| 60 | + POINTER(c_int64), | ||
| 61 | + c_int64, | ||
| 62 | + c_int, | ||
| 63 | + POINTER(c_int64), | ||
| 64 | + c_uint64, | ||
| 65 | + c_void_p, | ||
| 66 | +] | ||
| 67 | +_NNOP.aclCreateIntArray.restype = c_void_p | ||
| 68 | +_NNOP.aclCreateIntArray.argtypes = [POINTER(c_int64), c_uint64] | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def to_acl(tensor): | ||
| 72 | + """把 torch NPU tensor 包装成 aclTensor(None -> 空指针,用于可选输入)。""" | ||
| 73 | + if tensor is None: | ||
| 74 | + return c_void_p(None) | ||
| 75 | + shape = list(tensor.shape) | ||
| 76 | + n = len(shape) | ||
| 77 | + dims = (c_int64 * n)(*shape) | ||
| 78 | + strides, s = [], 1 | ||
| 79 | + for d in reversed(shape): | ||
| 80 | + strides.insert(0, s) | ||
| 81 | + s *= d | ||
| 82 | + strd = (c_int64 * n)(*strides) | ||
| 83 | + return _NNOP.aclCreateTensor( | ||
| 84 | + dims, | ||
| 85 | + n, | ||
| 86 | + _DTYPE[tensor.dtype], | ||
| 87 | + strd, | ||
| 88 | + 0, | ||
| 89 | + _FORMAT_ND, | ||
| 90 | + dims, | ||
| 91 | + n, | ||
| 92 | + c_void_p(tensor.data_ptr()), | ||
| 93 | + ) | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +def int_array(values): | ||
| 97 | + if values is None: | ||
| 98 | + return c_void_p(None) | ||
| 99 | + arr = (c_int64 * len(values))(*values) | ||
| 100 | + return _NNOP.aclCreateIntArray(arr, len(values)) | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +_CTYPE = { | ||
| 104 | + "tensor": c_void_p, | ||
| 105 | + "int64": c_int64, | ||
| 106 | + "double": c_double, | ||
| 107 | + "bool": c_bool, | ||
| 108 | + "str": c_char_p, | ||
| 109 | + "intarray": c_void_p, | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +def call(get_ws_name, op_name, spec): | ||
| 114 | + """spec: [(kind, value), ...],按 aclnn GetWorkspaceSize 的形参顺序(含输出)。 | ||
| 115 | + | ||
| 116 | + kind ∈ {tensor, int64, double, bool, str, intarray} | ||
| 117 | + """ | ||
| 118 | + fn = getattr(_OPAPI, get_ws_name) | ||
| 119 | + fn.restype = c_int | ||
| 120 | + argtypes, cargs = [], [] | ||
| 121 | + for kind, value in spec: | ||
| 122 | + argtypes.append(_CTYPE[kind]) | ||
| 123 | + if kind == "tensor": | ||
| 124 | + cargs.append(to_acl(value)) | ||
| 125 | + elif kind == "intarray": | ||
| 126 | + cargs.append(int_array(value)) | ||
| 127 | + elif kind == "str": | ||
| 128 | + cargs.append(c_char_p(None) if value is None else c_char_p(value.encode())) | ||
| 129 | + else: | ||
| 130 | + cargs.append(value) | ||
| 131 | + | ||
| 132 | + ws = c_uint64(0) | ||
| 133 | + executor = c_void_p() | ||
| 134 | + fn.argtypes = argtypes + [POINTER(c_uint64), POINTER(c_void_p)] | ||
| 135 | + st = fn(*(cargs + [byref(ws), byref(executor)])) | ||
| 136 | + if st != 0: | ||
| 137 | + raise RuntimeError("%s failed, status=%d" % (get_ws_name, st)) | ||
| 138 | + | ||
| 139 | + run = getattr(_OPAPI, op_name) | ||
| 140 | + run.restype = c_int | ||
| 141 | + run.argtypes = [c_void_p, c_uint64, c_void_p, c_void_p] | ||
| 142 | + dev = torch.npu.current_device() | ||
| 143 | + ws_tensor = torch.empty( | ||
| 144 | + max(int(ws.value), 1), dtype=torch.uint8, device="npu:%d" % dev | ||
| 145 | + ) | ||
| 146 | + stream = c_void_p(torch_npu.npu.current_stream().npu_stream) | ||
| 147 | + st = run(c_void_p(ws_tensor.data_ptr()), ws.value, executor, stream) | ||
| 148 | + if st != 0: | ||
| 149 | + raise RuntimeError("%s failed, status=%d" % (op_name, st)) | ||
| 150 | + torch.npu.synchronize() | ||
| @@ -0,0 +1,243 @@ | |||
| 1 | +#!/usr/bin/python | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +import math | ||
| 14 | + | ||
| 15 | +import numpy as np | ||
| 16 | +import torch | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def _gen_seq_len(batch, t1, seed): | ||
| 20 | + rng = np.random.RandomState(seed) | ||
| 21 | + random_numbers = rng.rand(batch) | ||
| 22 | + normalized = random_numbers / random_numbers.sum() | ||
| 23 | + q_len_tmp = [int(t1 * normalized[i]) for i in range(batch)] | ||
| 24 | + q_len = [1 if q_len_tmp[i] == 0 else q_len_tmp[i] for i in range(batch)] | ||
| 25 | + kv_len = [q_len[i] + int(rng.randint(100, 2000)) for i in range(batch)] | ||
| 26 | + return q_len, kv_len | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def _compute_golden( | ||
| 30 | + q, | ||
| 31 | + k, | ||
| 32 | + q_index, | ||
| 33 | + k_index, | ||
| 34 | + weights, | ||
| 35 | + mask_list, | ||
| 36 | + actual_q_len, | ||
| 37 | + actual_kv_len, | ||
| 38 | + cu_q_len, | ||
| 39 | + cu_kv_len, | ||
| 40 | + batch, | ||
| 41 | + n, | ||
| 42 | + ni, | ||
| 43 | + di, | ||
| 44 | + scale, | ||
| 45 | + device, | ||
| 46 | +): | ||
| 47 | + final_main_max = [] | ||
| 48 | + final_main_sum = [] | ||
| 49 | + final_index_max = [] | ||
| 50 | + final_index_sum = [] | ||
| 51 | + dw_batch_list = [] | ||
| 52 | + dq_batch_list = [] | ||
| 53 | + dk_batch_list = [] | ||
| 54 | + gt_loss = torch.zeros(1, dtype=torch.float, device=device) | ||
| 55 | + | ||
| 56 | + for b in range(batch): | ||
| 57 | + actual_s1 = actual_q_len[b] | ||
| 58 | + actual_s2 = actual_kv_len[b] | ||
| 59 | + start_s1 = cu_q_len[b] | ||
| 60 | + start_s2 = cu_kv_len[b] | ||
| 61 | + | ||
| 62 | + # main attention softmax | ||
| 63 | + actual_q = q[start_s1 : start_s1 + actual_s1, :, :].permute(1, 0, 2) # NSD | ||
| 64 | + actual_k = k[start_s2 : start_s2 + actual_s2, :, :].permute(1, 2, 0) # NDS | ||
| 65 | + p_list = [] | ||
| 66 | + main_max_list = [] | ||
| 67 | + main_sum_list = [] | ||
| 68 | + for head in range(n): | ||
| 69 | + p = actual_q[head] @ actual_k[head] | ||
| 70 | + p = p * scale | ||
| 71 | + p = p.masked_fill(mask_list[b].to(torch.bool), -100000000.0) | ||
| 72 | + main_max, _ = torch.max(p, dim=1, keepdim=True) | ||
| 73 | + main_sum = torch.sum(torch.exp(p - main_max), dim=1, keepdim=True) | ||
| 74 | + main_max_list.append(main_max) | ||
| 75 | + main_sum_list.append(main_sum) | ||
| 76 | + p = torch.exp(p - main_max) / main_sum | ||
| 77 | + p_list.append(p.unsqueeze(0)) | ||
| 78 | + p = torch.cat(p_list, dim=0) | ||
| 79 | + p = torch.sum(p, dim=0, keepdim=False) | ||
| 80 | + p = p / n | ||
| 81 | + main_max = torch.cat(main_max_list, dim=1) | ||
| 82 | + main_sum = torch.cat(main_sum_list, dim=1) | ||
| 83 | + final_main_max.append(main_max) | ||
| 84 | + final_main_sum.append(main_sum) | ||
| 85 | + | ||
| 86 | + # indexer softmax | ||
| 87 | + actual_q_index = q_index[start_s1 : start_s1 + actual_s1, :, :].permute( | ||
| 88 | + 1, 0, 2 | ||
| 89 | + ) # NI S1 DI | ||
| 90 | + actual_k_index = k_index[start_s2 : start_s2 + actual_s2, :].permute( | ||
| 91 | + 1, 0 | ||
| 92 | + ) # DI S2 | ||
| 93 | + actual_weights = weights[start_s1 : start_s1 + actual_s1, :] | ||
| 94 | + y_list = [] | ||
| 95 | + relu_list = [] | ||
| 96 | + for head in range(ni): | ||
| 97 | + y = actual_q_index[head] @ actual_k_index | ||
| 98 | + y = torch.relu(y) | ||
| 99 | + relu_list.append(y) | ||
| 100 | + y = y * (actual_weights[:, head].view(actual_s1, 1)) | ||
| 101 | + y_list.append(y.unsqueeze(0)) | ||
| 102 | + y = torch.cat(y_list, dim=0) | ||
| 103 | + y = torch.sum(y, dim=0, keepdim=False) | ||
| 104 | + y = y.masked_fill(mask_list[b].to(torch.bool), -100000000.0) | ||
| 105 | + index_max, _ = torch.max(y, dim=1, keepdim=True) | ||
| 106 | + index_sum = torch.sum(torch.exp(y - index_max), dim=1, keepdim=True) | ||
| 107 | + final_index_max.append(index_max) | ||
| 108 | + final_index_sum.append(index_sum) | ||
| 109 | + y = torch.exp(y - index_max) / index_sum | ||
| 110 | + | ||
| 111 | + # gradients | ||
| 112 | + di = y - p | ||
| 113 | + dw_list = [] | ||
| 114 | + dq_list = [] | ||
| 115 | + dk_list = [] | ||
| 116 | + for head in range(ni): | ||
| 117 | + dw = di * relu_list[head] | ||
| 118 | + dw = torch.sum(dw, dim=1, keepdim=False) | ||
| 119 | + dw_list.append(dw.unsqueeze(0)) | ||
| 120 | + | ||
| 121 | + ds_tmp = di * (actual_weights[:, head].view(actual_s1, 1)) | ||
| 122 | + ds = torch.where(relu_list[head] > 0, ds_tmp, torch.zeros_like(ds_tmp)) | ||
| 123 | + | ||
| 124 | + dq = ds @ actual_k_index.T | ||
| 125 | + dq = dq.unsqueeze(1) | ||
| 126 | + dq_list.append(dq) | ||
| 127 | + | ||
| 128 | + dk = ds.T @ actual_q_index[head] | ||
| 129 | + dk = dk.unsqueeze(0) | ||
| 130 | + dk_list.append(dk) | ||
| 131 | + | ||
| 132 | + dw = torch.cat(dw_list, dim=0) | ||
| 133 | + dw_batch_list.append(dw) | ||
| 134 | + dq = torch.cat(dq_list, dim=1) | ||
| 135 | + dq_batch_list.append(dq) | ||
| 136 | + dk = torch.cat(dk_list, dim=0) | ||
| 137 | + dk_batch_list.append(dk) | ||
| 138 | + | ||
| 139 | + # KL loss | ||
| 140 | + loss = torch.clip(p, min=1e-8) / torch.clip(y, min=1e-8) | ||
| 141 | + loss = torch.log(loss) | ||
| 142 | + loss = p * loss | ||
| 143 | + gt_loss += torch.sum(loss) | ||
| 144 | + | ||
| 145 | + gt_dw = torch.cat(dw_batch_list, dim=1).t().contiguous() # T1 NI | ||
| 146 | + gt_dq = torch.cat(dq_batch_list, dim=0) # T1 NI DI | ||
| 147 | + gt_dk = torch.cat(dk_batch_list, dim=1) # NI T2 DI | ||
| 148 | + gt_dk = torch.sum(gt_dk, dim=0, keepdim=False) # T2 DI | ||
| 149 | + | ||
| 150 | + main_max = torch.cat(final_main_max, dim=0).permute(1, 0) # N T1 | ||
| 151 | + main_sum = torch.cat(final_main_sum, dim=0).permute(1, 0) # N T1 | ||
| 152 | + index_max = torch.cat(final_index_max, dim=0).view(-1) # T1 | ||
| 153 | + index_sum = torch.cat(final_index_sum, dim=0).view(-1) # T1 | ||
| 154 | + | ||
| 155 | + return gt_loss, gt_dq, gt_dk, gt_dw, main_max, main_sum, index_max, index_sum | ||
| 156 | + | ||
| 157 | + | ||
| 158 | +def gen_data(params): | ||
| 159 | + """根据参数生成算子输入、属性与 CPU golden 结果(TND 变长,DSA dense 反向)。""" | ||
| 160 | + batch, t1_base, n, case_name = params | ||
| 161 | + device = torch.device("cpu") | ||
| 162 | + seed = 42 | ||
| 163 | + | ||
| 164 | + torch.manual_seed(seed) | ||
| 165 | + np.random.seed(seed) | ||
| 166 | + | ||
| 167 | + actual_q_len, actual_kv_len = _gen_seq_len(batch, t1_base, seed) | ||
| 168 | + t1 = int(np.sum(actual_q_len)) | ||
| 169 | + t2 = int(np.sum(actual_kv_len)) | ||
| 170 | + ni = n // 2 | ||
| 171 | + d = 192 | ||
| 172 | + di = 128 | ||
| 173 | + scale = 1.0 / math.sqrt(d) | ||
| 174 | + | ||
| 175 | + cu_q_len = [0] + list(np.cumsum(actual_q_len)) | ||
| 176 | + cu_kv_len = [0] + list(np.cumsum(actual_kv_len)) | ||
| 177 | + | ||
| 178 | + q = torch.randn(t1, n, d, device=device, dtype=torch.bfloat16).to(torch.float) | ||
| 179 | + k = torch.randn(t2, n, d, device=device, dtype=torch.bfloat16).to(torch.float) | ||
| 180 | + q_index = torch.randn(t1, ni, di, device=device, dtype=torch.bfloat16).to( | ||
| 181 | + torch.float | ||
| 182 | + ) | ||
| 183 | + k_index = torch.randn(t2, di, device=device, dtype=torch.bfloat16).to(torch.float) | ||
| 184 | + weights = torch.randn(t1, ni, device=device, dtype=torch.float) | ||
| 185 | + | ||
| 186 | + mask_list = [] | ||
| 187 | + for b in range(batch): | ||
| 188 | + actual_s1 = actual_q_len[b] | ||
| 189 | + actual_s2 = actual_kv_len[b] | ||
| 190 | + atten_mask_u = torch.triu( | ||
| 191 | + torch.ones([actual_s1, actual_s2], dtype=torch.uint8), | ||
| 192 | + diagonal=(actual_s2 - actual_s1) + 1, | ||
| 193 | + ).to(device) | ||
| 194 | + mask_list.append(atten_mask_u) | ||
| 195 | + | ||
| 196 | + gt_loss, gt_dq, gt_dk, gt_dw, main_max, main_sum, index_max, index_sum = ( | ||
| 197 | + _compute_golden( | ||
| 198 | + q, | ||
| 199 | + k, | ||
| 200 | + q_index, | ||
| 201 | + k_index, | ||
| 202 | + weights, | ||
| 203 | + mask_list, | ||
| 204 | + actual_q_len, | ||
| 205 | + actual_kv_len, | ||
| 206 | + cu_q_len, | ||
| 207 | + cu_kv_len, | ||
| 208 | + batch, | ||
| 209 | + n, | ||
| 210 | + ni, | ||
| 211 | + di, | ||
| 212 | + scale, | ||
| 213 | + device, | ||
| 214 | + ) | ||
| 215 | + ) | ||
| 216 | + | ||
| 217 | + input_data = { | ||
| 218 | + "input": { | ||
| 219 | + "query": q.to(torch.bfloat16), | ||
| 220 | + "key": k.to(torch.bfloat16), | ||
| 221 | + "max": main_max.contiguous(), | ||
| 222 | + "sum": main_sum.contiguous(), | ||
| 223 | + "q_len": torch.tensor(cu_q_len, dtype=torch.int64, device=device), | ||
| 224 | + "kv_len": torch.tensor(cu_kv_len, dtype=torch.int64, device=device), | ||
| 225 | + "query_index": q_index.to(torch.bfloat16), | ||
| 226 | + "key_index": k_index.to(torch.bfloat16), | ||
| 227 | + "weights": weights, | ||
| 228 | + "max_index": index_max.contiguous(), | ||
| 229 | + "sum_index": index_sum.contiguous(), | ||
| 230 | + }, | ||
| 231 | + "attr": { | ||
| 232 | + "sparse_mode": 1, | ||
| 233 | + "scale": scale, | ||
| 234 | + }, | ||
| 235 | + "cpu_output": { | ||
| 236 | + "loss": gt_loss, | ||
| 237 | + "dq": gt_dq, | ||
| 238 | + "dk": gt_dk, | ||
| 239 | + "dw": gt_dw, | ||
| 240 | + }, | ||
| 241 | + "case_name": case_name, | ||
| 242 | + } | ||
| 243 | + return input_data | ||
| @@ -0,0 +1,40 @@ | |||
| 1 | +#!/usr/bin/python | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 6 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 7 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 8 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 9 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 10 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 11 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +# 定义测试参数组合 | ||
| 14 | +# params 结构:(batch, t1_base, n, case_name) | ||
| 15 | +# - t1_base 为按 batch 归一化前的总 query 长度基准;实际 T1 = sum(q_len) | ||
| 16 | +# - n 为主注意力 head 数,NI = N // 2,D = 192,DI = 128 | ||
| 17 | +TEST_PARAMS = { | ||
| 18 | + "tnd_b2_t256_n8": {"batch": [2], "t1_base": [256], "n": [8]}, | ||
| 19 | + "tnd_b1_t256_n8": {"batch": [1], "t1_base": [256], "n": [8]}, | ||
| 20 | + "tnd_b2_t512_n16": {"batch": [2], "t1_base": [512], "n": [16]}, | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +# 按需选择要启用的测试参数(默认启用所有) | ||
| 24 | +ENABLED_PARAMS = [] | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def build_params(): | ||
| 28 | + for key in TEST_PARAMS.keys(): | ||
| 29 | + params = TEST_PARAMS[key] | ||
| 30 | + ENABLED_PARAMS.append( | ||
| 31 | + ( | ||
| 32 | + params["batch"][0], | ||
| 33 | + params["t1_base"][0], | ||
| 34 | + params["n"][0], | ||
| 35 | + key, | ||
| 36 | + ) | ||
| 37 | + ) | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +build_params() | ||
| @@ -0,0 +1,66 @@ | |||
| 1 | +#!/usr/bin/python | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 | ||
| 5 | + | ||
| 6 | +import torch | ||
| 7 | +import torch_npu | ||
| 8 | +import aclnn_runner | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +def call_npu(input_data): | ||
| 12 | + """直接调用 aclnnDsaDense,返回 {loss, dq, dk, dw}。""" | ||
| 13 | + ti = input_data["input"] | ||
| 14 | + attr = input_data["attr"] | ||
| 15 | + query = ti["query"].npu() | ||
| 16 | + key = ti["key"].npu() | ||
| 17 | + mx = ti["max"].npu() | ||
| 18 | + sm = ti["sum"].npu() | ||
| 19 | + qlen = ti["q_len"].npu() | ||
| 20 | + kvlen = ti["kv_len"].npu() | ||
| 21 | + qidx = ti["query_index"].npu() | ||
| 22 | + kidx = ti["key_index"].npu() | ||
| 23 | + wt = ti["weights"].npu() | ||
| 24 | + midx = ti["max_index"].npu() | ||
| 25 | + sidx = ti["sum_index"].npu() | ||
| 26 | + | ||
| 27 | + t1, n, _ = query.shape | ||
| 28 | + t2 = key.shape[0] | ||
| 29 | + ni, di = qidx.shape[1], qidx.shape[2] | ||
| 30 | + dt, dev = query.dtype, query.device | ||
| 31 | + mask = ( | ||
| 32 | + torch.triu(torch.ones(128, 128, dtype=torch.float32), diagonal=1) | ||
| 33 | + .to(torch.bool) | ||
| 34 | + .to(dev) | ||
| 35 | + ) | ||
| 36 | + | ||
| 37 | + loss = torch.empty(1, dtype=torch.float32, device=dev) | ||
| 38 | + dq = torch.empty(t1, ni, di, dtype=dt, device=dev) | ||
| 39 | + dk = torch.empty(t2, di, dtype=dt, device=dev) | ||
| 40 | + dw = torch.empty(ni, t1, dtype=torch.float32, device=dev) | ||
| 41 | + | ||
| 42 | + aclnn_runner.call( | ||
| 43 | + "aclnnDsaDenseGetWorkspaceSize", | ||
| 44 | + "aclnnDsaDense", | ||
| 45 | + [ | ||
| 46 | + ("tensor", query), | ||
| 47 | + ("tensor", key), | ||
| 48 | + ("tensor", mx), | ||
| 49 | + ("tensor", sm), | ||
| 50 | + ("tensor", qlen), | ||
| 51 | + ("tensor", kvlen), | ||
| 52 | + ("tensor", mask), | ||
| 53 | + ("tensor", qidx), | ||
| 54 | + ("tensor", kidx), | ||
| 55 | + ("tensor", wt), | ||
| 56 | + ("tensor", midx), | ||
| 57 | + ("tensor", sidx), | ||
| 58 | + ("int64", int(attr["sparse_mode"])), | ||
| 59 | + ("double", attr["scale"]), | ||
| 60 | + ("tensor", loss), | ||
| 61 | + ("tensor", dq), | ||
| 62 | + ("tensor", dk), | ||
| 63 | + ("tensor", dw), | ||
| 64 | + ], | ||
| 65 | + ) | ||
| 66 | + return {"loss": loss, "dq": dq, "dk": dk, "dw": dw.t().contiguous()} | ||
| @@ -0,0 +1,4 @@ | |||
| 1 | +[pytest] | ||
| 2 | +markers = | ||
| 3 | + ci: mark a test as a CI test | ||
| 4 | + graph: marks tests as graph mode compilation tests | ||