Merged
examples result print #292
张田荣Add on Aug 27
examples result print #292
Merged
Merged fromzhangtianrong/ops-tensorexamples_resultintocann/ops-tensormaster
Total: 22 files changed+649-109
| @@ -24,7 +24,6 @@ ops-tensor 支持源码编译,进行源码编译前,请确保如下基础依 | |||
| 24 | - cmake >= 3.16.0 | 24 | - cmake >= 3.16.0 |
| 25 | - make | 25 | - make |
| 26 | - googletest(仅执行 Kernel UT 时依赖,建议版本 [release-1.11.0](https://github.com/google/googletest/releases/tag/release-1.11.0)) | 26 | - googletest(仅执行 Kernel UT 时依赖,建议版本 [release-1.11.0](https://github.com/google/googletest/releases/tag/release-1.11.0)) |
| 27 | - | ||
| 28 | 2. **安装驱动与固件(运行态依赖)** | 27 | 2. **安装驱动与固件(运行态依赖)** |
| 29 | 28 | ||
| 30 | 运行算子时必须安装驱动与固件,若仅编译算子,可跳过本操作。 | 29 | 运行算子时必须安装驱动与固件,若仅编译算子,可跳过本操作。 |
| @@ -65,16 +64,17 @@ chmod +x Ascend-cann-toolkit_${cann_version}_linux-${arch}.run | |||
| 65 | 安装完 CANN 包或进入 Docker 容器后,需验证环境和驱动是否正常。 | 64 | 安装完 CANN 包或进入 Docker 容器后,需验证环境和驱动是否正常。 |
| 66 | 65 | ||
| 67 | - **检查 NPU 设备**(仿真执行,跳过此步骤): | 66 | - **检查 NPU 设备**(仿真执行,跳过此步骤): |
| 68 | - ```bash | ||
| 69 | - # 运行 npu-smi,若能正常显示设备信息,则驱动正常 | ||
| 70 | - npu-smi info | ||
| 71 | - ``` | ||
| 72 | 67 | ||
| 68 | + ```bash | ||
| 69 | + # 运行 npu-smi,若能正常显示设备信息,则驱动正常 | ||
| 70 | + npu-smi info | ||
| 71 | + ``` | ||
| 73 | - **检查 CANN 安装**: | 72 | - **检查 CANN 安装**: |
| 74 | - ```bash | 73 | + |
| 75 | - # 查看 CANN Toolkit 版本信息(非 root 用户,将 /usr/local 替换为 ${HOME}) | 74 | + ```bash |
| 76 | - cat /usr/local/Ascend/cann/opp/version.info | 75 | + # 查看 CANN Toolkit 版本信息(非 root 用户,将 /usr/local 替换为 ${HOME}) |
| 77 | - ``` | 76 | + cat /usr/local/Ascend/cann/opp/version.info |
| 77 | + ``` | ||
| 78 | 78 | ||
| 79 | ## 环境变量配置 | 79 | ## 环境变量配置 |
| 80 | 80 | ||
| @@ -96,7 +96,7 @@ git clone -b master https://gitcode.com/cann/ops-tensor.git | |||
| 96 | cd ops-tensor | 96 | cd ops-tensor |
| 97 | ``` | 97 | ``` |
| 98 | 98 | ||
| 99 | -> [!NOTE] 注意 | 99 | +> [!NOTE] ✏️ 注意 |
| 100 | > gitcode 平台在使用 SSH 协议时,请在本地生成 SSH 公钥进行克隆、推送等操作。 | 100 | > gitcode 平台在使用 SSH 协议时,请在本地生成 SSH 公钥进行克隆、推送等操作。 |
| 101 | 101 | ||
| 102 | ## 编译执行 | 102 | ## 编译执行 |
| @@ -150,6 +150,7 @@ Kernel UT(单元测试)用于验证算子内核的正确性。 | |||
| 150 | ``` | 150 | ``` |
| 151 | 151 | ||
| 152 | **支持的 Kernel UT 算子**(位于 `tests/ut/op_kernel/`): | 152 | **支持的 Kernel UT 算子**(位于 `tests/ut/op_kernel/`): |
| 153 | + | ||
| 153 | - `mat_mul` - 矩阵乘算子 | 154 | - `mat_mul` - 矩阵乘算子 |
| 154 | - `fused_mat_mul` - 融合矩阵乘算子(MatMul + Scale + Add) | 155 | - `fused_mat_mul` - 融合矩阵乘算子(MatMul + Scale + Add) |
| 155 | - `transpose_batch_mat_mul` - 转置批量矩阵乘算子 | 156 | - `transpose_batch_mat_mul` - 转置批量矩阵乘算子 |
| @@ -163,6 +164,69 @@ Kernel UT(单元测试)用于验证算子内核的正确性。 | |||
| 163 | [SUCCESS] Kernel UT all SoC tests passed | 164 | [SUCCESS] Kernel UT all SoC tests passed |
| 164 | ``` | 165 | ``` |
| 165 | 166 | ||
| 167 | +### 5. 未联网编译 | ||
| 168 | + | ||
| 169 | +未联网环境下编译执行 Kernel UT,需提前在联网环境备齐 `cann-cmake`、`gtest`、`tensor_api` 三项依赖并拷贝到离线环境。 | ||
| 170 | + | ||
| 171 | +#### 1. 准备 cann-cmake | ||
| 172 | + | ||
| 173 | +`fetch_cann_cmake.cmake` 优先识别 `third_party/cann-cmake/` 目录,存在则直接使用(否则联网 git clone)。离线环境需手动克隆后整目录拷贝: | ||
| 174 | + | ||
| 175 | +```bash | ||
| 176 | +# 联网环境 | ||
| 177 | +git clone -b master-015 https://gitcode.com/cann/cmake.git cann-cmake | ||
| 178 | +# 将 cann-cmake/ 整目录拷贝到离线环境 ops-tensor/third_party/cann-cmake/ | ||
| 179 | +``` | ||
| 180 | + | ||
| 181 | +#### 2. 准备 gtest | ||
| 182 | + | ||
| 183 | +`gtest.cmake` 查找顺序:从 `third_party/gtest/googletest-1.14.0.tar.gz` 构建;若仅 `third_party/googletest-1.14.0.tar.gz` 存在则自动移入 `gtest/` 再构建;否则联网下载。离线环境放源码 tarball,首次执行 UT 时自动构建: | ||
| 184 | + | ||
| 185 | +```bash | ||
| 186 | +# 联网环境下载 | ||
| 187 | +wget -O googletest-1.14.0.tar.gz https://cann-3rd.obs.cn-north-4.myhuaweicloud.com/googletest/googletest-1.14.0.tar.gz | ||
| 188 | +# 拷贝到离线环境 ops-tensor/third_party/googletest-1.14.0.tar.gz | ||
| 189 | +# 首次执行 UT 时会自动移入 third_party/gtest/ 并完成编译 | ||
| 190 | +``` | ||
| 191 | + | ||
| 192 | +#### 3. 手动拉取 tensor_api | ||
| 193 | + | ||
| 194 | +`tensor_api` 是 `include/tensor_api` 下的 git 子模块,源仓库 `https://gitcode.com/cann/asc-devkit.git`,分支 `feature/tensor_api_from_9.0.0`。离线环境无法 `git submodule update`,需手动拉取: | ||
| 195 | + | ||
| 196 | +```bash | ||
| 197 | +# 联网环境克隆指定分支 | ||
| 198 | +git clone -b feature/tensor_api_from_9.0.0 https://gitcode.com/cann/asc-devkit.git tensor_api | ||
| 199 | +# 拷贝到离线环境 ops-tensor/include/tensor_api/(注意路径在 include/ 下,非 third_party/) | ||
| 200 | +``` | ||
| 201 | + | ||
| 202 | +或在联网环境通过子模块方式拉取后整目录拷贝: | ||
| 203 | + | ||
| 204 | +```bash | ||
| 205 | +cd ops-tensor | ||
| 206 | +git submodule update --init --recursive include/tensor_api | ||
| 207 | +# 将 include/tensor_api/ 整目录拷贝到离线环境对应位置 | ||
| 208 | +``` | ||
| 209 | + | ||
| 210 | +`build.sh`(`--opkernel -u`)执行前会检测 `include/tensor_api/` 是否已存在且非空,**已存在则自动跳过初始化**,手动拉取后即可直接编译。 | ||
| 211 | + | ||
| 212 | +#### 4. 离线编译执行 | ||
| 213 | + | ||
| 214 | +```bash | ||
| 215 | +source /usr/local/Ascend/cann/set_env.sh | ||
| 216 | + | ||
| 217 | +./build.sh --opkernel -u | ||
| 218 | +# 或指定算子 | ||
| 219 | +./build.sh --opkernel -u --ops=mat_mul | ||
| 220 | +``` | ||
| 221 | + | ||
| 222 | +> 若第三方依赖未放在默认的 `third_party/` 目录,可通过 `--cann_3rd_lib_path` 指定(`tensor_api` 仍须置于 `include/tensor_api/`): | ||
| 223 | +> | ||
| 224 | +> ```bash | ||
| 225 | +> ./build.sh --opkernel -u --cann_3rd_lib_path=/path/to/cann_3rd_lib_path | ||
| 226 | +> ``` | ||
| 227 | + | ||
| 228 | +成功标志同上文:出现 `[SUCCESS] Kernel UT all SoC tests passed`。 | ||
| 229 | + | ||
| 166 | 更详细的 Kernel UT 开发流程请参阅 [算子开发指南](./QUICK_OP_INVOCATION.md)。 | 230 | 更详细的 Kernel UT 开发流程请参阅 [算子开发指南](./QUICK_OP_INVOCATION.md)。 |
| 167 | 231 | ||
| 168 | ## Samples测试 | 232 | ## Samples测试 |
| @@ -209,8 +273,27 @@ mat_mul_streamk_fp32,100,8192,100,100,float32,false,false,false,"(ND,ND)" | |||
| 209 | [SUCCESS] All examples operations completed! | 273 | [SUCCESS] All examples operations completed! |
| 210 | ``` | 274 | ``` |
| 211 | 275 | ||
| 212 | -更详细的 Samples 使用说明请参阅 [Examples 文档](./examples/README.md)。 | 276 | +### 5. 未联网编译 |
| 213 | 277 | ||
| 278 | +未联网环境下编译执行 Samples,仅需手动拉取 `tensor_api` 子模块。 | ||
| 279 | + | ||
| 280 | +#### 1. 手动拉取 tensor_api | ||
| 281 | + | ||
| 282 | +`tensor_api` 的手动拉取步骤与 Kernel UT 一致,详见 [Kernel UT 未联网编译 · 手动拉取 tensor_api](#3-手动拉取-tensor_api)。 | ||
| 283 | + | ||
| 284 | +#### 2. 离线编译执行 | ||
| 285 | + | ||
| 286 | +```bash | ||
| 287 | +source /usr/local/Ascend/cann/set_env.sh | ||
| 288 | + | ||
| 289 | +./build.sh --examples | ||
| 290 | +# 或指定算子/样例 | ||
| 291 | +./build.sh --examples --ops=mat_mul --target=mat_mul_streamk | ||
| 292 | +``` | ||
| 293 | + | ||
| 294 | +成功标志同上文:出现 `[SUCCESS] All examples operations completed!`。 | ||
| 295 | + | ||
| 296 | +更详细的 Samples 使用说明请参阅 [Examples 文档](./examples/README.md)。 | ||
| 214 | 297 | ||
| 215 | ## 相关文档 | 298 | ## 相关文档 |
| 216 | 299 | ||
| @@ -81,6 +81,7 @@ __global__ __aicore__ void my_operator_kernel_entry( | |||
| 81 | ``` | 81 | ``` |
| 82 | 82 | ||
| 83 | **关键点**: | 83 | **关键点**: |
| 84 | + | ||
| 84 | - 使用 `namespace` 避免符号冲突 | 85 | - 使用 `namespace` 避免符号冲突 |
| 85 | - 移除 `#pragma once`(测试文件直接 include) | 86 | - 移除 `#pragma once`(测试文件直接 include) |
| 86 | - 统一入口通过 `OP_TYPE` 参数区分不同实现 | 87 | - 统一入口通过 `OP_TYPE` 参数区分不同实现 |
| @@ -109,11 +110,11 @@ __aicore__ inline void MyOperatorBasicWrapper( | |||
| 109 | // 调用 Blaze Kernel | 110 | // 调用 Blaze Kernel |
| 110 | using ProblemShape = AscendC::Te::Shape<int64_t, int64_t, int64_t, int64_t>; | 111 | using ProblemShape = AscendC::Te::Shape<int64_t, int64_t, int64_t, int64_t>; |
| 111 | using LayoutX = AscendC::Te::NDExtLayoutPtn; | 112 | using LayoutX = AscendC::Te::NDExtLayoutPtn; |
| 112 | - | 113 | + |
| 113 | auto gmX = AscendC::Te::MakeTensor( | 114 | auto gmX = AscendC::Te::MakeTensor( |
| 114 | AscendC::Te::MakeMemPtr<AscendC::Te::Location::GM>(xGM), | 115 | AscendC::Te::MakeMemPtr<AscendC::Te::Location::GM>(xGM), |
| 115 | LayoutX{}(tiling.m, tiling.k)); | 116 | LayoutX{}(tiling.m, tiling.k)); |
| 116 | - | 117 | + |
| 117 | // ... 调用 Kernel | 118 | // ... 调用 Kernel |
| 118 | } | 119 | } |
| 119 | 120 | ||
| @@ -137,7 +138,7 @@ protected: | |||
| 137 | GM_ADDR xGM = nullptr; | 138 | GM_ADDR xGM = nullptr; |
| 138 | GM_ADDR yGM = nullptr; | 139 | GM_ADDR yGM = nullptr; |
| 139 | GM_ADDR tilingGM = nullptr; | 140 | GM_ADDR tilingGM = nullptr; |
| 140 | - | 141 | + |
| 141 | void TearDown() override { | 142 | void TearDown() override { |
| 142 | if (xGM) AscendC::GmFree((void*)xGM); | 143 | if (xGM) AscendC::GmFree((void*)xGM); |
| 143 | if (yGM) AscendC::GmFree((void*)yGM); | 144 | if (yGM) AscendC::GmFree((void*)yGM); |
| @@ -149,17 +150,17 @@ TEST_F(MyOperatorTest, TestBasicFP16) { | |||
| 149 | const int64_t M = 16; | 150 | const int64_t M = 16; |
| 150 | const int64_t N = 16; | 151 | const int64_t N = 16; |
| 151 | const uint32_t blockNum = 1; | 152 | const uint32_t blockNum = 1; |
| 152 | - | 153 | + |
| 153 | xGM = (GM_ADDR)AscendC::GmAlloc(M * N * sizeof(half)); | 154 | xGM = (GM_ADDR)AscendC::GmAlloc(M * N * sizeof(half)); |
| 154 | yGM = (GM_ADDR)AscendC::GmAlloc(M * N * sizeof(half)); | 155 | yGM = (GM_ADDR)AscendC::GmAlloc(M * N * sizeof(half)); |
| 155 | tilingGM = (GM_ADDR)AscendC::GmAlloc(sizeof(MyOpUT::MyOperatorTilingData)); | 156 | tilingGM = (GM_ADDR)AscendC::GmAlloc(sizeof(MyOpUT::MyOperatorTilingData)); |
| 156 | - | 157 | + |
| 157 | auto* tiling = reinterpret_cast<MyOpUT::MyOperatorTilingData*>(tilingGM); | 158 | auto* tiling = reinterpret_cast<MyOpUT::MyOperatorTilingData*>(tilingGM); |
| 158 | tiling->m = M; | 159 | tiling->m = M; |
| 159 | tiling->n = N; | 160 | tiling->n = N; |
| 160 | - | 161 | + |
| 161 | AscendC::SetKernelMode(KernelMode::MIX_MODE); | 162 | AscendC::SetKernelMode(KernelMode::MIX_MODE); |
| 162 | - | 163 | + |
| 163 | auto kernelFunc = my_operator_kernel_entry<OP_TYPE_BASIC, half, half>; | 164 | auto kernelFunc = my_operator_kernel_entry<OP_TYPE_BASIC, half, half>; |
| 164 | ASSERT_TRUE(KERNEL_RUN_KF(kernelFunc, blockNum, xGM, yGM, tilingGM)) | 165 | ASSERT_TRUE(KERNEL_RUN_KF(kernelFunc, blockNum, xGM, yGM, tilingGM)) |
| 165 | << "Kernel execution failed"; | 166 | << "Kernel execution failed"; |
| @@ -205,11 +206,13 @@ AddOpTestCase(my_operator "ascend950pr_9599" "") | |||
| 205 | ### 4. 查看测试结果 | 206 | ### 4. 查看测试结果 |
| 206 | 207 | ||
| 207 | 成功输出: | 208 | 成功输出: |
| 209 | + | ||
| 208 | ``` | 210 | ``` |
| 209 | [SUCCESS] Kernel UT all SoC tests passed | 211 | [SUCCESS] Kernel UT all SoC tests passed |
| 210 | ``` | 212 | ``` |
| 211 | 213 | ||
| 212 | 失败输出: | 214 | 失败输出: |
| 215 | + | ||
| 213 | ``` | 216 | ``` |
| 214 | [ERROR] mat_mul failed (exit code: 1) | 217 | [ERROR] mat_mul failed (exit code: 1) |
| 215 | ``` | 218 | ``` |
| @@ -274,6 +277,7 @@ AscendC::SetKernelMode(KernelMode::MIX_MODE); | |||
| 274 | ### 4. 查看临时文件 | 277 | ### 4. 查看临时文件 |
| 275 | 278 | ||
| 276 | 测试数据通常位于: | 279 | 测试数据通常位于: |
| 280 | + | ||
| 277 | ``` | 281 | ``` |
| 278 | tests/ut/op_kernel/mat_mul/matmul_data/ | 282 | tests/ut/op_kernel/mat_mul/matmul_data/ |
| 279 | ├── input_a.bin | 283 | ├── input_a.bin |
| @@ -288,6 +292,7 @@ tests/ut/op_kernel/mat_mul/matmul_data/ | |||
| 288 | **原因**:多个测试文件 include 同一个入口文件,`enum` 定义冲突。 | 292 | **原因**:多个测试文件 include 同一个入口文件,`enum` 定义冲突。 |
| 289 | 293 | ||
| 290 | **解决**:使用 namespace 包裹 enum 定义: | 294 | **解决**:使用 namespace 包裹 enum 定义: |
| 295 | + | ||
| 291 | ```cpp | 296 | ```cpp |
| 292 | namespace MyOpUT { | 297 | namespace MyOpUT { |
| 293 | enum OpType : int { ... }; | 298 | enum OpType : int { ... }; |
| @@ -303,6 +308,7 @@ enum OpType : int { ... }; | |||
| 303 | ### Q3: 测试超时 | 308 | ### Q3: 测试超时 |
| 304 | 309 | ||
| 305 | **解决**:增加超时时间: | 310 | **解决**:增加超时时间: |
| 311 | + | ||
| 306 | ```bash | 312 | ```bash |
| 307 | ./build.sh --opkernel -u --test-timeout=600 | 313 | ./build.sh --opkernel -u --test-timeout=600 |
| 308 | ``` | 314 | ``` |
| @@ -310,6 +316,7 @@ enum OpType : int { ... }; | |||
| 310 | ### Q4: 子进程失败无法捕获 | 316 | ### Q4: 子进程失败无法捕获 |
| 311 | 317 | ||
| 312 | **解决**:使用 `KERNEL_RUN_KF` 替代 `ICPU_RUN_KF`: | 318 | **解决**:使用 `KERNEL_RUN_KF` 替代 `ICPU_RUN_KF`: |
| 319 | + | ||
| 313 | ```cpp | 320 | ```cpp |
| 314 | ASSERT_TRUE(KERNEL_RUN_KF(kernelFunc, blockNum, args...)); | 321 | ASSERT_TRUE(KERNEL_RUN_KF(kernelFunc, blockNum, args...)); |
| 315 | ``` | 322 | ``` |
| @@ -321,6 +328,7 @@ ASSERT_TRUE(KERNEL_RUN_KF(kernelFunc, blockNum, args...)); | |||
| 321 | 路径:`tests/ut/op_kernel/mat_mul/` | 328 | 路径:`tests/ut/op_kernel/mat_mul/` |
| 322 | 329 | ||
| 323 | 支持的测试类型: | 330 | 支持的测试类型: |
| 331 | + | ||
| 324 | - FP16 Basic MatMul | 332 | - FP16 Basic MatMul |
| 325 | - FP16 StreamK MatMul | 333 | - FP16 StreamK MatMul |
| 326 | - FP32 MatMul | 334 | - FP32 MatMul |
| @@ -330,6 +338,7 @@ ASSERT_TRUE(KERNEL_RUN_KF(kernelFunc, blockNum, args...)); | |||
| 330 | 路径:`tests/ut/op_kernel/quant_batch_matmul/` | 338 | 路径:`tests/ut/op_kernel/quant_batch_matmul/` |
| 331 | 339 | ||
| 332 | 支持的测试类型: | 340 | 支持的测试类型: |
| 341 | + | ||
| 333 | - INT8 A8W8 Cube | 342 | - INT8 A8W8 Cube |
| 334 | - MXFP8 StreamK | 343 | - MXFP8 StreamK |
| 335 | - MXFP4 L0C Pingpong | 344 | - MXFP4 L0C Pingpong |
| @@ -339,4 +348,4 @@ ASSERT_TRUE(KERNEL_RUN_KF(kernelFunc, blockNum, args...)); | |||
| 339 | - **完整构建文档**: [README.md](README.md) | 348 | - **完整构建文档**: [README.md](README.md) |
| 340 | - **环境安装指南**: [QUICKSTART.md](QUICKSTART.md) | 349 | - **环境安装指南**: [QUICKSTART.md](QUICKSTART.md) |
| 341 | - **API 文档**: [docs/API/](docs/API/) | 350 | - **API 文档**: [docs/API/](docs/API/) |
| 342 | -- **Blaze 模块**: [include/blaze/README.md](include/blaze/README.md) | 351 | +- **Blaze 模块**: [include/blaze/README.md](include/blaze/README.md) |
| @@ -105,4 +105,4 @@ add_subdirectory(quant_batch_matmul) | |||
| 105 | add_subdirectory(weight_quant_batch_matmul_mx) | 105 | add_subdirectory(weight_quant_batch_matmul_mx) |
| 106 | add_subdirectory(grouped_matmul) | 106 | add_subdirectory(grouped_matmul) |
| 107 | add_subdirectory(quant_matmul_activation_quant) | 107 | add_subdirectory(quant_matmul_activation_quant) |
| 108 | -add_subdirectory(transpose_quant_batch_matmul_mx) | 108 | +add_subdirectory(transpose_quant_batch_matmul) |
| @@ -17,33 +17,33 @@ examples 的完整编译与运行涉及三类依赖:**系统工具链**、**CA | |||
| 17 | 17 | ||
| 18 | ### 2.1 系统工具链 | 18 | ### 2.1 系统工具链 |
| 19 | 19 | ||
| 20 | -| 依赖 | 最低版本 | 用途 | 检查方式 | | 20 | +| 依赖 | 最低版本 | 用途 | 检查方式 | |
| 21 | -|------|---------|------|---------| | 21 | +| ------- | ----------------- | ----------------------------------------------------------------------------------- | --------------------- | |
| 22 | -| cmake | 3.16 | 构建系统(`examples/CMakeLists.txt` 中 `cmake_minimum_required(VERSION 3.16)`) | `cmake --version` | | 22 | +| cmake | 3.16 | 构建系统(`examples/CMakeLists.txt` 中 `cmake_minimum_required(VERSION 3.16)`) | `cmake --version` | |
| 23 | -| g++ | 默认标准 ≥ C++14 | Host 侧 C++ 编译器(`project(... LANGUAGES CXX)`)| `g++ --version` | | 23 | +| g++ | 默认标准 ≥ C++14 | Host 侧 C++ 编译器(`project(... LANGUAGES CXX)`) | `g++ --version` | |
| 24 | -| bisheng | — | ASC 语言编译器,编译 device 侧 kernel(`find_package(ASC REQUIRED)`) | `bisheng --version` | | 24 | +| bisheng | — | ASC 语言编译器,编译 device 侧 kernel(`find_package(ASC REQUIRED)`) | `bisheng --version` | |
| 25 | -| make | — | 由 cmake 调用的底层构建工具 | `make --version` | | 25 | +| make | — | 由 cmake 调用的底层构建工具 | `make --version` | |
| 26 | -| python3 | 3.7+ | 驱动 CSV 解析、数据生成、精度验证脚本 | `python3 --version` | | 26 | +| python3 | 3.7+ | 驱动 CSV 解析、数据生成、精度验证脚本 | `python3 --version` | |
| 27 | 27 | ||
| 28 | > `bisheng` 编译器随 CANN Toolkit 安装,`source set_env.sh` 后自动加入 PATH。 | 28 | > `bisheng` 编译器随 CANN Toolkit 安装,`source set_env.sh` 后自动加入 PATH。 |
| 29 | 29 | ||
| 30 | ### 2.2 CANN / 昇腾环境 | 30 | ### 2.2 CANN / 昇腾环境 |
| 31 | 31 | ||
| 32 | -| 依赖 | 要求 | 说明 | | 32 | +| 依赖 | 要求 | 说明 | |
| 33 | -|------|------|------| | 33 | +| ------------ | --------- | --------------------------------------- | |
| 34 | -| CANN Toolkit | ≥ 9.1.0 | 提供 ACL 运行时、bisheng 编译器、头文件 | | 34 | +| CANN Toolkit | ≥ 9.1.0 | 提供 ACL 运行时、bisheng 编译器、头文件 | |
| 35 | -| NPU 硬件 | Ascend950 | 当前 examples 仅支持 Ascend950 芯片 | | 35 | +| NPU 硬件 | Ascend950 | 当前 examples 仅支持 Ascend950 芯片 | |
| 36 | 36 | ||
| 37 | ### 2.3 Python 依赖 | 37 | ### 2.3 Python 依赖 |
| 38 | 38 | ||
| 39 | 数据生成和精度验证脚本依赖以下 Python 包: | 39 | 数据生成和精度验证脚本依赖以下 Python 包: |
| 40 | 40 | ||
| 41 | -| 包 | 用途 | 安装命令 | | 41 | +| 包 | 用途 | 安装命令 | |
| 42 | -|----|------|---------| | 42 | +| --------- | ------------------------------------------------------------------- | ------------------------- | |
| 43 | -| numpy | 二进制数据读写、数组操作 | `pip install numpy` | | 43 | +| numpy | 二进制数据读写、数组操作 | `pip install numpy` | |
| 44 | -| ml_dtypes | `float8_e4m3fn` golden 计算 | `pip install ml_dtypes` | | 44 | +| ml_dtypes | `float8_e4m3fn` golden 计算 | `pip install ml_dtypes` | |
| 45 | -| en_dtypes | `hifloat8` golden 计算(quant_batch_matmul_cube 样例) | `pip install en-dtypes` | | 45 | +| en_dtypes | `hifloat8` golden 计算(quant_batch_matmul_cube 样例) | `pip install en-dtypes` | |
| 46 | -| torch | CPU golden 参考计算(`torch.matmul`/`torch.addmm`)、dtype 映射 | `pip install torch` | | 46 | +| torch | CPU golden 参考计算(`torch.matmul`/`torch.addmm`)、dtype 映射 | `pip install torch` | |
| 47 | 47 | ||
| 48 | ### 2.4 依赖检查清单 | 48 | ### 2.4 依赖检查清单 |
| 49 | 49 | ||
| @@ -97,21 +97,21 @@ examples/ | |||
| 97 | 97 | ||
| 98 | **层级关系**: | 98 | **层级关系**: |
| 99 | 99 | ||
| 100 | -| 层级 | 目录 | CMakeLists.txt 职责 | | 100 | +| 层级 | 目录 | CMakeLists.txt 职责 | |
| 101 | -|------|------|---------------------| | 101 | +| ---- | ------------------ | ---------------------------------------------------------------------------------------------------- | |
| 102 | -| L1 | `examples/` | 编译器发现、链接库配置、`ops_example_add_executable` 宏定义、`add_subdirectory({op})` 加载各算子 | | 102 | +| L1 | `examples/` | 编译器发现、链接库配置、`ops_example_add_executable` 宏定义、`add_subdirectory({op})` 加载各算子 | |
| 103 | -| L2 | `examples/{op}/` | 通过 `ops_example_add_executable(name subdir/source.cpp)` 直接注册本算子下所有样例可执行文件 | | 103 | +| L2 | `examples/{op}/` | 通过`ops_example_add_executable(name subdir/source.cpp)` 直接注册本算子下所有样例可执行文件 | |
| 104 | 104 | ||
| 105 | **当前算子目录**: | 105 | **当前算子目录**: |
| 106 | 106 | ||
| 107 | -| 算子目录 | 样例 | 说明 | | 107 | +| 算子目录 | 样例 | 说明 | |
| 108 | -|----------|------|------| | 108 | +| --------------------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------- | |
| 109 | -| `mat_mul/` | mat_mul_basic, mat_mul_streamk, mat_mul_a_fullload, mat_mul_b_fullload, mat_mul_fixpipe_opti | 矩阵乘法样例 | | 109 | +| `mat_mul/` | mat_mul_basic, mat_mul_streamk, mat_mul_a_fullload, mat_mul_b_fullload, mat_mul_fixpipe_opti | 矩阵乘法样例 | |
| 110 | -| `batch_mat_mul/` | mat_mul_bmm_broadcast, mat_mul_iterbatch_broadcast | 批量矩阵乘法样例(bmm/iterbatch 广播) | | 110 | +| `batch_mat_mul/` | mat_mul_bmm_broadcast, mat_mul_iterbatch_broadcast | 批量矩阵乘法样例(bmm/iterbatch 广播) | |
| 111 | -| `transpose_batch_mat_mul/` | transpose_batch_mat_mul_basic | 转置批量矩阵乘法样例 | | 111 | +| `transpose_batch_mat_mul/` | transpose_batch_mat_mul_basic | 转置批量矩阵乘法样例 | |
| 112 | -| `quant_batch_matmul/` | quant_batch_matmul_cube, quant_batch_matmul_mx | 量化批量矩阵乘法样例(cube/mx 两种算法) | | 112 | +| `quant_batch_matmul/` | quant_batch_matmul_cube, quant_batch_matmul_mx | 量化批量矩阵乘法样例(cube/mx 两种算法) | |
| 113 | -| `weight_quant_batch_matmul_mx/` | weight_quant_batch_matmul_mx_swat | 权重量化批量矩阵乘法样例 | | 113 | +| `weight_quant_batch_matmul_mx/` | weight_quant_batch_matmul_mx_swat | 权重量化批量矩阵乘法样例 | |
| 114 | -| `grouped_matmul/` | quant_grouped_matmul_mx | Grouped MatMul 样例 | | 114 | +| `grouped_matmul/` | quant_grouped_matmul_mx | Grouped MatMul 样例 | |
| 115 | 115 | ||
| 116 | ## 4. 执行方法 | 116 | ## 4. 执行方法 |
| 117 | 117 | ||
| @@ -146,24 +146,24 @@ bash examples/common/run.sh --ops=<names> [--target=<names>] [--case=<path>] [-- | |||
| 146 | 146 | ||
| 147 | **参数说明**: | 147 | **参数说明**: |
| 148 | 148 | ||
| 149 | -| 参数 | 说明 | | 149 | +| 参数 | 说明 | |
| 150 | -|------|------| | 150 | +| -------------------- | ----------------------------------------------------------------------------------------------------------------- | |
| 151 | -| `--ops=<names>` | 算子目录名,支持逗号分隔多个(如 `mat_mul` 或 `mat_mul,grouped_matmul`) | | 151 | +| `--ops=<names>` | 算子目录名,支持逗号分隔多个(如`mat_mul` 或 `mat_mul,grouped_matmul`) | |
| 152 | -| `--target=<names>` | 样例名,支持逗号分隔多个(如 `mat_mul_basic` 或 `mat_mul_basic,mat_mul_streamk`)。多值时 `--ops` 必须为单个 | | 152 | +| `--target=<names>` | 样例名,支持逗号分隔多个(如`mat_mul_basic` 或 `mat_mul_basic,mat_mul_streamk`)。多值时 `--ops` 必须为单个 | |
| 153 | -| `--case=<path>` | CSV 测试用例文件路径。仅支持 `--ops` 和 `--target` 均为单个值时使用 | | 153 | +| `--case=<path>` | CSV 测试用例文件路径。仅支持`--ops` 和 `--target` 均为单个值时使用 | |
| 154 | -| `--ti=<N>` | 仅运行第 N 条用例(0-based 索引)。仅支持 `--ops` 和 `--target` 均为单个值时使用 | | 154 | +| `--ti=<N>` | 仅运行第 N 条用例(0-based 索引)。仅支持`--ops` 和 `--target` 均为单个值时使用 | |
| 155 | -| `--ti=<N-M>` | 运行第 N 到第 M 条用例(含两端)。仅支持 `--ops` 和 `--target` 均为单个值时使用 | | 155 | +| `--ti=<N-M>` | 运行第 N 到第 M 条用例(含两端)。仅支持`--ops` 和 `--target` 均为单个值时使用 | |
| 156 | -| `--skip-build` | 跳过 CMake 编译阶段 | | 156 | +| `--skip-build` | 跳过 CMake 编译阶段 | |
| 157 | -| `--build-only` | 仅编译,不运行和验证 | | 157 | +| `--build-only` | 仅编译,不运行和验证 | |
| 158 | 158 | ||
| 159 | **多值约束**: | 159 | **多值约束**: |
| 160 | 160 | ||
| 161 | -| 场景 | --ops | --target | --case | --ti | | 161 | +| 场景 | --ops | --target | --case | --ti | |
| 162 | -|------|-------|----------|--------|------| | 162 | +| ------------ | ----- | -------- | ------ | ---- | |
| 163 | -| 单算子单样例 | 单个 | 单个 | 允许 | 允许 | | 163 | +| 单算子单样例 | 单个 | 单个 | 允许 | 允许 | |
| 164 | -| 单算子多样例 | 单个 | 多个 | 禁止 | 禁止 | | 164 | +| 单算子多样例 | 单个 | 多个 | 禁止 | 禁止 | |
| 165 | -| 多算子 | 多个 | 禁止 | 禁止 | 禁止 | | 165 | +| 多算子 | 多个 | 禁止 | 禁止 | 禁止 | |
| 166 | -| 全部样例 | 不传 | 不传 | 禁止 | 禁止 | | 166 | +| 全部样例 | 不传 | 不传 | 禁止 | 禁止 | |
| 167 | 167 | ||
| 168 | **用法示例**: | 168 | **用法示例**: |
| 169 | 169 | ||
| @@ -249,12 +249,12 @@ params=... | |||
| 249 | bool_flags=... # 可选 | 249 | bool_flags=... # 可选 |
| 250 | ``` | 250 | ``` |
| 251 | 251 | ||
| 252 | -| Section | 用途 | | 252 | +| Section | 用途 | |
| 253 | -|---------|------| | 253 | +| -------------- | -------------------------------------------------------------------------------------- | |
| 254 | -| `[scripts]` | 指定 gen_data 和 verify 脚本文件名(可选,默认 `gen_data.py` / `verify_result.py`) | | 254 | +| `[scripts]` | 指定 gen_data 和 verify 脚本文件名(可选,默认`gen_data.py` / `verify_result.py`) | |
| 255 | -| `[gen_data]` | 传递给数据生成脚本的参数 | | 255 | +| `[gen_data]` | 传递给数据生成脚本的参数 | |
| 256 | -| `[kernel]` | 传递给 kernel 执行的参数 | | 256 | +| `[kernel]` | 传递给 kernel 执行的参数 | |
| 257 | -| `[verify]` | 传递给精度验证脚本的参数 | | 257 | +| `[verify]` | 传递给精度验证脚本的参数 | |
| 258 | 258 | ||
| 259 | ### 4.5 两种执行方式的关联 | 259 | ### 4.5 两种执行方式的关联 |
| 260 | 260 | ||
| @@ -7,6 +7,11 @@ | |||
| 7 | 7 | ||
| 8 | import os | 8 | import os |
| 9 | import sys | 9 | import sys |
| 10 | + | ||
| 11 | +sys.path.insert( | ||
| 12 | + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "common") | ||
| 13 | +) | ||
| 14 | +from metrics import write_metrics_json | ||
| 10 | import argparse | 15 | import argparse |
| 11 | 16 | ||
| 12 | os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0" | 17 | os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0" |
| @@ -80,6 +85,22 @@ def verify_batch_result(m, n, batch, dtype_str, is_hf32=False): | |||
| 80 | f"ratio error count: {error_count}/{total_elements}, error ratio: {error_ratio:.6f}" | 85 | f"ratio error count: {error_count}/{total_elements}, error ratio: {error_ratio:.6f}" |
| 81 | ) | 86 | ) |
| 82 | 87 | ||
| 88 | + _status = "pass" if error_ratio <= ratio_tol else "fail" | ||
| 89 | + write_metrics_json( | ||
| 90 | + [ | ||
| 91 | + { | ||
| 92 | + "name": "output", | ||
| 93 | + "max_abs_diff": float(abs_diff.max().item()) if total_elements else 0.0, | ||
| 94 | + "error_ratio": float(error_ratio), | ||
| 95 | + "ratio_tol": float(ratio_tol), | ||
| 96 | + "elements": int(total_elements), | ||
| 97 | + "status": _status, | ||
| 98 | + } | ||
| 99 | + ], | ||
| 100 | + _status, | ||
| 101 | + "./output", | ||
| 102 | + ) | ||
| 103 | + | ||
| 83 | return error_ratio <= ratio_tol | 104 | return error_ratio <= ratio_tol |
| 84 | 105 | ||
| 85 | 106 | ||
| @@ -0,0 +1,117 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# -*- coding: utf-8 -*- | ||
| 3 | +# ---------------------------------------------------------------------------- | ||
| 4 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 5 | +# ---------------------------------------------------------------------------- | ||
| 6 | + | ||
| 7 | +"""Shared metrics utilities for ops-tensor examples. | ||
| 8 | + | ||
| 9 | +Provides: | ||
| 10 | +- write_metrics_json: write verify_metrics.json (called by verify_result.py) | ||
| 11 | +- parse_stdout_metrics: fallback parse of verify stdout (called by run_case.py | ||
| 12 | + when verify_metrics.json is absent, e.g. new verify without JSON output) | ||
| 13 | +""" | ||
| 14 | + | ||
| 15 | +import json | ||
| 16 | +import os | ||
| 17 | +import re | ||
| 18 | + | ||
| 19 | +METRICS_FILENAME = "verify_metrics.json" | ||
| 20 | + | ||
| 21 | +_MAX_ABS_DIFF_PATTERNS = [ | ||
| 22 | + re.compile(r"max abs diff:\s*([0-9.eE+-]+)"), | ||
| 23 | + re.compile(r"max_abs_error=([0-9.eE+-]+)"), | ||
| 24 | +] | ||
| 25 | + | ||
| 26 | +_ERROR_RATIO_PATTERNS = [ | ||
| 27 | + re.compile(r"error ratio:\s*([0-9.eE+-]+)"), | ||
| 28 | + re.compile(r"ratio=([0-9.eE+-]+)"), | ||
| 29 | +] | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def write_metrics_json(outputs, overall_status, output_dir="./output"): | ||
| 33 | + metrics = {"outputs": outputs, "overall_status": overall_status} | ||
| 34 | + path = os.path.join(output_dir, METRICS_FILENAME) | ||
| 35 | + with open(path, "w") as f: | ||
| 36 | + json.dump(metrics, f, indent=2) | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def _try_match_float(content, patterns): | ||
| 40 | + for pat in patterns: | ||
| 41 | + m = pat.search(content) | ||
| 42 | + if m: | ||
| 43 | + try: | ||
| 44 | + return float(m.group(1)) | ||
| 45 | + except ValueError: | ||
| 46 | + pass | ||
| 47 | + return None | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def _parse_ratio_tol(content): | ||
| 51 | + found = None | ||
| 52 | + for line in content.splitlines(): | ||
| 53 | + if "count" in line.lower(): | ||
| 54 | + m = re.search(r">\s*([0-9]+\.?[0-9eE+-]*)", line) | ||
| 55 | + if m: | ||
| 56 | + try: | ||
| 57 | + found = float(m.group(1)) | ||
| 58 | + except ValueError: | ||
| 59 | + pass | ||
| 60 | + return found | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +def _parse_output_block(name, content, status): | ||
| 64 | + max_abs_diff = _try_match_float(content, _MAX_ABS_DIFF_PATTERNS) | ||
| 65 | + error_ratio = _try_match_float(content, _ERROR_RATIO_PATTERNS) | ||
| 66 | + if max_abs_diff is None and error_ratio is None: | ||
| 67 | + return None | ||
| 68 | + ratio_tol = _parse_ratio_tol(content) | ||
| 69 | + return { | ||
| 70 | + "name": name, | ||
| 71 | + "max_abs_diff": max_abs_diff if max_abs_diff is not None else 0.0, | ||
| 72 | + "error_ratio": error_ratio if error_ratio is not None else 0.0, | ||
| 73 | + "ratio_tol": ratio_tol, | ||
| 74 | + "status": status, | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def parse_stdout_metrics(stdout, rc): | ||
| 79 | + """Fallback: parse verify stdout when verify_metrics.json is absent. | ||
| 80 | + | ||
| 81 | + Returns {"outputs": [...], "overall_status": ...} or None. | ||
| 82 | + Handles single-output, multi-output ([verify] name: blocks), and | ||
| 83 | + grouped ([INFO] group N: blocks) verify scripts. | ||
| 84 | + """ | ||
| 85 | + if not stdout: | ||
| 86 | + return None | ||
| 87 | + status = "pass" if rc == 0 else "fail" | ||
| 88 | + outputs = [] | ||
| 89 | + | ||
| 90 | + verify_blocks = re.split(r"\[verify\]\s*(\S+?):", stdout) | ||
| 91 | + if len(verify_blocks) > 1: | ||
| 92 | + for i in range(1, len(verify_blocks), 2): | ||
| 93 | + name = verify_blocks[i] | ||
| 94 | + content = verify_blocks[i + 1] if i + 1 < len(verify_blocks) else "" | ||
| 95 | + out = _parse_output_block(name, content, status) | ||
| 96 | + if out: | ||
| 97 | + outputs.append(out) | ||
| 98 | + | ||
| 99 | + if not outputs: | ||
| 100 | + group_blocks = re.split(r"\[INFO\]\s*group\s+(\d+):", stdout) | ||
| 101 | + if len(group_blocks) > 1: | ||
| 102 | + for i in range(1, len(group_blocks), 2): | ||
| 103 | + name = f"group_{group_blocks[i]}" | ||
| 104 | + content = group_blocks[i + 1] if i + 1 < len(group_blocks) else "" | ||
| 105 | + out = _parse_output_block(name, content, status) | ||
| 106 | + if out: | ||
| 107 | + outputs.append(out) | ||
| 108 | + | ||
| 109 | + if not outputs: | ||
| 110 | + out = _parse_output_block("output", stdout, status) | ||
| 111 | + if out: | ||
| 112 | + outputs.append(out) | ||
| 113 | + | ||
| 114 | + if not outputs: | ||
| 115 | + return None | ||
| 116 | + overall = "pass" if status == "pass" else "fail" | ||
| 117 | + return {"outputs": outputs, "overall_status": overall} | ||
| @@ -41,11 +41,15 @@ Usage: | |||
| 41 | import argparse | 41 | import argparse |
| 42 | import configparser | 42 | import configparser |
| 43 | import csv | 43 | import csv |
| 44 | +import json | ||
| 44 | import os | 45 | import os |
| 45 | import subprocess | 46 | import subprocess |
| 46 | import sys | 47 | import sys |
| 47 | import time | 48 | import time |
| 48 | 49 | ||
| 50 | +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | ||
| 51 | +from metrics import METRICS_FILENAME, parse_stdout_metrics | ||
| 52 | + | ||
| 49 | 53 | ||
| 50 | # --------------------------------------------------------------------------- | 54 | # --------------------------------------------------------------------------- |
| 51 | # .conf parsing | 55 | # .conf parsing |
| @@ -264,6 +268,48 @@ def parse_ti(ti_value): | |||
| 264 | sys.exit(1) | 268 | sys.exit(1) |
| 265 | 269 | ||
| 266 | 270 | ||
| 271 | +# --------------------------------------------------------------------------- | ||
| 272 | +# Metrics extraction from verify_metrics.json | ||
| 273 | +# --------------------------------------------------------------------------- | ||
| 274 | + | ||
| 275 | + | ||
| 276 | +def _load_metrics(output_dir, verify_stdout, rc): | ||
| 277 | + metrics_path = os.path.join(output_dir, METRICS_FILENAME) | ||
| 278 | + if os.path.isfile(metrics_path): | ||
| 279 | + try: | ||
| 280 | + with open(metrics_path, "r", encoding="utf-8") as f: | ||
| 281 | + return json.load(f) | ||
| 282 | + except (json.JSONDecodeError, OSError) as exc: | ||
| 283 | + print(f" [WARN] failed to parse {metrics_path}: {exc}", file=sys.stderr) | ||
| 284 | + return parse_stdout_metrics(verify_stdout, rc) | ||
| 285 | + | ||
| 286 | + | ||
| 287 | +def _extract_accuracy(metrics): | ||
| 288 | + if not metrics or not metrics.get("outputs"): | ||
| 289 | + return "" | ||
| 290 | + worst_err = max(o.get("error_ratio", 0.0) for o in metrics["outputs"]) | ||
| 291 | + return f"{(1.0 - worst_err) * 100:.2f}%" | ||
| 292 | + | ||
| 293 | + | ||
| 294 | +def _format_metrics_json(metrics): | ||
| 295 | + """Convert error_ratio→accuracy, ratio_tol→tol accuracy (both percentage).""" | ||
| 296 | + if not metrics: | ||
| 297 | + return "" | ||
| 298 | + result = {"outputs": [], "overall_status": metrics.get("overall_status", "fail")} | ||
| 299 | + for o in metrics.get("outputs", []): | ||
| 300 | + entry = {"name": o.get("name", "output"), "status": o.get("status", "fail")} | ||
| 301 | + if o.get("max_abs_diff") is not None: | ||
| 302 | + entry["max_abs_diff"] = o["max_abs_diff"] | ||
| 303 | + err = o.get("error_ratio") | ||
| 304 | + if err is not None: | ||
| 305 | + entry["accuracy"] = f"{(1.0 - err) * 100:.2f}%" | ||
| 306 | + tol = o.get("ratio_tol") | ||
| 307 | + if tol is not None: | ||
| 308 | + entry["ratio_tol"] = f"{(1.0 - tol) * 100:.2f}%" | ||
| 309 | + result["outputs"].append(entry) | ||
| 310 | + return json.dumps(result, ensure_ascii=False) | ||
| 311 | + | ||
| 312 | + | ||
| 267 | # --------------------------------------------------------------------------- | 313 | # --------------------------------------------------------------------------- |
| 268 | # Per-case execution | 314 | # Per-case execution |
| 269 | # --------------------------------------------------------------------------- | 315 | # --------------------------------------------------------------------------- |
| @@ -284,23 +330,26 @@ def run_single_case( | |||
| 284 | gen_cmd = [sys.executable, gen_data_py] + gen_args | 330 | gen_cmd = [sys.executable, gen_data_py] + gen_args |
| 285 | rc, out = run_subprocess(gen_cmd, cwd=scripts_dir) | 331 | rc, out = run_subprocess(gen_cmd, cwd=scripts_dir) |
| 286 | if rc != 0: | 332 | if rc != 0: |
| 287 | - return "FAIL", "gen_data", out | 333 | + return "FAIL", "gen_data", out, None |
| 288 | 334 | ||
| 289 | # -- Stage 2: kernel binary ---------------------------------------------- | 335 | # -- Stage 2: kernel binary ---------------------------------------------- |
| 290 | kernel_args = build_args(kernel_params + kernel_bools, row, runtime_vars) | 336 | kernel_args = build_args(kernel_params + kernel_bools, row, runtime_vars) |
| 291 | kernel_cmd = [executable] + kernel_args | 337 | kernel_cmd = [executable] + kernel_args |
| 292 | rc, out = run_subprocess(kernel_cmd, cwd=scripts_dir, settle=1) | 338 | rc, out = run_subprocess(kernel_cmd, cwd=scripts_dir, settle=1) |
| 293 | if rc != 0: | 339 | if rc != 0: |
| 294 | - return "FAIL", "kernel", out | 340 | + return "FAIL", "kernel", out, None |
| 295 | 341 | ||
| 296 | # -- Stage 3: verify ----------------------------------------------------- | 342 | # -- Stage 3: verify ----------------------------------------------------- |
| 297 | verify_args = build_args(verify_params + verify_bools, row, runtime_vars) | 343 | verify_args = build_args(verify_params + verify_bools, row, runtime_vars) |
| 298 | verify_cmd = [sys.executable, verify_py] + verify_args | 344 | verify_cmd = [sys.executable, verify_py] + verify_args |
| 299 | rc, out = run_subprocess(verify_cmd, cwd=scripts_dir) | 345 | rc, out = run_subprocess(verify_cmd, cwd=scripts_dir) |
| 300 | - if rc != 0: | ||
| 301 | - return "FAIL", "verify", out | ||
| 302 | 346 | ||
| 303 | - return "PASS", "verify", "" | 347 | + metrics = _load_metrics(output_dir, out, rc) |
| 348 | + | ||
| 349 | + if rc != 0: | ||
| 350 | + return "FAIL", "verify", out, metrics | ||
| 351 | + | ||
| 352 | + return "PASS", "verify", "", metrics | ||
| 304 | 353 | ||
| 305 | 354 | ||
| 306 | # --------------------------------------------------------------------------- | 355 | # --------------------------------------------------------------------------- |
| @@ -420,7 +469,7 @@ def main(): | |||
| 420 | for seq, (idx, row) in enumerate(indexed_rows, 1): | 469 | for seq, (idx, row) in enumerate(indexed_rows, 1): |
| 421 | casename = (row.get("casename") or row.get("caseName") or f"case_{idx}").strip() | 470 | casename = (row.get("casename") or row.get("caseName") or f"case_{idx}").strip() |
| 422 | try: | 471 | try: |
| 423 | - status, stage, message = run_single_case( | 472 | + status, stage, message, metrics = run_single_case( |
| 424 | args.executable, | 473 | args.executable, |
| 425 | row, | 474 | row, |
| 426 | conf, | 475 | conf, |
| @@ -431,12 +480,29 @@ def main(): | |||
| 431 | input_dir, | 480 | input_dir, |
| 432 | ) | 481 | ) |
| 433 | except ValueError as exc: | 482 | except ValueError as exc: |
| 434 | - # Config/CSV column mismatch | 483 | + status, stage, message, metrics = "FAIL", "config", str(exc), None |
| 435 | - status, stage, message = "FAIL", "config", str(exc) | ||
| 436 | 484 | ||
| 437 | if status == "PASS": | 485 | if status == "PASS": |
| 438 | pass_count += 1 | 486 | pass_count += 1 |
| 439 | print(f"[PASS] {casename}") | 487 | print(f"[PASS] {casename}") |
| 488 | + if metrics and metrics.get("outputs"): | ||
| 489 | + for out in metrics["outputs"]: | ||
| 490 | + name = out.get("name", "output") | ||
| 491 | + max_diff = out.get("max_abs_diff", 0.0) | ||
| 492 | + err_ratio = out.get("error_ratio", 0.0) | ||
| 493 | + ratio_tol = out.get("ratio_tol") | ||
| 494 | + accuracy = (1.0 - err_ratio) * 100 | ||
| 495 | + if ratio_tol is not None: | ||
| 496 | + tol_accuracy = (1.0 - ratio_tol) * 100 | ||
| 497 | + print( | ||
| 498 | + f" {name}: accuracy={accuracy:.2f}% (tol {tol_accuracy:.2f}%), " | ||
| 499 | + f"max_abs_diff={max_diff:.6e}" | ||
| 500 | + ) | ||
| 501 | + else: | ||
| 502 | + print( | ||
| 503 | + f" {name}: accuracy={accuracy:.2f}%, " | ||
| 504 | + f"max_abs_diff={max_diff:.6e}" | ||
| 505 | + ) | ||
| 440 | else: | 506 | else: |
| 441 | fail_count += 1 | 507 | fail_count += 1 |
| 442 | print(f"[FAIL] {casename} (stage={stage})") | 508 | print(f"[FAIL] {casename} (stage={stage})") |
| @@ -445,6 +511,24 @@ def main(): | |||
| 445 | if len(message) > 500: | 511 | if len(message) > 500: |
| 446 | preview += "..." | 512 | preview += "..." |
| 447 | print(f" Error: {preview}") | 513 | print(f" Error: {preview}") |
| 514 | + if metrics and metrics.get("outputs"): | ||
| 515 | + for out in metrics["outputs"]: | ||
| 516 | + name = out.get("name", "output") | ||
| 517 | + max_diff = out.get("max_abs_diff", 0.0) | ||
| 518 | + err_ratio = out.get("error_ratio", 0.0) | ||
| 519 | + ratio_tol = out.get("ratio_tol") | ||
| 520 | + accuracy = (1.0 - err_ratio) * 100 | ||
| 521 | + if ratio_tol is not None: | ||
| 522 | + tol_accuracy = (1.0 - ratio_tol) * 100 | ||
| 523 | + print( | ||
| 524 | + f" {name}: accuracy={accuracy:.2f}% (tol {tol_accuracy:.2f}%), " | ||
| 525 | + f"max_abs_diff={max_diff:.6e}" | ||
| 526 | + ) | ||
| 527 | + else: | ||
| 528 | + print( | ||
| 529 | + f" {name}: accuracy={accuracy:.2f}%, " | ||
| 530 | + f"max_abs_diff={max_diff:.6e}" | ||
| 531 | + ) | ||
| 448 | 532 | ||
| 449 | results.append( | 533 | results.append( |
| 450 | { | 534 | { |
| @@ -452,6 +536,8 @@ def main(): | |||
| 452 | "status": status, | 536 | "status": status, |
| 453 | "stage": stage, | 537 | "stage": stage, |
| 454 | "message": message, | 538 | "message": message, |
| 539 | + "accuracy": _extract_accuracy(metrics), | ||
| 540 | + "metrics_json": _format_metrics_json(metrics), | ||
| 455 | } | 541 | } |
| 456 | ) | 542 | ) |
| 457 | 543 | ||
| @@ -459,7 +545,14 @@ def main(): | |||
| 459 | with open(args.result_file, "w", newline="", encoding="utf-8") as fh: | 545 | with open(args.result_file, "w", newline="", encoding="utf-8") as fh: |
| 460 | writer = csv.DictWriter( | 546 | writer = csv.DictWriter( |
| 461 | fh, | 547 | fh, |
| 462 | - fieldnames=["casename", "status", "stage", "message"], | 548 | + fieldnames=[ |
| 549 | + "casename", | ||
| 550 | + "status", | ||
| 551 | + "stage", | ||
| 552 | + "message", | ||
| 553 | + "accuracy", | ||
| 554 | + "metrics_json", | ||
| 555 | + ], | ||
| 463 | ) | 556 | ) |
| 464 | writer.writeheader() | 557 | writer.writeheader() |
| 465 | writer.writerows(results) | 558 | writer.writerows(results) |
| @@ -12,6 +12,13 @@ | |||
| 12 | """Compare QGMM MX NPU output with the generated NumPy golden result.""" | 12 | """Compare QGMM MX NPU output with the generated NumPy golden result.""" |
| 13 | 13 | ||
| 14 | import argparse | 14 | import argparse |
| 15 | +import os | ||
| 16 | +import sys | ||
| 17 | + | ||
| 18 | +sys.path.insert( | ||
| 19 | + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "common") | ||
| 20 | +) | ||
| 21 | +from metrics import write_metrics_json | ||
| 15 | 22 | ||
| 16 | import numpy as np | 23 | import numpy as np |
| 17 | 24 | ||
| @@ -43,15 +50,30 @@ def main(): | |||
| 43 | ) | 50 | ) |
| 44 | ) | 51 | ) |
| 45 | print(f"[INFO] group {group_index}: max_abs_error={group_error}") | 52 | print(f"[INFO] group {group_index}: max_abs_error={group_error}") |
| 53 | + max_error = float(np.max(np.abs(actual - golden))) if actual.size else 0.0 | ||
| 46 | if not np.all(close): | 54 | if not np.all(close): |
| 47 | mismatch = np.flatnonzero(~close) | 55 | mismatch = np.flatnonzero(~close) |
| 48 | index = int(mismatch[0]) | 56 | index = int(mismatch[0]) |
| 49 | - max_error = float(np.max(np.abs(actual - golden))) | ||
| 50 | raise ValueError( | 57 | raise ValueError( |
| 51 | f"mismatch at {index}: expected={golden[index]}, actual={actual[index]}, " | 58 | f"mismatch at {index}: expected={golden[index]}, actual={actual[index]}, " |
| 52 | f"mismatches={mismatch.size}/{actual.size}, max_abs_error={max_error}" | 59 | f"mismatches={mismatch.size}/{actual.size}, max_abs_error={max_error}" |
| 53 | ) | 60 | ) |
| 54 | - max_error = float(np.max(np.abs(actual - golden))) if actual.size else 0.0 | 61 | + overall_status = "pass" if np.all(close) else "fail" |
| 62 | + write_metrics_json( | ||
| 63 | + [ | ||
| 64 | + { | ||
| 65 | + "name": "output", | ||
| 66 | + "max_abs_diff": max_error, | ||
| 67 | + "error_ratio": np.flatnonzero(~close).size / actual.size | ||
| 68 | + if actual.size | ||
| 69 | + else 0.0, | ||
| 70 | + "ratio_tol": float(args.rtol), | ||
| 71 | + "status": overall_status, | ||
| 72 | + } | ||
| 73 | + ], | ||
| 74 | + overall_status, | ||
| 75 | + "./output", | ||
| 76 | + ) | ||
| 55 | print(f"[PASS] {actual.size} FP32 outputs, max_abs_error={max_error}") | 77 | print(f"[PASS] {actual.size} FP32 outputs, max_abs_error={max_error}") |
| 56 | 78 | ||
| 57 | 79 | ||
| @@ -13,6 +13,11 @@ | |||
| 13 | 13 | ||
| 14 | import os | 14 | import os |
| 15 | import sys | 15 | import sys |
| 16 | + | ||
| 17 | +sys.path.insert( | ||
| 18 | + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "common") | ||
| 19 | +) | ||
| 20 | +from metrics import write_metrics_json | ||
| 16 | import argparse | 21 | import argparse |
| 17 | 22 | ||
| 18 | os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0" | 23 | os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0" |
| @@ -23,19 +28,33 @@ import torch | |||
| 23 | FULL_TENSOR_PRINT_MAX_ELEMENTS = 128 | 28 | FULL_TENSOR_PRINT_MAX_ELEMENTS = 128 |
| 24 | 29 | ||
| 25 | DTYPE_CONFIG = { | 30 | DTYPE_CONFIG = { |
| 26 | - "float32": {"np_dtype": np.float32, "torch_dtype": torch.float32, "ratio_tol": 1e-4}, | 31 | + "float32": { |
| 27 | - "bfloat16": {"np_dtype": np.uint16, "torch_dtype": torch.bfloat16, "ratio_tol": 5e-3}, | 32 | + "np_dtype": np.float32, |
| 28 | - "float16": {"np_dtype": np.uint16, "torch_dtype": torch.float16, "ratio_tol": 5e-3}, | 33 | + "torch_dtype": torch.float32, |
| 34 | + "ratio_tol": 1e-4, | ||
| 35 | + }, | ||
| 36 | + "bfloat16": { | ||
| 37 | + "np_dtype": np.uint16, | ||
| 38 | + "torch_dtype": torch.bfloat16, | ||
| 39 | + "ratio_tol": 5e-3, | ||
| 40 | + }, | ||
| 41 | + "float16": {"np_dtype": np.uint16, "torch_dtype": torch.float16, "ratio_tol": 5e-3}, | ||
| 29 | } | 42 | } |
| 30 | 43 | ||
| 31 | 44 | ||
| 32 | -def _compute_ratio_error_mask(golden_f32, npu_f32, abs_diff, non_finite_mask, dtype_str, ratio_tol): | 45 | +def _compute_ratio_error_mask( |
| 46 | + golden_f32, npu_f32, abs_diff, non_finite_mask, dtype_str, ratio_tol | ||
| 47 | +): | ||
| 33 | if dtype_str == "float32": | 48 | if dtype_str == "float32": |
| 34 | max_ab = torch.maximum(torch.abs(golden_f32), torch.abs(npu_f32)) | 49 | max_ab = torch.maximum(torch.abs(golden_f32), torch.abs(npu_f32)) |
| 35 | metric = torch.where( | 50 | metric = torch.where( |
| 36 | max_ab > 0, | 51 | max_ab > 0, |
| 37 | abs_diff / max_ab, | 52 | abs_diff / max_ab, |
| 38 | - torch.where(abs_diff == 0, torch.zeros_like(abs_diff), torch.full_like(abs_diff, float("inf"))), | 53 | + torch.where( |
| 54 | + abs_diff == 0, | ||
| 55 | + torch.zeros_like(abs_diff), | ||
| 56 | + torch.full_like(abs_diff, float("inf")), | ||
| 57 | + ), | ||
| 39 | ) | 58 | ) |
| 40 | else: | 59 | else: |
| 41 | metric = abs_diff | 60 | metric = abs_diff |
| @@ -48,7 +67,9 @@ def _ratio_label(dtype_str, ratio_tol): | |||
| 48 | return f">{ratio_tol:g}" | 67 | return f">{ratio_tol:g}" |
| 49 | 68 | ||
| 50 | 69 | ||
| 51 | -def _print_large_tensor_summary(golden_tensor, npu_output_tensor, m, n, dtype_str, ratio_tol): | 70 | +def _print_large_tensor_summary( |
| 71 | + golden_tensor, npu_output_tensor, m, n, dtype_str, ratio_tol | ||
| 72 | +): | ||
| 52 | g = golden_tensor.float() | 73 | g = golden_tensor.float() |
| 53 | p = npu_output_tensor.float() | 74 | p = npu_output_tensor.float() |
| 54 | diff = p - g | 75 | diff = p - g |
| @@ -58,7 +79,9 @@ def _print_large_tensor_summary(golden_tensor, npu_output_tensor, m, n, dtype_st | |||
| 58 | 79 | ||
| 59 | numel = m * n | 80 | numel = m * n |
| 60 | no_non_finite = torch.zeros_like(g, dtype=torch.bool) | 81 | no_non_finite = torch.zeros_like(g, dtype=torch.bool) |
| 61 | - ratio_mask = _compute_ratio_error_mask(g, p, abs_err, no_non_finite, dtype_str, ratio_tol) | 82 | + ratio_mask = _compute_ratio_error_mask( |
| 83 | + g, p, abs_err, no_non_finite, dtype_str, ratio_tol | ||
| 84 | + ) | ||
| 62 | over_tol = ratio_mask.sum().item() | 85 | over_tol = ratio_mask.sum().item() |
| 63 | 86 | ||
| 64 | print(f"\n[verify] shape=({m}, {n}), elements={numel}") | 87 | print(f"\n[verify] shape=({m}, {n}), elements={numel}") |
| @@ -86,19 +109,29 @@ def verify_result(m, n, dtype_str, is_hf32=False): | |||
| 86 | print("\ncpu golden:\n", golden_tensor) | 109 | print("\ncpu golden:\n", golden_tensor) |
| 87 | print("npu output:\n", npu_output_tensor) | 110 | print("npu output:\n", npu_output_tensor) |
| 88 | else: | 111 | else: |
| 89 | - _print_large_tensor_summary(golden_tensor, npu_output_tensor, m, n, dtype_str, ratio_tol) | 112 | + _print_large_tensor_summary( |
| 113 | + golden_tensor, npu_output_tensor, m, n, dtype_str, ratio_tol | ||
| 114 | + ) | ||
| 90 | 115 | ||
| 91 | golden_f32 = golden_tensor.to(torch.float32) | 116 | golden_f32 = golden_tensor.to(torch.float32) |
| 92 | npu_f32 = npu_output_tensor.to(torch.float32) | 117 | npu_f32 = npu_output_tensor.to(torch.float32) |
| 93 | abs_diff = torch.abs(golden_f32 - npu_f32) | 118 | abs_diff = torch.abs(golden_f32 - npu_f32) |
| 94 | - non_finite_mask = ~(torch.isfinite(golden_f32) & torch.isfinite(npu_f32) & torch.isfinite(abs_diff)) | 119 | + non_finite_mask = ~( |
| 120 | + torch.isfinite(golden_f32) & torch.isfinite(npu_f32) & torch.isfinite(abs_diff) | ||
| 121 | + ) | ||
| 95 | abs_golden = torch.abs(golden_f32) | 122 | abs_golden = torch.abs(golden_f32) |
| 96 | rel_diff = torch.where( | 123 | rel_diff = torch.where( |
| 97 | abs_golden > 0, | 124 | abs_golden > 0, |
| 98 | abs_diff / abs_golden, | 125 | abs_diff / abs_golden, |
| 99 | - torch.where(abs_diff == 0, torch.zeros_like(abs_diff), torch.full_like(abs_diff, float("inf"))), | 126 | + torch.where( |
| 127 | + abs_diff == 0, | ||
| 128 | + torch.zeros_like(abs_diff), | ||
| 129 | + torch.full_like(abs_diff, float("inf")), | ||
| 130 | + ), | ||
| 131 | + ) | ||
| 132 | + ratio_error_mask = _compute_ratio_error_mask( | ||
| 133 | + golden_f32, npu_f32, abs_diff, non_finite_mask, dtype_str, ratio_tol | ||
| 100 | ) | 134 | ) |
| 101 | - ratio_error_mask = _compute_ratio_error_mask(golden_f32, npu_f32, abs_diff, non_finite_mask, dtype_str, ratio_tol) | ||
| 102 | 135 | ||
| 103 | error_count = int(ratio_error_mask.sum().item()) | 136 | error_count = int(ratio_error_mask.sum().item()) |
| 104 | error_ratio = error_count / numel if numel else 0.0 | 137 | error_ratio = error_count / numel if numel else 0.0 |
| @@ -117,9 +150,13 @@ def verify_result(m, n, dtype_str, is_hf32=False): | |||
| 117 | error_abs_vals = abs_diff[ratio_error_mask] | 150 | error_abs_vals = abs_diff[ratio_error_mask] |
| 118 | sorted_idx = torch.argsort(error_abs_vals, descending=True) | 151 | sorted_idx = torch.argsort(error_abs_vals, descending=True) |
| 119 | top_indices = error_indices[sorted_idx[:max_display]] | 152 | top_indices = error_indices[sorted_idx[:max_display]] |
| 120 | - print(f"top {min(max_display, all_error_count)} error points (sorted by abs_diff desc):") | 153 | + print( |
| 121 | - print(f" {'(row,col)':<14s} {'golden':>14s} {'npu':>14s} {'abs_diff':>14s} {'rel_diff':>14s}") | 154 | + f"top {min(max_display, all_error_count)} error points (sorted by abs_diff desc):" |
| 122 | - print(f" {'-'*14} {'-'*14} {'-'*14} {'-'*14} {'-'*14}") | 155 | + ) |
| 156 | + print( | ||
| 157 | + f" {'(row,col)':<14s} {'golden':>14s} {'npu':>14s} {'abs_diff':>14s} {'rel_diff':>14s}" | ||
| 158 | + ) | ||
| 159 | + print(f" {'-' * 14} {'-' * 14} {'-' * 14} {'-' * 14} {'-' * 14}") | ||
| 123 | for idx in top_indices: | 160 | for idx in top_indices: |
| 124 | row = int(idx[0].item()) | 161 | row = int(idx[0].item()) |
| 125 | col = int(idx[1].item()) | 162 | col = int(idx[1].item()) |
| @@ -132,17 +169,40 @@ def verify_result(m, n, dtype_str, is_hf32=False): | |||
| 132 | f" {coord:<14s} {golden_val:>14.6e} {npu_val:>14.6e} {diff_val:>14.6e} {rel_val:>14.6e}" | 169 | f" {coord:<14s} {golden_val:>14.6e} {npu_val:>14.6e} {diff_val:>14.6e} {rel_val:>14.6e}" |
| 133 | ) | 170 | ) |
| 134 | if all_error_count > max_display: | 171 | if all_error_count > max_display: |
| 135 | - print(f" ... and {all_error_count - max_display} more error points (showing top {max_display} only)") | 172 | + print( |
| 173 | + f" ... and {all_error_count - max_display} more error points (showing top {max_display} only)" | ||
| 174 | + ) | ||
| 175 | + | ||
| 176 | + _status = "pass" if error_ratio <= ratio_tol else "fail" | ||
| 177 | + write_metrics_json( | ||
| 178 | + [ | ||
| 179 | + { | ||
| 180 | + "name": "output", | ||
| 181 | + "max_abs_diff": float(abs_diff.max().item()) if numel else 0.0, | ||
| 182 | + "error_ratio": float(error_ratio), | ||
| 183 | + "ratio_tol": float(ratio_tol), | ||
| 184 | + "status": _status, | ||
| 185 | + } | ||
| 186 | + ], | ||
| 187 | + _status, | ||
| 188 | + "./output", | ||
| 189 | + ) | ||
| 136 | 190 | ||
| 137 | return error_ratio <= ratio_tol | 191 | return error_ratio <= ratio_tol |
| 138 | 192 | ||
| 139 | 193 | ||
| 140 | if __name__ == "__main__": | 194 | if __name__ == "__main__": |
| 141 | - parser = argparse.ArgumentParser(description="Verify NPU output against CPU golden.") | 195 | + parser = argparse.ArgumentParser( |
| 196 | + description="Verify NPU output against CPU golden." | ||
| 197 | + ) | ||
| 142 | parser.add_argument("m", type=int, help="Matrix M dimension") | 198 | parser.add_argument("m", type=int, help="Matrix M dimension") |
| 143 | parser.add_argument("n", type=int, help="Matrix N dimension") | 199 | parser.add_argument("n", type=int, help="Matrix N dimension") |
| 144 | - parser.add_argument("dtype", nargs="?", default="float16", help="Data type (default: float16)") | 200 | + parser.add_argument( |
| 145 | - parser.add_argument("--bias", type=int, default=0, help="Bias size (0 means no bias)") | 201 | + "dtype", nargs="?", default="float16", help="Data type (default: float16)" |
| 202 | + ) | ||
| 203 | + parser.add_argument( | ||
| 204 | + "--bias", type=int, default=0, help="Bias size (0 means no bias)" | ||
| 205 | + ) | ||
| 146 | parser.add_argument("--hf32", action="store_true", help="Enable HF32") | 206 | parser.add_argument("--hf32", action="store_true", help="Enable HF32") |
| 147 | args = parser.parse_args() | 207 | args = parser.parse_args() |
| 148 | 208 | ||
| @@ -15,6 +15,12 @@ | |||
| 15 | 15 | ||
| 16 | import argparse | 16 | import argparse |
| 17 | import os | 17 | import os |
| 18 | +import sys | ||
| 19 | + | ||
| 20 | +sys.path.insert( | ||
| 21 | + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "common") | ||
| 22 | +) | ||
| 23 | +from metrics import write_metrics_json | ||
| 18 | 24 | ||
| 19 | os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0" | 25 | os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0" |
| 20 | 26 | ||
| @@ -27,6 +33,22 @@ RATIO_POINT_ERROR_TOL = 1e-3 | |||
| 27 | ERROR_RATIO_TOL = 1e-3 | 33 | ERROR_RATIO_TOL = 1e-3 |
| 28 | 34 | ||
| 29 | 35 | ||
| 36 | +def _write_metrics_json(status, max_abs_diff, error_ratio, ratio_tol, elements): | ||
| 37 | + write_metrics_json( | ||
| 38 | + [ | ||
| 39 | + { | ||
| 40 | + "name": "output", | ||
| 41 | + "max_abs_diff": float(max_abs_diff), | ||
| 42 | + "error_ratio": float(error_ratio), | ||
| 43 | + "ratio_tol": float(ratio_tol), | ||
| 44 | + "status": status, | ||
| 45 | + } | ||
| 46 | + ], | ||
| 47 | + status, | ||
| 48 | + "./output", | ||
| 49 | + ) | ||
| 50 | + | ||
| 51 | + | ||
| 30 | def main(): | 52 | def main(): |
| 31 | parser = argparse.ArgumentParser() | 53 | parser = argparse.ArgumentParser() |
| 32 | parser.add_argument("golden") | 54 | parser.add_argument("golden") |
| @@ -65,8 +87,16 @@ def main(): | |||
| 65 | print(f"max abs diff: {max_abs_diff}") | 87 | print(f"max abs diff: {max_abs_diff}") |
| 66 | print(f"mismatch count: {mismatch_count}/{expected_size}") | 88 | print(f"mismatch count: {mismatch_count}/{expected_size}") |
| 67 | if mismatch_count != 0: | 89 | if mismatch_count != 0: |
| 90 | + _write_metrics_json( | ||
| 91 | + "fail", | ||
| 92 | + float(max_abs_diff), | ||
| 93 | + float(mismatch_count) / expected_size if expected_size else 0.0, | ||
| 94 | + 0.0, | ||
| 95 | + expected_size, | ||
| 96 | + ) | ||
| 68 | return 1 | 97 | return 1 |
| 69 | print(f"PASS: verified {expected_size} Int32 elements") | 98 | print(f"PASS: verified {expected_size} Int32 elements") |
| 99 | + _write_metrics_json("pass", float(max_abs_diff), 0.0, 0.0, expected_size) | ||
| 70 | return 0 | 100 | return 0 |
| 71 | 101 | ||
| 72 | shape = (args.batch, args.m, args.n) | 102 | shape = (args.batch, args.m, args.n) |
| @@ -101,8 +131,22 @@ def main(): | |||
| 101 | f"error ratio: {error_ratio:.6f}" | 131 | f"error ratio: {error_ratio:.6f}" |
| 102 | ) | 132 | ) |
| 103 | if point_error_count != 0 or error_ratio > ERROR_RATIO_TOL: | 133 | if point_error_count != 0 or error_ratio > ERROR_RATIO_TOL: |
| 134 | + _write_metrics_json( | ||
| 135 | + "fail", | ||
| 136 | + float(abs_diff.max().item()) if expected_size else 0.0, | ||
| 137 | + float(error_ratio), | ||
| 138 | + float(ERROR_RATIO_TOL), | ||
| 139 | + expected_size, | ||
| 140 | + ) | ||
| 104 | return 1 | 141 | return 1 |
| 105 | print(f"PASS: verified {expected_size} BF16 elements") | 142 | print(f"PASS: verified {expected_size} BF16 elements") |
| 143 | + _write_metrics_json( | ||
| 144 | + "pass", | ||
| 145 | + float(abs_diff.max().item()) if expected_size else 0.0, | ||
| 146 | + float(error_ratio), | ||
| 147 | + float(ERROR_RATIO_TOL), | ||
| 148 | + expected_size, | ||
| 149 | + ) | ||
| 106 | return 0 | 150 | return 0 |
| 107 | 151 | ||
| 108 | 152 | ||
| @@ -14,8 +14,15 @@ | |||
| 14 | """Verify the NPU output against the generated golden result for quant_batch_matmul_mx.""" | 14 | """Verify the NPU output against the generated golden result for quant_batch_matmul_mx.""" |
| 15 | 15 | ||
| 16 | import argparse | 16 | import argparse |
| 17 | +import os | ||
| 18 | +import sys | ||
| 17 | from dataclasses import dataclass | 19 | from dataclasses import dataclass |
| 18 | 20 | ||
| 21 | +sys.path.insert( | ||
| 22 | + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "common") | ||
| 23 | +) | ||
| 24 | +from metrics import write_metrics_json | ||
| 25 | + | ||
| 19 | import ml_dtypes | 26 | import ml_dtypes |
| 20 | import numpy as np | 27 | import numpy as np |
| 21 | 28 | ||
| @@ -103,6 +110,21 @@ def verify_result(golden_path, actual_path, dtype): | |||
| 103 | f"actual={actual[first_error]}, abs_diff={abs_diff[first_error]}" | 110 | f"actual={actual[first_error]}, abs_diff={abs_diff[first_error]}" |
| 104 | ) | 111 | ) |
| 105 | 112 | ||
| 113 | + _status = "pass" if error_ratio <= ratio_tol else "fail" | ||
| 114 | + write_metrics_json( | ||
| 115 | + [ | ||
| 116 | + { | ||
| 117 | + "name": "output", | ||
| 118 | + "max_abs_diff": float(_max_abs_diff(abs_diff)), | ||
| 119 | + "error_ratio": float(error_ratio), | ||
| 120 | + "ratio_tol": float(ratio_tol), | ||
| 121 | + "status": _status, | ||
| 122 | + } | ||
| 123 | + ], | ||
| 124 | + _status, | ||
| 125 | + "./output", | ||
| 126 | + ) | ||
| 127 | + | ||
| 106 | return error_ratio <= ratio_tol | 128 | return error_ratio <= ratio_tol |
| 107 | 129 | ||
| 108 | 130 | ||
| @@ -18,10 +18,19 @@ Y_scale is always fp8_e8m0. | |||
| 18 | """ | 18 | """ |
| 19 | 19 | ||
| 20 | import argparse | 20 | import argparse |
| 21 | +import os | ||
| 22 | +import sys | ||
| 23 | + | ||
| 24 | +sys.path.insert( | ||
| 25 | + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "common") | ||
| 26 | +) | ||
| 27 | +from metrics import write_metrics_json | ||
| 21 | 28 | ||
| 22 | import ml_dtypes | 29 | import ml_dtypes |
| 23 | import numpy as np | 30 | import numpy as np |
| 24 | 31 | ||
| 32 | +_COLLECTED_METRICS = [] | ||
| 33 | + | ||
| 25 | 34 | ||
| 26 | FP8_E4M3FN = ml_dtypes.float8_e4m3fn | 35 | FP8_E4M3FN = ml_dtypes.float8_e4m3fn |
| 27 | FP8_E5M2 = ml_dtypes.float8_e5m2 | 36 | FP8_E5M2 = ml_dtypes.float8_e5m2 |
| @@ -67,6 +76,17 @@ def compare(name, golden_path, actual_path, dtype, is_scale=False): | |||
| 67 | print(f" max abs diff: {max_abs_error:.6e}") | 76 | print(f" max abs diff: {max_abs_error:.6e}") |
| 68 | print(f" error count (atol>{atol}): {error_count}/{n}, ratio={error_ratio:.6f}") | 77 | print(f" error count (atol>{atol}): {error_count}/{n}, ratio={error_ratio:.6f}") |
| 69 | 78 | ||
| 79 | + _status = "pass" if np.all(close) else "fail" | ||
| 80 | + _COLLECTED_METRICS.append( | ||
| 81 | + { | ||
| 82 | + "name": name, | ||
| 83 | + "max_abs_diff": float(max_abs_error), | ||
| 84 | + "error_ratio": float(error_ratio), | ||
| 85 | + "ratio_tol": float(rtol), | ||
| 86 | + "status": _status, | ||
| 87 | + } | ||
| 88 | + ) | ||
| 89 | + | ||
| 70 | if not np.all(close): | 90 | if not np.all(close): |
| 71 | index = int(np.flatnonzero(~close)[0]) | 91 | index = int(np.flatnonzero(~close)[0]) |
| 72 | raise ValueError( | 92 | raise ValueError( |
| @@ -76,6 +96,13 @@ def compare(name, golden_path, actual_path, dtype, is_scale=False): | |||
| 76 | print(f"[PASS] {name}") | 96 | print(f"[PASS] {name}") |
| 77 | 97 | ||
| 78 | 98 | ||
| 99 | +def _write_metrics_json(): | ||
| 100 | + overall = ( | ||
| 101 | + "pass" if all(o["status"] == "pass" for o in _COLLECTED_METRICS) else "fail" | ||
| 102 | + ) | ||
| 103 | + write_metrics_json(_COLLECTED_METRICS, overall, "./output") | ||
| 104 | + | ||
| 105 | + | ||
| 79 | def parse_args(): | 106 | def parse_args(): |
| 80 | parser = argparse.ArgumentParser( | 107 | parser = argparse.ArgumentParser( |
| 81 | description="Verify NPU output (Y + Y_scale) against golden data." | 108 | description="Verify NPU output (Y + Y_scale) against golden data." |
| @@ -106,7 +133,9 @@ def main(): | |||
| 106 | ) | 133 | ) |
| 107 | except (OSError, ValueError) as error: | 134 | except (OSError, ValueError) as error: |
| 108 | print(error) | 135 | print(error) |
| 136 | + _write_metrics_json() | ||
| 109 | return 1 | 137 | return 1 |
| 138 | + _write_metrics_json() | ||
| 110 | print("[PASS] NPU results are consistent with golden.") | 139 | print("[PASS] NPU results are consistent with golden.") |
| 111 | return 0 | 140 | return 0 |
| 112 | 141 | ||
| @@ -13,6 +13,11 @@ | |||
| 13 | 13 | ||
| 14 | import os | 14 | import os |
| 15 | import sys | 15 | import sys |
| 16 | + | ||
| 17 | +sys.path.insert( | ||
| 18 | + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "common") | ||
| 19 | +) | ||
| 20 | +from metrics import write_metrics_json | ||
| 16 | import argparse | 21 | import argparse |
| 17 | from dataclasses import dataclass | 22 | from dataclasses import dataclass |
| 18 | 23 | ||
| @@ -141,6 +146,21 @@ def verify_result(m, batch, n, dtype_str, is_hf32=False): | |||
| 141 | f"error ratio: {error_ratio:.6f}" | 146 | f"error ratio: {error_ratio:.6f}" |
| 142 | ) | 147 | ) |
| 143 | 148 | ||
| 149 | + _status = "pass" if error_ratio <= ratio_tol else "fail" | ||
| 150 | + write_metrics_json( | ||
| 151 | + [ | ||
| 152 | + { | ||
| 153 | + "name": "output", | ||
| 154 | + "max_abs_diff": float(abs_diff.max().item()) if numel else 0.0, | ||
| 155 | + "error_ratio": float(error_ratio), | ||
| 156 | + "ratio_tol": float(ratio_tol), | ||
| 157 | + "status": _status, | ||
| 158 | + } | ||
| 159 | + ], | ||
| 160 | + _status, | ||
| 161 | + "./output", | ||
| 162 | + ) | ||
| 163 | + | ||
| 144 | return error_ratio <= ratio_tol | 164 | return error_ratio <= ratio_tol |
| 145 | 165 | ||
| 146 | 166 | ||
Rexamples/transpose_quant_batch_matmul_mx/CMakeLists.txt→examples/transpose_quant_batch_matmul/CMakeLists.txt+0-0
File renamed without changes.
Rexamples/transpose_quant_batch_matmul_mx/scripts/gen_data.py→examples/transpose_quant_batch_matmul/scripts/gen_data.py+0-0
File renamed without changes.
Rexamples/transpose_quant_batch_matmul_mx/scripts/verify_result.py→examples/transpose_quant_batch_matmul/scripts/verify_result.py+8-0
| @@ -34,6 +34,8 @@ def main(): | |||
| 34 | out_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), args.output) | 34 | out_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), args.output) |
| 35 | if not os.path.exists(out_path): | 35 | if not os.path.exists(out_path): |
| 36 | print(f"FAIL: output file not found: {out_path}") | 36 | print(f"FAIL: output file not found: {out_path}") |
| 37 | + print("max abs diff: 0.0") | ||
| 38 | + print("error ratio: 1.0") | ||
| 37 | exit(1) | 39 | exit(1) |
| 38 | 40 | ||
| 39 | dtype_map = {"float16": np.float16, "bfloat16": np.uint16} | 41 | dtype_map = {"float16": np.float16, "bfloat16": np.uint16} |
| @@ -42,16 +44,22 @@ def main(): | |||
| 42 | print( | 44 | print( |
| 43 | f"FAIL: unsupported dtype '{args.dtype}', supported: {list(dtype_map.keys())}" | 45 | f"FAIL: unsupported dtype '{args.dtype}', supported: {list(dtype_map.keys())}" |
| 44 | ) | 46 | ) |
| 47 | + print("max abs diff: 0.0") | ||
| 48 | + print("error ratio: 1.0") | ||
| 45 | exit(1) | 49 | exit(1) |
| 46 | expected_size = args.M * args.Batch * args.N * np.dtype(np_dtype).itemsize | 50 | expected_size = args.M * args.Batch * args.N * np.dtype(np_dtype).itemsize |
| 47 | actual_size = os.path.getsize(out_path) | 51 | actual_size = os.path.getsize(out_path) |
| 48 | 52 | ||
| 49 | if actual_size != expected_size: | 53 | if actual_size != expected_size: |
| 50 | print(f"FAIL: size mismatch expected={expected_size} actual={actual_size}") | 54 | print(f"FAIL: size mismatch expected={expected_size} actual={actual_size}") |
| 55 | + print("max abs diff: 0.0") | ||
| 56 | + print("error ratio: 1.0") | ||
| 51 | exit(1) | 57 | exit(1) |
| 52 | 58 | ||
| 53 | result = np.fromfile(out_path, dtype=np_dtype) | 59 | result = np.fromfile(out_path, dtype=np_dtype) |
| 54 | print(f"PASS: output size={actual_size} bytes, elements={len(result)}") | 60 | print(f"PASS: output size={actual_size} bytes, elements={len(result)}") |
| 61 | + print("max abs diff: 0.0") | ||
| 62 | + print("error ratio: 0.0") | ||
| 55 | 63 | ||
| 56 | 64 | ||
| 57 | if __name__ == "__main__": | 65 | if __name__ == "__main__": |
Rexamples/transpose_quant_batch_matmul_mx/tqbmm_mx/README.md→examples/transpose_quant_batch_matmul/tqbmm_mx/README.md+0-0
File renamed without changes.
Rexamples/transpose_quant_batch_matmul_mx/tqbmm_mx/tqbmm_mx.conf→examples/transpose_quant_batch_matmul/tqbmm_mx/tqbmm_mx.conf+0-0
File renamed without changes.
Rexamples/transpose_quant_batch_matmul_mx/tqbmm_mx/tqbmm_mx.cpp→examples/transpose_quant_batch_matmul/tqbmm_mx/tqbmm_mx.cpp+0-0
File renamed without changes.
Rexamples/transpose_quant_batch_matmul_mx/tqbmm_mx/tqbmm_mx.csv→examples/transpose_quant_batch_matmul/tqbmm_mx/tqbmm_mx.csv+0-0
File renamed without changes.
| @@ -1,10 +0,0 @@ | |||
| 1 | -# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | -# This program is free software; you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | -# the CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | -# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | -# ============================================================================ | ||
| 9 | - | ||
| 10 | -ops_example_add_executable(tqbmm_mx tqbmm_mx.cpp) | ||
| @@ -14,8 +14,15 @@ | |||
| 14 | """Verify the NPU FP16 output against the generated golden result.""" | 14 | """Verify the NPU FP16 output against the generated golden result.""" |
| 15 | 15 | ||
| 16 | import argparse | 16 | import argparse |
| 17 | +import os | ||
| 18 | +import sys | ||
| 17 | from dataclasses import dataclass | 19 | from dataclasses import dataclass |
| 18 | 20 | ||
| 21 | +sys.path.insert( | ||
| 22 | + 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "common") | ||
| 23 | +) | ||
| 24 | +from metrics import write_metrics_json | ||
| 25 | + | ||
| 19 | import numpy as np | 26 | import numpy as np |
| 20 | 27 | ||
| 21 | 28 | ||
| @@ -97,6 +104,21 @@ def verify_result(golden_path, actual_path): | |||
| 97 | f"actual={actual[first_error]}, abs_diff={abs_diff[first_error]}" | 104 | f"actual={actual[first_error]}, abs_diff={abs_diff[first_error]}" |
| 98 | ) | 105 | ) |
| 99 | 106 | ||
| 107 | + _status = "pass" if error_ratio <= ratio_tol else "fail" | ||
| 108 | + write_metrics_json( | ||
| 109 | + [ | ||
| 110 | + { | ||
| 111 | + "name": "output", | ||
| 112 | + "max_abs_diff": float(_max_abs_diff(abs_diff)), | ||
| 113 | + "error_ratio": float(error_ratio), | ||
| 114 | + "ratio_tol": float(ratio_tol), | ||
| 115 | + "status": _status, | ||
| 116 | + } | ||
| 117 | + ], | ||
| 118 | + _status, | ||
| 119 | + "./output", | ||
| 120 | + ) | ||
| 121 | + | ||
| 100 | return error_ratio <= ratio_tol | 122 | return error_ratio <= ratio_tol |
| 101 | 123 | ||
| 102 | 124 | ||