Open
feat(cake): 导入 TileLang 轨三个技能 #71
JunyiAdd on Sep 30
feat(cake): 导入 TileLang 轨三个技能 #71
Open
Total: 324 files changed+64168-3
| @@ -118,6 +118,40 @@ This file records notable changes to the CANNBot plugin orchestration and delive | |||
| 118 | published in `cann/cannbot-skills`; registration files (`plugin-sources.json`, | 118 | published in `cann/cannbot-skills`; registration files (`plugin-sources.json`, |
| 119 | `init.sh`, `.codex-plugin/plugin.json`, marketplace entry, `OAT.xml` filteritem) are | 119 | `init.sh`, `.codex-plugin/plugin.json`, marketplace entry, `OAT.xml` filteritem) are |
| 120 | new here. The remaining Skills of the TileLang, EasyAsc and CV routes follow separately. | 120 | new here. The remaining Skills of the TileLang, EasyAsc and CV routes follow separately. |
| 121 | +- cake TileLang route: 4 further Skills at | ||
| 122 | + `plugins-community/collaborative-agent-kernel-evolution/skills/` — | ||
| 123 | + `tilelang-kernel-baseline` (TileLang kernel patterns, chip spec and precision | ||
| 124 | + references), `tilelang-host-bridge` (host-side operator build: emitters, validators and | ||
| 125 | + the cake_lowering passes), `tlcheck` (pre-build checks over kernel source and bundles), | ||
| 126 | + and `env-probe`. The content is the copy published in `cann/cannbot-skills`. This is the | ||
| 127 | + last of the route imports; the EasyAsc, CV and SIMT routes landed before it, so the cake | ||
| 128 | + Skill set is complete here and only the route wiring remains. | ||
| 129 | +- `skills/tilelang-kernel-baseline/scripts/` carried two symbolic links into the `tlcheck` | ||
| 130 | + Skill (`tlcheck` and the `checks/` directory). Git stores a symbolic link as a non-text | ||
| 131 | + blob, which the repository's binary-file check rejects, so both are removed. Nothing | ||
| 132 | + referenced the `tlcheck` link — the documentation calls `skills/tlcheck/tlcheck` | ||
| 133 | + directly — and the `check` dispatcher now resolves `CHECKS_DIR` to | ||
| 134 | + `$SCRIPT_DIR/../../tlcheck/checks`, the same target the link pointed at. The `checks/` | ||
| 135 | + tree is not duplicated: `skills/tlcheck/checks/shape_sweep/gen_sweep.py` stays the single | ||
| 136 | + source of truth its own README names. | ||
| 137 | +- cake declares `ops/ascendc-tiling-design` in `plugin-sources.json`, which was previously | ||
| 138 | + an empty skill list. Three files of this route name that Skill as an external reference, | ||
| 139 | + and it is published by the Skill repository this plugin already sources from, so it is | ||
| 140 | + installed by symbolic link rather than copied. Without the declaration the dependency | ||
| 141 | + gate reports the three references as runtime uses of a Skill outside the install | ||
| 142 | + whitelist. | ||
| 143 | +- Four scripts wrote their stdout contract with `print` or `sys.stdout.write`, which the | ||
| 144 | + repository's static check reports as a direct stream write. They now emit through a | ||
| 145 | + dedicated logger bound to `sys.stdout` with a `%(message)s` formatter and `propagate` | ||
| 146 | + off, so the bytes on stdout are unchanged: `env-probe/scripts/npu_probe.py`, | ||
| 147 | + `env-probe/scripts/probe_env.py`, `tlcheck/checks/shape_sweep/gen_sweep.py` and | ||
| 148 | + `tilelang-kernel-baseline/scripts/verify_precision.py`. | ||
| 149 | +- `env-probe` probes the local or a remote Ascend NPU host and writes `env.json`; | ||
| 150 | + `tilelang-kernel-baseline/lib/chip_spec.py` reads that file for core count and UB size, | ||
| 151 | + and names `skills/env-probe/SKILL.md` as the schema reference. It was left out of the | ||
| 152 | + route split because it belongs to no single route, so the reference had no target until | ||
| 153 | + now. No agent references it, so the dependency gate reports it as isolated until the | ||
| 154 | + route wiring lands. | ||
| 121 | - Third-party attribution for cake: 40 files obtained from `just-it/ascendopgenagent` | 155 | - Third-party attribution for cake: 40 files obtained from `just-it/ascendopgenagent` |
| 122 | (commit `d530e7b`, offered under Apache-2.0) now record that provenance and a | 156 | (commit `d530e7b`, offered under Apache-2.0) now record that provenance and a |
| 123 | modification notice instead of a CANN-2.0 header. The notice states where the content | 157 | modification notice instead of a CANN-2.0 header. The notice states where the content |
| @@ -17,9 +17,21 @@ | |||
| 17 | <policyitem type="license" name="MIT" path="plugins-official/tilelang-op-orchestrator/workflows/Ascend950/LICENSE" filefilter="tilelangLicenseHeaderFilter" desc="Retain and recognize the original MIT license text distributed with the Ascend950 workflow."/> | 17 | <policyitem type="license" name="MIT" path="plugins-official/tilelang-op-orchestrator/workflows/Ascend950/LICENSE" filefilter="tilelangLicenseHeaderFilter" desc="Retain and recognize the original MIT license text distributed with the Ascend950 workflow."/> |
| 18 | <policyitem type="license" name="CANN-2.0" path="plugins-official/tilelang-op-orchestrator/workflows/Ascend950/scripts/.*" filefilter="tilelangLicenseHeaderFilter" desc="TileLang framework preparation and search validation scripts retain their CANN-2.0 headers."/> | 18 | <policyitem type="license" name="CANN-2.0" path="plugins-official/tilelang-op-orchestrator/workflows/Ascend950/scripts/.*" filefilter="tilelangLicenseHeaderFilter" desc="TileLang framework preparation and search validation scripts retain their CANN-2.0 headers."/> |
| 19 | <policyitem type="copyright" name="Huawei Technologies Co., Ltd." path=".*" rule="may" group="defaultGroup" filefilter="copyrightPolicyFilter" desc=""/> | 19 | <policyitem type="copyright" name="Huawei Technologies Co., Ltd." path=".*" rule="may" group="defaultGroup" filefilter="copyrightPolicyFilter" desc=""/> |
| 20 | + <policyitem type="license" name="MIT" path="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/kernel_examples/conv2d_im2col_gemm_shape_specialized[.]py" filefilter="cakeTilelangUpstreamHeaderFilter" desc="Verify the complete retained upstream MIT notice in this registered TileLang-derived template."/> | ||
| 21 | + <policyitem type="copyright" name="Tile-AI" path="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/kernel_examples/conv2d_im2col_gemm_shape_specialized[.]py" rule="may" group="defaultGroup" filefilter="cakeTilelangUpstreamHeaderFilter" desc="Allow the retained upstream Tile-AI notice alongside the repository Huawei copyright."/> | ||
| 22 | + <policyitem type="license" name="MIT" path="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/kernel_examples/asymmetric_attention_mla[.]py" filefilter="cakeTilelangUpstreamHeaderFilter" desc="Verify the complete retained upstream MIT notice in this registered TileLang-derived template."/> | ||
| 23 | + <policyitem type="copyright" name="Tile-AI" path="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/kernel_examples/asymmetric_attention_mla[.]py" rule="may" group="defaultGroup" filefilter="cakeTilelangUpstreamHeaderFilter" desc="Allow the retained upstream Tile-AI notice alongside the repository Huawei copyright."/> | ||
| 24 | + <policyitem type="license" name="MIT" path="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/kernel_examples/cv_fusion_mha_symbolic[.]py" filefilter="cakeTilelangUpstreamHeaderFilter" desc="Verify the complete retained upstream MIT notice in this registered TileLang-derived template."/> | ||
| 25 | + <policyitem type="copyright" name="Tile-AI" path="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/kernel_examples/cv_fusion_mha_symbolic[.]py" rule="may" group="defaultGroup" filefilter="cakeTilelangUpstreamHeaderFilter" desc="Allow the retained upstream Tile-AI notice alongside the repository Huawei copyright."/> | ||
| 26 | + <policyitem type="license" name="MIT" path="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/kernel_examples/cv_fusion_quant_gemm_shape_specialized[.]py" filefilter="cakeTilelangUpstreamHeaderFilter" desc="Verify the complete retained upstream MIT notice in this registered TileLang-derived template."/> | ||
| 27 | + <policyitem type="copyright" name="Tile-AI" path="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/kernel_examples/cv_fusion_quant_gemm_shape_specialized[.]py" rule="may" group="defaultGroup" filefilter="cakeTilelangUpstreamHeaderFilter" desc="Allow the retained upstream Tile-AI notice alongside the repository Huawei copyright."/> | ||
| 28 | + <policyitem type="license" name="MIT" path="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/gemm_expert[.]py" filefilter="cakeTilelangUpstreamHeaderFilter" desc="Verify the complete retained upstream MIT notice in this registered TileLang-derived template."/> | ||
| 29 | + <policyitem type="copyright" name="Tile-AI" path="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/gemm_expert[.]py" rule="may" group="defaultGroup" filefilter="cakeTilelangUpstreamHeaderFilter" desc="Allow the retained upstream Tile-AI notice alongside the repository Huawei copyright."/> | ||
| 30 | + <policyitem type="copyright" name="copyright notice and this permission notice shall be included in all" path="(plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/kernel_examples/conv2d_im2col_gemm_shape_specialized[.]py|plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/kernel_examples/asymmetric_attention_mla[.]py|plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/kernel_examples/cv_fusion_mha_symbolic[.]py|plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/kernel_examples/cv_fusion_quant_gemm_shape_specialized[.]py|plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/gemm_expert[.]py)" rule="may" group="defaultGroup" filefilter="cakeTilelangUpstreamHeaderFilter" desc="OAT may parse this verbatim MIT permission clause as an owner. Accept only that exact clause on the five registered files; actual owner checks remain active."/> | ||
| 20 | </policy> | 31 | </policy> |
| 21 | </policylist> | 32 | </policylist> |
| 22 | <filefilterlist> | 33 | <filefilterlist> |
| 34 | + <filefilter name="cakeTilelangUpstreamHeaderFilter" desc="Apply explicit MIT and Tile-AI checks to registered standalone templates; no files are excluded."/> | ||
| 23 | <filefilter name="tilelangLicenseHeaderFilter" desc="Check TileLang license text and script headers against their explicitly declared licenses."/> | 35 | <filefilter name="tilelangLicenseHeaderFilter" desc="Check TileLang license text and script headers against their explicitly declared licenses."/> |
| 24 | <filefilter name="defaultFilter" desc="Files not checked by the root repository scan"> | 36 | <filefilter name="defaultFilter" desc="Files not checked by the root repository scan"> |
| 25 | <filteritem type="filename" name="*.mjs" desc="Workflow runtime ES modules, not distributed, skip OAT entirely"/> | 37 | <filteritem type="filename" name="*.mjs" desc="Workflow runtime ES modules, not distributed, skip OAT entirely"/> |
| @@ -43,6 +55,10 @@ | |||
| 43 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/requirements.txt" desc="pip requirements file; a header would be parsed as a dependency line."/> | 55 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/requirements.txt" desc="pip requirements file; a header would be parsed as a dependency line."/> |
| 44 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/cake-docs-search/requirements.txt" desc="pip requirements file; a header would be parsed as a dependency line."/> | 56 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/cake-docs-search/requirements.txt" desc="pip requirements file; a header would be parsed as a dependency line."/> |
| 45 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/op-dashboard/assets/chart.umd.min.js" desc="Third-party Chart.js 4.4.7 (MIT), vendored minified build; keeps its upstream notice."/> | 57 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/op-dashboard/assets/chart.umd.min.js" desc="Third-party Chart.js 4.4.7 (MIT), vendored minified build; keeps its upstream notice."/> |
| 58 | + <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/tl_helper.h" desc="Derived from tile-ai/tilelang-ascend common.h and Huawei Catlass; the file records that provenance and the upstream CANN Open Software License 1.0 notice, exempt from CANN-2.0 header policy."/> | ||
| 59 | + <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-host-bridge/templates/op_project_skeleton/op_kernel/tl_helper.h" desc="Derived from tile-ai/tilelang-ascend common.h and Huawei Catlass; the file records that provenance and the upstream CANN Open Software License 1.0 notice, exempt from CANN-2.0 header policy."/> | ||
| 60 | + <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-host-bridge/templates/op_project_skeleton/framework/tf_plugin/tensorflow_op_template_plugin.cc" desc="Part of the MindStudio project, offered under Mulan PSL v2; the file retains the upstream notice, exempt from CANN-2.0 header policy."/> | ||
| 61 | + <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-host-bridge/templates/pybind_verify/csrc/pytorch_npu_helper.hpp" desc="torch_npu helper header vendored from gitee.com/ascend/pytorch under BSD-3-Clause; retains the upstream notice, exempt from CANN-2.0 header policy."/> | ||
| 46 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/simt-codegen/references/operator_examples/torch_gather_20_20/gather_custom_tiling.h" desc="Part of the MindStudio project, offered under Mulan PSL v2; the file retains the upstream notice, exempt from CANN-2.0 header policy."/> | 62 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/simt-codegen/references/operator_examples/torch_gather_20_20/gather_custom_tiling.h" desc="Part of the MindStudio project, offered under Mulan PSL v2; the file retains the upstream notice, exempt from CANN-2.0 header policy."/> |
| 47 | <filteritem type="filepath" name="plugins-community/model-recommend-infer-optimize/framework/.*" desc="Bundled GE_SESSION_DEMO inference sample retains upstream Apache-2.0 licensing (LICENSE/NOTICE shipped under framework/); exempt from repository CANN-2.0 header policy."/> | 63 | <filteritem type="filepath" name="plugins-community/model-recommend-infer-optimize/framework/.*" desc="Bundled GE_SESSION_DEMO inference sample retains upstream Apache-2.0 licensing (LICENSE/NOTICE shipped under framework/); exempt from repository CANN-2.0 header policy."/> |
| 48 | </filefilter> | 64 | </filefilter> |
| @@ -56,6 +72,10 @@ | |||
| 56 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/requirements.txt" desc="pip requirements file; a header would be parsed as a dependency line."/> | 72 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/requirements.txt" desc="pip requirements file; a header would be parsed as a dependency line."/> |
| 57 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/cake-docs-search/requirements.txt" desc="pip requirements file; a header would be parsed as a dependency line."/> | 73 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/cake-docs-search/requirements.txt" desc="pip requirements file; a header would be parsed as a dependency line."/> |
| 58 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/op-dashboard/assets/chart.umd.min.js" desc="Third-party Chart.js 4.4.7 (MIT), vendored minified build; keeps its upstream notice."/> | 74 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/op-dashboard/assets/chart.umd.min.js" desc="Third-party Chart.js 4.4.7 (MIT), vendored minified build; keeps its upstream notice."/> |
| 75 | + <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/tl_helper.h" desc="Derived from tile-ai/tilelang-ascend common.h and Huawei Catlass; the file records that provenance and the upstream CANN Open Software License 1.0 notice, exempt from CANN-2.0 header policy."/> | ||
| 76 | + <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-host-bridge/templates/op_project_skeleton/op_kernel/tl_helper.h" desc="Derived from tile-ai/tilelang-ascend common.h and Huawei Catlass; the file records that provenance and the upstream CANN Open Software License 1.0 notice, exempt from CANN-2.0 header policy."/> | ||
| 77 | + <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-host-bridge/templates/op_project_skeleton/framework/tf_plugin/tensorflow_op_template_plugin.cc" desc="Part of the MindStudio project, offered under Mulan PSL v2; the file retains the upstream notice, exempt from CANN-2.0 header policy."/> | ||
| 78 | + <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-host-bridge/templates/pybind_verify/csrc/pytorch_npu_helper.hpp" desc="torch_npu helper header vendored from gitee.com/ascend/pytorch under BSD-3-Clause; retains the upstream notice, exempt from CANN-2.0 header policy."/> | ||
| 59 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/simt-codegen/references/operator_examples/torch_gather_20_20/gather_custom_tiling.h" desc="Part of the MindStudio project; the file retains the upstream Huawei copyright line from MindStudio rather than this repository's own."/> | 79 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/simt-codegen/references/operator_examples/torch_gather_20_20/gather_custom_tiling.h" desc="Part of the MindStudio project; the file retains the upstream Huawei copyright line from MindStudio rather than this repository's own."/> |
| 60 | <filteritem type="filepath" name="plugins-community/model-recommend-infer-optimize/framework/.*" desc="Bundled GE_SESSION_DEMO inference sample retains upstream Apache-2.0 licensing (LICENSE/NOTICE shipped under framework/); exempt from repository CANN-2.0 header policy."/> | 80 | <filteritem type="filepath" name="plugins-community/model-recommend-infer-optimize/framework/.*" desc="Bundled GE_SESSION_DEMO inference sample retains upstream Apache-2.0 licensing (LICENSE/NOTICE shipped under framework/); exempt from repository CANN-2.0 header policy."/> |
| 61 | </filefilter> | 81 | </filefilter> |
| @@ -121,6 +141,10 @@ | |||
| 121 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/README.OpenSource" desc="Third-party component register in JSON; a header would break the array."/> | 141 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/README.OpenSource" desc="Third-party component register in JSON; a header would break the array."/> |
| 122 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/requirements.txt" desc="pip requirements file; a header would be parsed as a dependency line."/> | 142 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/requirements.txt" desc="pip requirements file; a header would be parsed as a dependency line."/> |
| 123 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/cake-docs-search/requirements.txt" desc="pip requirements file; a header would be parsed as a dependency line."/> | 143 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/cake-docs-search/requirements.txt" desc="pip requirements file; a header would be parsed as a dependency line."/> |
| 144 | + <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-kernel-baseline/templates/tl_helper.h" desc="Derived from tile-ai/tilelang-ascend common.h and Huawei Catlass; the file records that provenance and the upstream CANN Open Software License 1.0 notice, exempt from CANN-2.0 header policy."/> | ||
| 145 | + <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-host-bridge/templates/op_project_skeleton/op_kernel/tl_helper.h" desc="Derived from tile-ai/tilelang-ascend common.h and Huawei Catlass; the file records that provenance and the upstream CANN Open Software License 1.0 notice, exempt from CANN-2.0 header policy."/> | ||
| 146 | + <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-host-bridge/templates/op_project_skeleton/framework/tf_plugin/tensorflow_op_template_plugin.cc" desc="Part of the MindStudio project, offered under Mulan PSL v2; the file retains the upstream notice, exempt from CANN-2.0 header policy."/> | ||
| 147 | + <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/tilelang-host-bridge/templates/pybind_verify/csrc/pytorch_npu_helper.hpp" desc="torch_npu helper header vendored from gitee.com/ascend/pytorch under BSD-3-Clause; retains the upstream notice, exempt from CANN-2.0 header policy."/> | ||
| 124 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/simt-codegen/references/operator_examples/torch_gather_20_20/gather_custom_tiling.h" desc="Part of the MindStudio project, offered under Mulan PSL v2; the file retains the upstream notice, exempt from CANN-2.0 header policy."/> | 148 | <filteritem type="filepath" name="plugins-community/collaborative-agent-kernel-evolution/skills/simt-codegen/references/operator_examples/torch_gather_20_20/gather_custom_tiling.h" desc="Part of the MindStudio project, offered under Mulan PSL v2; the file retains the upstream notice, exempt from CANN-2.0 header policy."/> |
| 125 | </filefilter> | 149 | </filefilter> |
| 126 | <filefilter name="readmeFileNamePolicyFilter" desc="Filters for README file policies"> | 150 | <filefilter name="readmeFileNamePolicyFilter" desc="Filters for README file policies"> |
| @@ -15,7 +15,7 @@ | |||
| 15 | "Version Number": "vendored", | 15 | "Version Number": "vendored", |
| 16 | "Owner": "Huawei Technologies Co., Ltd", | 16 | "Owner": "Huawei Technologies Co., Ltd", |
| 17 | "Upstream URL": "https://gitee.com/ascend/samples", | 17 | "Upstream URL": "https://gitee.com/ascend/samples", |
| 18 | - "Description": "The torch_npu path discovery and source collection block in skills/ascendc-evaluation/scripts/template/CppExtension/setup.py is taken from operator/ascendc/0_introduction/1_add_frameworklaunch/CppExtensionInvocation/setup.py." | 18 | + "Description": "The torch_npu path discovery and source collection block is taken from operator/ascendc/0_introduction/1_add_frameworklaunch/CppExtensionInvocation/setup.py. Two copies carry it: skills/ascendc-evaluation/scripts/template/CppExtension/setup.py and skills/tilelang-host-bridge/templates/pybind_verify/setup.py; both record the provenance in a header comment." |
| 19 | }, | 19 | }, |
| 20 | { | 20 | { |
| 21 | "Name": "torch_npu PyTorch NPU helper header", | 21 | "Name": "torch_npu PyTorch NPU helper header", |
| @@ -24,7 +24,7 @@ | |||
| 24 | "Version Number": "vendored", | 24 | "Version Number": "vendored", |
| 25 | "Owner": "Huawei Technologies Co., Ltd", | 25 | "Owner": "Huawei Technologies Co., Ltd", |
| 26 | "Upstream URL": "https://gitee.com/ascend/pytorch", | 26 | "Upstream URL": "https://gitee.com/ascend/pytorch", |
| 27 | - "Description": "skills/ascendc-evaluation/scripts/template/CppExtension/csrc/pytorch_npu_helper.hpp is the torch_npu helper header, vendored for the pybind operator template. It retains its upstream BSD-3-Clause notice; the same file is registered under the identical terms elsewhere in this plugin family." | 27 | + "Description": "Two vendored copies of the torch_npu helper header: skills/ascendc-evaluation/scripts/template/CppExtension/csrc/pytorch_npu_helper.hpp and skills/tilelang-host-bridge/templates/pybind_verify/csrc/pytorch_npu_helper.hpp. Both retain the upstream BSD-3-Clause notice and are used by the pybind operator templates." |
| 28 | }, | 28 | }, |
| 29 | { | 29 | { |
| 30 | "Name": "Chart.js", | 30 | "Name": "Chart.js", |
| @@ -35,6 +35,24 @@ | |||
| 35 | "Upstream URL": "https://www.chartjs.org", | 35 | "Upstream URL": "https://www.chartjs.org", |
| 36 | "Description": "Vendored minified UMD build used by the op-dashboard skill to render evaluation charts offline. The MIT notice is retained in the file banner." | 36 | "Description": "Vendored minified UMD build used by the op-dashboard skill to render evaluation charts offline. The MIT notice is retained in the file banner." |
| 37 | }, | 37 | }, |
| 38 | + { | ||
| 39 | + "Name": "TileLang-Ascend AscendC common header", | ||
| 40 | + "License": "CANN Open Software License Agreement Version 1.0", | ||
| 41 | + "License File": "skills/tilelang-kernel-baseline/templates/tl_helper.h", | ||
| 42 | + "Version Number": "e74c06b4d903f2c418a7a4d5712d5afa9b80f841", | ||
| 43 | + "Owner": "tile-ai (TileLang-Ascend); original Catlass: Huawei Technologies Co., Ltd", | ||
| 44 | + "Upstream URL": "https://github.com/tile-ai/tilelang-ascend", | ||
| 45 | + "Description": "skills/tilelang-kernel-baseline/templates/tl_helper.h and skills/tilelang-host-bridge/templates/op_project_skeleton/op_kernel/tl_helper.h are derived from TileLang-Ascend's tl_templates/ascend/common.h, which itself derives from Huawei Catlass (CANN Open Software License 1.0). Both files record that provenance in their banner. The pinned upstream commit and branch (ascendc_pto) are recorded in skills/tlcheck/tl_pin.env, which is the single source of truth used by the tlcheck environment resolver." | ||
| 46 | + }, | ||
| 47 | + { | ||
| 48 | + "Name": "MindStudio TensorFlow operator plugin template", | ||
| 49 | + "License": "Mulan PSL v2", | ||
| 50 | + "License File": "skills/tilelang-host-bridge/templates/op_project_skeleton/framework/tf_plugin/tensorflow_op_template_plugin.cc", | ||
| 51 | + "Version Number": "vendored", | ||
| 52 | + "Owner": "Huawei Technologies Co., Ltd", | ||
| 53 | + "Upstream URL": "https://www.hiascend.com/developer/mindstudio", | ||
| 54 | + "Description": "skills/tilelang-host-bridge/templates/op_project_skeleton/framework/tf_plugin/tensorflow_op_template_plugin.cc is the TensorFlow operator plugin template emitted by MindStudio's operator project generator. It retains the upstream Mulan PSL v2 notice and the license URL." | ||
| 55 | + }, | ||
| 38 | { | 56 | { |
| 39 | "Name": "MindStudio operator tiling header template", | 57 | "Name": "MindStudio operator tiling header template", |
| 40 | "License": "Mulan PSL v2", | 58 | "License": "Mulan PSL v2", |
| @@ -43,5 +61,41 @@ | |||
| 43 | "Owner": "Huawei Technologies Co., Ltd", | 61 | "Owner": "Huawei Technologies Co., Ltd", |
| 44 | "Upstream URL": "https://www.hiascend.com/developer/mindstudio", | 62 | "Upstream URL": "https://www.hiascend.com/developer/mindstudio", |
| 45 | "Description": "skills/simt-codegen/references/operator_examples/torch_gather_20_20/gather_custom_tiling.h is the operator tiling header emitted by MindStudio's operator project generator and kept as a reference example for the SIMT route. It retains the upstream Mulan PSL v2 notice and the license URL." | 63 | "Description": "skills/simt-codegen/references/operator_examples/torch_gather_20_20/gather_custom_tiling.h is the operator tiling header emitted by MindStudio's operator project generator and kept as a reference example for the SIMT route. It retains the upstream Mulan PSL v2 notice and the license URL." |
| 64 | + }, | ||
| 65 | + { | ||
| 66 | + "Name": "TileLang-Ascend QuantMatmul GEMM pattern acknowledgement", | ||
| 67 | + "License": "MIT", | ||
| 68 | + "License File": "skills/tilelang-kernel-baseline/templates/kernel_examples/conv2d_im2col_gemm_shape_specialized.py", | ||
| 69 | + "Version Number": "272c0ab3928df30f84d7ac644456856366ff60c4; 644aa5366cb92b1c65d9dc500598a41c48510dd2 (SCA comparison revisions)", | ||
| 70 | + "Owner": "Tile-AI", | ||
| 71 | + "Upstream URL": "https://github.com/tile-ai/tilelang-ascend/blob/272c0ab3928df30f84d7ac644456856366ff60c4/examples/quant_batch_matmul/example_quant_matmul.py", | ||
| 72 | + "Description": "Acknowledges the shared allocation/copy/accumulation scaffold in the fp16 im2col GEMM template. The complete upstream MIT notice is retained inline. This revision is the SCA comparison reference, not a claim about the original import revision. The template retains its local fork/adaptation history and its CANN-2.0 notice for local contributions. The additional v0.1.0-pre-release comparison identifies the same upstream QuantMatmul example, whose root MIT notice was also verified." | ||
| 73 | + }, | ||
| 74 | + { | ||
| 75 | + "Name": "TileLang-Ascend flash-attention reference patterns", | ||
| 76 | + "License": "MIT", | ||
| 77 | + "License File": "skills/tilelang-kernel-baseline/templates/kernel_examples/asymmetric_attention_mla.py", | ||
| 78 | + "Version Number": "9da16d6646f8b0f21cc5f90763ef06b25749ea3a (SCA comparison revision)", | ||
| 79 | + "Owner": "Tile-AI", | ||
| 80 | + "Upstream URL": "https://github.com/tile-ai/tilelang-ascend/blob/9da16d6646f8b0f21cc5f90763ef06b25749ea3a/examples/flash_attention/fa_opt/flash_attn_bhsd_auto_pipeline_h32_d512.py", | ||
| 81 | + "Description": "The two standalone attention templates retain the upstream MIT notice inline and document their existing local fork/adaptation history; kernel calculations are unchanged. Files: skills/tilelang-kernel-baseline/templates/kernel_examples/asymmetric_attention_mla.py, skills/tilelang-kernel-baseline/templates/kernel_examples/cv_fusion_mha_symbolic.py. Comparison revisions do not establish the original import revision." | ||
| 82 | + }, | ||
| 83 | + { | ||
| 84 | + "Name": "TileLang-Ascend QuantMatmul reference", | ||
| 85 | + "License": "MIT", | ||
| 86 | + "License File": "skills/tilelang-kernel-baseline/templates/kernel_examples/cv_fusion_quant_gemm_shape_specialized.py", | ||
| 87 | + "Version Number": "272c0ab3928df30f84d7ac644456856366ff60c4 (SCA comparison revision)", | ||
| 88 | + "Owner": "Tile-AI", | ||
| 89 | + "Upstream URL": "https://github.com/tile-ai/tilelang-ascend/blob/272c0ab3928df30f84d7ac644456856366ff60c4/examples/quant_batch_matmul/example_quant_matmul.py", | ||
| 90 | + "Description": "The template explicitly records its fork of the upstream quantized GEMM example and retains the complete MIT notice inline. Files: skills/tilelang-kernel-baseline/templates/kernel_examples/cv_fusion_quant_gemm_shape_specialized.py. Comparison revisions do not establish the original import revision." | ||
| 91 | + }, | ||
| 92 | + { | ||
| 93 | + "Name": "TileLang-Ascend GEMM intrinsic reference", | ||
| 94 | + "License": "MIT", | ||
| 95 | + "License File": "skills/tilelang-kernel-baseline/templates/gemm_expert.py", | ||
| 96 | + "Version Number": "63bef063c5453fa0fa88444606d06c89a16eca8b (SCA comparison revision)", | ||
| 97 | + "Owner": "Tile-AI", | ||
| 98 | + "Upstream URL": "https://github.com/tile-ai/tilelang-ascend/blob/63bef063c5453fa0fa88444606d06c89a16eca8b/examples/gemm/example_gemm_intrinsic.py", | ||
| 99 | + "Description": "The template documents its basis in the official GEMM intrinsic example and retains the complete MIT notice inline. SCA identifies the release package METADATA as its comparison source; the original package metadata was not available for byte-level verification. Files: skills/tilelang-kernel-baseline/templates/gemm_expert.py. Comparison revisions do not establish the original import revision." | ||
| 46 | } | 100 | } |
| 47 | ] | 101 | ] |
| @@ -1,6 +1,8 @@ | |||
| 1 | { | 1 | { |
| 2 | "skillsRepository": "vendor/cannbot-skills", | 2 | "skillsRepository": "vendor/cannbot-skills", |
| 3 | "skillInstallMode": "symlink", | 3 | "skillInstallMode": "symlink", |
| 4 | - "skills": [], | 4 | + "skills": [ |
| 5 | + "ops/ascendc-tiling-design" | ||
| 6 | + ], | ||
| 5 | "preserveSkillInvocationPolicy": true | 7 | "preserveSkillInvocationPolicy": true |
| 6 | } | 8 | } |
| @@ -0,0 +1,62 @@ | |||
| 1 | +--- | ||
| 2 | +name: env-probe | ||
| 3 | +disable-model-invocation: true | ||
| 4 | +description: Probe the current Ascend NPU/CANN environment and write a reusable env.json contract. Use when CAKE stages or downstream skills need the live SoC, core counts, memory sizes, CANN version, or remote/local execution mode instead of hardcoded defaults. | ||
| 5 | +--- | ||
| 6 | + | ||
| 7 | +# Env Probe | ||
| 8 | + | ||
| 9 | +## Purpose | ||
| 10 | + | ||
| 11 | +Use this skill before any hardware-dependent CAKE stage. It probes the actual | ||
| 12 | +local or remote NPU environment, writes `env.json`, and makes the result | ||
| 13 | +available to downstream skills. | ||
| 14 | + | ||
| 15 | +Do not reuse a stale `env.json` without re-probing. Hardware, remote targets, | ||
| 16 | +visible devices, and CANN installs can change between runs. | ||
| 17 | + | ||
| 18 | +## Probe | ||
| 19 | + | ||
| 20 | +Local probe: | ||
| 21 | + | ||
| 22 | +```bash | ||
| 23 | +python3 ${CLAUDE_SKILL_DIR}/scripts/probe_env.py \ | ||
| 24 | + --write output/{op_name}/env.json | ||
| 25 | +``` | ||
| 26 | + | ||
| 27 | +Remote probe through `.npus.yaml`: | ||
| 28 | + | ||
| 29 | +```bash | ||
| 30 | +python3 ${CLAUDE_SKILL_DIR}/scripts/probe_env.py \ | ||
| 31 | + --target <target> \ | ||
| 32 | + --write output/{op_name}/env.json | ||
| 33 | +``` | ||
| 34 | + | ||
| 35 | +The command always prints the JSON envelope to stdout. With `--write`, it also | ||
| 36 | +writes formatted JSON atomically to the requested path, creating parent | ||
| 37 | +directories when needed. | ||
| 38 | + | ||
| 39 | +## Failure Policy | ||
| 40 | + | ||
| 41 | +If the probe exits non-zero, stop and ask the user how to proceed. Do not | ||
| 42 | +invent a default SoC. | ||
| 43 | + | ||
| 44 | +If the command exits zero but fields such as `soc_version`, `ub_size`, or | ||
| 45 | +`vector_core_cnt` are `null`, treat those fields as unknown. Downstream skills | ||
| 46 | +must not silently substitute `Ascend910B2`, `48`, `192 KB`, or any other default. | ||
| 47 | + | ||
| 48 | +## Consumers | ||
| 49 | + | ||
| 50 | +Downstream skills should read `output/{op_name}/env.json` before making | ||
| 51 | +hardware-dependent decisions: | ||
| 52 | + | ||
| 53 | +- `soc_version`: build target, CANN package path, Catlass target | ||
| 54 | +- `cube_core_cnt` / `vector_core_cnt`: block/core scheduling | ||
| 55 | +- `ub_size`, `l1_size`, `l0a_size`, `l0b_size`, `l0c_size`, `l2_size`: tiling and buffer budgets | ||
| 56 | +- `cann_version`: diagnostics and compatibility notes | ||
| 57 | +- `mode`: local or remote execution | ||
| 58 | +- `perf` (schema 2+): roofline anchors — `aic_freq_hz`, `hbm_bw_bytes_per_s`, | ||
| 59 | + `l2_bw_bytes_per_s`, `cube_peak_flops_fp16` — for the cost model / performance | ||
| 60 | + ceiling analysis. `null` when the SoC has no spec entry (never fabricated). | ||
| 61 | + | ||
| 62 | +Schema and field semantics are documented in @references/env-json-schema.md. | ||
| @@ -0,0 +1,96 @@ | |||
| 1 | +# Environment Config Contract | ||
| 2 | + | ||
| 3 | +`env.json` is the cross-skill contract for the live Ascend NPU/CANN | ||
| 4 | +environment. CAKE stage 0 should re-probe and write it before downstream skills | ||
| 5 | +make hardware-dependent decisions. | ||
| 6 | + | ||
| 7 | +## Producer | ||
| 8 | + | ||
| 9 | +Local: | ||
| 10 | + | ||
| 11 | +```bash | ||
| 12 | +python3 skills/env-probe/scripts/probe_env.py --write output/<op_name>/env.json | ||
| 13 | +``` | ||
| 14 | + | ||
| 15 | +Remote through `.npus.yaml`: | ||
| 16 | + | ||
| 17 | +```bash | ||
| 18 | +python3 skills/env-probe/scripts/probe_env.py --target <target> --write output/<op_name>/env.json | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +The probe detects SoC from live `npu-smi` output first. Legacy Board ID mapping | ||
| 22 | +is only a last resort. TBE platform APIs are used, when available, to fill core | ||
| 23 | +counts and memory sizes. | ||
| 24 | + | ||
| 25 | +## Policy | ||
| 26 | + | ||
| 27 | +Always re-probe for each run. Do not trust an old `env.json` across local/remote | ||
| 28 | +switches, target changes, visible-device changes, or CANN upgrades. | ||
| 29 | + | ||
| 30 | +If `soc_version` is `null`, stop and ask the user. Do not fall back to a | ||
| 31 | +hardcoded SoC such as `Ascend910B2`. | ||
| 32 | + | ||
| 33 | +If a memory/core field is `null`, treat it as unknown. Do not substitute default | ||
| 34 | +UB/L1/core counts silently. | ||
| 35 | + | ||
| 36 | +## Schema | ||
| 37 | + | ||
| 38 | +| Field | Type | Meaning | | ||
| 39 | +| --- | --- | --- | | ||
| 40 | +| `schema_version` | int | Contract version. Currently `2` (added the `perf` block). | | ||
| 41 | +| `probed_at` | int | Unix timestamp of the probe. | | ||
| 42 | +| `mode` | `"local"` or `"remote"` | Where the probe ran. | | ||
| 43 | +| `target` | string, optional | Remote target name when `mode == "remote"`. | | ||
| 44 | +| `soc_version` | string or null | Full SoC name, for example `Ascend910B2`. | | ||
| 45 | +| `soc_source` | string or null | Detection source: `npu-smi-top`, `npu-smi-product`, `npu-smi-common`, `npu-smi-board`, `board-id-fallback`, or `none`. | | ||
| 46 | +| `board_id` | string or null | Diagnostic Board ID from `npu-smi`, if available. | | ||
| 47 | +| `aicore_count` | int or null | AI core count reported by `npu-smi -t common`. | | ||
| 48 | +| `cube_core_cnt` | int or null | Cube core count from TBE platform APIs. | | ||
| 49 | +| `vector_core_cnt` | int or null | Vector core count from TBE platform APIs. | | ||
| 50 | +| `ub_size` | int or null | UB size in bytes. | | ||
| 51 | +| `l1_size` | int or null | L1 size in bytes. | | ||
| 52 | +| `l0a_size` | int or null | L0A size in bytes. | | ||
| 53 | +| `l0b_size` | int or null | L0B size in bytes. | | ||
| 54 | +| `l0c_size` | int or null | L0C size in bytes. | | ||
| 55 | +| `l2_size` | int or null | L2 size in bytes. | | ||
| 56 | +| `cann_version` | string or null | CANN toolkit version, if detectable. | | ||
| 57 | +| `perf` | object | Roofline / performance-ceiling spec block (schema 2+). See below. | | ||
| 58 | +| `warnings` | list[string] | Probe warnings. Non-empty warnings do not necessarily mean failure. | | ||
| 59 | + | ||
| 60 | +### `perf` block (roofline anchors) | ||
| 61 | + | ||
| 62 | +Physical specs that cannot be derived from core counts and are not exposed by | ||
| 63 | +TBE. Populated from an inline SoC spec table in `npu_probe.py` (keyed by | ||
| 64 | +lowercased `soc_version` prefix, longest match wins). An unknown SoC yields all | ||
| 65 | +`null` perf fields plus a `perf_spec_missing` warning — never a fabricated | ||
| 66 | +value. To support a new SoC, add an entry to `_SOC_PERF_SPEC` in | ||
| 67 | +`skills/env-probe/scripts/npu_probe.py` (the table is inline, not a sibling | ||
| 68 | +file, because the probe source is shipped over SSH and run via heredoc on the | ||
| 69 | +remote host). | ||
| 70 | + | ||
| 71 | +| Field | Type | Meaning | | ||
| 72 | +| --- | --- | --- | | ||
| 73 | +| `aic_freq_hz` | int or null | AI Core clock in Hz. | | ||
| 74 | +| `hbm_bw_bytes_per_s` | int or null | HBM/GM peak bandwidth (memory roofline). | | ||
| 75 | +| `l2_bw_bytes_per_s` | int or null | L2 peak bandwidth. | | ||
| 76 | +| `cube_macs_per_cycle_per_core` | int or null | Cube MACs/cycle/core (16×16×16 = 4096). | | ||
| 77 | +| `cube_peak_macs_per_s` | int or null | Derived: `cube_core_cnt × aic_freq_hz × cube_macs_per_cycle_per_core`. Null when `cube_core_cnt` is unknown. | | ||
| 78 | +| `cube_peak_flops_fp16` | int or null | Derived: `cube_peak_macs_per_s × 2` (1 MAC = 2 FLOPs). | | ||
| 79 | +| `source` | string or null | `soc-perf-table` when matched, `none` when no spec entry. | | ||
| 80 | +| `confidence` | string or null | `spec` (from datasheet/docs) or `estimated`. | | ||
| 81 | + | ||
| 82 | +These anchors drive the P1 cost model (arithmetic intensity, roofline position, | ||
| 83 | +theoretical lower-bound time). Memory T_min = `total_bytes / hbm_bw_bytes_per_s`; | ||
| 84 | +cube compute T_min = `MNK / cube_peak_macs_per_s`. | ||
| 85 | + | ||
| 86 | +## Consumers | ||
| 87 | + | ||
| 88 | +Read `output/<op_name>/env.json` before choosing hardware-dependent values: | ||
| 89 | + | ||
| 90 | +- `ascendc-tiling-design`: UB/L1/L0 sizes and core counts | ||
| 91 | +- `dsl-lowering` and `dsl-lowering-cv`: SoC and memory constraints | ||
| 92 | +- `ascend-call-generation` and `ascend-call-generation-cv`: block/core counts and target SoC | ||
| 93 | +- `dsl-baseline-generation` and `dsl-baseline-generation-cv`: buffer budgets and core counts | ||
| 94 | +- `ascendc-evaluation`: build/deploy SoC and diagnostics | ||
| 95 | +- `code-performance-advisor`: hardware budgets for performance advice | ||
| 96 | +- `kernel-optimization-workflow`: build `--soc` and kernel path selection | ||
| @@ -0,0 +1,400 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 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 | +"""Probe the current NPU host and emit an env.json envelope on stdout. | ||
| 13 | + | ||
| 14 | +This script is intentionally self-contained and stdlib-only at import time so | ||
| 15 | +it can be piped over SSH and executed on the host that owns the NPU. Optional | ||
| 16 | +TBE APIs are imported lazily; failures produce null fields plus warnings rather | ||
| 17 | +than aborting the probe. | ||
| 18 | +""" | ||
| 19 | + | ||
| 20 | +from __future__ import annotations | ||
| 21 | + | ||
| 22 | +import json | ||
| 23 | +import logging | ||
| 24 | +import os | ||
| 25 | +import re | ||
| 26 | +import shutil | ||
| 27 | +import subprocess | ||
| 28 | +import sys | ||
| 29 | +import time | ||
| 30 | +from typing import Any | ||
| 31 | + | ||
| 32 | +# stdout 上的 env.json 是本脚本的输出契约,用专属 logger 发出(G.LOG.02)。 | ||
| 33 | +# 格式串只有 %(message)s,故写出的字节与原先的 print 一致。 | ||
| 34 | +_LOG = logging.getLogger(__name__ + ".stdout") | ||
| 35 | +if not _LOG.handlers: | ||
| 36 | + _handler = logging.StreamHandler(sys.stdout) | ||
| 37 | + _handler.setFormatter(logging.Formatter("%(message)s")) | ||
| 38 | + _LOG.addHandler(_handler) | ||
| 39 | + _LOG.setLevel(logging.INFO) | ||
| 40 | + _LOG.propagate = False | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +# `npu-smi info` walks every chip on the host, so its runtime grows with card | ||
| 44 | +# count — 70 s measured on an 8-card 910B2, and every `-t <subcmd>` variant on | ||
| 45 | +# that host took 12-24 s. A timeout below the slowest call is not a partial | ||
| 46 | +# result: `_run` returns "" and the caller emits an env.json whose soc_version | ||
| 47 | +# and entire perf block are null, which downstream tiling and roofline steps | ||
| 48 | +# then have to treat as unknown. Ceiling is generous and overridable. | ||
| 49 | +_NPU_SMI_TIMEOUT_S = float(os.environ.get("CAKE_NPU_SMI_TIMEOUT", "120")) | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +def _exe(name: str) -> str: | ||
| 53 | + """外部程序按绝对路径调用 (G.EDV.05)。PATH 上解析不到时退回裸名, | ||
| 54 | + 行为与原先交给 execvp 解析完全相同。""" | ||
| 55 | + return shutil.which(name) or name | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +def _run(cmd: list[str]) -> str: | ||
| 59 | + try: | ||
| 60 | + result = subprocess.run( | ||
| 61 | + cmd, | ||
| 62 | + capture_output=True, | ||
| 63 | + text=True, | ||
| 64 | + timeout=_NPU_SMI_TIMEOUT_S, | ||
| 65 | + shell=False, | ||
| 66 | + ) | ||
| 67 | + except Exception: | ||
| 68 | + return "" | ||
| 69 | + if result.returncode != 0: | ||
| 70 | + return result.stdout or "" | ||
| 71 | + return result.stdout or "" | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +_LEGACY_BOARD_ID_FALLBACK = { | ||
| 75 | + "0x60": "Ascend910B2", | ||
| 76 | + "0x61": "Ascend910B1", | ||
| 77 | + "0x20": "Ascend910A", | ||
| 78 | + "0x30": "Ascend310P3", | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +# --------------------------------------------------------------------------- | ||
| 82 | +# Roofline / performance-ceiling spec table. | ||
| 83 | +# | ||
| 84 | +# These physical specs (clock, HBM/L2 peak bandwidth, cube MAC throughput) | ||
| 85 | +# CANNOT be derived from core counts alone and are not exposed by the TBE | ||
| 86 | +# platform APIs, so they are tabulated here. Keyed by a lowercased soc-family | ||
| 87 | +# prefix; lookup uses longest-prefix match against `soc_version`. | ||
| 88 | +# | ||
| 89 | +# IMPORTANT: this table is embedded inline (not a sibling data file) on purpose | ||
| 90 | +# — `probe_env.py` ships this script's source over SSH and runs it via a | ||
| 91 | +# heredoc on the remote host, where sibling files are not present. | ||
| 92 | +# | ||
| 93 | +# Values are best-effort from public CANN material and in-repo references | ||
| 94 | +# (e.g. skills/ascendc-tiling-design/references/matmul/cube-perf-path.md). | ||
| 95 | +# `confidence`: "spec" means from datasheet/docs; "estimated" means derived or approximate. | ||
| 96 | +# Unknown SoCs intentionally resolve to null perf fields + a warning rather | ||
| 97 | +# than a fabricated number. To support a new SoC, add an entry here. | ||
| 98 | +# | ||
| 99 | +# Fields per entry (any may be null when not confidently known): | ||
| 100 | +# aic_freq_hz AI Core clock, Hz | ||
| 101 | +# hbm_bw_bytes_per_s HBM/GM peak bandwidth, bytes/s | ||
| 102 | +# l2_bw_bytes_per_s L2 peak bandwidth, bytes/s | ||
| 103 | +# cube_macs_per_cycle_per_core Cube MACs/cycle/core (16x16x16 = 4096) | ||
| 104 | +# confidence "spec" | "estimated" | ||
| 105 | +_SOC_PERF_SPEC: dict[str, dict[str, Any]] = { | ||
| 106 | + # 910B family (A2). Clock from the in-repo matmul perf-path reference. | ||
| 107 | + "ascend910b": { | ||
| 108 | + "aic_freq_hz": 1_850_000_000, | ||
| 109 | + "hbm_bw_bytes_per_s": 1_800_000_000_000, | ||
| 110 | + "l2_bw_bytes_per_s": 5_000_000_000_000, | ||
| 111 | + "cube_macs_per_cycle_per_core": 4096, | ||
| 112 | + # Vector basic-op throughput in elements/s (add/mul/sub/cast). Special | ||
| 113 | + # transcendentals (exp/log/sqrt/rsqrt) run ~1/2, division ~1/4 (derived | ||
| 114 | + # in the cost model). "estimated" — sourced from cann-bench's SOL | ||
| 115 | + # constants, not a datasheet; cross-check before trusting tight margins. | ||
| 116 | + "vector_basic_eps_fp16": 12_000_000_000_000, | ||
| 117 | + "vector_basic_eps_fp32": 6_000_000_000_000, | ||
| 118 | + "vector_eps_confidence": "estimated", | ||
| 119 | + "confidence": "spec", | ||
| 120 | + }, | ||
| 121 | + # Add 910_93xx (A3/A5-class) and other SKUs here once specs are confirmed. | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | + | ||
| 125 | +def match_perf_spec(soc: str | None) -> tuple[str | None, dict[str, Any] | None]: | ||
| 126 | + """Return (matched_key, spec) using longest lowercased-prefix match.""" | ||
| 127 | + if not soc: | ||
| 128 | + return None, None | ||
| 129 | + needle = soc.lower() | ||
| 130 | + best_key: str | None = None | ||
| 131 | + for key in _SOC_PERF_SPEC: | ||
| 132 | + if not needle.startswith(key): | ||
| 133 | + continue | ||
| 134 | + if best_key is None or len(key) > len(best_key): | ||
| 135 | + best_key = key | ||
| 136 | + if best_key is None: | ||
| 137 | + return None, None | ||
| 138 | + return best_key, _SOC_PERF_SPEC[best_key] | ||
| 139 | + | ||
| 140 | + | ||
| 141 | +def _empty_perf() -> dict[str, Any]: | ||
| 142 | + return { | ||
| 143 | + "aic_freq_hz": None, | ||
| 144 | + "hbm_bw_bytes_per_s": None, | ||
| 145 | + "l2_bw_bytes_per_s": None, | ||
| 146 | + "cube_macs_per_cycle_per_core": None, | ||
| 147 | + "cube_peak_macs_per_s": None, | ||
| 148 | + "cube_peak_flops_fp16": None, | ||
| 149 | + "vector_basic_eps_fp16": None, | ||
| 150 | + "vector_basic_eps_fp32": None, | ||
| 151 | + "l2_cap_bytes": None, | ||
| 152 | + "source": None, | ||
| 153 | + "confidence": None, | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + | ||
| 157 | +def compute_perf(env: dict[str, Any]) -> dict[str, Any]: | ||
| 158 | + """Fill the roofline perf block from the spec table + probed core counts. | ||
| 159 | + | ||
| 160 | + Pure function of `env`; appends a warning to env['warnings'] when the SoC | ||
| 161 | + has no perf spec entry. Derived cube peak throughput needs cube_core_cnt | ||
| 162 | + from the TBE block and stays null when that is unavailable. | ||
| 163 | + """ | ||
| 164 | + perf = _empty_perf() | ||
| 165 | + _, spec = match_perf_spec(env.get("soc_version")) | ||
| 166 | + if spec is None: | ||
| 167 | + perf["source"] = "none" | ||
| 168 | + if env.get("soc_version"): | ||
| 169 | + env["warnings"].append( | ||
| 170 | + "perf_spec_missing: no roofline spec for " | ||
| 171 | + f"{env['soc_version']}; add it to _SOC_PERF_SPEC in npu_probe.py" | ||
| 172 | + ) | ||
| 173 | + return perf | ||
| 174 | + | ||
| 175 | + perf["aic_freq_hz"] = spec.get("aic_freq_hz") | ||
| 176 | + perf["hbm_bw_bytes_per_s"] = spec.get("hbm_bw_bytes_per_s") | ||
| 177 | + perf["l2_bw_bytes_per_s"] = spec.get("l2_bw_bytes_per_s") | ||
| 178 | + perf["cube_macs_per_cycle_per_core"] = spec.get("cube_macs_per_cycle_per_core") | ||
| 179 | + perf["vector_basic_eps_fp16"] = spec.get("vector_basic_eps_fp16") | ||
| 180 | + perf["vector_basic_eps_fp32"] = spec.get("vector_basic_eps_fp32") | ||
| 181 | + # L2 capacity (for the L2-fill-first write model) comes from the probed | ||
| 182 | + # l2_size, not the spec table. | ||
| 183 | + perf["l2_cap_bytes"] = env.get("l2_size") | ||
| 184 | + perf["source"] = "soc-perf-table" | ||
| 185 | + perf["confidence"] = spec.get("confidence") | ||
| 186 | + | ||
| 187 | + freq = perf["aic_freq_hz"] | ||
| 188 | + macs = perf["cube_macs_per_cycle_per_core"] | ||
| 189 | + cube_cores = env.get("cube_core_cnt") | ||
| 190 | + if freq and macs and cube_cores: | ||
| 191 | + peak_macs = int(cube_cores) * int(freq) * int(macs) | ||
| 192 | + perf["cube_peak_macs_per_s"] = peak_macs | ||
| 193 | + # One MAC counts as two FLOPs (one multiply plus one add). | ||
| 194 | + perf["cube_peak_flops_fp16"] = peak_macs * 2 | ||
| 195 | + | ||
| 196 | + return perf | ||
| 197 | + | ||
| 198 | + | ||
| 199 | +# Open-ended on purpose: new SKUs such as 910B4 or 310P4 should be detected | ||
| 200 | +# from npu-smi output without code changes. | ||
| 201 | +_SOC_NAME_RE = re.compile(r"\b(?:Ascend)?(\d{3}(?:[A-Z]\d*|_\d+))\b") | ||
| 202 | +_SOC_NAME_DENYLIST = {"mcu"} | ||
| 203 | + | ||
| 204 | + | ||
| 205 | +def _scan_for_soc(text: str) -> str | None: | ||
| 206 | + for match in _SOC_NAME_RE.finditer(text): | ||
| 207 | + token = match.group(1) | ||
| 208 | + if token.lower() in _SOC_NAME_DENYLIST: | ||
| 209 | + continue | ||
| 210 | + at = match.start() | ||
| 211 | + lead = max(0, at - 6) | ||
| 212 | + prefix = text[lead:at].lower() | ||
| 213 | + return token if prefix.endswith("ascend") else f"Ascend{token}" | ||
| 214 | + return None | ||
| 215 | + | ||
| 216 | + | ||
| 217 | +def _scan_board_id(text: str) -> str | None: | ||
| 218 | + match = re.search(r"Board ID\s*:\s*(0x[0-9a-fA-F]+)", text, re.IGNORECASE) | ||
| 219 | + return match.group(1).lower() if match else None | ||
| 220 | + | ||
| 221 | + | ||
| 222 | +def detect_soc_live() -> tuple[str | None, str | None, str]: | ||
| 223 | + """Return (soc_version, board_id, source).""" | ||
| 224 | + out = _run([_exe("npu-smi"), "info"]) | ||
| 225 | + soc = _scan_for_soc(out) | ||
| 226 | + if soc: | ||
| 227 | + return soc, _scan_board_id(out), "npu-smi-top" | ||
| 228 | + | ||
| 229 | + for subcmd in ("product", "common", "board"): | ||
| 230 | + out = _run([_exe("npu-smi"), "info", "-t", subcmd, "-i", "0"]) | ||
| 231 | + soc = _scan_for_soc(out) | ||
| 232 | + if soc: | ||
| 233 | + return soc, _scan_board_id(out), f"npu-smi-{subcmd}" | ||
| 234 | + | ||
| 235 | + board = _run([_exe("npu-smi"), "info", "-t", "board", "-i", "0"]) | ||
| 236 | + board_id = _scan_board_id(board) | ||
| 237 | + if board_id and board_id in _LEGACY_BOARD_ID_FALLBACK: | ||
| 238 | + return _LEGACY_BOARD_ID_FALLBACK[board_id], board_id, "board-id-fallback" | ||
| 239 | + return None, board_id, "none" | ||
| 240 | + | ||
| 241 | + | ||
| 242 | +def read_aicore_count() -> int | None: | ||
| 243 | + out = _run([_exe("npu-smi"), "info", "-t", "common", "-i", "0"]) | ||
| 244 | + for line in out.splitlines(): | ||
| 245 | + match = re.search(r"Aicore Count\s*:\s*(\d+)", line) | ||
| 246 | + if match: | ||
| 247 | + return int(match.group(1)) | ||
| 248 | + return None | ||
| 249 | + | ||
| 250 | + | ||
| 251 | +def _version_from_line(line: str, kind: str) -> str | None: | ||
| 252 | + """从 version 文件的一行里取 CANN 版本号;该行不含版本信息时返回 None。""" | ||
| 253 | + if kind == "info" and line.startswith("Version="): | ||
| 254 | + return line.split("=", 1)[1].strip().strip('"') | ||
| 255 | + if kind != "cfg" or "toolkit_running_version" not in line: | ||
| 256 | + return None | ||
| 257 | + match = re.search(r"\[([^\]]+)\]", line) | ||
| 258 | + if match: | ||
| 259 | + return match.group(1).strip() | ||
| 260 | + return line.split("=", 1)[-1].strip() | ||
| 261 | + | ||
| 262 | + | ||
| 263 | +def _version_from_file(path: str, kind: str) -> str | None: | ||
| 264 | + """逐行扫一个 version 文件;文件不可读或不含版本号时返回 None。 | ||
| 265 | + | ||
| 266 | + 原先用 FileNotFoundError 与 OSError 两个分支做同一件事,现只留 OSError | ||
| 267 | + (前者是后者的子类,行为不变,也避免重复捕获同类异常)。version 文件只有 | ||
| 268 | + 几行,先整体读入再逐行扫,open 得以留在 with 内且嵌套深度不超限。 | ||
| 269 | + """ | ||
| 270 | + try: | ||
| 271 | + with open(path, encoding="utf-8") as handle: | ||
| 272 | + lines = handle.readlines() | ||
| 273 | + except OSError: | ||
| 274 | + return None | ||
| 275 | + for line in lines: | ||
| 276 | + found = _version_from_line(line, kind) | ||
| 277 | + if found is not None: | ||
| 278 | + return found | ||
| 279 | + return None | ||
| 280 | + | ||
| 281 | + | ||
| 282 | +def read_cann_version() -> str | None: | ||
| 283 | + candidates: list[tuple[str, str]] = [] | ||
| 284 | + ascend_home = os.environ.get("ASCEND_HOME_PATH", "").strip() | ||
| 285 | + if ascend_home: | ||
| 286 | + candidates.append((os.path.join(ascend_home, "compiler/version.info"), "info")) | ||
| 287 | + candidates.append((os.path.join(ascend_home, "opp/version.info"), "info")) | ||
| 288 | + candidates.extend( | ||
| 289 | + [ | ||
| 290 | + ("/usr/local/Ascend/ascend-toolkit/latest/compiler/version.info", "info"), | ||
| 291 | + ("/usr/local/Ascend/ascend-toolkit/latest/opp/version.info", "info"), | ||
| 292 | + ("/usr/local/Ascend/ascend-toolkit/latest/version.cfg", "cfg"), | ||
| 293 | + ("/usr/local/Ascend/ascend-toolkit/version.cfg", "cfg"), | ||
| 294 | + ] | ||
| 295 | + ) | ||
| 296 | + | ||
| 297 | + for path, kind in candidates: | ||
| 298 | + found = _version_from_file(path, kind) | ||
| 299 | + if found is not None: | ||
| 300 | + return found | ||
| 301 | + return None | ||
| 302 | + | ||
| 303 | + | ||
| 304 | +def _empty_envelope() -> dict[str, Any]: | ||
| 305 | + return { | ||
| 306 | + "schema_version": 2, | ||
| 307 | + "probed_at": int(time.time()), | ||
| 308 | + "mode": None, | ||
| 309 | + "soc_version": None, | ||
| 310 | + "soc_source": None, | ||
| 311 | + "board_id": None, | ||
| 312 | + "aicore_count": None, | ||
| 313 | + "cube_core_cnt": None, | ||
| 314 | + "vector_core_cnt": None, | ||
| 315 | + "ub_size": None, | ||
| 316 | + "l1_size": None, | ||
| 317 | + "l0a_size": None, | ||
| 318 | + "l0b_size": None, | ||
| 319 | + "l0c_size": None, | ||
| 320 | + "l2_size": None, | ||
| 321 | + "cann_version": None, | ||
| 322 | + "perf": _empty_perf(), | ||
| 323 | + "warnings": [], | ||
| 324 | + } | ||
| 325 | + | ||
| 326 | + | ||
| 327 | +def _fill_soc(env: dict[str, Any]) -> None: | ||
| 328 | + """探测 SoC 名与 board id;任何失败只记 warning,不中断整次探测。""" | ||
| 329 | + try: | ||
| 330 | + soc, board_id, source = detect_soc_live() | ||
| 331 | + env["soc_version"] = soc | ||
| 332 | + env["board_id"] = board_id | ||
| 333 | + env["soc_source"] = source | ||
| 334 | + if soc is None: | ||
| 335 | + env["warnings"].append( | ||
| 336 | + "soc_detection_failed: npu-smi did not report an Ascend chip name" | ||
| 337 | + ) | ||
| 338 | + elif source == "board-id-fallback": | ||
| 339 | + env["warnings"].append( | ||
| 340 | + f"soc_from_legacy_board_map: board_id={board_id} -> {soc}; verify manually" | ||
| 341 | + ) | ||
| 342 | + except Exception as exc: | ||
| 343 | + env["warnings"].append(f"soc_probe_failed: {exc}") | ||
| 344 | + | ||
| 345 | + | ||
| 346 | +def _fill_tbe_spec(env: dict[str, Any]) -> None: | ||
| 347 | + """从 TBE platform 取核数与各级缓冲容量;无 soc_version 或 TBE 不可用时只记 warning。""" | ||
| 348 | + if not env["soc_version"]: | ||
| 349 | + env["warnings"].append("tbe_spec_skipped: no soc_version to query") | ||
| 350 | + return | ||
| 351 | + try: | ||
| 352 | + from tbe.common.platform import get_soc_spec, set_current_compile_soc_info | ||
| 353 | + from tbe.common.platform import platform_info as pi | ||
| 354 | + | ||
| 355 | + set_current_compile_soc_info(env["soc_version"]) | ||
| 356 | + env["soc_version"] = get_soc_spec(pi.FULL_SOC_VERSION) or env["soc_version"] | ||
| 357 | + env["cube_core_cnt"] = int(get_soc_spec(pi.CUBE_CORE_CNT)) | ||
| 358 | + env["vector_core_cnt"] = int(get_soc_spec(pi.VECTOR_CORE_CNT)) | ||
| 359 | + env["ub_size"] = int(get_soc_spec(pi.UB_SIZE)) | ||
| 360 | + env["l1_size"] = int(get_soc_spec(pi.L1_SIZE)) | ||
| 361 | + env["l0a_size"] = int(get_soc_spec(pi.L0A_SIZE)) | ||
| 362 | + env["l0b_size"] = int(get_soc_spec(pi.L0B_SIZE)) | ||
| 363 | + env["l0c_size"] = int(get_soc_spec(pi.L0C_SIZE)) | ||
| 364 | + env["l2_size"] = int(get_soc_spec(pi.L2_SIZE)) | ||
| 365 | + except Exception as exc: | ||
| 366 | + env["warnings"].append(f"tbe_platform_unavailable: {exc}") | ||
| 367 | + | ||
| 368 | + | ||
| 369 | +def collect_json() -> dict[str, Any]: | ||
| 370 | + env = _empty_envelope() | ||
| 371 | + | ||
| 372 | + _fill_soc(env) | ||
| 373 | + | ||
| 374 | + try: | ||
| 375 | + env["aicore_count"] = read_aicore_count() | ||
| 376 | + except Exception as exc: | ||
| 377 | + env["warnings"].append(f"aicore_count_probe_failed: {exc}") | ||
| 378 | + | ||
| 379 | + _fill_tbe_spec(env) | ||
| 380 | + | ||
| 381 | + try: | ||
| 382 | + env["cann_version"] = read_cann_version() | ||
| 383 | + except Exception as exc: | ||
| 384 | + env["warnings"].append(f"cann_version_probe_failed: {exc}") | ||
| 385 | + | ||
| 386 | + try: | ||
| 387 | + env["perf"] = compute_perf(env) | ||
| 388 | + except Exception as exc: | ||
| 389 | + env["warnings"].append(f"perf_spec_failed: {exc}") | ||
| 390 | + | ||
| 391 | + return env | ||
| 392 | + | ||
| 393 | + | ||
| 394 | +def main() -> int: | ||
| 395 | + _LOG.info(json.dumps(collect_json(), ensure_ascii=True, sort_keys=True)) | ||
| 396 | + return 0 | ||
| 397 | + | ||
| 398 | + | ||
| 399 | +if __name__ == "__main__": | ||
| 400 | + raise SystemExit(main()) | ||
| @@ -0,0 +1,388 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 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 | +"""Probe local or remote Ascend NPU/CANN environment and optionally write env.json.""" | ||
| 13 | + | ||
| 14 | +from __future__ import annotations | ||
| 15 | + | ||
| 16 | +import argparse | ||
| 17 | +import json | ||
| 18 | +import logging | ||
| 19 | +import shutil | ||
| 20 | +import subprocess | ||
| 21 | +import sys | ||
| 22 | +from pathlib import Path | ||
| 23 | +from typing import Any | ||
| 24 | + | ||
| 25 | +# 诊断信息与 stdout 上的 JSON 各走一个专属 logger(G.LOG.02)。stdout 上的 | ||
| 26 | +# JSON 仍是本脚本的输出契约:格式串只有 %(message)s,写出的字节与原先的 print 一致。 | ||
| 27 | +# 这里直接绑定 sys.stderr / sys.stdout,不另立流代理——本模块不存在进程内重定向。 | ||
| 28 | +_ERR = logging.getLogger(__name__ + ".stderr") | ||
| 29 | +if not _ERR.handlers: | ||
| 30 | + _handler = logging.StreamHandler(sys.stderr) | ||
| 31 | + _handler.setFormatter(logging.Formatter("%(message)s")) | ||
| 32 | + _ERR.addHandler(_handler) | ||
| 33 | + _ERR.setLevel(logging.INFO) | ||
| 34 | + _ERR.propagate = False | ||
| 35 | + | ||
| 36 | +_LOG = logging.getLogger(__name__ + ".stdout") | ||
| 37 | +if not _LOG.handlers: | ||
| 38 | + _out_handler = logging.StreamHandler(sys.stdout) | ||
| 39 | + _out_handler.setFormatter(logging.Formatter("%(message)s")) | ||
| 40 | + _LOG.addHandler(_out_handler) | ||
| 41 | + _LOG.setLevel(logging.INFO) | ||
| 42 | + _LOG.propagate = False | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +def _exe(name: str) -> str: | ||
| 46 | + """外部程序按绝对路径调用 (G.EDV.05)。PATH 上解析不到时退回裸名, | ||
| 47 | + 行为与原先交给 execvp 解析完全相同。""" | ||
| 48 | + return shutil.which(name) or name | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +class ProbeError(Exception): | ||
| 52 | + """探测流程中的致命错误。 | ||
| 53 | + | ||
| 54 | + 由 main() 转成进程退出码——sys.exit 与 raise SystemExit 只出现在主入口 | ||
| 55 | + (G.ERR.11)。 | ||
| 56 | + """ | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def find_repo_root(start: Path | None = None) -> Path: | ||
| 60 | + path = (start or Path.cwd()).resolve() | ||
| 61 | + while path != path.parent: | ||
| 62 | + git = path / ".git" | ||
| 63 | + if git.exists(): | ||
| 64 | + return path | ||
| 65 | + path = path.parent | ||
| 66 | + return (start or Path.cwd()).resolve() | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def load_config(path: Path) -> dict[str, Any]: | ||
| 70 | + try: | ||
| 71 | + import yaml | ||
| 72 | + except ImportError as exc: | ||
| 73 | + raise ProbeError( | ||
| 74 | + "Error: remote probing requires PyYAML to read .npus.yaml" | ||
| 75 | + ) from exc | ||
| 76 | + | ||
| 77 | + if not path.is_file(): | ||
| 78 | + raise ProbeError(f"Error: config not found: {path}") | ||
| 79 | + with path.open(encoding="utf-8") as handle: | ||
| 80 | + data = yaml.safe_load(handle) | ||
| 81 | + if data is None: | ||
| 82 | + return {} | ||
| 83 | + if not isinstance(data, dict): | ||
| 84 | + raise ProbeError(f"Error: {path} must contain a YAML mapping") | ||
| 85 | + return data | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +def get_remote( | ||
| 89 | + config: dict[str, Any], target: str | None | ||
| 90 | +) -> tuple[str, dict[str, Any]]: | ||
| 91 | + remotes = config.get("remotes", {}) | ||
| 92 | + if not isinstance(remotes, dict) or not remotes: | ||
| 93 | + raise ProbeError("Error: .npus.yaml must define at least one remote") | ||
| 94 | + name = target or config.get("default") | ||
| 95 | + if not name: | ||
| 96 | + if len(remotes) == 1: | ||
| 97 | + name = next(iter(remotes)) | ||
| 98 | + else: | ||
| 99 | + raise ProbeError( | ||
| 100 | + "Error: specify --target or set 'default' in .npus.yaml. " | ||
| 101 | + f"Available: {', '.join(sorted(remotes))}" | ||
| 102 | + ) | ||
| 103 | + if name not in remotes: | ||
| 104 | + raise ProbeError( | ||
| 105 | + f"Error: remote '{name}' not found. Available: {', '.join(sorted(remotes))}" | ||
| 106 | + ) | ||
| 107 | + remote = remotes[name] | ||
| 108 | + if not isinstance(remote, dict): | ||
| 109 | + raise ProbeError(f"Error: remote '{name}' must be a mapping") | ||
| 110 | + return str(name), remote | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +def ssh_port_args(remote: dict[str, Any]) -> list[str]: | ||
| 114 | + port = remote.get("port") | ||
| 115 | + return ["-p", str(port)] if port else [] | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +def _match_alias(parts: list[str], wanted: str) -> str | None: | ||
| 119 | + """从一行 Host 声明里找出匹配 wanted 的别名;不匹配返回 None。""" | ||
| 120 | + if len(parts) < 2 or parts[0].lower() != "host": | ||
| 121 | + return None | ||
| 122 | + for alias in parts[1:]: | ||
| 123 | + lowered = alias.lower() | ||
| 124 | + if lowered == wanted or lowered.startswith(wanted + "."): | ||
| 125 | + return alias | ||
| 126 | + return None | ||
| 127 | + | ||
| 128 | + | ||
| 129 | +def _hdspace_alias(name: str, config_path: Path) -> str | None: | ||
| 130 | + """在 hdspace 的 ssh config 里找匹配 name 的 Host 别名;找不到返回 None。""" | ||
| 131 | + wanted = name.lower() | ||
| 132 | + with config_path.open(encoding="utf-8") as handle: | ||
| 133 | + for line in handle: | ||
| 134 | + alias = _match_alias(line.strip().split(), wanted) | ||
| 135 | + if alias is not None: | ||
| 136 | + return alias | ||
| 137 | + return None | ||
| 138 | + | ||
| 139 | + | ||
| 140 | +def _resolve_hdspace(remote: dict[str, Any]) -> str: | ||
| 141 | + """hdspace backend:按 name 在 ~/.devenv/.ssh/config 里解析出 Host 别名。""" | ||
| 142 | + name = str(remote.get("name") or "").strip() | ||
| 143 | + if not name: | ||
| 144 | + raise ProbeError("Error: hdspace remote requires 'name'") | ||
| 145 | + config_path = Path.home() / ".devenv" / ".ssh" / "config" | ||
| 146 | + if not config_path.is_file(): | ||
| 147 | + raise ProbeError(f"Error: {config_path} not found. Run hdspace tunnel first.") | ||
| 148 | + alias = _hdspace_alias(name, config_path) | ||
| 149 | + if alias is None: | ||
| 150 | + raise ProbeError( | ||
| 151 | + f"Error: no hdspace host alias matching '{name}' in {config_path}" | ||
| 152 | + ) | ||
| 153 | + return alias | ||
| 154 | + | ||
| 155 | + | ||
| 156 | +def resolve_ssh_host(remote: dict[str, Any]) -> str: | ||
| 157 | + backend = remote.get("backend", "docker") | ||
| 158 | + if backend == "docker" or backend == "immutable": | ||
| 159 | + host = remote.get("host") | ||
| 160 | + if not host: | ||
| 161 | + raise ProbeError(f"Error: {backend} remote requires 'host'") | ||
| 162 | + return str(host) | ||
| 163 | + | ||
| 164 | + if backend == "hdspace": | ||
| 165 | + return _resolve_hdspace(remote) | ||
| 166 | + | ||
| 167 | + raise ProbeError(f"Error: unknown remote backend '{backend}'") | ||
| 168 | + | ||
| 169 | + | ||
| 170 | +def ssh_base(host: str, remote: dict[str, Any]) -> list[str]: | ||
| 171 | + return [_exe("ssh"), *ssh_port_args(remote), host] | ||
| 172 | + | ||
| 173 | + | ||
| 174 | +def shell_single_quote(value: str) -> str: | ||
| 175 | + return "'" + value.replace("'", "'\\''") + "'" | ||
| 176 | + | ||
| 177 | + | ||
| 178 | +def ssh_exec( | ||
| 179 | + host: str, command: str, remote: dict[str, Any] | ||
| 180 | +) -> subprocess.CompletedProcess[str]: | ||
| 181 | + backend = remote.get("backend", "docker") | ||
| 182 | + container = remote.get("container", "") | ||
| 183 | + login_shell = bool(remote.get("login_shell", False)) | ||
| 184 | + base = ssh_base(host, remote) | ||
| 185 | + | ||
| 186 | + if backend == "docker" and container: | ||
| 187 | + shell = "bash -l -c" if login_shell else "bash -c" | ||
| 188 | + inner = shell_single_quote(command) | ||
| 189 | + remote_cmd = ( | ||
| 190 | + f"docker exec -i {shell_single_quote(str(container))} {shell} {inner}" | ||
| 191 | + ) | ||
| 192 | + return subprocess.run( | ||
| 193 | + base + [remote_cmd], | ||
| 194 | + capture_output=True, | ||
| 195 | + text=True, | ||
| 196 | + errors="replace", | ||
| 197 | + shell=False, | ||
| 198 | + ) | ||
| 199 | + | ||
| 200 | + if backend in {"docker", "hdspace", "immutable"}: | ||
| 201 | + shell = ["bash", "-l"] if login_shell or backend == "hdspace" else ["bash"] | ||
| 202 | + return subprocess.run( | ||
| 203 | + base + shell, | ||
| 204 | + input=command, | ||
| 205 | + capture_output=True, | ||
| 206 | + text=True, | ||
| 207 | + errors="replace", | ||
| 208 | + shell=False, | ||
| 209 | + ) | ||
| 210 | + | ||
| 211 | + raise ProbeError(f"Error: unknown remote backend '{backend}'") | ||
| 212 | + | ||
| 213 | + | ||
| 214 | +def build_cann_preamble(remote: dict[str, Any]) -> str: | ||
| 215 | + cann_path = str(remote.get("cann") or "").strip() | ||
| 216 | + lines: list[str] = [] | ||
| 217 | + if cann_path: | ||
| 218 | + lines.append( | ||
| 219 | + f'[ -f "{cann_path}/bin/setenv.bash" ] && source "{cann_path}/bin/setenv.bash"' | ||
| 220 | + ) | ||
| 221 | + lines.append( | ||
| 222 | + f'[ -f "{cann_path}/aarch64-linux/bin/setenv.bash" ] && ' | ||
| 223 | + f'source "{cann_path}/aarch64-linux/bin/setenv.bash"' | ||
| 224 | + ) | ||
| 225 | + lines.append(f'export ASCEND_HOME_PATH="{cann_path}"') | ||
| 226 | + else: | ||
| 227 | + lines.append( | ||
| 228 | + "for p in " | ||
| 229 | + "/home/developer/Ascend/cann-*/aarch64-linux/bin/setenv.bash " | ||
| 230 | + "/usr/local/Ascend/cann-*/bin/setenv.bash " | ||
| 231 | + "/usr/local/Ascend/ascend-toolkit/latest/bin/setenv.bash; " | ||
| 232 | + 'do [ -f "$p" ] && source "$p" && break; done' | ||
| 233 | + ) | ||
| 234 | + lines.append( | ||
| 235 | + "export LD_LIBRARY_PATH=/usr/local/Ascend/driver/lib64/common:" | ||
| 236 | + "/usr/local/Ascend/driver/lib64/driver:" | ||
| 237 | + "/usr/local/Ascend/driver/lib64:${LD_LIBRARY_PATH:-}" | ||
| 238 | + ) | ||
| 239 | + device = remote.get("device_isolate") | ||
| 240 | + if device is not None: | ||
| 241 | + lines.append(f"export ASCEND_RT_VISIBLE_DEVICES={device}") | ||
| 242 | + return "\n".join(lines) | ||
| 243 | + | ||
| 244 | + | ||
| 245 | +def extract_json(raw: str) -> dict[str, Any]: | ||
| 246 | + for line in reversed(raw.splitlines()): | ||
| 247 | + candidate = line.strip() | ||
| 248 | + if not candidate.startswith("{"): | ||
| 249 | + continue | ||
| 250 | + try: | ||
| 251 | + data = json.loads(candidate) | ||
| 252 | + except json.JSONDecodeError: | ||
| 253 | + continue | ||
| 254 | + if isinstance(data, dict): | ||
| 255 | + return data | ||
| 256 | + raise ValueError("probe produced no JSON object on stdout") | ||
| 257 | + | ||
| 258 | + | ||
| 259 | +def run_local_probe(probe_path: Path) -> tuple[str, str, int]: | ||
| 260 | + result = subprocess.run( | ||
| 261 | + [sys.executable, str(probe_path)], | ||
| 262 | + capture_output=True, | ||
| 263 | + text=True, | ||
| 264 | + errors="replace", | ||
| 265 | + shell=False, | ||
| 266 | + ) | ||
| 267 | + return result.stdout, result.stderr, result.returncode | ||
| 268 | + | ||
| 269 | + | ||
| 270 | +def run_remote_probe( | ||
| 271 | + probe_path: Path, host: str, remote: dict[str, Any] | ||
| 272 | +) -> tuple[str, str, int]: | ||
| 273 | + probe_src = probe_path.read_text(encoding="utf-8") | ||
| 274 | + sentinel = "ENV_CONFIG_PROBE_EOF" | ||
| 275 | + if sentinel in probe_src: | ||
| 276 | + raise ProbeError(f"Error: probe script contains sentinel {sentinel!r}") | ||
| 277 | + command = ( | ||
| 278 | + f"{build_cann_preamble(remote)}\n" | ||
| 279 | + f"python3 - <<'{sentinel}'\n" | ||
| 280 | + f"{probe_src}\n" | ||
| 281 | + f"{sentinel}\n" | ||
| 282 | + ) | ||
| 283 | + result = ssh_exec(host, command, remote) | ||
| 284 | + return result.stdout, result.stderr, result.returncode | ||
| 285 | + | ||
| 286 | + | ||
| 287 | +def write_json(path: Path, envelope: dict[str, Any]) -> None: | ||
| 288 | + path = path.expanduser() | ||
| 289 | + path.parent.mkdir(parents=True, exist_ok=True) | ||
| 290 | + tmp = path.with_name(path.name + ".tmp") | ||
| 291 | + tmp.write_text( | ||
| 292 | + json.dumps(envelope, ensure_ascii=True, indent=2, sort_keys=True) + "\n", | ||
| 293 | + encoding="utf-8", | ||
| 294 | + ) | ||
| 295 | + tmp.replace(path) | ||
| 296 | + | ||
| 297 | + | ||
| 298 | +def parse_args(argv: list[str]) -> argparse.Namespace: | ||
| 299 | + parser = argparse.ArgumentParser( | ||
| 300 | + description="Probe local or remote Ascend NPU/CANN environment into env.json." | ||
| 301 | + ) | ||
| 302 | + parser.add_argument( | ||
| 303 | + "--target", help="Remote target from .npus.yaml. Omit for local probe." | ||
| 304 | + ) | ||
| 305 | + parser.add_argument( | ||
| 306 | + "--config", help="Path to .npus.yaml. Defaults to repo root .npus.yaml." | ||
| 307 | + ) | ||
| 308 | + parser.add_argument("--write", help="Write formatted env.json to this path.") | ||
| 309 | + parser.add_argument( | ||
| 310 | + "--require-soc", | ||
| 311 | + action="store_true", | ||
| 312 | + help="Exit non-zero when soc_version is null.", | ||
| 313 | + ) | ||
| 314 | + return parser.parse_args(argv) | ||
| 315 | + | ||
| 316 | + | ||
| 317 | +def _probe(probe_path: Path, args: argparse.Namespace): | ||
| 318 | + """按 --target 决定本地或远端探测,返回 (stdout, stderr, returncode, mode, target)。""" | ||
| 319 | + if not args.target: | ||
| 320 | + stdout, stderr, returncode = run_local_probe(probe_path) | ||
| 321 | + return stdout, stderr, returncode, "local", None | ||
| 322 | + config_path = ( | ||
| 323 | + Path(args.config).expanduser() | ||
| 324 | + if args.config | ||
| 325 | + else find_repo_root() / ".npus.yaml" | ||
| 326 | + ) | ||
| 327 | + config = load_config(config_path) | ||
| 328 | + target_name, remote = get_remote(config, args.target) | ||
| 329 | + host = resolve_ssh_host(remote) | ||
| 330 | + stdout, stderr, returncode = run_remote_probe(probe_path, host, remote) | ||
| 331 | + return stdout, stderr, returncode, "remote", target_name | ||
| 332 | + | ||
| 333 | + | ||
| 334 | +def _decode_envelope(stdout: str, stderr: str) -> dict[str, Any] | None: | ||
| 335 | + """从探测输出里取 JSON envelope;取不到时打印原始输出并返回 None。""" | ||
| 336 | + try: | ||
| 337 | + return extract_json(stdout) | ||
| 338 | + except ValueError as exc: | ||
| 339 | + _ERR.info(f"Error: {exc}") | ||
| 340 | + if stdout: | ||
| 341 | + _ERR.info("--- raw stdout ---") | ||
| 342 | + _ERR.info(stdout) | ||
| 343 | + if stderr: | ||
| 344 | + _ERR.info("--- raw stderr ---") | ||
| 345 | + _ERR.info(stderr) | ||
| 346 | + return None | ||
| 347 | + | ||
| 348 | + | ||
| 349 | +def main(argv: list[str] | None = None) -> int: | ||
| 350 | + args = parse_args(argv or sys.argv[1:]) | ||
| 351 | + probe_path = Path(__file__).with_name("npu_probe.py") | ||
| 352 | + if not probe_path.is_file(): | ||
| 353 | + _ERR.info(f"Error: probe script not found: {probe_path}") | ||
| 354 | + return 1 | ||
| 355 | + | ||
| 356 | + try: | ||
| 357 | + stdout, stderr, returncode, mode, target_name = _probe(probe_path, args) | ||
| 358 | + except ProbeError as exc: | ||
| 359 | + sys.exit(str(exc)) | ||
| 360 | + | ||
| 361 | + if returncode != 0: | ||
| 362 | + _ERR.info(f"Error: probe failed with exit code {returncode}") | ||
| 363 | + if stderr: | ||
| 364 | + _ERR.info(stderr) | ||
| 365 | + return returncode | ||
| 366 | + | ||
| 367 | + envelope = _decode_envelope(stdout, stderr) | ||
| 368 | + if envelope is None: | ||
| 369 | + return 1 | ||
| 370 | + | ||
| 371 | + envelope["mode"] = mode | ||
| 372 | + if target_name is not None: | ||
| 373 | + envelope["target"] = target_name | ||
| 374 | + | ||
| 375 | + if args.require_soc and not envelope.get("soc_version"): | ||
| 376 | + _ERR.info("Error: soc_version is null") | ||
| 377 | + _LOG.info(json.dumps(envelope, ensure_ascii=True, sort_keys=True)) | ||
| 378 | + return 2 | ||
| 379 | + | ||
| 380 | + if args.write: | ||
| 381 | + write_json(Path(args.write), envelope) | ||
| 382 | + | ||
| 383 | + _LOG.info(json.dumps(envelope, ensure_ascii=True, sort_keys=True)) | ||
| 384 | + return 0 | ||
| 385 | + | ||
| 386 | + | ||
| 387 | +if __name__ == "__main__": | ||
| 388 | + raise SystemExit(main()) | ||
Aplugins-community/collaborative-agent-kernel-evolution/skills/env-probe/tests/test_npu_probe.py+87-0
| @@ -0,0 +1,87 @@ | |||
| 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 | +from pathlib import Path | ||
| 12 | +import importlib.util | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +def load_probe_module(): | ||
| 16 | + path = Path(__file__).resolve().parents[1] / "scripts" / "npu_probe.py" | ||
| 17 | + spec = importlib.util.spec_from_file_location("npu_probe", path) | ||
| 18 | + module = importlib.util.module_from_spec(spec) | ||
| 19 | + assert spec.loader is not None | ||
| 20 | + spec.loader.exec_module(module) | ||
| 21 | + return module | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +def test_scan_for_soc_accepts_new_sku_without_whitelist(): | ||
| 25 | + probe = load_probe_module() | ||
| 26 | + assert probe._scan_for_soc("NPU Name : 910B4") == "Ascend910B4" | ||
| 27 | + assert probe._scan_for_soc("Chip Name : Ascend310P3") == "Ascend310P3" | ||
| 28 | + assert probe._scan_for_soc("SoC : Ascend910_93") == "Ascend910_93" | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def test_empty_envelope_has_schema_keys(): | ||
| 32 | + probe = load_probe_module() | ||
| 33 | + envelope = probe._empty_envelope() | ||
| 34 | + assert envelope["schema_version"] == 2 | ||
| 35 | + assert envelope["warnings"] == [] | ||
| 36 | + assert "soc_version" in envelope | ||
| 37 | + assert "vector_core_cnt" in envelope | ||
| 38 | + assert "perf" in envelope | ||
| 39 | + assert envelope["perf"]["aic_freq_hz"] is None | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +def test_match_perf_spec_longest_prefix(): | ||
| 43 | + probe = load_probe_module() | ||
| 44 | + key, spec = probe.match_perf_spec("Ascend910B2") | ||
| 45 | + assert key == "ascend910b" | ||
| 46 | + assert spec["aic_freq_hz"] == 1_850_000_000 | ||
| 47 | + # Unknown SoC resolves to no spec rather than a fabricated value. | ||
| 48 | + assert probe.match_perf_spec("Ascend910_9391") == (None, None) | ||
| 49 | + assert probe.match_perf_spec(None) == (None, None) | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +def test_compute_perf_derives_cube_peak_from_core_count(): | ||
| 53 | + probe = load_probe_module() | ||
| 54 | + env = probe._empty_envelope() | ||
| 55 | + env["soc_version"] = "Ascend910B2" | ||
| 56 | + env["cube_core_cnt"] = 24 | ||
| 57 | + env["l2_size"] = 201_326_592 # 192 MB | ||
| 58 | + perf = probe.compute_perf(env) | ||
| 59 | + assert perf["source"] == "soc-perf-table" | ||
| 60 | + assert perf["hbm_bw_bytes_per_s"] == 1_800_000_000_000 | ||
| 61 | + # 24 cores x 1.85e9 Hz x 4096 MAC gives peak MACs/s; FLOPs is twice that. | ||
| 62 | + assert perf["cube_peak_macs_per_s"] == 24 * 1_850_000_000 * 4096 | ||
| 63 | + assert perf["cube_peak_flops_fp16"] == perf["cube_peak_macs_per_s"] * 2 | ||
| 64 | + # vector throughput + L2 capacity for the refined roofline (cann-bench port) | ||
| 65 | + assert perf["vector_basic_eps_fp16"] == 12_000_000_000_000 | ||
| 66 | + assert perf["vector_basic_eps_fp32"] == 6_000_000_000_000 | ||
| 67 | + assert perf["l2_cap_bytes"] == 201_326_592 | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +def test_compute_perf_unknown_soc_is_null_with_warning(): | ||
| 71 | + probe = load_probe_module() | ||
| 72 | + env = probe._empty_envelope() | ||
| 73 | + env["soc_version"] = "Ascend910_9391" | ||
| 74 | + perf = probe.compute_perf(env) | ||
| 75 | + assert perf["source"] == "none" | ||
| 76 | + assert perf["aic_freq_hz"] is None | ||
| 77 | + assert any("perf_spec_missing" in w for w in env["warnings"]) | ||
| 78 | + | ||
| 79 | + | ||
| 80 | +def test_compute_perf_cube_peak_null_without_core_count(): | ||
| 81 | + probe = load_probe_module() | ||
| 82 | + env = probe._empty_envelope() | ||
| 83 | + env["soc_version"] = "Ascend910B2" | ||
| 84 | + # cube_core_cnt stays None (TBE unavailable) | ||
| 85 | + perf = probe.compute_perf(env) | ||
| 86 | + assert perf["hbm_bw_bytes_per_s"] == 1_800_000_000_000 | ||
| 87 | + assert perf["cube_peak_macs_per_s"] is None | ||
| @@ -0,0 +1,73 @@ | |||
| 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 | +"""op_builder — semantic-affinity AscendC op builder (Phase α POC). | ||
| 12 | + | ||
| 13 | +★ Recommended entry for NEW ops ★ | ||
| 14 | + | ||
| 15 | +Usage: | ||
| 16 | + from op_builder import build_op, Paradigm, Input, Output, Workspace, KernelSource | ||
| 17 | + | ||
| 18 | + result = build_op( | ||
| 19 | + op_name='grouped_matmul_swiglu_quant_custom', | ||
| 20 | + paradigm=Paradigm.CV_FUSION_MANUAL_SYNC, | ||
| 21 | + kernel=KernelSource(...), | ||
| 22 | + inputs=[Input('x', 'int8', ('M', 'K')), ...], | ||
| 23 | + outputs=[Output('y', 'int8', ('M', 'N_out')), ...], | ||
| 24 | + workspaces=[Workspace('ws1', 'int32', 'M*N*4'), ...], | ||
| 25 | + ) | ||
| 26 | + | ||
| 27 | +★ Why use this ★: | ||
| 28 | + - 7 host-bridge pitfalls (P1-P7 in references/common_pitfalls.md §22-28) hidden from caller | ||
| 29 | + - Paradigm enum picks all paradigm-specific fixes (inline NOT static, ws offset | ||
| 30 | + convention, install path, etc.) | ||
| 31 | + - Validators check build invariants (deployed cpp timestamp, AIV binary size, | ||
| 32 | + input shape match compile-time const) | ||
| 33 | + | ||
| 34 | +★ Fallback ★: For edge cases NOT covered by current paradigms, see | ||
| 35 | + skills/tilelang-host-bridge/scripts/cake_lowering/rebuild_<op>_*.sh | ||
| 36 | + (LEGACY shell scripts — direct sed/build invocation). Phase α covers only | ||
| 37 | + CV_FUSION_MANUAL_SYNC; others coming Phase β. | ||
| 38 | + | ||
| 39 | +Phase α scope (this commit, 2026-05-28): | ||
| 40 | + - Paradigm enum + config dict | ||
| 41 | + - build_op() orchestrator wrapping existing emit + sed + build + install | ||
| 42 | + - Proven on GMSQ V4 (end-to-end max_diff=1, deterministic) | ||
| 43 | + - Other paradigms: throw NotImplementedError, point to legacy scripts | ||
| 44 | + | ||
| 45 | +Reference: skills/tilelang-host-bridge/references/higher_level_api_proposal.md | ||
| 46 | +""" | ||
| 47 | + | ||
| 48 | +from op_builder.paradigms import Paradigm, ParadigmConfig | ||
| 49 | +from op_builder.api import ( | ||
| 50 | + build_op, | ||
| 51 | + Input, | ||
| 52 | + Output, | ||
| 53 | + Workspace, | ||
| 54 | + Attr, | ||
| 55 | + InternalTensor, | ||
| 56 | + KernelSource, | ||
| 57 | + BucketSpec, | ||
| 58 | + BuildResult, | ||
| 59 | +) | ||
| 60 | + | ||
| 61 | +__all__ = [ | ||
| 62 | + "build_op", | ||
| 63 | + "Paradigm", | ||
| 64 | + "ParadigmConfig", | ||
| 65 | + "Input", | ||
| 66 | + "Output", | ||
| 67 | + "Workspace", | ||
| 68 | + "Attr", | ||
| 69 | + "InternalTensor", | ||
| 70 | + "KernelSource", | ||
| 71 | + "BucketSpec", | ||
| 72 | + "BuildResult", | ||
| 73 | +] | ||
| @@ -0,0 +1,178 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 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 | +"""task #31 Gap 1 — pybind output-dtype STATIC GATE (regression checker). | ||
| 13 | + | ||
| 14 | +PROBLEM (real, cost debugging on exp/grouped_matmul): emit_pybind once hardcoded every | ||
| 15 | +output to `at::kHalf`, so bf16/fp32 inputs silently produced an fp16 output. The bug was | ||
| 16 | +found only by reading the emitted C++. emit_pybind is fixed, but nothing stops a regression. | ||
| 17 | + | ||
| 18 | +This checker re-verifies an EMITTED pybind op.cpp statically: | ||
| 19 | + For a MULTI-DTYPE op (the emitter writes a `// op_builder-dtype-gate:` marker with | ||
| 20 | + multi_dtype=1 + the VARIANT output names + the dispatch input), every variant output's | ||
| 21 | + at::empty(...) MUST take the dispatch input's runtime options (`<dispatch_input>.options()`) | ||
| 22 | + and MUST NOT bake a hardcoded `.dtype(at::kHalf/at::kFloat/...)`. Fixed-dtype outputs | ||
| 23 | + (int8 Y, fp32 SCALE) are NOT in the marker's variant_outputs list → exempt. | ||
| 24 | + | ||
| 25 | +Usage: | ||
| 26 | + python3 check_dtype_gate.py <emitted_op.cpp> | ||
| 27 | +Exit 0 = PASS (gate satisfied / not applicable). Exit 1 = FAIL (regression found). | ||
| 28 | +""" | ||
| 29 | + | ||
| 30 | +import logging | ||
| 31 | +import re | ||
| 32 | +import sys | ||
| 33 | +from pathlib import Path | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +class _StreamProxy: | ||
| 37 | + """按名字在写出时解析 sys.stdout / sys.stderr。 | ||
| 38 | + | ||
| 39 | + logging.StreamHandler 在构造时就持有流对象,而 print 每次调用才取 | ||
| 40 | + sys.stdout / sys.stderr。用本代理转发,使二者行为一致——进程内替换或 | ||
| 41 | + 重定向标准流时,输出仍落到替换后的流。sys 模块存在实例上,避免解释器 | ||
| 42 | + 退出时模块全局被清空导致 flush 抛 NameError。 | ||
| 43 | + """ | ||
| 44 | + | ||
| 45 | + def __init__(self, name: str, sys_module=sys) -> None: | ||
| 46 | + self._name = name | ||
| 47 | + self._sys = sys_module | ||
| 48 | + | ||
| 49 | + def write(self, text: str) -> int: | ||
| 50 | + return getattr(self._sys, self._name).write(text) | ||
| 51 | + | ||
| 52 | + def flush(self) -> None: | ||
| 53 | + getattr(self._sys, self._name).flush() | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +_LOG = logging.getLogger(__name__ + ".stdout") | ||
| 57 | +_ERR = logging.getLogger(__name__ + ".stderr") | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def _init_loggers() -> None: | ||
| 61 | + """把脚本输出接到 logging,格式为 %(message)s,每行内容与原 print 一致。""" | ||
| 62 | + for logger, name in ((_LOG, "stdout"), (_ERR, "stderr")): | ||
| 63 | + if logger.handlers: | ||
| 64 | + continue | ||
| 65 | + handler = logging.StreamHandler(_StreamProxy(name)) | ||
| 66 | + handler.setFormatter(logging.Formatter("%(message)s")) | ||
| 67 | + logger.addHandler(handler) | ||
| 68 | + logger.setLevel(logging.INFO) | ||
| 69 | + logger.propagate = False | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +_init_loggers() | ||
| 73 | + | ||
| 74 | +_HARDCODED_AT = re.compile(r"\.dtype\(\s*at::k\w+\s*\)") | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +def _parse_marker(text): | ||
| 78 | + """Parse the `// op_builder-dtype-gate: ...` marker into a dict. None if absent.""" | ||
| 79 | + m = re.search(r"//\s*op_builder-dtype-gate:\s*(.*)", text) | ||
| 80 | + if not m: | ||
| 81 | + return None | ||
| 82 | + d = {} | ||
| 83 | + for tok in m.group(1).split(): | ||
| 84 | + if "=" in tok: | ||
| 85 | + k, v = tok.split("=", 1) | ||
| 86 | + d[k] = v | ||
| 87 | + return d | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +def _check_variant_outputs(text, variant_outs, dispatch_in, report): | ||
| 91 | + """逐个核查随 dtype 变化的输出:其 at::empty 必须取自调度输入的 options(), | ||
| 92 | + | ||
| 93 | + 不得写死 at::kHalf/at::kFloat。返回失败说明列表,核查痕迹追加到 report。 | ||
| 94 | + """ | ||
| 95 | + fails = [] | ||
| 96 | + for out_name in variant_outs: | ||
| 97 | + # Find the alloc line for this output: `at::Tensor <name> = at::empty(...);` | ||
| 98 | + am = re.search( | ||
| 99 | + rf"at::Tensor\s+{re.escape(out_name)}\s*=\s*at::empty\((.*?)\);", | ||
| 100 | + text, | ||
| 101 | + re.DOTALL, | ||
| 102 | + ) | ||
| 103 | + if not am: | ||
| 104 | + fails.append( | ||
| 105 | + f"✘ variant output '{out_name}': no `at::Tensor {out_name} = at::empty(...)` alloc found" | ||
| 106 | + ) | ||
| 107 | + continue | ||
| 108 | + alloc = am.group(1) | ||
| 109 | + if _HARDCODED_AT.search(alloc): | ||
| 110 | + bad = _HARDCODED_AT.search(alloc).group(0) | ||
| 111 | + fails.append( | ||
| 112 | + f"✘ variant output '{out_name}': HARDCODED dtype `{bad}` — must track runtime " | ||
| 113 | + f"input dtype via `{dispatch_in}.options()` (the fp16-output regression)\n" | ||
| 114 | + f" line: at::Tensor {out_name} = at::empty({alloc.strip()});" | ||
| 115 | + ) | ||
| 116 | + elif f"{dispatch_in}.options()" not in alloc: | ||
| 117 | + fails.append( | ||
| 118 | + f"✘ variant output '{out_name}': alloc does not use `{dispatch_in}.options()` " | ||
| 119 | + f"(runtime dtype source). got: at::empty({alloc.strip()});" | ||
| 120 | + ) | ||
| 121 | + else: | ||
| 122 | + report.append( | ||
| 123 | + f" ✓ variant output '{out_name}' allocs from {dispatch_in}.options() (runtime dtype)" | ||
| 124 | + ) | ||
| 125 | + return fails | ||
| 126 | + | ||
| 127 | + | ||
| 128 | +def check(cpp_path): | ||
| 129 | + """Return (ok: bool, lines: list[str]) — human report lines.""" | ||
| 130 | + p = Path(cpp_path) | ||
| 131 | + if not p.exists(): | ||
| 132 | + return False, [f"✘ file not found: {cpp_path}"] | ||
| 133 | + text = p.read_text() | ||
| 134 | + marker = _parse_marker(text) | ||
| 135 | + | ||
| 136 | + if marker is None: | ||
| 137 | + # No marker → emitted by an older/foreign emitter. Fall back to a heuristic: if this | ||
| 138 | + # op declares multiple `EXEC_NPU_CMD` dtype configs we cannot know variants; report | ||
| 139 | + # SKIP (not FAIL) — the gate is advisory for un-marked files. | ||
| 140 | + return True, [ | ||
| 141 | + f"○ SKIP {p.name}: no op_builder-dtype-gate marker (not a build_op multi-dtype emit)" | ||
| 142 | + ] | ||
| 143 | + | ||
| 144 | + if marker.get("multi_dtype") != "1": | ||
| 145 | + return True, [f"✓ PASS {p.name}: single-dtype op — dtype gate N/A"] | ||
| 146 | + | ||
| 147 | + variant_outs = [n for n in marker.get("variant_outputs", "").split("|") if n] | ||
| 148 | + dispatch_in = marker.get("dispatch_input", "") | ||
| 149 | + if not variant_outs: | ||
| 150 | + return True, [ | ||
| 151 | + f"✓ PASS {p.name}: multi-dtype but no variant outputs declared (all fixed-dtype)" | ||
| 152 | + ] | ||
| 153 | + | ||
| 154 | + report = [ | ||
| 155 | + f" multi-dtype op, dispatch_input='{dispatch_in}', variant_outputs={variant_outs}" | ||
| 156 | + ] | ||
| 157 | + fails = _check_variant_outputs(text, variant_outs, dispatch_in, report) | ||
| 158 | + if fails: | ||
| 159 | + return False, [f"✘ FAIL {p.name}: pybind output-dtype gate"] + report + [ | ||
| 160 | + " " + f for f in fails | ||
| 161 | + ] | ||
| 162 | + return True, [ | ||
| 163 | + f"✓ PASS {p.name}: all variant outputs track runtime input dtype" | ||
| 164 | + ] + report | ||
| 165 | + | ||
| 166 | + | ||
| 167 | +def main(argv): | ||
| 168 | + if len(argv) != 2: | ||
| 169 | + _ERR.info("Usage: check_dtype_gate.py <emitted_op.cpp>") | ||
| 170 | + return 2 | ||
| 171 | + ok, lines = check(argv[1]) | ||
| 172 | + for line in lines: | ||
| 173 | + _LOG.info(line) | ||
| 174 | + return 0 if ok else 1 | ||
| 175 | + | ||
| 176 | + | ||
| 177 | +if __name__ == "__main__": | ||
| 178 | + sys.exit(main(sys.argv)) | ||
| @@ -0,0 +1,318 @@ | |||
| 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 | +"""Vector-only FUSED add + rms_norm + per-token int8 quant — RUNTIME-Dp tiled (任意 D). | ||
| 12 | + | ||
| 13 | +★ 为何这版存在 (vs add_rms_norm_dynamic_quant_strided.py 的根差异) ★ | ||
| 14 | + strided 版把 Dp(hidden width) **烤成编译期常量 512**, alloc_ub([1, Dp]) 一次 load 整行 | ||
| 15 | + → 单 binary 只处理 512 列. eval D=4096/8192/16384 → int8 ~90% 错, 净分回退到 1/20. | ||
| 16 | + 本版把 Dp 变成 **RUNTIME symbolic** (Dp = T.symbolic("Dp"), lower 成 inner kernel | ||
| 17 | + `int64_t Dp` 参数, host set_Dp(GetDim(1))), UB buffer 只开 TILE=512 宽, 用 3 个 | ||
| 18 | + `for t in T.serial(ceildiv(Dp, 512))` 内层 tile-loop 沿 reduce 维流式扫. 单 binary 通吃任意 D | ||
| 19 | + 且无 UB overflow. 这正是 run157 已证 (int8 EXACT on fp16, 任意 D) 的 3-pass 结构. | ||
| 20 | + | ||
| 21 | +★ INVD (第4输入, 2-element fp32 = [1/real_D, eps]) ★ | ||
| 22 | + 归一化分母必须是 REAL D (= 运行时 Dp, 因为本版 **不 host-pad**, eval 直接喂真 D). | ||
| 23 | + 1/D 与 eps 需在 kernel 内当 fp32 标量用 — 但 symbolic int Dp 在本 reduce path 上转 fp32 | ||
| 24 | + 未经验证, run157 走的是把 [1/D, eps] 在 host 算好塞进一个 2-elem fp32 GM tensor INVD, | ||
| 25 | + kernel 读 INVD[0]=1/D, INVD[1]=eps. op_plugin 暴露上游 schema (x1,x2,gamma,float eps) | ||
| 26 | + 自己构造 INVD (见 run157 plugin). 本 DSL 因此声明 4 输入. | ||
| 27 | + | ||
| 28 | +公式 (golden 对齐 torch_npu.npu_add_rms_norm_dynamic_quant): | ||
| 29 | + xOut = x1 + x2 # fp16/bf16 输出 | ||
| 30 | + y_norm = xOut / sqrt(mean(xOut²)+eps) * gamma # mean = sum(xOut²) * (1/D) | ||
| 31 | + scaleOut = row_max(|y_norm|) / 127 # fp32, shape=(M,) | ||
| 32 | + y = round(clamp(y_norm/scaleOut, -127,127)) # int8, shape=(M,D) | ||
| 33 | + | ||
| 34 | +★ 3-pass 结构 (mirror run157) ★ | ||
| 35 | + pass1: 沿 D tile-loop — load x1/x2 tile, add → xOut tile 写回, 累加 acc_sq += xOut² | ||
| 36 | + tile 后 reduce_sum(acc_sq) → mean*inv_D + eps → sqrt → rms_t broadcast | ||
| 37 | + (Sqrt+Div, NOT rsqrt: Vrsqrt 是 ~1e-3 近似, 破 fp32 scaleOut 阈 1.22e-4) | ||
| 38 | + pass2: 沿 D tile-loop — 重算 xOut tile (x1+x2), *rms_t *gamma → y_norm tile, 累加 acc_max | ||
| 39 | + tile 后 reduce_max(acc_max) → scale = amax/127 (clamp eps) → 写 SCALE, broadcast scale_t | ||
| 40 | + pass3: 沿 D tile-loop — 重算 y_norm tile, /scale → clamp → round → fp16 → int8 → 写 Y | ||
| 41 | + (pass2/3 重算 xOut 而非缓存整行: 整行可能 16384 宽, 缓存爆 UB; 重算 cheap.) | ||
| 42 | + | ||
| 43 | +★ TILE 整除 / tail 处理 ★ | ||
| 44 | + copy span = TILE(512) 编译期常量 → codegen 不 emit 动态 L (避 issue#1228). 当 Dp 非 512 | ||
| 45 | + 整数倍, 尾 tile 仍按 512 宽算: 越界 lane copy 用 0 fill (copy_gm_to_ub pad), gamma 同. | ||
| 46 | + pad=0 安全: x1/x2 pad 0+0=0 → xOut=0 → 0²=0 不进 acc_sq; gamma pad 0 → y_norm=0 不进 acc_max. | ||
| 47 | +""" | ||
| 48 | +import logging as _console_logging | ||
| 49 | +import sys as _console_sys | ||
| 50 | + | ||
| 51 | +import sys | ||
| 52 | +from pathlib import Path | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +class _StreamProxy: | ||
| 56 | + """Resolve stdout when writing so redirected output retains its destination.""" | ||
| 57 | + | ||
| 58 | + def __init__(self, sys_module=_console_sys): | ||
| 59 | + self._console_sys = sys_module | ||
| 60 | + | ||
| 61 | + def write(self, text: str) -> int: | ||
| 62 | + return self._console_sys.stdout.write(text) | ||
| 63 | + | ||
| 64 | + def flush(self) -> None: | ||
| 65 | + self._console_sys.stdout.flush() | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +_LOG = _console_logging.getLogger(__name__ + ".stdout") | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def _init_loggers() -> None: | ||
| 72 | + """Keep console messages visible without changing the root logger.""" | ||
| 73 | + if not _LOG.handlers: | ||
| 74 | + handler = _console_logging.StreamHandler(_StreamProxy()) | ||
| 75 | + handler.setFormatter(_console_logging.Formatter("%(message)s")) | ||
| 76 | + _LOG.addHandler(handler) | ||
| 77 | + _LOG.setLevel(_console_logging.INFO) | ||
| 78 | + _LOG.propagate = False | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +_init_loggers() | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def _add_kb_lib(): | ||
| 85 | + for _anc in Path(__file__).resolve().parents: | ||
| 86 | + for _cand in (_anc / "lib", _anc / "skills" / "tilelang-kernel-baseline" / "lib"): | ||
| 87 | + if (_cand / "chip_spec.py").exists(): | ||
| 88 | + sys.path.insert(0, str(_cand)) | ||
| 89 | + return | ||
| 90 | +_add_kb_lib() | ||
| 91 | +import tilelang | ||
| 92 | +from tilelang import language as T | ||
| 93 | +import torch | ||
| 94 | +from chip_spec import cores as _soc_cores | ||
| 95 | + | ||
| 96 | +TILE = 512 # reduce-dim 流式 tile 宽 (fp32 vector 256B=64 lane 的 8 倍, run157 已证) | ||
| 97 | + | ||
| 98 | +pass_configs = { | ||
| 99 | + tilelang.PassConfigKey.TL_ASCEND_AUTO_CV_COMBINE: False, | ||
| 100 | + tilelang.PassConfigKey.TL_ASCEND_AUTO_CV_SYNC: False, | ||
| 101 | + tilelang.PassConfigKey.TL_ASCEND_MEMORY_PLANNING: False, | ||
| 102 | + tilelang.PassConfigKey.TL_ASCEND_AUTO_SYNC: True, | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +INT8_ABS_MAX = 127.0 | ||
| 106 | +SCALE_EPS = 1e-12 # golden clamp(min=1e-12) 防全零行 0/0=NaN | ||
| 107 | + | ||
| 108 | + | ||
| 109 | +@tilelang.jit(out_idx=[4, 5, 6], pass_configs=pass_configs) | ||
| 110 | +def add_rms_norm_dynamic_quant_runtime_dp(MAX_CORES=None, dtype="float16"): | ||
| 111 | + """row-wise add+rms_norm+per-token int8 quant over RUNTIME width Dp (tiled by TILE=512). | ||
| 112 | + | ||
| 113 | + M, Dp 都 symbolic → lower 成 inner kernel `int64_t M, int64_t Dp`. | ||
| 114 | + INVD[0]=1/real_D (mean 分母), INVD[1]=eps. MAX_CORES cubes stride over rows. | ||
| 115 | + Outputs (out_idx=[4,5,6]): Y(int8 M,Dp), XOUT(dtype M,Dp), SCALE(fp32 M,1). | ||
| 116 | + """ | ||
| 117 | + if MAX_CORES is None: | ||
| 118 | + MAX_CORES = _soc_cores() | ||
| 119 | + sym_M = T.symbolic("M") | ||
| 120 | + Dp = T.symbolic("Dp") | ||
| 121 | + not_fp32 = dtype != "float32" | ||
| 122 | + | ||
| 123 | + @T.prim_func | ||
| 124 | + def main( | ||
| 125 | + X1: T.Tensor((sym_M, Dp), dtype), | ||
| 126 | + X2: T.Tensor((sym_M, Dp), dtype), | ||
| 127 | + GAMMA: T.Tensor((Dp,), dtype), | ||
| 128 | + INVD: T.Tensor((2,), "float32"), | ||
| 129 | + Y: T.Tensor((sym_M, Dp), "int8"), | ||
| 130 | + XOUT: T.Tensor((sym_M, Dp), dtype), | ||
| 131 | + SCALE: T.Tensor((sym_M, 1), "float32"), | ||
| 132 | + ): | ||
| 133 | + with T.Kernel(MAX_CORES, is_npu=True) as (cid_base, vid): | ||
| 134 | + # ── scalar runtime params (1/D, eps) from INVD GM tensor ── | ||
| 135 | + invd_ub = T.alloc_ub([1, 1], "float32") | ||
| 136 | + eps_ub = T.alloc_ub([1, 1], "float32") | ||
| 137 | + # ── TILE-wide working buffers (NOT full Dp) ── | ||
| 138 | + io_ub = T.alloc_ub([1, TILE], dtype) # x1/x2 tile load + xOut/int8 writeback (复用) | ||
| 139 | + x_fp = T.alloc_ub([1, TILE], "float32") # xOut/y_norm tile (fp32) | ||
| 140 | + sq = T.alloc_ub([1, TILE], "float32") # x2_fp / xOut² / |y| scratch | ||
| 141 | + g_ub = T.alloc_ub([1, TILE], dtype) | ||
| 142 | + g_fp = T.alloc_ub([1, TILE], "float32") | ||
| 143 | + acc_sq = T.alloc_ub([1, TILE], "float32") # sumsq accumulator (TILE lane) | ||
| 144 | + acc_max = T.alloc_ub([1, TILE], "float32") # amax accumulator (TILE lane) | ||
| 145 | + rms_t = T.alloc_ub([1, TILE], "float32") # rstd broadcast | ||
| 146 | + scale_t = T.alloc_ub([1, TILE], "float32") # scale broadcast | ||
| 147 | + y_half = T.alloc_ub([1, TILE], "float16") | ||
| 148 | + y_i8 = T.alloc_ub([1, TILE], "int8") | ||
| 149 | + rsum = T.alloc_ub([1, 1], "float32") | ||
| 150 | + ramax = T.alloc_ub([1, 1], "float32") | ||
| 151 | + scl = T.alloc_ub([1, 1], "float32") | ||
| 152 | + iter_count = T.ceildiv(sym_M, MAX_CORES) | ||
| 153 | + n_tiles = T.ceildiv(Dp, TILE) | ||
| 154 | + with T.Scope("V"): | ||
| 155 | + # load runtime scalars once (INVD[0]=1/D, INVD[1]=eps) | ||
| 156 | + T.copy(INVD[0:1], invd_ub[0, 0:1]) | ||
| 157 | + T.copy(INVD[1:2], eps_ub[0, 0:1]) | ||
| 158 | + for iter_idx in T.serial(iter_count): | ||
| 159 | + cid = cid_base + iter_idx * MAX_CORES | ||
| 160 | + if cid < sym_M: | ||
| 161 | + # ── PASS 1: add → xOut writeback + accumulate sum(xOut²) ── | ||
| 162 | + T.tile.fill(acc_sq, 0.0) | ||
| 163 | + for t in T.serial(n_tiles): | ||
| 164 | + c0 = t * TILE | ||
| 165 | + T.copy(X1[cid, c0:c0 + TILE], io_ub[0, 0:TILE]) | ||
| 166 | + if not_fp32: | ||
| 167 | + T.tile.cast(x_fp, io_ub, "CAST_NONE", TILE) | ||
| 168 | + else: | ||
| 169 | + T.copy(io_ub, x_fp) | ||
| 170 | + T.copy(X2[cid, c0:c0 + TILE], io_ub[0, 0:TILE]) | ||
| 171 | + if not_fp32: | ||
| 172 | + T.tile.cast(sq, io_ub, "CAST_NONE", TILE) | ||
| 173 | + else: | ||
| 174 | + T.copy(io_ub, sq) | ||
| 175 | + T.tile.add(x_fp, x_fp, sq) # x_fp = xOut tile | ||
| 176 | + if not_fp32: | ||
| 177 | + T.tile.cast(io_ub, x_fp, "CAST_RINT", TILE) | ||
| 178 | + else: | ||
| 179 | + T.copy(x_fp, io_ub) | ||
| 180 | + T.copy(io_ub[0, 0:TILE], XOUT[cid, c0:c0 + TILE]) | ||
| 181 | + T.tile.mul(sq, x_fp, x_fp) # xOut² (pad lane = 0) | ||
| 182 | + T.tile.add(acc_sq, acc_sq, sq) # accumulate | ||
| 183 | + T.reduce_sum(acc_sq, rsum, dim=-1) # sum(xOut²) over all tiles | ||
| 184 | + T.tile.mul(rsum, rsum, invd_ub) # mean = sum * (1/D) | ||
| 185 | + T.tile.add(rsum, rsum, eps_ub) # mean + eps | ||
| 186 | + # rms = sqrt(mean+eps) (run157: Sqrt+Div NOT rsqrt; Vrsqrt ~1e-3 approx | ||
| 187 | + # breaks fp32 scaleOut th 1.22e-4) | ||
| 188 | + T.tile.sqrt(rsum, rsum) | ||
| 189 | + T.tile.broadcast(rms_t, rsum) # [1,1]→[1,TILE] | ||
| 190 | + # ── PASS 2: recompute xOut → y_norm → accumulate amax(|y_norm|) ── | ||
| 191 | + T.tile.fill(acc_max, 0.0) | ||
| 192 | + for t in T.serial(n_tiles): | ||
| 193 | + c0 = t * TILE | ||
| 194 | + T.copy(X1[cid, c0:c0 + TILE], io_ub[0, 0:TILE]) | ||
| 195 | + if not_fp32: | ||
| 196 | + T.tile.cast(x_fp, io_ub, "CAST_NONE", TILE) | ||
| 197 | + else: | ||
| 198 | + T.copy(io_ub, x_fp) | ||
| 199 | + T.copy(X2[cid, c0:c0 + TILE], io_ub[0, 0:TILE]) | ||
| 200 | + if not_fp32: | ||
| 201 | + T.tile.cast(sq, io_ub, "CAST_NONE", TILE) | ||
| 202 | + else: | ||
| 203 | + T.copy(io_ub, sq) | ||
| 204 | + T.tile.add(x_fp, x_fp, sq) # xOut tile | ||
| 205 | + T.copy(GAMMA[c0:c0 + TILE], g_ub[0, 0:TILE]) | ||
| 206 | + if not_fp32: | ||
| 207 | + T.tile.cast(g_fp, g_ub, "CAST_NONE", TILE) | ||
| 208 | + else: | ||
| 209 | + T.copy(g_ub, g_fp) | ||
| 210 | + T.tile.div(x_fp, x_fp, rms_t) # xOut / rms | ||
| 211 | + T.tile.mul(x_fp, x_fp, g_fp) # * gamma → y_norm (pad gamma=0 → 0) | ||
| 212 | + T.tile.abs(sq, x_fp) # |y_norm| (pad=0) | ||
| 213 | + T.tile.max(acc_max, acc_max, sq) # accumulate row max | ||
| 214 | + T.reduce_max(acc_max, ramax, dim=-1) # row amax over all tiles | ||
| 215 | + T.tile.mul(ramax, ramax, 1.0 / INT8_ABS_MAX) # amax/127 | ||
| 216 | + T.tile.add(scl, ramax, SCALE_EPS) # +eps guard | ||
| 217 | + T.copy(scl[0, 0:1], SCALE[cid, 0:1]) # write scaleOut (fp32) | ||
| 218 | + T.tile.broadcast(scale_t, scl) # [1,1]→[1,TILE] | ||
| 219 | + # ── PASS 3: recompute y_norm → quant → int8 write ── | ||
| 220 | + for t in T.serial(n_tiles): | ||
| 221 | + c0 = t * TILE | ||
| 222 | + T.copy(X1[cid, c0:c0 + TILE], io_ub[0, 0:TILE]) | ||
| 223 | + if not_fp32: | ||
| 224 | + T.tile.cast(x_fp, io_ub, "CAST_NONE", TILE) | ||
| 225 | + else: | ||
| 226 | + T.copy(io_ub, x_fp) | ||
| 227 | + T.copy(X2[cid, c0:c0 + TILE], io_ub[0, 0:TILE]) | ||
| 228 | + if not_fp32: | ||
| 229 | + T.tile.cast(sq, io_ub, "CAST_NONE", TILE) | ||
| 230 | + else: | ||
| 231 | + T.copy(io_ub, sq) | ||
| 232 | + T.tile.add(x_fp, x_fp, sq) # xOut tile | ||
| 233 | + T.copy(GAMMA[c0:c0 + TILE], g_ub[0, 0:TILE]) | ||
| 234 | + if not_fp32: | ||
| 235 | + T.tile.cast(g_fp, g_ub, "CAST_NONE", TILE) | ||
| 236 | + else: | ||
| 237 | + T.copy(g_ub, g_fp) | ||
| 238 | + T.tile.div(x_fp, x_fp, rms_t) # xOut / rms | ||
| 239 | + T.tile.mul(x_fp, x_fp, g_fp) # * gamma → y_norm | ||
| 240 | + T.tile.div(x_fp, x_fp, scale_t) # y_norm / scale | ||
| 241 | + T.tile.clamp(x_fp, x_fp, -127.0, 127.0, TILE) | ||
| 242 | + T.tile.round(x_fp, x_fp, TILE) | ||
| 243 | + T.tile.cast(y_half, x_fp, "CAST_RINT", TILE) # fp32→fp16 | ||
| 244 | + T.tile.cast(y_i8, y_half, "CAST_TRUNC", TILE) # fp16→int8 | ||
| 245 | + T.copy(y_i8[0, 0:TILE], Y[cid, c0:c0 + TILE]) | ||
| 246 | + | ||
| 247 | + return main | ||
| 248 | + | ||
| 249 | + | ||
| 250 | +# ---- HOST 包装 (build_op pybind_pre/post; 离线 self-test 用) ---- | ||
| 251 | +def run_op(x1, x2, gamma, eps, dtype_tl): | ||
| 252 | + """x1,x2: (..., D) torch; gamma: (D,). flatten leading → (M, D), 构造 INVD=[1/D, eps], | ||
| 253 | + 跑 kernel (无 host pad — kernel 内 tile 处理任意 D), 返回 (y_int8, xOut, scale). | ||
| 254 | + """ | ||
| 255 | + real_D = x1.shape[-1] | ||
| 256 | + M = x1.numel() // real_D | ||
| 257 | + x1f = x1.reshape(M, real_D).contiguous() | ||
| 258 | + x2f = x2.reshape(M, real_D).contiguous() | ||
| 259 | + gf = gamma.reshape(real_D).contiguous() | ||
| 260 | + invd = torch.tensor([1.0 / real_D, eps], dtype=torch.float32) | ||
| 261 | + k = add_rms_norm_dynamic_quant_runtime_dp(None, dtype_tl) | ||
| 262 | + y, xout, scale = k(x1f.npu(), x2f.npu(), gf.npu(), invd.npu()) | ||
| 263 | + y = y.detach().cpu().reshape(x1.shape) | ||
| 264 | + xout = xout.detach().cpu().reshape(x1.shape) | ||
| 265 | + scale = scale.detach().cpu().reshape(M) | ||
| 266 | + return y, xout, scale | ||
| 267 | + | ||
| 268 | + | ||
| 269 | +def golden(x1, x2, gamma, eps): | ||
| 270 | + out_dtype = x1.dtype | ||
| 271 | + x1 = x1.float() | ||
| 272 | + x2 = x2.float() | ||
| 273 | + gamma = gamma.float() | ||
| 274 | + xOut = x1 + x2 | ||
| 275 | + var = xOut.pow(2).mean(-1, keepdim=True) | ||
| 276 | + y_norm = xOut * torch.rsqrt(var + eps) * gamma | ||
| 277 | + abs_max = y_norm.abs().amax(dim=-1, keepdim=True) | ||
| 278 | + scale = (abs_max.clamp(min=1e-12) / 127.0) | ||
| 279 | + y = torch.clamp((y_norm / scale).round(), -128, 127).to(torch.int8) | ||
| 280 | + return y, xOut.to(out_dtype), scale.squeeze(-1).float() | ||
| 281 | + | ||
| 282 | + | ||
| 283 | +def run_demo(): | ||
| 284 | + import torch_npu # noqa | ||
| 285 | + tilelang.disable_cache() | ||
| 286 | + torch.manual_seed(0) | ||
| 287 | + TLD = {torch.float16: "float16", torch.float32: "float32", torch.bfloat16: "bfloat16"} | ||
| 288 | + cases = [ | ||
| 289 | + ((512, 512), 1e-6, torch.float16, (-1, 1)), # aligned 1 tile | ||
| 290 | + ((256, 4096), 1e-6, torch.float16, (-1, 1)), # 8 tiles | ||
| 291 | + ((64, 8192), 1e-6, torch.bfloat16, (-0.1, 0.1)), # 16 tiles bf16 | ||
| 292 | + ((32, 16384), 1e-6, torch.float16, (-1, 1)), # 32 tiles (max eval D) | ||
| 293 | + ((1021, 1023), 1e-6, torch.bfloat16, (-0.1, 0.1)), # 质数非整除 bf16 (尾 tile) | ||
| 294 | + ((128, 4093), 1e-6, torch.float16, (-1, 2)), # 质数 4093 (尾 tile) | ||
| 295 | + ((100, 373), 1e-6, torch.float32, (-2, 2)), # fp32 质数非整除 | ||
| 296 | + ((1024, 128), 1e-6, torch.float16, (-1, 1)), # small D < TILE | ||
| 297 | + ] | ||
| 298 | + allpass = True | ||
| 299 | + for shape, eps, dt, (lo, hi) in cases: | ||
| 300 | + tld = TLD[dt] | ||
| 301 | + M, D = shape | ||
| 302 | + x1 = (torch.rand(M, D) * (hi - lo) + lo).to(dt) | ||
| 303 | + x2 = (torch.rand(M, D) * (hi - lo) + lo).to(dt) | ||
| 304 | + gamma = (torch.rand(D) * 2 - 1).to(dt) | ||
| 305 | + y, xout, scale = run_op(x1, x2, gamma, eps, tld) | ||
| 306 | + gy, gxout, gscale = golden(x1, x2, gamma, eps) | ||
| 307 | + y_diff = (y.int() - gy.int()).abs().max().item() | ||
| 308 | + xout_diff = (xout.float() - gxout.float()).abs().max().item() | ||
| 309 | + scale_rel = ((scale - gscale).abs() / (gscale.abs() + 1e-7)).max().item() | ||
| 310 | + th_xout = {torch.float16: 5e-3, torch.float32: 1e-4, torch.bfloat16: 4e-2}[dt] | ||
| 311 | + ok = (y_diff <= 1) and (xout_diff < th_xout) and (scale_rel < 5e-3) | ||
| 312 | + allpass &= ok | ||
| 313 | + _LOG.info("%s", f"[{'PASS' if ok else 'FAIL'}] {shape} D={D} {tld}: " | ||
| 314 | + f"y_maxdiff={y_diff} xout_diff={xout_diff:.2e} scale_rel={scale_rel:.2e}") | ||
| 315 | + _LOG.info("%s", "ALL_PASS" if allpass else "SOME_FAIL") | ||
| 316 | + | ||
| 317 | +if __name__ == "__main__": | ||
| 318 | + run_demo() | ||
| @@ -0,0 +1,267 @@ | |||
| 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 | +"""Vector-only FUSED add + rms_norm + per-token dynamic int8 quant — strided + pad-D 默认开. | ||
| 12 | + | ||
| 13 | +范式: VECTOR_ONLY_STRIDED · tiling-regime = row-structured (沿固定语义宽 D reduce). | ||
| 14 | +compose 自三个已证模板: | ||
| 15 | + - vector_only_reduce_strided.py (rms_norm fork: mean(x²)→rsqrt→scale) ← 主干 | ||
| 16 | + - vector_only_elementwise_strided.py (add residual: xOut = x1 + x2) | ||
| 17 | + - deepseek_v4/act_quant.py (per-token int8: amax→scale=max/127→div→clamp→round→cast) | ||
| 18 | + | ||
| 19 | +公式 (golden 对齐 torch_npu.npu_add_rms_norm_dynamic_quant): | ||
| 20 | + xOut = x1 + x2 # fp16/bf16 输出 | ||
| 21 | + y_norm = xOut / sqrt(mean(xOut²)+eps) * gamma # mean 除以 REAL D 不是 padded Dp | ||
| 22 | + scaleOut = row_max(|y_norm|) / 127 # fp32, 反量化系数, shape=(M,) | ||
| 23 | + y = round(clamp(y_norm/scaleOut, -127,127)) # int8, shape=(M,D) | ||
| 24 | + | ||
| 25 | +★ 默认翻转 (§0.1): 非对齐/多 dtype/质数 D 是基线. flatten leading→M 行, | ||
| 26 | + pad reduce-dim D→Dp(64 整数倍), 固定 tile, 无动态 L. pad 值: | ||
| 27 | + x1/x2 pad=0 (0+0=0, 0²=0 不进平方和), gamma pad=0 (0 不进 y_norm → 不污染 amax). | ||
| 28 | + 归一化分母 = REAL D (编译期标量 inv_D=1/real_D mul 进去, 非 padded 宽求平均). | ||
| 29 | + | ||
| 30 | +★ precision (gated): 全程 fp32 reduce/rsqrt/amax; int8 量化走 fp32→fp16→int8 双 cast | ||
| 31 | + (act_quant 范式). quantized_output → atol=1 (±1 LSB). | ||
| 32 | +""" | ||
| 33 | +import logging as _console_logging | ||
| 34 | +import sys as _console_sys | ||
| 35 | + | ||
| 36 | +import sys | ||
| 37 | +from pathlib import Path | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +class _StreamProxy: | ||
| 41 | + """Resolve stdout when writing so redirected output retains its destination.""" | ||
| 42 | + | ||
| 43 | + def __init__(self, sys_module=_console_sys): | ||
| 44 | + self._console_sys = sys_module | ||
| 45 | + | ||
| 46 | + def write(self, text: str) -> int: | ||
| 47 | + return self._console_sys.stdout.write(text) | ||
| 48 | + | ||
| 49 | + def flush(self) -> None: | ||
| 50 | + self._console_sys.stdout.flush() | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +_LOG = _console_logging.getLogger(__name__ + ".stdout") | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +def _init_loggers() -> None: | ||
| 57 | + """Keep console messages visible without changing the root logger.""" | ||
| 58 | + if not _LOG.handlers: | ||
| 59 | + handler = _console_logging.StreamHandler(_StreamProxy()) | ||
| 60 | + handler.setFormatter(_console_logging.Formatter("%(message)s")) | ||
| 61 | + _LOG.addHandler(handler) | ||
| 62 | + _LOG.setLevel(_console_logging.INFO) | ||
| 63 | + _LOG.propagate = False | ||
| 64 | + | ||
| 65 | + | ||
| 66 | +_init_loggers() | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def _add_kb_lib(): | ||
| 70 | + for _anc in Path(__file__).resolve().parents: | ||
| 71 | + for _cand in (_anc / "lib", _anc / "skills" / "tilelang-kernel-baseline" / "lib"): | ||
| 72 | + if (_cand / "chip_spec.py").exists(): | ||
| 73 | + sys.path.insert(0, str(_cand)) | ||
| 74 | + return | ||
| 75 | +_add_kb_lib() | ||
| 76 | +import tilelang | ||
| 77 | +from tilelang import language as T | ||
| 78 | +import torch | ||
| 79 | +# ⚠️ MAX_CORES = build-time 核数(烧死, 非运行时); 跨设备提交需运行时 GetCoreNumAiv, 见 chip_spec 注释 | ||
| 80 | +from chip_spec import cores as _soc_cores | ||
| 81 | + | ||
| 82 | +PAD_ALIGN = 64 # fp32 vector reduce block = 256B = 64 lane | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +def pad_align(D): | ||
| 86 | + return ((D + PAD_ALIGN - 1) // PAD_ALIGN) * PAD_ALIGN | ||
| 87 | + | ||
| 88 | + | ||
| 89 | +pass_configs = { | ||
| 90 | + tilelang.PassConfigKey.TL_ASCEND_AUTO_CV_COMBINE: False, | ||
| 91 | + tilelang.PassConfigKey.TL_ASCEND_AUTO_CV_SYNC: False, | ||
| 92 | + tilelang.PassConfigKey.TL_ASCEND_MEMORY_PLANNING: False, | ||
| 93 | + tilelang.PassConfigKey.TL_ASCEND_AUTO_SYNC: True, | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +INT8_ABS_MAX = 127.0 | ||
| 97 | +SCALE_EPS = 1e-12 # golden clamp(min=1e-12) 防全零行 0/0=NaN | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +@tilelang.jit(out_idx=[3, 4, 5], pass_configs=pass_configs) | ||
| 101 | +def add_rms_norm_dynamic_quant_strided(Dp, real_D, eps=1e-6, MAX_CORES=None, dtype="float16"): | ||
| 102 | + """row-wise add+rms_norm+per-token int8 quant over PADDED width Dp. | ||
| 103 | + real_D = 真 reduce 宽 (mean 分母 + amax 范围), Dp = pad 到 64 整数倍 (编译期常量). | ||
| 104 | + M symbolic; MAX_CORES cubes stride over rows. | ||
| 105 | + Outputs (out_idx=[3,4,5]): Y(int8 M,Dp), XOUT(dtype M,Dp), SCALE(fp32 M,1). | ||
| 106 | + """ | ||
| 107 | + if MAX_CORES is None: | ||
| 108 | + MAX_CORES = _soc_cores() | ||
| 109 | + sym_M = T.symbolic("M") | ||
| 110 | + not_fp32 = dtype != "float32" | ||
| 111 | + inv_D = 1.0 / real_D # 编译期标量 — 归一化除以 REAL D 不是 Dp | ||
| 112 | + | ||
| 113 | + @T.prim_func | ||
| 114 | + def main( | ||
| 115 | + X1: T.Tensor((sym_M, Dp), dtype), | ||
| 116 | + X2: T.Tensor((sym_M, Dp), dtype), | ||
| 117 | + GAMMA: T.Tensor((Dp,), dtype), | ||
| 118 | + Y: T.Tensor((sym_M, Dp), "int8"), | ||
| 119 | + XOUT: T.Tensor((sym_M, Dp), dtype), | ||
| 120 | + SCALE: T.Tensor((sym_M, 1), "float32"), | ||
| 121 | + ): | ||
| 122 | + with T.Kernel(MAX_CORES, is_npu=True) as (cid_base, vid): | ||
| 123 | + # ── buffer 收敛 (ub_budget) : 2 dtype + 4 fp32 + 1 fp16 + 1 int8 wide ── | ||
| 124 | + io_ub = T.alloc_ub([1, Dp], dtype) # X1/X2 load + xOut writeback (复用) | ||
| 125 | + g_ub = T.alloc_ub([1, Dp], dtype) # gamma (load once) | ||
| 126 | + g_fp = T.alloc_ub([1, Dp], "float32") | ||
| 127 | + x_fp = T.alloc_ub([1, Dp], "float32") # xOut → y_norm → quant scratch (in-place) | ||
| 128 | + sq = T.alloc_ub([1, Dp], "float32") # x2_fp / x² / |y| scratch (复用) | ||
| 129 | + r_t = T.alloc_ub([1, Dp], "float32") # broadcast scratch | ||
| 130 | + y_half = T.alloc_ub([1, Dp], "float16") # fp32→fp16 step of int8 cast | ||
| 131 | + y_i8 = T.alloc_ub([1, Dp], "int8") | ||
| 132 | + rsum = T.alloc_ub([1, 1], "float32") | ||
| 133 | + ramax = T.alloc_ub([1, 1], "float32") | ||
| 134 | + scl = T.alloc_ub([1, 1], "float32") | ||
| 135 | + iter_count = T.ceildiv(sym_M, MAX_CORES) | ||
| 136 | + with T.Scope("V"): | ||
| 137 | + # gamma load once outside stride loop (per-channel [Dp], pad lanes = 0) | ||
| 138 | + T.copy(GAMMA[0:Dp], g_ub[0, 0:Dp]) | ||
| 139 | + if not_fp32: | ||
| 140 | + T.tile.cast(g_fp, g_ub, "CAST_NONE", Dp) | ||
| 141 | + else: | ||
| 142 | + T.copy(g_ub, g_fp) | ||
| 143 | + for iter_idx in T.serial(iter_count): | ||
| 144 | + cid = cid_base + iter_idx * MAX_CORES | ||
| 145 | + if cid < sym_M: | ||
| 146 | + # ── add residual: xOut = x1 + x2 (in fp32) ── | ||
| 147 | + T.copy(X1[cid:cid + 1, 0:Dp], io_ub) | ||
| 148 | + if not_fp32: | ||
| 149 | + T.tile.cast(x_fp, io_ub, "CAST_NONE", Dp) | ||
| 150 | + else: | ||
| 151 | + T.copy(io_ub, x_fp) | ||
| 152 | + T.copy(X2[cid:cid + 1, 0:Dp], io_ub) # reuse io_ub for x2 load | ||
| 153 | + if not_fp32: | ||
| 154 | + T.tile.cast(sq, io_ub, "CAST_NONE", Dp) | ||
| 155 | + else: | ||
| 156 | + T.copy(io_ub, sq) | ||
| 157 | + T.tile.add(x_fp, x_fp, sq) # x_fp = xOut | ||
| 158 | + # write xOut back; padded lanes harmless (host slices [:, :real_D]) | ||
| 159 | + if not_fp32: | ||
| 160 | + T.tile.cast(io_ub, x_fp, "CAST_RINT", Dp) # reuse io_ub for writeback | ||
| 161 | + else: | ||
| 162 | + T.copy(x_fp, io_ub) | ||
| 163 | + T.copy(io_ub, XOUT[cid:cid + 1, 0:Dp]) | ||
| 164 | + # ── rms_norm: y_norm = xOut * rsqrt(mean(xOut²)+eps) * gamma (in-place in x_fp) ── | ||
| 165 | + T.tile.mul(sq, x_fp, x_fp) # xOut² (pad=0² → 0, 不进 sum) | ||
| 166 | + T.reduce_sum(sq, rsum, dim=-1) # sum(xOut²) over Dp == over real_D | ||
| 167 | + T.tile.mul(rsum, rsum, inv_D) # mean = sum / REAL D | ||
| 168 | + T.tile.add(rsum, rsum, eps) # mean + eps | ||
| 169 | + T.tile.rsqrt(rsum, rsum) # 1/sqrt(mean+eps) | ||
| 170 | + T.tile.broadcast(r_t, rsum) # [1,1]→[1,Dp] | ||
| 171 | + T.tile.mul(x_fp, x_fp, r_t) # xOut * rstd | ||
| 172 | + T.tile.mul(x_fp, x_fp, g_fp) # * gamma → y_norm (pad gamma=0 → 0) | ||
| 173 | + # ── per-token dynamic int8 quant ── | ||
| 174 | + T.tile.abs(sq, x_fp) # |y_norm| (pad=0) | ||
| 175 | + T.reduce_max(sq, ramax, dim=-1) # row amax over Dp == over real_D | ||
| 176 | + T.tile.mul(ramax, ramax, 1.0 / INT8_ABS_MAX) # scale = amax/127 | ||
| 177 | + T.tile.add(scl, ramax, SCALE_EPS) # +eps guard (amax≥0 → ≈clamp(min)) | ||
| 178 | + T.copy(scl, SCALE[cid:cid + 1, 0:1]) # write scaleOut (fp32) | ||
| 179 | + T.tile.broadcast(r_t, scl) # [1,1]→[1,Dp] | ||
| 180 | + T.tile.div(x_fp, x_fp, r_t) # y_norm / scale | ||
| 181 | + T.tile.clamp(x_fp, x_fp, -127.0, 127.0, Dp) | ||
| 182 | + T.tile.round(x_fp, x_fp, Dp) # round-to-nearest | ||
| 183 | + # values already round-to-int in [-127,127]: fp16 holds exactly. | ||
| 184 | + T.tile.cast(y_half, x_fp, "CAST_RINT", Dp) # fp32→fp16 (RINT precision.md §downcast) | ||
| 185 | + T.tile.cast(y_i8, y_half, "CAST_TRUNC", Dp) # fp16→int8 (TRUNC = INT8 final cast) | ||
| 186 | + T.copy(y_i8, Y[cid:cid + 1, 0:Dp]) | ||
| 187 | + | ||
| 188 | + return main | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +# ---- HOST flatten + pad-D 包装 (build_op 里进 pybind_pre/post) ---- | ||
| 192 | +def run_op(x1, x2, gamma, eps, dtype_tl): | ||
| 193 | + """x1,x2: (..., D) torch; gamma: (D,). flatten leading → (M, D), pad real_D → Dp | ||
| 194 | + (0 fill), 跑 kernel, 切回 real_D。返回 (y_int8, xOut, scale). | ||
| 195 | + """ | ||
| 196 | + real_D = x1.shape[-1] | ||
| 197 | + M = x1.numel() // real_D | ||
| 198 | + x1f = x1.reshape(M, real_D) | ||
| 199 | + x2f = x2.reshape(M, real_D) | ||
| 200 | + Dp = pad_align(real_D) | ||
| 201 | + x1p = torch.zeros((M, Dp), dtype=x1.dtype) | ||
| 202 | + x1p[:, :real_D] = x1f | ||
| 203 | + x2p = torch.zeros((M, Dp), dtype=x2.dtype) | ||
| 204 | + x2p[:, :real_D] = x2f | ||
| 205 | + gp = torch.zeros((Dp,), dtype=gamma.dtype) | ||
| 206 | + gp[:real_D] = gamma | ||
| 207 | + k = add_rms_norm_dynamic_quant_strided(Dp, real_D, eps, None, dtype_tl) | ||
| 208 | + y, xout, scale = k(x1p.npu(), x2p.npu(), gp.npu()) | ||
| 209 | + y = y.detach().cpu()[:, :real_D].reshape(x1.shape) | ||
| 210 | + xout = xout.detach().cpu()[:, :real_D].reshape(x1.shape) | ||
| 211 | + scale = scale.detach().cpu().reshape(M) | ||
| 212 | + return y, xout, scale | ||
| 213 | + | ||
| 214 | + | ||
| 215 | +def golden(x1, x2, gamma, eps): | ||
| 216 | + out_dtype = x1.dtype | ||
| 217 | + x1 = x1.float() | ||
| 218 | + x2 = x2.float() | ||
| 219 | + gamma = gamma.float() | ||
| 220 | + xOut = x1 + x2 | ||
| 221 | + var = xOut.pow(2).mean(-1, keepdim=True) | ||
| 222 | + y_norm = xOut * torch.rsqrt(var + eps) * gamma | ||
| 223 | + abs_max = y_norm.abs().amax(dim=-1, keepdim=True) | ||
| 224 | + scale = (abs_max.clamp(min=1e-12) / 127.0) | ||
| 225 | + y = torch.clamp((y_norm / scale).round(), -128, 127).to(torch.int8) | ||
| 226 | + return y, xOut.to(out_dtype), scale.squeeze(-1).float() | ||
| 227 | + | ||
| 228 | + | ||
| 229 | +def run_demo(): | ||
| 230 | + import torch_npu # noqa | ||
| 231 | + tilelang.disable_cache() | ||
| 232 | + torch.manual_seed(0) | ||
| 233 | + TLD = {torch.float16: "float16", torch.float32: "float32", torch.bfloat16: "bfloat16"} | ||
| 234 | + # REAL cann-bench regime: 非对齐/质数 D + 多 dtype + 多值域 (取自 cases.yaml)。 | ||
| 235 | + cases = [ | ||
| 236 | + ((512, 512), 1e-6, torch.float16, (-1, 1)), # c15 smoke aligned | ||
| 237 | + ((1021, 1023), 1e-6, torch.bfloat16, (-0.1, 0.1)), # c16 质数非对齐 bf16 | ||
| 238 | + ((1024, 128), 1e-6, torch.float16, (-1, 1)), # c19-style small D | ||
| 239 | + ((256, 257), 1e-6, torch.float16, (-2, 2)), # 质数非对齐 fp16 | ||
| 240 | + ((300, 4093), 1e-6, torch.bfloat16, (-1, 2)), # c12-style 质数 4093 bf16 | ||
| 241 | + ((200, 2053), 1e-5, torch.float16, (-3, 6)), # c13-style 质数 2053 fp16 | ||
| 242 | + ((128, 4096), 1e-6, torch.float32, (-2, 2)), # fp32 aligned | ||
| 243 | + ((100, 373), 1e-6, torch.float32, (-2, 2)), # fp32 质数非对齐 (天真版崩) | ||
| 244 | + ] | ||
| 245 | + allpass = True | ||
| 246 | + for shape, eps, dt, (lo, hi) in cases: | ||
| 247 | + tld = TLD[dt] | ||
| 248 | + M, D = shape | ||
| 249 | + x1 = (torch.rand(M, D) * (hi - lo) + lo).to(dt) | ||
| 250 | + x2 = (torch.rand(M, D) * (hi - lo) + lo).to(dt) | ||
| 251 | + gamma = (torch.rand(D) * 2 - 1).to(dt) | ||
| 252 | + y, xout, scale = run_op(x1, x2, gamma, eps, tld) | ||
| 253 | + gy, gxout, gscale = golden(x1, x2, gamma, eps) | ||
| 254 | + # int8: ±1 LSB tolerance (quantized_output) | ||
| 255 | + y_diff = (y.int() - gy.int()).abs().max().item() | ||
| 256 | + xout_diff = (xout.float() - gxout.float()).abs().max().item() | ||
| 257 | + scale_rel = ((scale - gscale).abs() / (gscale.abs() + 1e-7)).max().item() | ||
| 258 | + th_xout = {torch.float16: 5e-3, torch.float32: 1e-4, torch.bfloat16: 4e-2}[dt] | ||
| 259 | + ok = (y_diff <= 1) and (xout_diff < th_xout) and (scale_rel < 5e-3) | ||
| 260 | + allpass &= ok | ||
| 261 | + Dp = pad_align(D) | ||
| 262 | + _LOG.info("%s", f"[{'PASS' if ok else 'FAIL'}] {shape} D={D}->Dp={Dp} {tld}: " | ||
| 263 | + f"y_maxdiff={y_diff} xout_diff={xout_diff:.2e} scale_rel={scale_rel:.2e}") | ||
| 264 | + _LOG.info("%s", "ALL_PASS" if allpass else "SOME_FAIL") | ||
| 265 | + | ||
| 266 | +if __name__ == "__main__": | ||
| 267 | + run_demo() | ||
| @@ -0,0 +1,172 @@ | |||
| 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 | +"""build_adaptive_avg_pool_3d — VECTOR_ONLY_STRIDED + host adaptive-window gather (mean-pool). | ||
| 12 | + | ||
| 13 | +adaptive_avg_pool3d: out[b,c,od,oh,ow] = mean over x[b,c, ds:de, hs:he, ws:we] | ||
| 14 | + ds=floor(od*D/OD), de=ceil((od+1)*D/OD) (同 H/W). 窗口大小逐输出位置变化. | ||
| 15 | +语义 = 窗口 mean-reduce (reduce 类), 故 paradigm = VECTOR_ONLY_STRIDED; | ||
| 16 | +与 dilation2d 同构 (窗口展开 host + kernel 每行 reduce), 差异: reduce_sum→×INV (mean), | ||
| 17 | +INV 逐行 (M,NPAD broadcast) 因窗口大小逐行变. | ||
| 18 | + | ||
| 19 | +kernel: output/AdaptiveAvgPool3d/adaptive_avg_pool_3d_strided.py | ||
| 20 | + (fork dilation_2d_strided; reduce 链 add-se→max 换成 sum→×inv; K pad 32B pad=0; 输出 widen 16). | ||
| 21 | +OpDef 内部: A(M,Kpad)+INV(M,NPAD) → Y(M,NPAD); user-facing = x(B,C,D,H,W) + output_size 编入 build. | ||
| 22 | +single-binary fp16 (JIT smoke fp16/fp32/bf16 全 PASS; 部署单 dtype 同 ExpTl/dilation 约定). | ||
| 23 | + | ||
| 24 | +★ output_size 处理 ★: adaptive pool 的 output_size 是构建期常量 (编进 KPAD 推导 + host 循环). | ||
| 25 | + 本 build 锁定 OUT=(4,4,4) 单 binary; 其它 output_size 需另 build (同 conv shape-specialized 约定). | ||
| 26 | +""" | ||
| 27 | +import logging as _console_logging | ||
| 28 | +import sys as _console_sys | ||
| 29 | + | ||
| 30 | +import sys | ||
| 31 | +from pathlib import Path | ||
| 32 | +PROJECT_ROOT = Path(__file__).resolve().parents[2] | ||
| 33 | +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # .../lib —— 自定位, | ||
| 34 | +# 不经 PROJECT_ROOT:op_builder 属技能侧,与用户算子工程不在同一棵树 | ||
| 35 | +from op_builder import build_op, Paradigm, Input, Output, KernelSource | ||
| 36 | + | ||
| 37 | +# ── build-time constants: output_size + derived Kpad/NPAD ── | ||
| 38 | +OD = OH = OW = 4 # adaptive output size (this binary) | ||
| 39 | +NPAD = 16 # output width pad (单元素 store <32B → 507015) | ||
| 40 | +# Kpad must cover the worst-case 3D window over the deployed input range. | ||
| 41 | +# For OUT=(4,4,4), maxwin per dim: In8->2, In≤16->≤4. Worst 3D window vol = 4*4*4 = 64. | ||
| 42 | +# Pick KPAD=64 (32B-mult) so input dims up to 16 are covered; pad lane = 0 (sum-safe). | ||
| 43 | +KPAD = 64 | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +# host adaptive-window gather (runs before EXEC_NPU_CMD). | ||
| 47 | +# user input: x (B,C,D,H,W). Produce OpDef tensors A (M,KPAD) pad=0, INV (M,NPAD)=1/vol. | ||
| 48 | +PYBIND_PREPROCESS = f""" | ||
| 49 | + // ── adaptive_avg_pool3d pre-process: host adaptive-window gather ── | ||
| 50 | + auto x_sizes = x.sizes(); // (B, C, D, H, W) | ||
| 51 | + int64_t Bsz = x_sizes[0]; | ||
| 52 | + int64_t C_in = x_sizes[1]; | ||
| 53 | + int64_t Din = x_sizes[2]; | ||
| 54 | + int64_t Hin = x_sizes[3]; | ||
| 55 | + int64_t Win = x_sizes[4]; | ||
| 56 | + const int64_t ODc = {OD}, OHc = {OH}, OWc = {OW}; | ||
| 57 | + const int64_t Kp = {KPAD}, Np = {NPAD}; | ||
| 58 | + int64_t Mrows = Bsz * C_in * ODc * OHc * OWc; | ||
| 59 | + // ★ host gather MUST be on CPU ★: x arrives on NPU; .accessor<> needs a CPU tensor — | ||
| 60 | + // writing an NPU tensor via host accessor → invalid mem (507015/segfault, faults inside | ||
| 61 | + // the implicit aclnnInplaceCopy/Cast, NOT the custom kernel). Build A + xf on CPU, fill | ||
| 62 | + // via accessor, then .to(x.options()) moves to NPU at the end. | ||
| 63 | + auto cpu_f = at::TensorOptions().dtype(at::kFloat).device(at::kCPU); | ||
| 64 | + // A: (Mrows, Kp) pad=0; each window element PRE-DIVIDED by its volume → kernel sum = mean | ||
| 65 | + at::Tensor A = at::zeros({{Mrows, Kp}}, cpu_f); | ||
| 66 | + auto xf = x.to(at::kCPU).to(at::kFloat).contiguous(); | ||
| 67 | + auto A_acc = A.accessor<float, 2>(); | ||
| 68 | + auto xf_acc = xf.accessor<float, 5>(); | ||
| 69 | + (void)Np; | ||
| 70 | + int64_t m = 0; | ||
| 71 | + for (int64_t b = 0; b < Bsz; ++b) | ||
| 72 | + for (int64_t c = 0; c < C_in; ++c) | ||
| 73 | + for (int64_t oi = 0; oi < ODc; ++oi) {{ | ||
| 74 | + int64_t ds = (oi * Din) / ODc; | ||
| 75 | + int64_t de = ((oi + 1) * Din + ODc - 1) / ODc; | ||
| 76 | + for (int64_t oj = 0; oj < OHc; ++oj) {{ | ||
| 77 | + int64_t hs = (oj * Hin) / OHc; | ||
| 78 | + int64_t he = ((oj + 1) * Hin + OHc - 1) / OHc; | ||
| 79 | + for (int64_t ok = 0; ok < OWc; ++ok) {{ | ||
| 80 | + int64_t ws = (ok * Win) / OWc; | ||
| 81 | + int64_t we = ((ok + 1) * Win + OWc - 1) / OWc; | ||
| 82 | + float inv = 1.0f / (float)((de - ds) * (he - hs) * (we - ws)); | ||
| 83 | + int64_t kk = 0; | ||
| 84 | + for (int64_t dd = ds; dd < de; ++dd) | ||
| 85 | + for (int64_t hh = hs; hh < he; ++hh) | ||
| 86 | + for (int64_t ww = ws; ww < we; ++ww) {{ | ||
| 87 | + A_acc[m][kk] = xf_acc[b][c][dd][hh][ww] * inv; // pre-divide | ||
| 88 | + ++kk; | ||
| 89 | + }} | ||
| 90 | + ++m; | ||
| 91 | + }} | ||
| 92 | + }} | ||
| 93 | + }} | ||
| 94 | + A = A.to(x.options()); // back to kernel dtype (float16) | ||
| 95 | +""" | ||
| 96 | + | ||
| 97 | +# after EXEC_NPU_CMD: Y is (Mrows, NPAD); take col 0 and reshape to (B,C,OD,OH,OW). | ||
| 98 | +PYBIND_POSTPROCESS = f""" | ||
| 99 | + // ── adaptive_avg_pool3d post-process: (M,NPAD) → (B,C,OD,OH,OW) ── | ||
| 100 | + auto Y_col0 = Y.slice(1, 0, 1).contiguous().view({{Bsz, C_in, {OD}, {OH}, {OW}}}); | ||
| 101 | + Y = Y_col0; | ||
| 102 | +""" | ||
| 103 | + | ||
| 104 | + | ||
| 105 | +class _StreamProxy: | ||
| 106 | + """Resolve stdout when writing so redirected output retains its destination.""" | ||
| 107 | + | ||
| 108 | + def __init__(self, sys_module=_console_sys): | ||
| 109 | + self._console_sys = sys_module | ||
| 110 | + | ||
| 111 | + def write(self, text: str) -> int: | ||
| 112 | + return self._console_sys.stdout.write(text) | ||
| 113 | + | ||
| 114 | + def flush(self) -> None: | ||
| 115 | + self._console_sys.stdout.flush() | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +_LOG = _console_logging.getLogger(__name__ + ".stdout") | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def _init_loggers() -> None: | ||
| 122 | + """Keep console messages visible without changing the root logger.""" | ||
| 123 | + if not _LOG.handlers: | ||
| 124 | + handler = _console_logging.StreamHandler(_StreamProxy()) | ||
| 125 | + handler.setFormatter(_console_logging.Formatter("%(message)s")) | ||
| 126 | + _LOG.addHandler(handler) | ||
| 127 | + _LOG.setLevel(_console_logging.INFO) | ||
| 128 | + _LOG.propagate = False | ||
| 129 | + | ||
| 130 | + | ||
| 131 | +_init_loggers() | ||
| 132 | + | ||
| 133 | + | ||
| 134 | +def main(): | ||
| 135 | + r = build_op( | ||
| 136 | + op_name='adaptive_avg_pool3d_custom', | ||
| 137 | + paradigm=Paradigm.VECTOR_ONLY_STRIDED, | ||
| 138 | + kernel=KernelSource( | ||
| 139 | + module='adaptive_avg_pool_3d_strided', func='adaptive_avg_pool_3d_strided', | ||
| 140 | + compile_args=(KPAD, None, 'float16'), | ||
| 141 | + sys_path_add='output/AdaptiveAvgPool3d', | ||
| 142 | + ), | ||
| 143 | + inputs=[ | ||
| 144 | + Input('A', 'float16', ('M', 'K')), | ||
| 145 | + ], | ||
| 146 | + outputs=[ | ||
| 147 | + # output width = NPAD literal 16 (kernel widens single-elem store to 16); | ||
| 148 | + # K(=64) != NPAD(=16) so can't reuse input dim — emit literal in InferShape. | ||
| 149 | + Output('Y', 'float16', ('M', str(NPAD))), | ||
| 150 | + ], | ||
| 151 | + workspaces=[], | ||
| 152 | + op_dir='output/AdaptiveAvgPool3d/AdaptiveAvgPool3dCustom', | ||
| 153 | + project_root=str(PROJECT_ROOT), | ||
| 154 | + tiling_fields=['M'], | ||
| 155 | + dynamic_params=[], | ||
| 156 | + bypass_preflight=True, | ||
| 157 | + auto_emit_host=True, | ||
| 158 | + | ||
| 159 | + # pybind: user-facing (x); inject host adaptive-window gather + reshape | ||
| 160 | + pybind_dir='output/AdaptiveAvgPool3d/ascend_op_pybind/CppExtension', | ||
| 161 | + pybind_alias='adaptive_avg_pool3d_custom', | ||
| 162 | + pybind_user_signature=[ | ||
| 163 | + Input('x', 'float16', ('B', 'C_in', 'D', 'H', 'W')), | ||
| 164 | + ], | ||
| 165 | + pybind_preprocess=PYBIND_PREPROCESS, | ||
| 166 | + pybind_postprocess=PYBIND_POSTPROCESS, | ||
| 167 | + ) | ||
| 168 | + _LOG.info("%s %s", "AdaptiveAvgPool3d VECTOR_ONLY_STRIDED build_op E2E:", r.run_pkg) | ||
| 169 | + | ||
| 170 | + | ||
| 171 | +if __name__ == '__main__': | ||
| 172 | + main() | ||
| @@ -0,0 +1,92 @@ | |||
| 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 | +"""build_add_rms_norm_dynamic_quant — VECTOR_ONLY_STRIDED fused add+rms_norm+per-token int8 quant. | ||
| 12 | + | ||
| 13 | +compose 自 rms_norm (reduce) + add (elementwise) + act_quant (per-token int8). | ||
| 14 | +3-in (X1,X2,GAMMA) / 3-out (Y int8, XOUT fp16, SCALE fp32). out_idx=[3,4,5]. | ||
| 15 | + | ||
| 16 | +baked shape: Dp=512 real_D=512 fp16 (case-15 smoke, aligned). M symbolic. | ||
| 17 | +非对齐 D 通过 host pad 到 Dp (pybind_preprocess / test.py 侧). 多 dtype = 多 build. | ||
| 18 | +""" | ||
| 19 | +import logging as _console_logging | ||
| 20 | +import sys as _console_sys | ||
| 21 | + | ||
| 22 | +import sys | ||
| 23 | +from pathlib import Path | ||
| 24 | +PROJECT_ROOT = Path(__file__).resolve().parents[2] | ||
| 25 | +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # .../lib —— 自定位, | ||
| 26 | +# 不经 PROJECT_ROOT:op_builder 属技能侧,与用户算子工程不在同一棵树 | ||
| 27 | +from op_builder import build_op, Paradigm, Input, Output, KernelSource | ||
| 28 | + | ||
| 29 | +Dp = 512 | ||
| 30 | +real_D = 512 | ||
| 31 | +EPS = 1e-6 | ||
| 32 | +DT = 'float16' | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +class _StreamProxy: | ||
| 36 | + """Resolve stdout when writing so redirected output retains its destination.""" | ||
| 37 | + | ||
| 38 | + def __init__(self, sys_module=_console_sys): | ||
| 39 | + self._console_sys = sys_module | ||
| 40 | + | ||
| 41 | + def write(self, text: str) -> int: | ||
| 42 | + return self._console_sys.stdout.write(text) | ||
| 43 | + | ||
| 44 | + def flush(self) -> None: | ||
| 45 | + self._console_sys.stdout.flush() | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +_LOG = _console_logging.getLogger(__name__ + ".stdout") | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def _init_loggers() -> None: | ||
| 52 | + """Keep console messages visible without changing the root logger.""" | ||
| 53 | + if not _LOG.handlers: | ||
| 54 | + handler = _console_logging.StreamHandler(_StreamProxy()) | ||
| 55 | + handler.setFormatter(_console_logging.Formatter("%(message)s")) | ||
| 56 | + _LOG.addHandler(handler) | ||
| 57 | + _LOG.setLevel(_console_logging.INFO) | ||
| 58 | + _LOG.propagate = False | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +_init_loggers() | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def main(): | ||
| 65 | + r = build_op( | ||
| 66 | + op_name='add_rms_norm_dynamic_quant_custom', | ||
| 67 | + paradigm=Paradigm.VECTOR_ONLY_STRIDED, | ||
| 68 | + kernel=KernelSource( | ||
| 69 | + module='add_rms_norm_dynamic_quant_strided', | ||
| 70 | + func='add_rms_norm_dynamic_quant_strided', | ||
| 71 | + compile_args=(Dp, real_D, EPS, None, DT), | ||
| 72 | + sys_path_add='output/AddRmsNormDynamicQuant'), | ||
| 73 | + inputs=[ | ||
| 74 | + Input('X1', DT, ('M', 'D')), | ||
| 75 | + Input('X2', DT, ('M', 'D')), | ||
| 76 | + Input('GAMMA', DT, ('D',)), | ||
| 77 | + ], | ||
| 78 | + outputs=[ | ||
| 79 | + Output('Y', 'int8', ('M', 'D')), | ||
| 80 | + Output('XOUT', DT, ('M', 'D')), | ||
| 81 | + Output('SCALE', 'float32', ('M', '1')), | ||
| 82 | + ], | ||
| 83 | + workspaces=[], | ||
| 84 | + op_dir='output/AddRmsNormDynamicQuant/AddRmsNormDynamicQuantCustom', | ||
| 85 | + project_root=str(PROJECT_ROOT), | ||
| 86 | + tiling_fields=['M'], dynamic_params=[], | ||
| 87 | + bypass_preflight=True, auto_emit_host=True) | ||
| 88 | + _LOG.info("%s %s", "AddRmsNormDynamicQuant VECTOR_ONLY_STRIDED build_op E2E:", r.run_pkg) | ||
| 89 | + | ||
| 90 | + | ||
| 91 | +if __name__ == '__main__': | ||
| 92 | + main() | ||
| @@ -0,0 +1,114 @@ | |||
| 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 | +"""build_add_rms_norm_dynamic_quant_multidtype — fp16 + bf16, RUNTIME-Dp tiled. | ||
| 12 | + | ||
| 13 | +Root fix v2 (runtime-Dp): the strided DSL baked Dp=512 compile-time → single binary only | ||
| 14 | +processed 512 cols → eval D=4096/8192/16384 int8 ~90% wrong → net 1/20. This switches to | ||
| 15 | +add_rms_norm_dynamic_quant_runtime_dp.py where Dp is T.symbolic("Dp") (lowers to inner | ||
| 16 | +kernel `int64_t Dp`), UB buffers are TILE=512 wide, and 3 inner ceildiv(Dp,512) tile-loops | ||
| 17 | +stream the row → ONE binary handles any D without UB overflow (mirrors run157 proven kernel). | ||
| 18 | + | ||
| 19 | +Still TWO dtype buckets dispatched by input dtype (fp16 tk=0, bf16 tk=1); ζ multi-dtype | ||
| 20 | +emitter declares both DT_FLOAT16 + DT_BF16 in OpDef + XOUT InferDataType mirrors input. | ||
| 21 | + | ||
| 22 | +4th input INVD (fp32 [2] = [1/real_D, eps]) carries the runtime mean divisor + eps. The | ||
| 23 | +op_plugin must synthesize INVD from the upstream schema (x1,x2,gamma,float eps) — see run157. | ||
| 24 | + | ||
| 25 | +Set CAKE_TARGET_CORES=20 for 910c before running. | ||
| 26 | +""" | ||
| 27 | +import logging as _console_logging | ||
| 28 | +import sys as _console_sys | ||
| 29 | + | ||
| 30 | +import sys | ||
| 31 | +from pathlib import Path | ||
| 32 | +_P = Path(__file__).resolve() | ||
| 33 | +LIB = _P.parents[2] # .../skills/tilelang-host-bridge/lib | ||
| 34 | +PROJECT_ROOT = _P.parents[5] # repo root (pure-tilelang) | ||
| 35 | +sys.path.insert(0, str(LIB)) | ||
| 36 | +from op_builder import build_op, Paradigm, Input, Output, KernelSource, BucketSpec | ||
| 37 | + | ||
| 38 | +DSL_DIR = 'skills/tilelang-host-bridge/lib/op_builder/examples' | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +class _StreamProxy: | ||
| 42 | + """Resolve stdout when writing so redirected output retains its destination.""" | ||
| 43 | + | ||
| 44 | + def __init__(self, sys_module=_console_sys): | ||
| 45 | + self._console_sys = sys_module | ||
| 46 | + | ||
| 47 | + def write(self, text: str) -> int: | ||
| 48 | + return self._console_sys.stdout.write(text) | ||
| 49 | + | ||
| 50 | + def flush(self) -> None: | ||
| 51 | + self._console_sys.stdout.flush() | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +_LOG = _console_logging.getLogger(__name__ + ".stdout") | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +def _init_loggers() -> None: | ||
| 58 | + """Keep console messages visible without changing the root logger.""" | ||
| 59 | + if not _LOG.handlers: | ||
| 60 | + handler = _console_logging.StreamHandler(_StreamProxy()) | ||
| 61 | + handler.setFormatter(_console_logging.Formatter("%(message)s")) | ||
| 62 | + _LOG.addHandler(handler) | ||
| 63 | + _LOG.setLevel(_console_logging.INFO) | ||
| 64 | + _LOG.propagate = False | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +_init_loggers() | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +def kernel_source(dtype): | ||
| 71 | + return KernelSource( | ||
| 72 | + module='add_rms_norm_dynamic_quant_runtime_dp', | ||
| 73 | + func='add_rms_norm_dynamic_quant_runtime_dp', | ||
| 74 | + compile_args=(None, dtype), # MAX_CORES=None (env), dtype; Dp/real_D/eps now RUNTIME | ||
| 75 | + sys_path_add=DSL_DIR) | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def main(): | ||
| 79 | + buckets = [ | ||
| 80 | + BucketSpec(kernel=kernel_source('float16'), tiling_key=0, | ||
| 81 | + kernel_symbol='arndq_fp16', | ||
| 82 | + dispatch_condition='dt == ge::DT_FLOAT16'), | ||
| 83 | + BucketSpec(kernel=kernel_source('bfloat16'), tiling_key=1, | ||
| 84 | + kernel_symbol='arndq_bf16', | ||
| 85 | + dispatch_condition='dt == ge::DT_BF16'), | ||
| 86 | + ] | ||
| 87 | + r = build_op( | ||
| 88 | + op_name='add_rms_norm_dynamic_quant_custom', | ||
| 89 | + paradigm=Paradigm.VECTOR_ONLY_STRIDED, | ||
| 90 | + kernel=buckets[0].kernel, # placeholder; buckets drives compile | ||
| 91 | + inputs=[ | ||
| 92 | + Input('X1', 'float16', ('M', 'Dp')), | ||
| 93 | + Input('X2', 'float16', ('M', 'Dp')), | ||
| 94 | + Input('GAMMA', 'float16', ('Dp',)), | ||
| 95 | + Input('INVD', 'float32', (2,)), # [1/real_D, eps]; literal dim (not symbolic) | ||
| 96 | + ], | ||
| 97 | + outputs=[ | ||
| 98 | + Output('Y', 'int8', ('M', 'Dp')), | ||
| 99 | + Output('XOUT', 'float16', ('M', 'Dp')), | ||
| 100 | + Output('SCALE', 'float32', ('M',)), | ||
| 101 | + ], | ||
| 102 | + workspaces=[], | ||
| 103 | + op_dir='output/AddRmsNormDynamicQuant/AddRmsNormDynamicQuantCustomRuntimeDp', | ||
| 104 | + project_root=str(PROJECT_ROOT), | ||
| 105 | + tiling_fields=['M', 'Dp', 'tiling_key'], dynamic_params=[], | ||
| 106 | + buckets=buckets, | ||
| 107 | + tiling_key_dtype_input_idx=0, # dispatch on X1 dtype | ||
| 108 | + dtype_variants=['float16', 'bfloat16'], # ζ: multi-dtype OpDef | ||
| 109 | + bypass_preflight=True, auto_emit_host=True) | ||
| 110 | + _LOG.info("%s %s", "AddRmsNormDynamicQuant runtime-Dp multi-dtype build_op:", r.run_pkg) | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +if __name__ == '__main__': | ||
| 114 | + main() | ||
| @@ -0,0 +1,114 @@ | |||
| 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 | +"""SORT_SELECT first E2E: build cann-bench ArgMax via build_op() API. | ||
| 12 | + | ||
| 13 | +arg_max(dim=-1): row-reduce over N → INDEX of max. Output int32 (CANN op dtype; | ||
| 14 | +bench indices=int64 提升在 harness 侧, bitwise-equal). Vendor-compatible strided | ||
| 15 | +skeleton (same host emit as VECTOR_ONLY_STRIDED; only diff = int output dtype). | ||
| 16 | + | ||
| 17 | +kernel = templates/kernel_examples/sort_select_argmax_strided.py (port of | ||
| 18 | +$TL_ROOT/examples/topk_selector: argmax = topk(K=1) index 分量). | ||
| 19 | + | ||
| 20 | +Validated 2026-06-24: JIT 4/4 PASS (M∈{4,52,2048,1024}×fp16/fp32, 0 mismatch vs | ||
| 21 | +torch.argmax) + scaffold + build_op emit + bisheng compile + install PASS | ||
| 22 | +(REGISTER_CUSTOM_OP ArgMaxCustom, aclnnArgMaxCustom(x,out)). | ||
| 23 | + | ||
| 24 | +Two fork pitfalls surfaced + fixed (tool-first, see PARADIGM_GAPS batch-2 sediment): | ||
| 25 | + 1. emitter: tiling_extras key that is ALSO a shape-derived primary sym → op_host | ||
| 26 | + "redeclaration of const uint32_t N". Fixed in emitters.py (skip k in sym_map). | ||
| 27 | + Best practice: keep shape dims OUT of tiling_extras (only K/consts go there). | ||
| 28 | + 2. tl_helper.h: vendor's stale 4-arg TopK vs JIT-emitted 6-arg → "no matching | ||
| 29 | + function". Fixed by syncing Sort+TopK from common.h into op_project_skeleton. | ||
| 30 | + | ||
| 31 | +Run from project root with TL env (tlcheck ensure) + TILELANG_CACHE_DIR set: | ||
| 32 | + python skills/tilelang-host-bridge/lib/op_builder/examples/build_arg_max.py | ||
| 33 | +(adjust ROOT below to your checkout / worktree). | ||
| 34 | +""" | ||
| 35 | +import logging as _console_logging | ||
| 36 | +import sys as _console_sys | ||
| 37 | + | ||
| 38 | +import sys | ||
| 39 | +from pathlib import Path | ||
| 40 | + | ||
| 41 | +# project root = 4 parents up from this file (examples/op_builder/lib/tilelang-host-bridge) | ||
| 42 | +ROOT = str(Path(__file__).resolve().parents[5]) | ||
| 43 | +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # .../lib —— parents[2] 即 lib 本身 | ||
| 44 | +from op_builder import build_op, Paradigm, Input, Output, KernelSource | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +class _StreamProxy: | ||
| 48 | + """Resolve stdout when writing so redirected output retains its destination.""" | ||
| 49 | + | ||
| 50 | + def __init__(self, sys_module=_console_sys): | ||
| 51 | + self._console_sys = sys_module | ||
| 52 | + | ||
| 53 | + def write(self, text: str) -> int: | ||
| 54 | + return self._console_sys.stdout.write(text) | ||
| 55 | + | ||
| 56 | + def flush(self) -> None: | ||
| 57 | + self._console_sys.stdout.flush() | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +_LOG = _console_logging.getLogger(__name__ + ".stdout") | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +def _init_loggers() -> None: | ||
| 64 | + """Keep console messages visible without changing the root logger.""" | ||
| 65 | + if not _LOG.handlers: | ||
| 66 | + handler = _console_logging.StreamHandler(_StreamProxy()) | ||
| 67 | + handler.setFormatter(_console_logging.Formatter("%(message)s")) | ||
| 68 | + _LOG.addHandler(handler) | ||
| 69 | + _LOG.setLevel(_console_logging.INFO) | ||
| 70 | + _LOG.propagate = False | ||
| 71 | + | ||
| 72 | + | ||
| 73 | +_init_loggers() | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +def main(): | ||
| 77 | + N = 512 # compile-time reduce length (topk repeat sizing); matches bench last-axis case | ||
| 78 | + result = build_op( | ||
| 79 | + op_name='arg_max_custom', | ||
| 80 | + paradigm=Paradigm.SORT_SELECT, | ||
| 81 | + | ||
| 82 | + kernel=KernelSource( | ||
| 83 | + module='arg_max_strided', | ||
| 84 | + func='arg_max_strided', | ||
| 85 | + compile_args=(N, 24, 'float16'), # N, MAX_CORES, dtype | ||
| 86 | + sys_path_add='output/ArgMax', # fork of sort_select_argmax_strided.py | ||
| 87 | + ), | ||
| 88 | + | ||
| 89 | + inputs=[Input('X', 'float16', ('M', 'N'))], | ||
| 90 | + outputs=[Output('Indices', 'int32', ('M', 'K'))], | ||
| 91 | + workspaces=[], # vector_only, no workspaces | ||
| 92 | + | ||
| 93 | + op_dir='output/ArgMax/ArgMaxCustom', | ||
| 94 | + project_root=ROOT, | ||
| 95 | + | ||
| 96 | + # N baked compile-time + also a shape dim → NOT in tiling_extras (see fix #1). | ||
| 97 | + # K(=1) const used in Indices output shape → declared via tiling_extras. | ||
| 98 | + tiling_fields=['M'], | ||
| 99 | + tiling_extras={'K': '1'}, | ||
| 100 | + dynamic_params=[], # kernel main only takes IO; N baked compile-time | ||
| 101 | + | ||
| 102 | + inner_call_inputs=['X'], | ||
| 103 | + inner_call_outputs=['Indices'], | ||
| 104 | + | ||
| 105 | + auto_emit_host=True, | ||
| 106 | + bypass_preflight=True, | ||
| 107 | + set_block_dim_expr='24', # MAX_CORES const baked in kernel | ||
| 108 | + ) | ||
| 109 | + | ||
| 110 | + _LOG.info("%s %s", "\nArgMax SORT_SELECT build_op() OK — cpp chars:", result.cpp_chars) | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +if __name__ == '__main__': | ||
| 114 | + main() | ||
| @@ -0,0 +1,152 @@ | |||
| 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 | +"""Phase δ4 POC: Conv2D via build_op() — pybind_preprocess for host-side im2col. | ||
| 12 | + | ||
| 13 | +★ Per L0-L8 flow ★: | ||
| 14 | + L0-L7: skills/tilelang-kernel-baseline/examples/conv2d_gemm_fp16.py (JIT smoke PASSED) | ||
| 15 | + L8: this script — build full Conv2DCustom vendor via build_op() + pybind im2col | ||
| 16 | + | ||
| 17 | +★ Approach ★: | ||
| 18 | + - Kernel = pure fp16 GEMM (forked from QuantMatmul, validated) | ||
| 19 | + - Pybind takes user-facing (x, filter) → host im2col → calls GEMM kernel | ||
| 20 | + - new build_op param: pybind_preprocess + pybind_user_signature | ||
| 21 | + | ||
| 22 | +★ Smoke shape ★ (matches kernel JIT smoke PASS): | ||
| 23 | + B=4 C=8 H=W=16 OC=16 kh=kw=3 → im2col M=784(pad 896), K=72(pad 80), N=16 | ||
| 24 | + | ||
| 25 | +Per dual-loop-tdd: this is FIRST validated TRUE-new paradigm (Conv2D requires | ||
| 26 | +pybind_preprocess which existing 4 paradigms didn't need). | ||
| 27 | +""" | ||
| 28 | +import logging as _console_logging | ||
| 29 | +import sys as _console_sys | ||
| 30 | + | ||
| 31 | +import sys | ||
| 32 | +from pathlib import Path | ||
| 33 | +sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) | ||
| 34 | +from op_builder import build_op, Paradigm, Input, Output, Workspace, KernelSource | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +# Smoke shape (matches kernel.py) | ||
| 38 | +SMOKE_M_PAD = 896 # 7 * 128 ≥ 784 | ||
| 39 | +SMOKE_N_PAD = 16 | ||
| 40 | +SMOKE_K_PAD = 80 | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +PYBIND_PREPROCESS = """ | ||
| 44 | + // Conv2D pre-process: host-side im2col + weight reshape | ||
| 45 | + auto x_sizes = x.sizes(); // (Bsz, C_in, H, W) | ||
| 46 | + int64_t Bsz = x_sizes[0]; | ||
| 47 | + int64_t C_in = x_sizes[1]; | ||
| 48 | + int64_t H = x_sizes[2]; | ||
| 49 | + int64_t W = x_sizes[3]; | ||
| 50 | + auto f_sizes = filter.sizes(); // (OC, C_in, kh, kw) | ||
| 51 | + int64_t OC = f_sizes[0]; | ||
| 52 | + int64_t kh = f_sizes[2]; | ||
| 53 | + int64_t kw = f_sizes[3]; | ||
| 54 | + int64_t H_out = H - kh + 1; | ||
| 55 | + int64_t W_out = W - kw + 1; | ||
| 56 | + int64_t M = Bsz * H_out * W_out; | ||
| 57 | + int64_t Kv = C_in * kh * kw; | ||
| 58 | + int64_t Nv = OC; | ||
| 59 | + auto unfolded = at::im2col(x, {kh, kw}, {1, 1}, {0, 0}, {1, 1}); | ||
| 60 | + auto A_raw = unfolded.transpose(1, 2).contiguous().view({M, Kv}); | ||
| 61 | + auto B_raw = filter.reshape({OC, Kv}).transpose(0, 1).contiguous(); | ||
| 62 | + int64_t M_pad = """ + str(SMOKE_M_PAD) + """; | ||
| 63 | + int64_t N_pad = """ + str(SMOKE_N_PAD) + """; | ||
| 64 | + int64_t K_pad = """ + str(SMOKE_K_PAD) + """; | ||
| 65 | + auto opts = x.options(); | ||
| 66 | + // Use OpDef input names directly (NEW tensors shadow const& params) | ||
| 67 | + at::Tensor A = at::zeros({M_pad, K_pad}, opts); | ||
| 68 | + A.slice(0, 0, M).slice(1, 0, Kv).copy_(A_raw); | ||
| 69 | + at::Tensor B = at::zeros({K_pad, N_pad}, opts); | ||
| 70 | + B.slice(0, 0, Kv).slice(1, 0, Nv).copy_(B_raw); | ||
| 71 | +""" | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +class _StreamProxy: | ||
| 75 | + """Resolve stdout when writing so redirected output retains its destination.""" | ||
| 76 | + | ||
| 77 | + def __init__(self, sys_module=_console_sys): | ||
| 78 | + self._console_sys = sys_module | ||
| 79 | + | ||
| 80 | + def write(self, text: str) -> int: | ||
| 81 | + return self._console_sys.stdout.write(text) | ||
| 82 | + | ||
| 83 | + def flush(self) -> None: | ||
| 84 | + self._console_sys.stdout.flush() | ||
| 85 | + | ||
| 86 | + | ||
| 87 | +_LOG = _console_logging.getLogger(__name__ + ".stdout") | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +def _init_loggers() -> None: | ||
| 91 | + """Keep console messages visible without changing the root logger.""" | ||
| 92 | + if not _LOG.handlers: | ||
| 93 | + handler = _console_logging.StreamHandler(_StreamProxy()) | ||
| 94 | + handler.setFormatter(_console_logging.Formatter("%(message)s")) | ||
| 95 | + _LOG.addHandler(handler) | ||
| 96 | + _LOG.setLevel(_console_logging.INFO) | ||
| 97 | + _LOG.propagate = False | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +_init_loggers() | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +def main(): | ||
| 104 | + result = build_op( | ||
| 105 | + op_name='conv2d_custom', | ||
| 106 | + paradigm=Paradigm.CV_FUSION_AUTO_SYNC, | ||
| 107 | + | ||
| 108 | + kernel=KernelSource( | ||
| 109 | + module='conv2d_gemm_fp16', | ||
| 110 | + func='conv2d_gemm_fp16', | ||
| 111 | + compile_args=(SMOKE_M_PAD, SMOKE_N_PAD, SMOKE_K_PAD, 128, 16, 16), | ||
| 112 | + # M, N, K, block_M, block_N, block_K | ||
| 113 | + sys_path_add='skills/tilelang-kernel-baseline/examples', | ||
| 114 | + ), | ||
| 115 | + | ||
| 116 | + # OpDef sees flattened (M, K) and (K, N) — im2col'd by pybind | ||
| 117 | + inputs=[ | ||
| 118 | + Input('A', 'float16', ('M', 'K')), | ||
| 119 | + Input('B', 'float16', ('K', 'N')), | ||
| 120 | + ], | ||
| 121 | + outputs=[ | ||
| 122 | + Output('C', 'float16', ('M', 'N')), | ||
| 123 | + ], | ||
| 124 | + workspaces=[ | ||
| 125 | + Workspace('workspace_1', 'float32', 'M*N*4'), | ||
| 126 | + ], | ||
| 127 | + | ||
| 128 | + op_dir='output/Conv2D/Conv2DCustom', | ||
| 129 | + | ||
| 130 | + # Pybind: USER-facing args are (x, filter), pybind injects im2col preprocess | ||
| 131 | + pybind_dir='output/Conv2D/ascend_op_pybind/CppExtension', | ||
| 132 | + pybind_alias='conv2d_custom', | ||
| 133 | + auto_emit_host=True, | ||
| 134 | + | ||
| 135 | + # ★ δ4 NEW: pybind_user_signature + pybind_preprocess ★ | ||
| 136 | + pybind_user_signature=[ | ||
| 137 | + Input('x', 'float16', ('B', 'C_in', 'H', 'W')), | ||
| 138 | + Input('filter', 'float16', ('OC', 'C_in', 'kh', 'kw')), | ||
| 139 | + ], | ||
| 140 | + pybind_preprocess=PYBIND_PREPROCESS, | ||
| 141 | + # Conv2D grid: m_num * n_num = ceildiv(M_pad/block_M) * ceildiv(N_pad/block_N) | ||
| 142 | + # = ceildiv(896/128) * ceildiv(16/16) = 7 * 1 = 7 | ||
| 143 | + set_block_dim_expr='7', | ||
| 144 | + ) | ||
| 145 | + | ||
| 146 | + _LOG.info("%s", f"\n══════════════════════════════════════════════════════") | ||
| 147 | + _LOG.info("%s", f"Conv2D build_op() OK — cpp chars: {result.cpp_chars}, AIV: {result.aiv_binary_size}") | ||
| 148 | + _LOG.info("%s", f"══════════════════════════════════════════════════════") | ||
| 149 | + | ||
| 150 | + | ||
| 151 | +if __name__ == '__main__': | ||
| 152 | + main() | ||
| @@ -0,0 +1,154 @@ | |||
| 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 | +"""Phase δ4 SYMBOLIC: Conv2D vendor with symbolic M/N/K — single binary multi-shape. | ||
| 12 | + | ||
| 13 | +Per dubin push: "conv2d 的 symbolic 泛化 shape 输入做了吗?" | ||
| 14 | + | ||
| 15 | +★ Generalization over hardcoded conv2d ★: | ||
| 16 | + Old build_conv2d.py: M_pad=896, K_pad=80, N_pad=16 baked in JIT compile. | ||
| 17 | + Shape change → must rebuild kernel. | ||
| 18 | + This: M/N/K = T.symbolic. ONE binary covers ALL conv2d shapes. | ||
| 19 | + | ||
| 20 | +★ Approach ★: | ||
| 21 | + - Kernel: conv2d_gemm_symbolic.py (validated JIT 5/5 multi-shape PASS) | ||
| 22 | + - Pybind: dynamic im2col + dynamic pad to block multiples (M_pad, N_pad, K_pad | ||
| 23 | + computed AT RUNTIME from input shape) | ||
| 24 | + - op_host: SetBlockDim(MAX_CORES) fixed, M_total/N_total/K_total dynamic from | ||
| 25 | + input shape (in TilingData) | ||
| 26 | + | ||
| 27 | +★ Per dual-loop-tdd ★: must verify 4+ different shapes via SAME vendor binary | ||
| 28 | + to prove symbolic generalization is REAL (not just compile-once-test-once). | ||
| 29 | +""" | ||
| 30 | +import logging as _console_logging | ||
| 31 | +import sys as _console_sys | ||
| 32 | + | ||
| 33 | +import sys | ||
| 34 | +from pathlib import Path | ||
| 35 | +sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) | ||
| 36 | +from op_builder import build_op, Paradigm, Input, Output, Workspace, KernelSource | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +# Pybind preprocess: DYNAMIC im2col + pad — runtime shape adaptation | ||
| 40 | +PYBIND_PREPROCESS = """ | ||
| 41 | + auto x_sizes = x.sizes(); | ||
| 42 | + int64_t Bsz = x_sizes[0]; | ||
| 43 | + int64_t C_in = x_sizes[1]; | ||
| 44 | + int64_t H = x_sizes[2]; | ||
| 45 | + int64_t W = x_sizes[3]; | ||
| 46 | + auto f_sizes = filter.sizes(); | ||
| 47 | + int64_t OC = f_sizes[0]; | ||
| 48 | + int64_t kh = f_sizes[2]; | ||
| 49 | + int64_t kw = f_sizes[3]; | ||
| 50 | + int64_t H_out = H - kh + 1; | ||
| 51 | + int64_t W_out = W - kw + 1; | ||
| 52 | + int64_t M = Bsz * H_out * W_out; | ||
| 53 | + int64_t Kv = C_in * kh * kw; | ||
| 54 | + int64_t Nv = OC; | ||
| 55 | + | ||
| 56 | + auto unfolded = at::im2col(x, {kh, kw}, {1, 1}, {0, 0}, {1, 1}); | ||
| 57 | + auto A_raw = unfolded.transpose(1, 2).contiguous().view({M, Kv}); | ||
| 58 | + auto B_raw = filter.reshape({OC, Kv}).transpose(0, 1).contiguous(); | ||
| 59 | + | ||
| 60 | + // Dynamic pad to block multiples (block_M=128, block_N=16, block_K=32) | ||
| 61 | + const int64_t bM = 128, bN = 16, bK = 32; | ||
| 62 | + int64_t M_pad = ((M + bM - 1) / bM) * bM; | ||
| 63 | + int64_t N_pad = ((Nv + bN - 1) / bN) * bN; | ||
| 64 | + int64_t K_pad = ((Kv + bK - 1) / bK) * bK; | ||
| 65 | + | ||
| 66 | + auto opts = x.options(); | ||
| 67 | + at::Tensor A = at::zeros({M_pad, K_pad}, opts); | ||
| 68 | + A.slice(0, 0, M).slice(1, 0, Kv).copy_(A_raw); | ||
| 69 | + at::Tensor B = at::zeros({K_pad, N_pad}, opts); | ||
| 70 | + B.slice(0, 0, Kv).slice(1, 0, Nv).copy_(B_raw); | ||
| 71 | +""" | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +class _StreamProxy: | ||
| 75 | + """Resolve stdout when writing so redirected output retains its destination.""" | ||
| 76 | + | ||
| 77 | + def __init__(self, sys_module=_console_sys): | ||
| 78 | + self._console_sys = sys_module | ||
| 79 | + | ||
| 80 | + def write(self, text: str) -> int: | ||
| 81 | + return self._console_sys.stdout.write(text) | ||
| 82 | + | ||
| 83 | + def flush(self) -> None: | ||
| 84 | + self._console_sys.stdout.flush() | ||
| 85 | + | ||
| 86 | + | ||
| 87 | +_LOG = _console_logging.getLogger(__name__ + ".stdout") | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +def _init_loggers() -> None: | ||
| 91 | + """Keep console messages visible without changing the root logger.""" | ||
| 92 | + if not _LOG.handlers: | ||
| 93 | + handler = _console_logging.StreamHandler(_StreamProxy()) | ||
| 94 | + handler.setFormatter(_console_logging.Formatter("%(message)s")) | ||
| 95 | + _LOG.addHandler(handler) | ||
| 96 | + _LOG.setLevel(_console_logging.INFO) | ||
| 97 | + _LOG.propagate = False | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +_init_loggers() | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +def main(): | ||
| 104 | + result = build_op( | ||
| 105 | + op_name='conv2d_sym_custom', | ||
| 106 | + paradigm=Paradigm.CV_FUSION_AUTO_SYNC, | ||
| 107 | + | ||
| 108 | + kernel=KernelSource( | ||
| 109 | + module='conv2d_gemm_symbolic', | ||
| 110 | + func='conv2d_gemm_symbolic', | ||
| 111 | + compile_args=(128, 16, 32, 24), # block_M, block_N, block_K, MAX_CORES | ||
| 112 | + sys_path_add='skills/tilelang-kernel-baseline/examples', | ||
| 113 | + ), | ||
| 114 | + | ||
| 115 | + # Symbolic input shapes (M/K/N runtime from input tensor shape) | ||
| 116 | + inputs=[ | ||
| 117 | + Input('A', 'float16', ('M', 'K')), | ||
| 118 | + Input('B', 'float16', ('K', 'N')), | ||
| 119 | + ], | ||
| 120 | + outputs=[ | ||
| 121 | + Output('C', 'float16', ('M', 'N')), | ||
| 122 | + ], | ||
| 123 | + workspaces=[ | ||
| 124 | + Workspace('workspace_1', 'float32', 'M*N*4'), | ||
| 125 | + ], | ||
| 126 | + | ||
| 127 | + op_dir='output/Conv2DSym/Conv2DSymCustom', | ||
| 128 | + | ||
| 129 | + # Workspace bytes formulas use M, N — runtime computed in TilingFunc | ||
| 130 | + tiling_fields=['M', 'N', 'K'], | ||
| 131 | + # ★ dynamic_params order MUST match JIT cu kernel sig (M, K, N — first-occurrence | ||
| 132 | + # in tensor shapes: A=(M,K) → M, K; B=(K,N) → N). NOT ['M', 'N', 'K']. | ||
| 133 | + dynamic_params=['M', 'K', 'N'], | ||
| 134 | + | ||
| 135 | + pybind_dir='output/Conv2DSym/ascend_op_pybind/CppExtension', | ||
| 136 | + pybind_alias='conv2d_sym', | ||
| 137 | + auto_emit_host=True, | ||
| 138 | + | ||
| 139 | + pybind_user_signature=[ | ||
| 140 | + Input('x', 'float16', ('B', 'C_in', 'H', 'W')), | ||
| 141 | + Input('filter', 'float16', ('OC', 'C_in', 'kh', 'kw')), | ||
| 142 | + ], | ||
| 143 | + pybind_preprocess=PYBIND_PREPROCESS, | ||
| 144 | + | ||
| 145 | + set_block_dim_expr='24', # MAX_CORES (kernel does stride loop within) | ||
| 146 | + ) | ||
| 147 | + | ||
| 148 | + _LOG.info("%s", f"\n══════════════════════════════════════════════════════") | ||
| 149 | + _LOG.info("%s", f"Conv2D symbolic build_op() OK — cpp chars: {result.cpp_chars}") | ||
| 150 | + _LOG.info("%s", f"══════════════════════════════════════════════════════") | ||
| 151 | + | ||
| 152 | + | ||
| 153 | +if __name__ == '__main__': | ||
| 154 | + main() | ||
| @@ -0,0 +1,172 @@ | |||
| 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 | +"""build_op() for conv3d_backprop_filter — host 3D im2col + pure GEMM (CONV_2D3D). | ||
| 12 | + | ||
| 13 | +Deploy smoke shape (fixed, shape-specialized): | ||
| 14 | + x=[2,8,5,5,5] dy=[2,16,4,4,4] k=2x2x2 s=1 p=0 d=1 | ||
| 15 | + -> od=oh=ow=4, L=N*od*oh*ow=128, Kc=C*kd*kh*kw=64, OC=16 | ||
| 16 | + GEMM: dW[OC,Kc] = dyT[OC,L] @ A[L,Kc] (M=OC=16, Kg=L=128, N=Kc=64) | ||
| 17 | + pad to cube tiles (block 64): M_pad=64, K_pad=128, N_pad=64. grid = 1*1 = 1. | ||
| 18 | + | ||
| 19 | +OpDef sees flattened GEMM tensors (A[M,K], B[K,N]) -> C[M,N]; pybind preprocess | ||
| 20 | +does the 3D im2col + dy reshape from user-facing (x, dy). | ||
| 21 | +""" | ||
| 22 | +import logging as _console_logging | ||
| 23 | +import sys as _console_sys | ||
| 24 | + | ||
| 25 | +import sys | ||
| 26 | +from pathlib import Path | ||
| 27 | +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # .../lib —— parents[2] 即 lib 本身 | ||
| 28 | +sys.path.insert(0, 'output/Conv3dBackpropFilter') | ||
| 29 | +from op_builder import build_op, Paradigm, Input, Output, Workspace, KernelSource | ||
| 30 | + | ||
| 31 | +# GEMM padded dims for deploy shape | ||
| 32 | +SMOKE_M_PAD = 64 # OC=16 -> 64 | ||
| 33 | +SMOKE_N_PAD = 64 # Kc=64 -> 64 | ||
| 34 | +SMOKE_K_PAD = 128 # L=128 -> 128 | ||
| 35 | +BLOCK_M = BLOCK_N = BLOCK_K = 64 | ||
| 36 | + | ||
| 37 | +# deploy conv geometry (baked into preprocess) | ||
| 38 | +N_, C_, D_, H_, W_ = 2, 8, 5, 5, 5 | ||
| 39 | +OC_, KD_, KH_, KW_ = 16, 2, 2, 2 | ||
| 40 | +S_, P_, DIL_ = 1, 0, 1 | ||
| 41 | + | ||
| 42 | +# host 3D im2col + dy reshape -> padded GEMM operands A[M_pad,K_pad], B[K_pad,N_pad] | ||
| 43 | +# (here build_op OpDef names the GEMM inputs A and B; user sees x, dy) | ||
| 44 | +PYBIND_PREPROCESS = f""" | ||
| 45 | + // conv3d_backprop_filter pre-process: host 3D im2col(x) + dy reshape -> GEMM operands. | ||
| 46 | + // x:[N,C,D,H,W] dy:[N,OC,od,oh,ow] -> A=dyT[OC,L], B=A_unf[L,Kc] | ||
| 47 | + int64_t Nn = {N_}, Cc = {C_}, Dd = {D_}, Hh = {H_}, Ww = {W_}; | ||
| 48 | + int64_t OCc = {OC_}, kd = {KD_}, kh = {KH_}, kw = {KW_}; | ||
| 49 | + int64_t s = {S_}, p = {P_}, dl = {DIL_}; | ||
| 50 | + int64_t od = (Dd + 2*p - dl*(kd-1) - 1)/s + 1; | ||
| 51 | + int64_t oh = (Hh + 2*p - dl*(kh-1) - 1)/s + 1; | ||
| 52 | + int64_t ow = (Ww + 2*p - dl*(kw-1) - 1)/s + 1; | ||
| 53 | + int64_t L = Nn * od * oh * ow; | ||
| 54 | + int64_t Kc = Cc * kd * kh * kw; | ||
| 55 | + | ||
| 56 | + // 3D im2col of x -> [N, Kc, L_sp]; collapse over batch into L. | ||
| 57 | + // Use im2col on a merged (D-as-extra) layout: do it per-(kd) plane via unfold of 2D | ||
| 58 | + // then gather along D. Simpler: build A_unf with explicit gather using narrow/slice. | ||
| 59 | + auto opts = x.options(); | ||
| 60 | + // padded x: [N, C, D+2p, H+2p, W+2p] | ||
| 61 | + at::Tensor xp = at::constant_pad_nd(x, {{p, p, p, p, p, p}}, 0); | ||
| 62 | + // A_unf[N, C, kd, kh, kw, od, oh, ow] | ||
| 63 | + at::Tensor A_unf = at::zeros({{Nn, Cc, kd, kh, kw, od, oh, ow}}, opts); | ||
| 64 | + for (int64_t a = 0; a < kd; ++a) | ||
| 65 | + for (int64_t b = 0; b < kh; ++b) | ||
| 66 | + for (int64_t c = 0; c < kw; ++c) {{ | ||
| 67 | + // slice xp[:, :, a*dl : a*dl+s*od : s, ...] | ||
| 68 | + at::Tensor sl = xp | ||
| 69 | + .slice(2, a*dl, a*dl + s*od, s) | ||
| 70 | + .slice(3, b*dl, b*dl + s*oh, s) | ||
| 71 | + .slice(4, c*dl, c*dl + s*ow, s); | ||
| 72 | + A_unf.select(2, a).select(2, b).select(2, c).copy_(sl); | ||
| 73 | + }} | ||
| 74 | + // -> [N, Kc, L_sp] then [L, Kc] | ||
| 75 | + at::Tensor A_cols = A_unf.reshape({{Nn, Kc, od*oh*ow}}); | ||
| 76 | + at::Tensor B_mat = A_cols.permute({{0, 2, 1}}).contiguous().reshape({{L, Kc}}); // [L, Kc] | ||
| 77 | + // dyT[OC, L] | ||
| 78 | + at::Tensor dyT = dy.reshape({{Nn, OCc, od*oh*ow}}).permute({{1, 0, 2}}).contiguous().reshape({{OCc, L}}); | ||
| 79 | + | ||
| 80 | + int64_t M_pad = {SMOKE_M_PAD}; | ||
| 81 | + int64_t N_pad = {SMOKE_N_PAD}; | ||
| 82 | + int64_t K_pad = {SMOKE_K_PAD}; | ||
| 83 | + // A = dyT padded to [M_pad, K_pad] (M=OC, Kg=L) | ||
| 84 | + at::Tensor A = at::zeros({{M_pad, K_pad}}, opts); | ||
| 85 | + A.slice(0, 0, OCc).slice(1, 0, L).copy_(dyT); | ||
| 86 | + // B = B_mat padded to [K_pad, N_pad] (Kg=L, N=Kc) | ||
| 87 | + at::Tensor B = at::zeros({{K_pad, N_pad}}, opts); | ||
| 88 | + B.slice(0, 0, L).slice(1, 0, Kc).copy_(B_mat); | ||
| 89 | +""" | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +class _StreamProxy: | ||
| 93 | + """Resolve stdout when writing so redirected output retains its destination.""" | ||
| 94 | + | ||
| 95 | + def __init__(self, sys_module=_console_sys): | ||
| 96 | + self._console_sys = sys_module | ||
| 97 | + | ||
| 98 | + def write(self, text: str) -> int: | ||
| 99 | + return self._console_sys.stdout.write(text) | ||
| 100 | + | ||
| 101 | + def flush(self) -> None: | ||
| 102 | + self._console_sys.stdout.flush() | ||
| 103 | + | ||
| 104 | + | ||
| 105 | +_LOG = _console_logging.getLogger(__name__ + ".stdout") | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +def _init_loggers() -> None: | ||
| 109 | + """Keep console messages visible without changing the root logger.""" | ||
| 110 | + if not _LOG.handlers: | ||
| 111 | + handler = _console_logging.StreamHandler(_StreamProxy()) | ||
| 112 | + handler.setFormatter(_console_logging.Formatter("%(message)s")) | ||
| 113 | + _LOG.addHandler(handler) | ||
| 114 | + _LOG.setLevel(_console_logging.INFO) | ||
| 115 | + _LOG.propagate = False | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +_init_loggers() | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def main(): | ||
| 122 | + result = build_op( | ||
| 123 | + op_name='conv3d_backprop_filter_custom', | ||
| 124 | + paradigm=Paradigm.CONV_2D3D, | ||
| 125 | + | ||
| 126 | + kernel=KernelSource( | ||
| 127 | + module='conv_3d_backprop_filter_strided', | ||
| 128 | + func='conv_3d_backprop_filter_gemm', | ||
| 129 | + compile_args=(SMOKE_M_PAD, SMOKE_N_PAD, SMOKE_K_PAD, BLOCK_M, BLOCK_N, BLOCK_K), | ||
| 130 | + sys_path_add='output/Conv3dBackpropFilter', | ||
| 131 | + ), | ||
| 132 | + | ||
| 133 | + inputs=[ | ||
| 134 | + Input('A', 'float16', ('M', 'K')), | ||
| 135 | + Input('B', 'float16', ('K', 'N')), | ||
| 136 | + ], | ||
| 137 | + outputs=[ | ||
| 138 | + Output('C', 'float16', ('M', 'N')), | ||
| 139 | + ], | ||
| 140 | + workspaces=[ | ||
| 141 | + Workspace('workspace_1', 'float32', 'M*N*4'), | ||
| 142 | + ], | ||
| 143 | + | ||
| 144 | + op_dir='output/Conv3dBackpropFilter/Conv3dBackpropFilterCustom', | ||
| 145 | + | ||
| 146 | + pybind_dir='output/Conv3dBackpropFilter/ascend_op_pybind/CppExtension', | ||
| 147 | + pybind_alias='conv3d_backprop_filter_custom', | ||
| 148 | + auto_emit_host=True, | ||
| 149 | + | ||
| 150 | + pybind_user_signature=[ | ||
| 151 | + Input('x', 'float16', ('N', 'C', 'D', 'H', 'W')), | ||
| 152 | + Input('dy', 'float16', ('N', 'OC', 'od', 'oh', 'ow')), | ||
| 153 | + ], | ||
| 154 | + pybind_preprocess=PYBIND_PREPROCESS, | ||
| 155 | + # grid = ceildiv(M_pad/block_M)*ceildiv(N_pad/block_N) = 1*1 = 1 | ||
| 156 | + set_block_dim_expr='1', | ||
| 157 | + | ||
| 158 | + tiling_fields=['M'], | ||
| 159 | + dynamic_params=[], | ||
| 160 | + bypass_preflight=True, | ||
| 161 | + ) | ||
| 162 | + | ||
| 163 | + _LOG.info("%s", "\n══════════════════════════════════════════════════════") | ||
| 164 | + _LOG.info( | ||
| 165 | + "%s", | ||
| 166 | + f"Conv3dBackpropFilter build_op() OK — cpp chars: {result.cpp_chars}, AIV: {result.aiv_binary_size}", | ||
| 167 | + ) | ||
| 168 | + _LOG.info("%s", "══════════════════════════════════════════════════════") | ||
| 169 | + | ||
| 170 | + | ||
| 171 | +if __name__ == '__main__': | ||
| 172 | + main() | ||
这个
if分支和下面的return result.stdout or ""完全一样,returncode 判断没有意义,可以去掉。