Merged
refactor(skills): 整合 PyPTO-Pro 工作流、API 适配与仓内验证 #927
ddddweAdd on 29 days ago
refactor(skills): 整合 PyPTO-Pro 工作流、API 适配与仓内验证 #927
Merged
Total: 297 files changed+33917-7851
| @@ -76,6 +76,7 @@ package-lock.json | |||
| 76 | 76 | ||
| 77 | /.claude/ | 77 | /.claude/ |
| 78 | /CLAUDE.md | 78 | /CLAUDE.md |
| 79 | +/AGENTS.md | ||
| 79 | 80 | ||
| 80 | # PyPTO-Pro devkit cache. Bare pattern, not `.devkit/`: a trailing slash matches | 81 | # PyPTO-Pro devkit cache. Bare pattern, not `.devkit/`: a trailing slash matches |
| 81 | # directories only, and init.sh installs symlinks, which the bare form also covers. | 82 | # directories only, and init.sh installs symlinks, which the bare form also covers. |
| @@ -63,8 +63,8 @@ cannbot-skills/ | |||
| 63 | ├── ops/ # 算子 Skills(PyPTO classic + PyPTO-Pro) | 63 | ├── ops/ # 算子 Skills(PyPTO classic + PyPTO-Pro) |
| 64 | │ ├── pypto-api-explore/ | 64 | │ ├── pypto-api-explore/ |
| 65 | │ ├── pypto-op-design/ | 65 | │ ├── pypto-op-design/ |
| 66 | -│ ├── pypto-pro-op-develop/ | 66 | +│ ├── pypto-pro-kernel/ |
| 67 | -│ └── ... # 共 34 个顶层 Skill 子目录 | 67 | +│ └── ... # 共 29 个顶层 Skill 子目录 |
| 68 | ├── model/ # 模型适配与推理优化 Skills | 68 | ├── model/ # 模型适配与推理优化 Skills |
| 69 | │ ├── hf-npu-e2e-workflow/ | 69 | │ ├── hf-npu-e2e-workflow/ |
| 70 | │ ├── pypto-convert-model/ | 70 | │ ├── pypto-convert-model/ |
| @@ -96,8 +96,8 @@ cannbot-skills/ | |||
| 96 | | 验证与调优类 | `pypto-golden-generate`、`pypto-precision-compare`、`pypto-precision-debug`、`pypto-op-verify`、`pypto-op-review`、`pypto-op-perf-tune`、`pypto-op-perf-panko-manual`、`pypto-kernel-validate` | Golden 生成、精度对比与排查、功能验证、代码检视、性能调优(分步骤 / PANKO 搜索式)、产物校验(反作弊 + 精度 + 性能) | | 96 | | 验证与调优类 | `pypto-golden-generate`、`pypto-precision-compare`、`pypto-precision-debug`、`pypto-op-verify`、`pypto-op-review`、`pypto-op-perf-tune`、`pypto-op-perf-panko-manual`、`pypto-kernel-validate` | Golden 生成、精度对比与排查、功能验证、代码检视、性能调优(分步骤 / PANKO 搜索式)、产物校验(反作弊 + 精度 + 性能) | |
| 97 | | 监控与调试类 | `pypto-op-monitor`、`pypto-general-debug` | 任务监控、通用诊断 | | 97 | | 监控与调试类 | `pypto-op-monitor`、`pypto-general-debug` | 任务监控、通用诊断 | |
| 98 | | 断裂点分析与报告类 | `pypto-benchmark-fracture-aggregator`、`pypto-fracture-point-detector`、`pypto-session-dfx-report` | Session 断裂点聚合/检测/复现取证、Issue 文档产出、DFX 报告 | | 98 | | 断裂点分析与报告类 | `pypto-benchmark-fracture-aggregator`、`pypto-fracture-point-detector`、`pypto-session-dfx-report` | Session 断裂点聚合/检测/复现取证、Issue 文档产出、DFX 报告 | |
| 99 | -| Pro 专属类 | `pypto-pro-intent-understand`、`pypto-pro-material-explore`、`pypto-pro-op-plan`、`pypto-pro-op-design`、`pypto-pro-op-develop`、`pypto-pro-op-perf-tune`、`pypto-pro-golden-generate`、`pypto-pro-environment-check`、`pypto-pro-precision-debug`、`pypto-pro-cann-delivery`、`pypto-pro-docs-search` | PyPTO-Pro 需求、开发、调优与调试、CANN 交付与文档检索 | | 99 | +| Pro 专属类 | `pypto-pro-op-perf-tune`、`pypto-pro-golden-generate`、`pypto-pro-environment-check`、`pypto-pro-precision-debug`、`pypto-pro-cann-delivery`、`pypto-pro-docs-search` | PyPTO-Pro 需求、开发、调优与调试、CANN 交付与文档检索 | |
| 100 | -| Pro 独立技能(实验) | `pypto-pro-kernel` | 原生 kernel 开发、验证、调试与优化,内含参考资料、检查工具和样例 | | 100 | +| Pro 核心技能 | `pypto-pro-kernel` | 原生 kernel 开发、验证、调试与优化,内含参考资料、检查工具和样例 | |
| 101 | 101 | ||
| 102 | ### 模型适配(model/) | 102 | ### 模型适配(model/) |
| 103 | 103 | ||
| @@ -9,7 +9,7 @@ | |||
| 9 | 9 | ||
| 10 | ## 📢 项目概述 | 10 | ## 📢 项目概述 |
| 11 | 11 | ||
| 12 | -**CANNBot Skills — PyPTO-Gym** 是面向 PyPTO 与 PyPTO-Pro Tile 算子开发、大模型适配和模型治理的 CANNBot Agent Skills 模块,提供 37 个领域技能、1 个公共技能与 4 个开发路径插件。 | 12 | +**CANNBot Skills — PyPTO-Gym** 是面向 PyPTO 与 PyPTO-Pro Tile 算子开发、大模型适配和模型治理的 CANNBot Agent Skills 模块,提供 32 个领域技能、1 个公共技能与 4 个开发路径插件。 |
| 13 | 13 | ||
| 14 | **面向用户**:基于 PyPTO 编程框架的昇腾 NPU 算子开发者、模型适配工程师。 | 14 | **面向用户**:基于 PyPTO 编程框架的昇腾 NPU 算子开发者、模型适配工程师。 |
| 15 | 15 | ||
| @@ -43,9 +43,9 @@ cd /path/to/pypto-gym-toolkit/cannbot-skills/ops/pypto-pro-kernel | |||
| 43 | python scripts/check.py | 43 | python scripts/check.py |
| 44 | ``` | 44 | ``` |
| 45 | 45 | ||
| 46 | -需要核对 PyPTO API 时,用 `PYPTO_SRC` 或 `--pypto-root` 指定匹配目标安装版本的外部源码树。上板样例需要对应的 PyPTO、PyTorch、torch_npu 和 Ascend NPU 环境;该 skill 不包含仿真器。 | 46 | +完整知识准入和 API 核对需要用 `PYPTO_SRC` 或 `--pypto-root` 指定匹配目标安装版本的外部源码树;缺少该来源时保留 `unverified`,不将 API 缺失当作事实。`rules`、`coverage`、`catalog` 和 `links` 可独立使用,源码相关检查仍会说明未核对的范围。上板样例需要对应的 PyPTO、PyTorch、torch_npu 和 Ascend NPU 环境;该 skill 不包含仿真器。 |
| 47 | 47 | ||
| 48 | -`scripts/check.py links` 检查内置 Markdown 链接与标题引用,`explain` 分析候选源码的契约和工作量变化。可选的词法名称检查依赖 `scripts/requirements-checks.txt` 中固定版本的 Pyflakes。样例统一以 `kernel.py`、`reference.py`、`test.py` 为公开入口;Sparse Attention 的原始评估器对照额外需要 `CANN_BENCH_ROOT` 和可导入的 `kernel_eval`。 | 48 | +`scripts/check.py query` 统一检索契约、API、原始文档和完整样例,`query --validate` 检查知识准入,`links` 检查内置 Markdown 链接与标题引用。`native` 通过匹配安装版本的 PyPTO 进行元数据预检,`run` 执行调用方指定的验证命令,`suggest` 与 `experiment` 辅助优化候选和当前实验状态;这些结果不替代数值或性能验收。CLI 无需 MCP SDK;可选的 [MCP stdio 接口](ops/pypto-pro-kernel/references/tooling/mcp.md)复用同一实现。词法名称检查依赖 `scripts/requirements-checks.txt` 中固定版本的 Pyflakes。样例统一以 `kernel.py`、`reference.py`、`test.py` 为公开入口;Sparse Attention 的原始评估器对照额外需要 `CANN_BENCH_ROOT` 和可导入的 `kernel_eval`。 |
| 49 | 49 | ||
| 50 | ### 安装后使用 | 50 | ### 安装后使用 |
| 51 | 51 | ||
| @@ -67,7 +67,7 @@ python scripts/check.py | |||
| 67 | 67 | ||
| 68 | ### 技能清单 | 68 | ### 技能清单 |
| 69 | 69 | ||
| 70 | -**算子开发**(ops/,共 34 个顶层技能) | 70 | +**算子开发**(ops/,共 29 个顶层技能) |
| 71 | 71 | ||
| 72 | | 类别 | 技能 | 说明 | | 72 | | 类别 | 技能 | 说明 | |
| 73 | |------|------|------| | 73 | |------|------|------| |
| @@ -83,8 +83,8 @@ python scripts/check.py | |||
| 83 | | 监控与调试 | `pypto-op-monitor`、`pypto-general-debug` | 任务进度监控与通用问题诊断 | | 83 | | 监控与调试 | `pypto-op-monitor`、`pypto-general-debug` | 任务进度监控与通用问题诊断 | |
| 84 | | 断裂点分析 | `pypto-benchmark-fracture-aggregator`、`pypto-fracture-point-detector` | Session 断裂点批量聚合、检测、复现取证与 Issue 文档产出 | | 84 | | 断裂点分析 | `pypto-benchmark-fracture-aggregator`、`pypto-fracture-point-detector` | Session 断裂点批量聚合、检测、复现取证与 Issue 文档产出 | |
| 85 | | 报告与可视化 | `pypto-session-dfx-report` | Session DFX 报告(端到端耗时、token 消耗、执行轨迹) | | 85 | | 报告与可视化 | `pypto-session-dfx-report` | Session DFX 报告(端到端耗时、token 消耗、执行轨迹) | |
| 86 | -| **Pro 专属** | `pypto-pro-intent-understand`、`pypto-pro-material-explore`、`pypto-pro-op-plan`、`pypto-pro-op-design`、`pypto-pro-op-develop`、`pypto-pro-op-perf-tune`、`pypto-pro-golden-generate`、`pypto-pro-environment-check`、`pypto-pro-precision-debug`、`pypto-pro-cann-delivery`、`pypto-pro-docs-search` | PyPTO-Pro 开发、精度诊断、CANN 交付与文档检索 | | 86 | +| **Pro 专属** | `pypto-pro-op-perf-tune`、`pypto-pro-golden-generate`、`pypto-pro-environment-check`、`pypto-pro-precision-debug`、`pypto-pro-cann-delivery`、`pypto-pro-docs-search` | PyPTO-Pro 开发、精度诊断、CANN 交付与文档检索 | |
| 87 | -| **Pro 独立技能(实验)** | [pypto-pro-kernel](ops/pypto-pro-kernel/SKILL.md) | 原生 kernel 开发、验证、调试与优化,内含参考资料、检查工具和样例 | | 87 | +| **Pro 核心技能** | [pypto-pro-kernel](ops/pypto-pro-kernel/SKILL.md) | 原生 kernel 开发、验证、调试与优化,内含参考资料、检查工具和样例 | |
| 88 | 88 | ||
| 89 | **模型适配**(model/,共 3 个) | 89 | **模型适配**(model/,共 3 个) |
| 90 | 90 | ||
| @@ -1,15 +1,15 @@ | |||
| 1 | --- | 1 | --- |
| 2 | name: pypto-pro-docs-search | 2 | name: pypto-pro-docs-search |
| 3 | -description: 装配和检索 PyPTO-Pro 的本地 API、编程指南、快速入门与官方指定算子样例。用于 Pro 工作流查 API 用法、指南依据或参考样例;不用于普通 PyPTO 文档与算子仓检索。 | 3 | +description: 为 PyPTO-Pro 任务准备、校验和检索指定版本的本地文档缓存。用于离线资料准备、缓存完整性检查与资源定位;API 和能力查证衔接 pypto-pro-kernel 的核心查询。 |
| 4 | --- | 4 | --- |
| 5 | 5 | ||
| 6 | # pypto-pro-docs-search | 6 | # pypto-pro-docs-search |
| 7 | 7 | ||
| 8 | -按关键词在当前 Pro 缓存中发现资料位置,再读取全文。已有 `PRO_MATERIAL_INDEX.md` 时先按其路径取证;需要补充发现时使用下方限定范围。 | 8 | +围绕当前问题定位 Pro 原始资料。已有准确路径时直接读取;核心 skill 与匹配源码可用时,API、指南和能力查证使用[核心查询](../pypto-pro-kernel/references/tooling/checks.md#official-documents-guides-and-docstrings)。需要本地文档缓存时,按下方说明准备并限定路径检索;独立装配缓存只需要本 skill 的同步脚本和资源清单。 |
| 9 | 9 | ||
| 10 | ## 资源缓存 | 10 | ## 资源缓存 |
| 11 | 11 | ||
| 12 | -`$PYPTO_DEVKIT_DIR` 默认是当前项目的 `.devkit/`。Pro 工作流由 orchestrator 在会话开始时装配一次,并向所有子代理传递同一缓存的绝对路径。 | 12 | +`$PYPTO_DEVKIT_DIR` 默认是当前项目的 `.devkit/`。资料缓存按任务需要准备,使用任务明确给出的来源和路径;协作执行时传递同一缓存的实际路径。 |
| 13 | 13 | ||
| 14 | | 子目录 | 内容 | | 14 | | 子目录 | 内容 | |
| 15 | |---|---| | 15 | |---|---| |
| @@ -20,22 +20,22 @@ description: 装配和检索 PyPTO-Pro 的本地 API、编程指南、快速入 | |||
| 20 | 20 | ||
| 21 | ## 准备缓存 | 21 | ## 准备缓存 |
| 22 | 22 | ||
| 23 | -首次或需要更新时,在项目根目录运行本技能的独立脚本。已安装资源根由 `init.sh` 渲染的 `$CANNBOT_CONFIG_ROOT` 提供。 | 23 | +需要准备或更新缓存时运行本技能的独立脚本。将 `<skill-dir>` 替换为本 skill 的实际绝对路径,沿用任务指定的源码与缓存位置: |
| 24 | 24 | ||
| 25 | ```bash | 25 | ```bash |
| 26 | -export PYPTO_DEVKIT_DIR="$(pwd)/.devkit" | 26 | +PYPTO_SRC="/path/to/matching/pypto" \ |
| 27 | -CANNBOT_ROOT="$CANNBOT_CONFIG_ROOT" | 27 | +PYPTO_DEVKIT_DIR="/path/to/.devkit" \ |
| 28 | -python "$CANNBOT_ROOT/skills/pypto-pro-docs-search/scripts/sync_devkit.py" \ | 28 | +python "<skill-dir>/scripts/sync_devkit.py" \ |
| 29 | - --samples "$CANNBOT_ROOT/skills/pypto-pro-material-explore/references/official_samples.md" | 29 | + --samples "<skill-dir>/references/official_samples.md" |
| 30 | ``` | 30 | ``` |
| 31 | 31 | ||
| 32 | 在同一调用末尾增加 `--check` 只校验已有缓存:`READY` 且退出码为 0 表示就绪;`NEED_PROVISION` 且退出码为 4 表示需要装配。正常装配按清单复制样例并校验结果,无需再清理 `pro_ops/`。 | 32 | 在同一调用末尾增加 `--check` 只校验已有缓存:`READY` 且退出码为 0 表示就绪;`NEED_PROVISION` 且退出码为 4 表示需要装配。正常装配按清单复制样例并校验结果,无需再清理 `pro_ops/`。 |
| 33 | 33 | ||
| 34 | 脚本默认从 `https://gitcode.com/cann/pypto.git` 获取 Pro 资料。`PYPTO_SRC` 可指定已有 PyPTO 工作树,`PYPTO_SRC_URL` 可覆盖远端源,`--pin <git-ref>` 从远端获取指定版本。成功后写入 `MANIFEST.json` 和就绪标记,记录缓存来源与版本,以目标运行环境对应的资料为准。 | 34 | 脚本默认从 `https://gitcode.com/cann/pypto.git` 获取 Pro 资料。`PYPTO_SRC` 可指定已有 PyPTO 工作树,`PYPTO_SRC_URL` 可覆盖远端源,`--pin <git-ref>` 从远端获取指定版本。成功后写入 `MANIFEST.json` 和就绪标记,记录缓存来源与版本,以目标运行环境对应的资料为准。 |
| 35 | 35 | ||
| 36 | -在 Pro 工作流中,装配由 orchestrator 负责,子代理只检索同一缓存。 | 36 | +文档缓存与完整源码根是不同资源。核心查询的 `PYPTO_SRC` / `--pypto-root` 指向匹配版本的源码 checkout;本缓存只保留资料与清单文件,不能作为完整源码或已安装运行时的替代。 |
| 37 | 37 | ||
| 38 | -**子代理路径传递**:命令的路径参数直接代入编排器给定的绝对路径并加引号;Python 从环境读取路径时,仅将给定的 `PYPTO_DEVKIT_DIR`、`CANNBOT_CONFIG_ROOT` 原样传入单条命令,如 `PYPTO_DEVKIT_DIR="<缓存绝对路径>" CANNBOT_CONFIG_ROOT="<资源根绝对路径>" python "<脚本绝对路径>"`。不使用 `export`、猜测或更换路径,也不设置其他环境变量;未收到路径时返回 `env_error` 交回编排器。 | 38 | +**协作路径传递**:将当前任务选定的绝对路径和版本交给执行者,命令中的路径加引号。缺少路径时核对实际配置,明确缺项;已有有效来源时直接复用。 |
| 39 | 39 | ||
| 40 | ## 检索 | 40 | ## 检索 |
| 41 | 41 | ||
| @@ -53,7 +53,7 @@ python "$CANNBOT_ROOT/skills/pypto-pro-docs-search/scripts/sync_devkit.py" \ | |||
| 53 | 53 | ||
| 54 | ## 缓存未就绪时 | 54 | ## 缓存未就绪时 |
| 55 | 55 | ||
| 56 | -`--check` 返回 `NEED_PROVISION`,或下游发现文档、指定样例缺失时,报告具体缺项,由 orchestrator 按“准备缓存”处理。子代理不自行同步、切换缓存或改用普通 PyPTO 同步器及在线索引。离线无法装配时报告缺项,不编造路径或索引。 | 56 | +`--check` 返回 `NEED_PROVISION`,或发现缓存资料缺失时,报告具体缺项。任务确需缓存时按“准备缓存”处理,并遵循当前协作方式。已有匹配源码根时,核心查询可以直接核对原资料。离线且无可用来源时报告缺口,不编造路径、版本或能力结论。 |
| 57 | 57 | ||
| 58 | ## 详细索引(按入口键) | 58 | ## 详细索引(按入口键) |
| 59 | 59 | ||
| @@ -16,6 +16,6 @@ | |||
| 16 | 16 | ||
| 17 | 从快速入门总索引读取当前版本的样例页面路径;不同版本可能采用子目录或同级文件布局。 | 17 | 从快速入门总索引读取当前版本的样例页面路径;不同版本可能采用子目录或同级文件布局。 |
| 18 | 18 | ||
| 19 | -按关键词补充发现时,仅检索 `guide/programming_guide/pro/`、`guide/quick_start/pro/` 和 `guide/introduction.md`。`PRO_MATERIAL_INDEX.md` §C 覆盖这三个范围的全部 Markdown 文件,包括各级 `index.md`;本表用于主题导航,不替代 §C 的完整清单。 | 19 | +按当前问题补充发现时,限定检索 `guide/programming_guide/pro/`、`guide/quick_start/pro/` 和 `guide/introduction.md`。需要目录导航时读取对应 `index.md`,不要求先生成或遍历全量资料索引。 |
| 20 | 20 | ||
| 21 | 缓存保留配套图片,未缓存的安装与通用配置页面由指南中的远端链接指向。当前缓存不含独立的错误码排障资料;报错时从上述调试指南与实际日志定位。API 参数与约束见 [`api-index.md`](api-index.md),官方样例见 [`sample-index.md`](sample-index.md)。 | 21 | 缓存保留配套图片,未缓存的安装与通用配置页面由指南中的远端链接指向。当前缓存不含独立的错误码排障资料;报错时从上述调试指南与实际日志定位。API 参数与约束见 [`api-index.md`](api-index.md),官方样例见 [`sample-index.md`](sample-index.md)。 |
Rcannbot-skills/ops/pypto-pro-material-explore/references/official_samples.md→cannbot-skills/ops/pypto-pro-docs-search/references/official_samples.md+3-8
| @@ -1,13 +1,8 @@ | |||
| 1 | # 官方指定算子样例清单 | 1 | # 官方指定算子样例清单 |
| 2 | 2 | ||
| 3 | -> **用途**:本文件是整个 PyPTO-Pro 工作流的**统一官方样例索引来源**。 | 3 | +本清单由 `pypto-pro-docs-search` 维护,是 Pro 资料装配与缓存检索共用的文件清单。`sync_devkit.py` 通过 `--samples` 读取本文件,按清单准备 `$PYPTO_DEVKIT_DIR/pro_ops/`。 |
| 4 | -> - **orchestrator** 资源缓存准备时,按本清单装配 `$PYPTO_DEVKIT_DIR/pro_ops/`,只保留清单内文件。 | 4 | + |
| 5 | -> - **material-explore** 生成 `PRO_MATERIAL_INDEX.md` §B 时,以本清单为唯一来源。 | 5 | +维护规则:增删或重命名条目时只维护本清单,并核对引用相应文件名的使用方。路径使用相对 `$PYPTO_DEVKIT_DIR` 的 `pro_ops/` 前缀。各条目的接口与行为仍须在匹配目标版本的原文件中核实。 |
| 6 | -> - **所有 skill / agent** 提到"官方指定算子样例""§B"时,最终都指向本文件。 | ||
| 7 | -> | ||
| 8 | -> **维护规则**:增删样例时**只改本文件**,无需改动其他文件。路径用 `pro_ops/` 开头的相对路径(相对 `$PYPTO_DEVKIT_DIR`)。 | ||
| 9 | -> | ||
| 10 | -> **注意**:部分 skill(如 `pypto-pro-op-develop`)在 SKILL.md 中按具体文件名引用了某些样例(如 `test_matmul_perf_asw_4k_dn_move_offset_dynamic.py`、`test_fa_with_mask.py`)。删除或重命名清单中的样例前,请全局搜索确认无具体引用残留。 | ||
| 11 | 6 | ||
| 12 | | # | 算子名称 | 缓存相对路径 | 类型 | 描述 | | 7 | | # | 算子名称 | 缓存相对路径 | 类型 | 描述 | |
| 13 | |---|---------|-------------|------|------| | 8 | |---|---------|-------------|------|------| |
| @@ -1,9 +1,9 @@ | |||
| 1 | # PyPTO Pro 官方样例索引 | 1 | # PyPTO Pro 官方样例索引 |
| 2 | 2 | ||
| 3 | -唯一的文件清单是 [`official_samples.md`](../../pypto-pro-material-explore/references/official_samples.md)。按其“算子名称 / 类型 / 描述”选样例,再读取 `$PYPTO_DEVKIT_DIR/<缓存相对路径>`;路径已包含 `pro_ops/` 前缀。 | 3 | +唯一的文件清单是 [`official_samples.md`](official_samples.md)。按其“算子名称 / 类型 / 描述”定位资料,再读取 `$PYPTO_DEVKIT_DIR/<缓存相对路径>`;路径已包含 `pro_ops/` 前缀。 |
| 4 | 4 | ||
| 5 | 需要按 API 调用或关键词补充发现时,在 `$PYPTO_DEVKIT_DIR/pro_ops/` 使用 `Grep` / `Glob`,并对照统一清单确认命中文件。缓存只装配清单内样例,不能依赖上游 frontend 中的其他文件。 | 5 | 需要按 API 调用或关键词补充发现时,在 `$PYPTO_DEVKIT_DIR/pro_ops/` 使用 `Grep` / `Glob`,并对照统一清单确认命中文件。缓存只装配清单内样例,不能依赖上游 frontend 中的其他文件。 |
| 6 | 6 | ||
| 7 | -`PRO_MATERIAL_INDEX.md` §B 直接复制统一清单。本索引只提供检索方法,增删或重命名样例仍维护 `official_samples.md`,无需在这里同步另一份列表。 | 7 | +本索引只提供检索方法。增删或重命名条目时维护 `official_samples.md`,不生成项目内的第二份列表。 |
| 8 | 8 | ||
| 9 | 样例中的 Kernel、调用方式与验证逻辑以文件原文为准;Pro 缓存不另设普通 PyPTO 的 `ops/`、`tests/` 目录。确认接口语义时继续读取 [`api-index.md`](api-index.md) 指向的 API 文档,样例缺失则按 [缓存未就绪时](../SKILL.md#缓存未就绪时) 交还 orchestrator。 | 9 | 样例中的 Kernel、调用方式与验证逻辑以文件原文为准;Pro 缓存不另设普通 PyPTO 的 `ops/`、`tests/` 目录。确认接口语义时继续读取 [`api-index.md`](api-index.md) 指向的 API 文档,样例缺失则按 [缓存未就绪时](../SKILL.md#缓存未就绪时) 交还 orchestrator。 |
| @@ -5,18 +5,20 @@ description: 为 PyPTO-Pro 算子生成、规范化和验证 golden 参考实现 | |||
| 5 | 5 | ||
| 6 | # PyPTO-Pro Golden 参考实现 | 6 | # PyPTO-Pro Golden 参考实现 |
| 7 | 7 | ||
| 8 | -负责 Stage 2 的数学参考实现,不决定 Module 划分、kernel 写法或优化策略。 | 8 | +负责数学参考实现,不决定 kernel 写法或优化策略。 |
| 9 | 9 | ||
| 10 | ## 输入、路径与交付 | 10 | ## 输入、路径与交付 |
| 11 | 11 | ||
| 12 | 支持两种入口: | 12 | 支持两种入口: |
| 13 | 13 | ||
| 14 | - 编排模式:接收已经通过 canonical validator 的 `custom/<op>/SPEC.md`,交付目录固定为 `custom/<op>/`。 | 14 | - 编排模式:接收已经通过 canonical validator 的 `custom/<op>/SPEC.md`,交付目录固定为 `custom/<op>/`。 |
| 15 | -- 单独使用:可接收已校验 SPEC、自然语言需求或既有 PyTorch/NumPy 参考。没有已校验 SPEC 时,先加载 `pypto-pro-intent-understand` 创建并校验 SPEC;信息不足时由该 skill 澄清或返回 `blocked`,本 skill 不猜测合同。 | 15 | +- 单独使用:可接收已校验 SPEC、自然语言需求或既有 PyTorch/NumPy 参考。按核心的[需求指引](../pypto-pro-kernel/references/workflows/requirements.md)明确数学合同;使用本 skill 的 SPEC 生成工具链时,将已确定的事实写入其可选模板并校验。本 skill 不猜测合同,也不改变已有参考或验收标准。 |
| 16 | + | ||
| 17 | +SPEC 模板和校验器由同级 `pypto-pro-kernel` 提供;独立安装本工具链时一并提供该核心 skill。普通 kernel 任务沿用核心流程,按实际需要选择是否使用 SPEC。 | ||
| 16 | 18 | ||
| 17 | 下文以 `<spec-path>` 表示已校验 SPEC,以 `<op-dir>` 表示交付目录。编排模式下二者分别为 `custom/<op>/SPEC.md` 和 `custom/<op>/`;单独使用时 `<op-dir>` 可由用户指定,否则取 `<spec-path>` 的父目录,不存在时先创建该目录。 | 19 | 下文以 `<spec-path>` 表示已校验 SPEC,以 `<op-dir>` 表示交付目录。编排模式下二者分别为 `custom/<op>/SPEC.md` 和 `custom/<op>/`;单独使用时 `<op-dir>` 可由用户指定,否则取 `<spec-path>` 的父目录,不存在时先创建该目录。 |
| 18 | 20 | ||
| 19 | -SPEC 中唯一的 JSON machine-contract 是 Stage 2 的机器事实源。至少确认: | 21 | +使用 SPEC 生成工具链时,SPEC 中唯一的 JSON machine-contract 是机器事实源。至少确认: |
| 20 | 22 | ||
| 21 | - 算子名称和数学公式; | 23 | - 算子名称和数学公式; |
| 22 | - 全部输入、输出、参数及默认值; | 24 | - 全部输入、输出、参数及默认值; |
| @@ -25,11 +27,9 @@ SPEC 中唯一的 JSON machine-contract 是 Stage 2 的机器事实源。至少 | |||
| 25 | 27 | ||
| 26 | machine-contract 缺字段、类型错误或 P0 不完整时停止并退回修正 SPEC;不要从正文、动态范围或经验补造数学语义、参数、shape 或 P0。 | 28 | machine-contract 缺字段、类型错误或 P0 不完整时停止并退回修正 SPEC;不要从正文、动态范围或经验补造数学语义、参数、shape 或 P0。 |
| 27 | 29 | ||
| 28 | -编排模式直接复用已通过的 Stage 1 产物,不重复检索 devkit。仅当生成 Golden 所需的明确 | 30 | +直接复用已经确认的需求和数学参考。仅当生成 Golden 所需的明确数学事实缺失时,才按 [reference-normalization.md](references/reference-normalization.md) §1 检索仓内 PyTorch/NumPy 参考;仍不足则列明缺口和已核对证据,返回调用方补齐。 |
| 29 | -数学事实缺失时,才按 [reference-normalization.md](references/reference-normalization.md) §1 | ||
| 30 | -检索仓内 PyTorch/NumPy 参考;仍不足则返回 `stage1_material_gap`,列明缺口和已核对证据。 | ||
| 31 | 31 | ||
| 32 | -Stage 2 必须交付并验证: | 32 | +调用本工具链时交付并验证: |
| 33 | 33 | ||
| 34 | | 文件 | 职责 | | 34 | | 文件 | 职责 | |
| 35 | |---|---| | 35 | |---|---| |
| @@ -54,7 +54,7 @@ python <skill-dir>/scripts/gen_golden_scaffold.py \ | |||
| 54 | --out <op-dir>/<op>_golden.py | 54 | --out <op-dir>/<op>_golden.py |
| 55 | ``` | 55 | ``` |
| 56 | 56 | ||
| 57 | -脚手架通过 Intent Understand 的 `load_spec_contract()` 读取并验证该合同,将校验后的 `formula` 内容写入生成源码的 `_SPEC_FORMULA`,并按合同顺序生成全部 `p0_cases` 的签名、shape、参数和 case 名。合同无效或字段缺失时会非零退出;先修正 SPEC,再继续。 | 57 | +脚手架通过核心 `scripts/validate_spec.py` 的 `load_spec_contract()` 读取并验证该合同,将校验后的 `formula` 内容写入生成源码的 `_SPEC_FORMULA`,并按合同顺序生成全部 `p0_cases` 的签名、shape、参数和 case 名。合同无效或字段缺失时会非零退出;先修正 SPEC,再继续。 |
| 58 | 58 | ||
| 59 | 参考源与交付目标同名时,按 [reference-normalization.md](references/reference-normalization.md) 的候选流程处理。其他已存在的交付文件须先取得用户覆盖确认再写入;未确认则保留原文件并返回 `blocked`。 | 59 | 参考源与交付目标同名时,按 [reference-normalization.md](references/reference-normalization.md) 的候选流程处理。其他已存在的交付文件须先取得用户覆盖确认再写入;未确认则保留原文件并返回 `blocked`。 |
| 60 | 60 | ||
| @@ -114,7 +114,7 @@ return [ | |||
| 114 | 5. 公式可推导的值域、边界/特殊点和数学属性; | 114 | 5. 公式可推导的值域、边界/特殊点和数学属性; |
| 115 | 6. 存在独立 PyTorch 等价 API 或既有参考时的数值对比。 | 115 | 6. 存在独立 PyTorch 等价 API 或既有参考时的数值对比。 |
| 116 | 116 | ||
| 117 | -P1 或可选分支缺少可执行的已确认值时,先退回 `pypto-pro-intent-understand` 补全 SPEC,不自行填值。容差必须与 dtype 和算子数值特性一致。验证失败时定位数学、输入或合同根因并修复;不要用放宽容差、吞掉异常或加入未定义 epsilon 掩盖失败。同一根因连续 3 次失败且没有新证据时停止重试,报告失败命令、原始错误和已尝试修复。 | 117 | +P1 或可选分支缺少可执行的已确认值时,按核心的[需求指引](../pypto-pro-kernel/references/workflows/requirements.md)补齐相关事实并更新 SPEC,不自行填值。容差必须与 dtype 和算子数值特性一致。验证失败时定位数学、输入或合同根因并修复;不要用放宽容差、吞掉异常或加入未定义 epsilon 掩盖失败。同一根因连续 3 次失败且没有新证据时停止重试,报告失败命令、原始错误和已尝试修复。 |
| 118 | 118 | ||
| 119 | 复杂公式没有独立 PyTorch API 或既有参考作为 oracle 时,在交付结果中标记 `semantic_review_required` 并说明缺少何种对照;该标记不替代自验证,也不使用星级置信度。 | 119 | 复杂公式没有独立 PyTorch API 或既有参考作为 oracle 时,在交付结果中标记 `semantic_review_required` 并说明缺少何种对照;该标记不替代自验证,也不使用星级置信度。 |
| 120 | 120 | ||
| @@ -142,6 +142,8 @@ CPU 自验证至少覆盖 FP32/低精度浮点输入可运行、输出为 FP32 | |||
| 142 | TILE_FWK_DEVICE_ID=<id> python <skill-dir>/scripts/validate_golden_once.py --op-dir <op-dir> --spec <spec-path> | 142 | TILE_FWK_DEVICE_ID=<id> python <skill-dir>/scripts/validate_golden_once.py --op-dir <op-dir> --spec <spec-path> |
| 143 | ``` | 143 | ``` |
| 144 | 144 | ||
| 145 | +runner 执行前静态核对必需函数,并拒绝直接或字面量动态导入 `pypto` / `pypto_pro` 的参考文件。该检查不追踪任意间接依赖,仍须确认数学参考独立于待测实现;自验证也不能替代数学语义核对。 | ||
| 146 | + | ||
| 145 | 未指定卡号时省略环境变量;`--spec` 缺省时读取 `<op-dir>/SPEC.md`。相同 SPEC 与文件哈希下, | 147 | 未指定卡号时省略环境变量;`--spec` 缺省时读取 `<op-dir>/SPEC.md`。相同 SPEC 与文件哈希下, |
| 146 | 成功项只复用回执,不再次执行;失败项修正文件后自动重试,仅环境问题且文件未变时显式传 | 148 | 成功项只复用回执,不再次执行;失败项修正文件后自动重试,仅环境问题且文件未变时显式传 |
| 147 | `--retry-failed cpu|npu|all`。两份 golden 的 exit code 均为 0 且源码在执行期间未变, | 149 | `--retry-failed cpu|npu|all`。两份 golden 的 exit code 均为 0 且源码在执行期间未变, |
| @@ -149,13 +151,13 @@ TILE_FWK_DEVICE_ID=<id> python <skill-dir>/scripts/validate_golden_once.py --op- | |||
| 149 | 151 | ||
| 150 | ### 7. 按开关处理 profiling | 152 | ### 7. 按开关处理 profiling |
| 151 | 153 | ||
| 152 | -- `collect_golden_perf=false` 或缺失:跳过,继续完成 Stage 2。 | 154 | +- `collect_golden_perf=false` 或缺失:跳过,继续完成参考实现的交付。 |
| 153 | - `collect_golden_perf=true`:先保证 NPU golden 自验证通过,再阅读并执行 [references/profiling.md](references/profiling.md)。单独使用时沿用本 skill 的显式开关定义,并把 reference 命令中的 `custom/<op>/` 换成实际 `<op-dir>/`;采集流程和判定不变。多个 P0 必须逐 case 采集。 | 155 | - `collect_golden_perf=true`:先保证 NPU golden 自验证通过,再阅读并执行 [references/profiling.md](references/profiling.md)。单独使用时沿用本 skill 的显式开关定义,并把 reference 命令中的 `custom/<op>/` 换成实际 `<op-dir>/`;采集流程和判定不变。多个 P0 必须逐 case 采集。 |
| 154 | - `profile-only=true`:仅在 `collect_golden_perf=true` 且 | 156 | - `profile-only=true`:仅在 `collect_golden_perf=true` 且 |
| 155 | `python <skill-dir>/scripts/validate_golden_once.py --op-dir <op-dir> --spec <spec-path> --check` 通过时执行 | 157 | `python <skill-dir>/scripts/validate_golden_once.py --op-dir <op-dir> --spec <spec-path> --check` 通过时执行 |
| 156 | profiling;不得重写或重新验证 golden。 | 158 | profiling;不得重写或重新验证 golden。 |
| 157 | 159 | ||
| 158 | -Profiling 是 Stage 2 对 NPU golden 的独立可选能力;采集逻辑只存在于 `scripts/profile_golden.py`,不得写入 golden 文件,也不绑定任何下游阶段的协议。 | 160 | +Profiling 是 NPU golden 的独立可选能力;采集逻辑只存在于 `scripts/profile_golden.py`,不得写入 golden 文件,也不绑定任何下游阶段的协议。 |
| 159 | 161 | ||
| 160 | ## 完成条件 | 162 | ## 完成条件 |
| 161 | 163 | ||
| @@ -176,11 +176,13 @@ def _build_validate(op: str, case_names: list[str]) -> str: | |||
| 176 | 176 | ||
| 177 | 177 | ||
| 178 | def _load_spec_contract(path: Path) -> dict[str, Any]: | 178 | def _load_spec_contract(path: Path) -> dict[str, Any]: |
| 179 | - """Load Stage 1's canonical parser without copying its schema rules.""" | 179 | + """Load the companion kernel skill's optional SPEC parser.""" |
| 180 | parser_path = ( | 180 | parser_path = ( |
| 181 | Path(__file__).resolve().parents[2] | 181 | Path(__file__).resolve().parents[2] |
| 182 | - / "pypto-pro-intent-understand" / "scripts" / "validate_spec.py" | 182 | + / "pypto-pro-kernel" / "scripts" / "validate_spec.py" |
| 183 | ) | 183 | ) |
| 184 | + if not parser_path.is_file(): | ||
| 185 | + raise ValueError(f"SPEC validation requires pypto-pro-kernel: {parser_path}") | ||
| 184 | module_spec = importlib.util.spec_from_file_location("pypto_spec_contract", parser_path) | 186 | module_spec = importlib.util.spec_from_file_location("pypto_spec_contract", parser_path) |
| 185 | if module_spec is None or module_spec.loader is None: | 187 | if module_spec is None or module_spec.loader is None: |
| 186 | raise ValueError(f"cannot load canonical SPEC parser: {parser_path}") | 188 | raise ValueError(f"cannot load canonical SPEC parser: {parser_path}") |
| @@ -119,8 +119,10 @@ def _read_json(path: Path) -> dict[str, Any]: | |||
| 119 | 119 | ||
| 120 | def _op_name(spec_path: Path) -> str: | 120 | def _op_name(spec_path: Path) -> str: |
| 121 | validator = Path(__file__).resolve().parents[2] / ( | 121 | validator = Path(__file__).resolve().parents[2] / ( |
| 122 | - "pypto-pro-intent-understand/scripts/validate_spec.py" | 122 | + "pypto-pro-kernel/scripts/validate_spec.py" |
| 123 | ) | 123 | ) |
| 124 | + if not validator.is_file(): | ||
| 125 | + raise ReceiptError(f"SPEC validation requires pypto-pro-kernel: {validator}") | ||
| 124 | spec = importlib.util.spec_from_file_location("_pypto_spec_validator", validator) | 126 | spec = importlib.util.spec_from_file_location("_pypto_spec_validator", validator) |
| 125 | if spec is None or spec.loader is None: | 127 | if spec is None or spec.loader is None: |
| 126 | raise ReceiptError(f"cannot load canonical SPEC validator: {validator}") | 128 | raise ReceiptError(f"cannot load canonical SPEC validator: {validator}") |
| @@ -132,12 +134,55 @@ def _op_name(spec_path: Path) -> str: | |||
| 132 | raise ReceiptError(f"invalid SPEC.md: {error}") from error | 134 | raise ReceiptError(f"invalid SPEC.md: {error}") from error |
| 133 | 135 | ||
| 134 | 136 | ||
| 137 | +def _framework_imports(tree: ast.Module) -> list[str]: | ||
| 138 | + """Find direct framework imports, including literal dynamic imports.""" | ||
| 139 | + names: set[str] = set() | ||
| 140 | + importlib_aliases = {"importlib"} | ||
| 141 | + loader_aliases = {"__import__"} | ||
| 142 | + for node in ast.walk(tree): | ||
| 143 | + if isinstance(node, ast.Import): | ||
| 144 | + names.update(alias.name for alias in node.names) | ||
| 145 | + for alias in node.names: | ||
| 146 | + if alias.name == "importlib": | ||
| 147 | + importlib_aliases.add(alias.asname or alias.name) | ||
| 148 | + elif isinstance(node, ast.ImportFrom): | ||
| 149 | + module = node.module or "" | ||
| 150 | + names.add(module) | ||
| 151 | + names.update( | ||
| 152 | + f"{module}.{alias.name}" if module else alias.name | ||
| 153 | + for alias in node.names | ||
| 154 | + ) | ||
| 155 | + if module == "importlib": | ||
| 156 | + loader_aliases.update( | ||
| 157 | + alias.asname or alias.name | ||
| 158 | + for alias in node.names if alias.name == "import_module" | ||
| 159 | + ) | ||
| 160 | + for node in ast.walk(tree): | ||
| 161 | + if not isinstance(node, ast.Call) or not node.args: | ||
| 162 | + continue | ||
| 163 | + function = node.func | ||
| 164 | + is_loader = isinstance(function, ast.Name) and function.id in loader_aliases | ||
| 165 | + is_module_loader = ( | ||
| 166 | + isinstance(function, ast.Attribute) | ||
| 167 | + and function.attr == "import_module" | ||
| 168 | + and isinstance(function.value, ast.Name) | ||
| 169 | + and function.value.id in importlib_aliases | ||
| 170 | + ) | ||
| 171 | + argument = node.args[0] | ||
| 172 | + if (is_loader or is_module_loader) and isinstance(argument, ast.Constant) and isinstance(argument.value, str): | ||
| 173 | + names.add(argument.value) | ||
| 174 | + return sorted(name for name in names if name.split(".", 1)[0] in {"pypto", "pypto_pro"}) | ||
| 175 | + | ||
| 176 | + | ||
| 135 | def _golden_contract(path: Path, op_name: str, role: str) -> None: | 177 | def _golden_contract(path: Path, op_name: str, role: str) -> None: |
| 136 | - """Reject scripts without the required validation function definitions.""" | 178 | + """Check direct framework independence and required validation functions.""" |
| 137 | try: | 179 | try: |
| 138 | tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) | 180 | tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) |
| 139 | except (OSError, SyntaxError, UnicodeError) as error: | 181 | except (OSError, SyntaxError, UnicodeError) as error: |
| 140 | raise ReceiptError(f"invalid {path.name}: {error}") from error | 182 | raise ReceiptError(f"invalid {path.name}: {error}") from error |
| 183 | + forbidden = _framework_imports(tree) | ||
| 184 | + if forbidden: | ||
| 185 | + raise ReceiptError(f"{path.name} must be independent of PyPTO: {', '.join(forbidden)}") | ||
| 141 | functions = { | 186 | functions = { |
| 142 | node.name: node for node in tree.body | 187 | node.name: node for node in tree.body |
| 143 | if isinstance(node, ast.FunctionDef) | 188 | if isinstance(node, ast.FunctionDef) |
| @@ -5,7 +5,7 @@ | |||
| 5 | """PyPTO-Pro {op} CPU golden reference (higher precision). | 5 | """PyPTO-Pro {op} CPU golden reference (higher precision). |
| 6 | 6 | ||
| 7 | 基于 NPU golden ({op}_golden.py) 的数学逻辑,在 CPU 上以更高精度(FP32)计算。 | 7 | 基于 NPU golden ({op}_golden.py) 的数学逻辑,在 CPU 上以更高精度(FP32)计算。 |
| 8 | -供 test_{op}.py 的精度校验使用(方案A混合容差标准,见 precision_compare.py)。 | 8 | +供 test_{op}.py 的精度校验使用;precision_compare.py 须保持任务明确的数值判据。 |
| 9 | 9 | ||
| 10 | 与 NPU golden 的差异: | 10 | 与 NPU golden 的差异: |
| 11 | - 不使用 NPU 设备,纯 CPU 计算 | 11 | - 不使用 NPU 设备,纯 CPU 计算 |
| @@ -1,135 +0,0 @@ | |||
| 1 | ---- | ||
| 2 | -name: pypto-pro-intent-understand | ||
| 3 | -description: 将自然语言、官方 API、论文或用户代码中的 PyPTO-Pro 算子需求整理为可执行的 SPEC.md。用于 Stage 1 的需求澄清、公式与接口冻结、特性优先级和验收规格定义;不要用于 API 可行性探索、tile/Module 设计、golden 或 kernel 实现。 | ||
| 4 | ---- | ||
| 5 | - | ||
| 6 | -# PyPTO-Pro 需求规格化 | ||
| 7 | - | ||
| 8 | -只负责回答“算什么、接口是什么、怎样算正确”。不要选择 PyPTO-Pro API、计算拓扑、 | ||
| 9 | -Module、tile、同步或 kernel 写法;这些分别属于 material-explore 和 Stage 3/4。 | ||
| 10 | - | ||
| 11 | -## 输入与输出 | ||
| 12 | - | ||
| 13 | -- 输入:用户陈述,以及用户明确给出的公式、代码、测试、论文或官方 API 引用。 | ||
| 14 | -- 输出:`custom/<op>/SPEC.md`,使用 [SPEC 模板](templates/spec-template.md)。 | ||
| 15 | -- 若 `SPEC.md` 已存在,不得静默覆盖;先让用户确认覆盖,或在无人值守任务中保留原文件并返回 `blocked`。 | ||
| 16 | - | ||
| 17 | -按输入形态恢复事实,不改变同一证据标准:标准 API 以目标版本官方定义为准;外部 URL | ||
| 18 | -必须先读取原文,读取失败时只形成低置信度待确认草稿;代码/测试按实际签名和控制流提取; | ||
| 19 | -自定义描述缺公式或最小输入输出合同时直接列出缺失项。不要把模型记忆升级成外部材料证据。 | ||
| 20 | - | ||
| 21 | -## 事实与决策规则 | ||
| 22 | - | ||
| 23 | -按以下优先级采用事实: | ||
| 24 | - | ||
| 25 | -1. 用户明确陈述及用户提供的测试; | ||
| 26 | -2. 项目已经批准的接口合同; | ||
| 27 | -3. 目标版本官方文档或标准 API; | ||
| 28 | -4. 用户提供的论文、源码或参考实现; | ||
| 29 | -5. 模型知识只可形成待确认草稿,不可冒充已确认事实。 | ||
| 30 | - | ||
| 31 | -为每项非显然结论记录来源和置信度: | ||
| 32 | - | ||
| 33 | -- `✓ 高`:用户事实、已批准合同或目标版本官方资料; | ||
| 34 | -- `⚠ 中`:从论文、源码或用户代码分析得到; | ||
| 35 | -- `❓ 低`:推断,只能等待确认或按无人值守规则披露。 | ||
| 36 | - | ||
| 37 | -不得静默为公式、输入输出、shape、dtype、optional 参数、动态轴或边界语义填值。 | ||
| 38 | - | ||
| 39 | -## 工作流 | ||
| 40 | - | ||
| 41 | -### 1. 提取最小语义合同 | ||
| 42 | - | ||
| 43 | -识别并整理公开接口的 rank、shape、dtype、动态轴和语义: | ||
| 44 | - | ||
| 45 | -- 合法算子名:小写字母开头,只含小写字母、数字和下划线; | ||
| 46 | -- 数学公式或等价的逐步算法; | ||
| 47 | -- 每个公开输入、输出及可选参数的名称、rank、shape、dtype、动态轴和语义; | ||
| 48 | -- 每个输出 shape/dtype 相对输入与参数的推导关系;rank-0 tensor 的 shape 明确写 `[]`; | ||
| 49 | -- machine-contract 的每个输入/输出都写可解析的有限闭区间 `value_range: [min, max]`,供 Stage 3 | ||
| 50 | - 分析有限值;界限须有语义依据,未知时不得猜测。P0 输入含 NaN/Inf 时,还须在对应 | ||
| 51 | - `p0_cases[].input_special_values` 按输入名列出实际出现的 `"-inf"`、`"+inf"`、`"nan"`; | ||
| 52 | - 有限区间不能代替这些特殊值,也不能删掉原任务的特殊输入; | ||
| 53 | -- 零值、极值、NaN/Inf、空维度及尾部元素的数学行为; | ||
| 54 | -- 精度标准、功能优先级和至少一组可执行 P0 典型配置。 | ||
| 55 | - | ||
| 56 | -公开接口是否要求辅助 tensor 由调用方预展开/预广播,属于输入 shape 关系,必须在这里保留; | ||
| 57 | -kernel 内如何据此 broadcast、切 tile 或索引属于 Stage 3,不能提前设计。 | ||
| 58 | - | ||
| 59 | -公式不能表达分块、循环、递推、在线更新或状态依赖时,补充带编号的算法步骤。 | ||
| 60 | -算法描述定义数学过程,不提前规定 tile 或硬件实现。 | ||
| 61 | - | ||
| 62 | -### 2. 识别会改变公开语义的特性 | ||
| 63 | - | ||
| 64 | -只列当前算子实际涉及的特性,例如 mask、量化、融合、动态 shape、混合精度、随机性、 | ||
| 65 | -稀疏性或数值稳定策略。每项记录: | ||
| 66 | - | ||
| 67 | -- 是否需要; | ||
| 68 | -- 来源与置信度; | ||
| 69 | -- P0/P1/P2/P3 优先级; | ||
| 70 | -- 对公式、接口或验收的影响。 | ||
| 71 | - | ||
| 72 | -P0/P1 必须进入首个版本;P2 可选;P3 明确暂缓。不要在本 skill 中判断 PyPTO-Pro | ||
| 73 | -实现复杂度或 API 支持度,交给 material-explore。 | ||
| 74 | - | ||
| 75 | -对 optional 参数执行四项语义分析:在公式中的位置、计算作用、与其他参数的依赖/互斥、 | ||
| 76 | -省略时的默认语义。不要把 kernel 实现方式混入这项分析。 | ||
| 77 | - | ||
| 78 | -### 3. 集中处理歧义 | ||
| 79 | - | ||
| 80 | -- 交互模式:一次展示数据流摘要、规格清单、关键歧义及拟采用默认值,整体确认;最多两轮。 | ||
| 81 | -- 用户输入已经完整时,直接展示确认稿,不机械追问已给出的事实。 | ||
| 82 | -- 用户明确要求不提问或持续执行时,进入无人值守模式;仅对非阻塞字段使用可追溯默认, | ||
| 83 | - 并在 SPEC“自动决策”中记录采用值、来源、理由和影响。 | ||
| 84 | -- 若数学语义或最小输入输出合同仍无法确定,不猜测,返回 `blocked` 和缺失项。 | ||
| 85 | - | ||
| 86 | -允许使用的默认值必须先披露再持久化。shape、dtype 和动态轴只有在目标标准接口确有默认 | ||
| 87 | -或用户确认后才可采用;没有依据时保持未决并阻断,不能用示例模板值替代。 | ||
| 88 | - | ||
| 89 | -### 4. 生成并自检 SPEC | ||
| 90 | - | ||
| 91 | -复制 [SPEC 模板](templates/spec-template.md),逐项替换占位符;删除不适用的可选行,禁止把 | ||
| 92 | -模板占位符或示例值留在成品中。`json machine-contract` fenced block 是唯一机器事实源; | ||
| 93 | -正文只解释公式、接口语义、边界和证据,不重复 shape、dtype、容差或 P0 字段值: | ||
| 94 | - | ||
| 95 | -- `op_name` 对应算子名; | ||
| 96 | -- `formula` 用等式或编号伪代码步骤定义每个公开输出;复杂算法仍须让每个输出成为赋值或箭头目标,正文只解释符号与依据; | ||
| 97 | -- `supported_dtypes` 按首次出现顺序列出默认输入输出和 P0 case 实际使用的全部 canonical dtype;同一接口的不同 dtype 组合保留在同一 SPEC,逐 case 明确输入和输出 dtype,避免静默丢失 index、mask 或量化辅助 tensor 的 dtype; | ||
| 98 | -- `inputs` / `outputs` 按公开签名顺序完整记录 name、shape、dtype、有限 value_range; | ||
| 99 | - 非有限输入另按 P0 case 记录 `input_special_values`,例如 | ||
| 100 | - `{"x":["-inf","+inf"]}` 或 `{"x":["nan"]}`。列出的每一种必须在该 case 的实际输入出现; | ||
| 101 | -- 同一公开 tensor 的 P0 case 跨 rank 时,顶层 `shape` 使用 `["..."]`,逐案 `input_shapes` / `output_shapes` 仍写具体维度;只承诺列明的 P0 范围,输出形状关系由公式和独立 Golden 验证; | ||
| 102 | -- `p0_cases` 逐案记录 name、params、input_shapes、output_shapes;dtype 与默认 tensor 不同时成对记录完整的 input_dtypes、output_dtypes;校验器会从第一项导出 | ||
| 103 | - 只供旧调用方使用的内存字段 `p0_shapes`,SPEC 不再双写该字段; | ||
| 104 | -- `default_params` 只包含公开签名中已确认的标量默认参数;没有则写 `{}`; | ||
| 105 | -- `tolerance`、动态轴范围、shape 约束和性能目标直接记录已确认裁定; | ||
| 106 | - | ||
| 107 | -性能目标遵循单一来源规则:只有用户明确给出且可复算的数值目标时,才把该值写入 | ||
| 108 | -`perf_target`,并在 SPEC“P0 与性能目标依据”中记录用户来源。用户未指定数值目标时, | ||
| 109 | -`perf_target` 写 `null`,并在“自动决策”中说明 Stage 5 将使用逐 P0 case 的默认理想参考 | ||
| 110 | -`golden_reference_ratio >= 1.0`;不得把这一系统默认值写成用户要求或交付硬门禁。 | ||
| 111 | - | ||
| 112 | -所有 P0 的映射 key 与顺序分别等于 `default_params`、`inputs`、`outputs`;具体 shape 必须 | ||
| 113 | -等于把本 case 输入/参数代入合同 shape 表达式后的结果。rank-0 tensor 写 `[]`。tile/kernel | ||
| 114 | -shape 仍由 Stage 3 决定。每个动态 shape 符号须在至少一个输入维中单独出现,保证 P0 | ||
| 115 | -具体 shape 能确定地绑定该符号;其他输入/输出可使用由它组成的表达式。 | ||
| 116 | - | ||
| 117 | -运行模板旁的校验器;非零退出时修复后重跑: | ||
| 118 | - | ||
| 119 | -```bash | ||
| 120 | -python "$CANNBOT_CONFIG_ROOT/skills/pypto-pro-intent-understand/scripts/validate_spec.py" \ | ||
| 121 | - custom/<op>/SPEC.md | ||
| 122 | -``` | ||
| 123 | - | ||
| 124 | -## 完成条件 | ||
| 125 | - | ||
| 126 | -- 算子名、数学语义和最小输入输出合同均已确定; | ||
| 127 | -- shape、dtype、动态轴、optional 参数和边界行为已确认或按无人值守规则留有证据; | ||
| 128 | -- 复杂算子含可恢复的算法步骤; | ||
| 129 | -- 所有功能均标优先级,P0/P1 没有遗漏; | ||
| 130 | -- 所有 P0 配置均可供 golden 构造输入,且输出 shape 与机器合同公式一致; | ||
| 131 | -- 所有机器合同输入/输出均有有依据、可解析的有限 `value_range`;原任务含非有限 P0 输入时, | ||
| 132 | - 每案的 `input_special_values` 与原任务一致,Golden 和后续真机测试不得以有限值替换; | ||
| 133 | -- SPEC 恰有一个严格 JSON machine-contract、正文没有重复机器字段、无占位符或未披露默认值; | ||
| 134 | -- 用户性能目标或 Stage 5 默认 Golden 1.0 理想参考的来源已按规则明确记录; | ||
| 135 | -- `validate_spec.py` 通过。 | ||
| @@ -1,92 +0,0 @@ | |||
| 1 | -# 算子需求规范 | ||
| 2 | - | ||
| 3 | -## 机器合同 | ||
| 4 | - | ||
| 5 | -> 下列 JSON 是公式、公开接口、验收配置的唯一机器事实源。正文只解释语义与证据,不复制字段值。 | ||
| 6 | - | ||
| 7 | -```json machine-contract | ||
| 8 | -{ | ||
| 9 | - "schema_version": 1, | ||
| 10 | - "op_name": "{{OP_NAME}}", | ||
| 11 | - "formula": "{{FORMULA_OR_NUMBERED_STEPS}}", | ||
| 12 | - "supported_dtypes": [], | ||
| 13 | - "inputs": [], | ||
| 14 | - "outputs": [], | ||
| 15 | - "default_params": {}, | ||
| 16 | - "tolerance": { | ||
| 17 | - "atol": null, | ||
| 18 | - "rtol": null | ||
| 19 | - }, | ||
| 20 | - "dynamic_axes_ranges": {}, | ||
| 21 | - "shape_constraints": [], | ||
| 22 | - "p0_cases": [], | ||
| 23 | - "perf_target": null, | ||
| 24 | - "exit_criteria": null | ||
| 25 | -} | ||
| 26 | -``` | ||
| 27 | - | ||
| 28 | -填写约束: | ||
| 29 | - | ||
| 30 | -- `op_name` 使用 lower_snake_case;`supported_dtypes` 按首次出现顺序列出默认输入输出及全部 P0 case 实际使用的 canonical dtype。 | ||
| 31 | -- `formula` 用一个 JSON 字符串定义每个公开输出;简单算子写可审查的等式,复杂递推写编号伪代码步骤(换行转义为 `\n`),且每个输出都必须是赋值或箭头目标。不要只写自然语言标签。 | ||
| 32 | -- `inputs` / `outputs` 按公开签名顺序填写,每项包含 `name`、`shape`、`dtype`、`value_range`,可选布尔字段 `is_list`(缺省为 `false`);rank-0 shape 写 `[]`,有限部分的闭区间值域写 `[min, max]`。某 P0 输入还包含非有限值时,该 case 增加 `input_special_values`,按输入名列出实际出现的 `"-inf"`、`"+inf"`、`"nan"`(例如 `{"x":["-inf","+inf"]}`);不能用有限样本替换原任务的特殊值。 | ||
| 33 | -- shape 维度只使用正整数,或由符号、整数、`+ - * //` 和括号构成的表达式;每个动态符号须在至少一个输入 shape 中作为独立维度出现,并在 `dynamic_axes_ranges` 中给出正整数闭区间。公开接口确实跨 rank 时可将该 tensor 的顶层 shape 写成单独的 `["..."]`,表示 rank 多态;此时 P0 case 仍须给出逐案完整具体 shape,不能由此声称覆盖未声明的 rank/shape。输出形状语义仍须由公式和独立 Golden 验证。 | ||
| 34 | -- `default_params` 只放公开签名中的标量默认参数,顺序与签名一致;无默认参数时写 `{}`。 | ||
| 35 | -- 采用 Pro `precision_compare.py` 的方案 A 时,`tolerance` 填 `{"policy":"pro_scheme_a"}`;采用已确认的逐元素容差时填写 `atol/rtol`。两种格式不可混用。 | ||
| 36 | -- `p0_cases` 至少一项,每项包含 `name`、`params`、`input_shapes`、`output_shapes`,可增加成对的 `input_dtypes`、`output_dtypes`,以及非有限输入的 `input_special_values`。dtype 映射必须按声明顺序覆盖全部输入/输出;缺省时继承顶层 tensor dtype。首项 `params` 等于 `default_params`,首项 dtype 等于顶层默认值;每个 shape 都是公式代入后的具体整数数组。同一公开接口的多 dtype case 放在同一 SPEC。 | ||
| 37 | -- TensorList 输入/输出显式声明 `is_list: true`:顶层 `shape` 是成员约束,异构 shape 可用 `["..."]`;P0 的 `input_shapes[name]` / `output_shapes[name]` 是非空成员 shape 数组,例如 `[[8,64],[16,64]]`,不能编码为 `[arity, ...]`。每个列表的成员 dtype 相同、rank 相同且至少为 1,连续且在同一设备;公共 `[min,max]` 值域逐成员生效。成员 shape 中的符号遵循已有共享符号规则;跨成员不同的维度通过 `["..."]` 和具体 P0 shapes 表达。列表特殊值通过 `input_special_values[name]` 声明,按整个列表所有成员的并集核对,有限值域仍逐成员检查。单个 TensorList 输出作为一个公开输出,不能按列表长度拆成多个输出。非有限 scalar 使用 JSON 字符串 `"inf"` / `"+inf"` / `"-inf"` / `"nan"`,作为数值参数传给 Golden 和公开 wrapper;kernel 使用显式浮点 scalar 形参,勿在 VF 内直接写裸 `inf` / `nan`。当前仍不支持空列表;未导出的长度/成员 shape 不属于交付范围。 | ||
| 38 | -- 不适用的可选字段使用空数组、空对象或 `null`,不要保留示例值或另建第二份机器表格。 | ||
| 39 | - | ||
| 40 | -## 语义说明 | ||
| 41 | - | ||
| 42 | -### 1. 功能与分类 | ||
| 43 | - | ||
| 44 | -{{DESCRIPTION_AND_CATEGORY}} | ||
| 45 | - | ||
| 46 | -### 2. 公式符号与依据 | ||
| 47 | - | ||
| 48 | -{{FORMULA_NOTATION_AND_RATIONALE_WITHOUT_REPEATING_MACHINE_FIELD}} | ||
| 49 | - | ||
| 50 | -### 3. 算法描述 | ||
| 51 | - | ||
| 52 | -{{ALGORITHM_OR_NOT_APPLICABLE}} | ||
| 53 | - | ||
| 54 | -### 4. 数据流说明 | ||
| 55 | - | ||
| 56 | -{{DATAFLOW}} | ||
| 57 | - | ||
| 58 | -### 5. 接口语义 | ||
| 59 | - | ||
| 60 | -{{INTERFACE_SEMANTICS_WITHOUT_REPEATING_MACHINE_FIELDS}} | ||
| 61 | - | ||
| 62 | -### 6. 功能与可选参数依据 | ||
| 63 | - | ||
| 64 | -{{FEATURE_AND_OPTIONAL_PARAM_RATIONALE}} | ||
| 65 | - | ||
| 66 | -### 7. 精度语义 | ||
| 67 | - | ||
| 68 | -{{PRECISION_SEMANTICS_WITHOUT_REPEATING_TOLERANCE}} | ||
| 69 | - | ||
| 70 | -### 8. 动态 Shape 与约束依据 | ||
| 71 | - | ||
| 72 | -{{SHAPE_RATIONALE_WITHOUT_REPEATING_MACHINE_FIELDS}} | ||
| 73 | - | ||
| 74 | -### 9. 边界条件处理 | ||
| 75 | - | ||
| 76 | -{{ZERO_EXTREME_NAN_INF_BEHAVIOR}} | ||
| 77 | - | ||
| 78 | -### 10. P0 与性能目标依据 | ||
| 79 | - | ||
| 80 | -{{P0_AND_PERF_RATIONALE_WITHOUT_REPEATING_MACHINE_FIELDS}} | ||
| 81 | - | ||
| 82 | -### 11. 参考与来源 | ||
| 83 | - | ||
| 84 | -{{SOURCES_AND_CONFIDENCE}} | ||
| 85 | - | ||
| 86 | -### 12. 自动决策 | ||
| 87 | - | ||
| 88 | -{{DECISIONS_OR_NOT_APPLICABLE}} | ||
| 89 | - | ||
| 90 | ---- | ||
| 91 | -*生成时间: {{TIMESTAMP}}* | ||
| 92 | -*确认状态: {{CONFIRMATION_STATUS}}* | ||
| @@ -5,86 +5,55 @@ description: Write, verify, debug and optimize native pypto_pro kernels on Ascen | |||
| 5 | 5 | ||
| 6 | # PyPTO Pro Kernel Workflow | 6 | # PyPTO Pro Kernel Workflow |
| 7 | 7 | ||
| 8 | -Use native `pypto_pro.language` to turn a mathematical contract into a verified kernel. This entry selects the next action; the [reference index](references/index.md) locates the topic that owns each rule. | 8 | +Use native `pypto_pro.language` to implement and verify the user's mathematical contract. Resolve links relative to this file; runnable [examples](examples/) are bundled inside this skill. The external framework source checkout and installed PyPTO package are separate roots. |
| 9 | - | ||
| 10 | -Resolve links relative to this `SKILL.md`. Runnable kernels live in the bundled [examples](examples/) directory. Paths written as `pypto/...` refer to a separately supplied PyPTO source checkout, which must match the target installation; the checkout and installed package are different roots. Machine configuration is external to the skill. | ||
| 11 | - | ||
| 12 | -A directory, heading outline or link list locates instructions; it does not expose their body. When a document reader offers section selection, select **Choose the current stage**, then read the section owning the selected action. A truncated body is also an incomplete read: fetch its required missing portion before treating routing or preflight as complete. | ||
| 13 | 9 | ||
| 14 | ## Constraints and workspace policy | 10 | ## Constraints and workspace policy |
| 15 | 11 | ||
| 16 | -- **Keep kernels native.** No skill-specific tensor types, decorators or transfer wrappers. Removing this skill must leave an ordinary PyPTO kernel. Keep the framework independent of the skill. | 12 | +- Keep kernels native: no skill-specific tensor types, decorators or transfer wrappers. Keep compiler semantics and framework diagnostics in the independent framework, and guard internal interfaces against the installed version. |
| 17 | -- **Keep ownership clear.** Usage guidance and runnable examples belong here; repeated statically decidable mistakes can justify a checker. Compiler semantics, source-location diagnostics and missing IR interfaces belong to PyPTO. Guard internal interfaces with version checks and focused probes; do not reproduce compiler analysis in a skill checker. | 13 | +- Preserve the numerical contract, public layouts and tolerances. Report numerical correctness, model diagnostics and hardware performance separately, bound to source and toolchain identity. |
| 18 | -- **Make generalization verifiable.** Before choosing tiling keys, establish the [supported domain, specialization reasons and reuse checks](references/workflows/authoring.md#generalization-and-specialization). Apply those checks to the delivered implementation; one JIT entry alone does not establish generalization. | 14 | +- Vector computation uses actual `vf.*` operations inside `@pl.vector_function`; only `pl.sort32`, `pl.mrgsort` and `pl.mrgsort2` may use tile Vector compute. Allocation, movement/padding, synchronization, scalar control and SIMT remain available. Cube matmul starts with `pl.gemm` / `pl.gemm_mx`, subject to the [closed exceptions](references/patterns/gemm-desugar.md). This is authoring policy, not an API-support or speed claim. |
| 19 | -- **Keep evidence distinct.** Official docs and their call examples discover contracts; installed Python/C++ source verifies interfaces; a probe confirms current behavior. An API name alone does not prove support, and one failed form does not prove absence. Check version identity and name variants before declaring a capability missing; use the [evidence checks](references/verification/evidence.md). | 15 | +- Establish the [supported domain and specialization rules](references/workflows/authoring.md#generalization-and-specialization); one entry and a few passing shapes do not prove generalization. |
| 20 | -- **Preserve the numerical contract.** Do not silently widen tolerances or change public layouts. Report numerical correctness, model diagnostics and hardware performance separately, tied to source and toolchain identity. | 16 | +- Keep official contracts, installed signatures and observed behavior distinct. Before claiming a capability absent, check Python/C++ source, alternate names and a focused probe using the [evidence rules](references/verification/evidence.md). |
| 21 | -- **Vector compute uses VF; only sorting may use tile compute.** Outside `pl.sort32`, `pl.mrgsort` and `pl.mrgsort2`, tile Vector computation is prohibited, including in teaching examples. Use actual `vf.*` operations inside `@pl.vector_function`; replacing a `pl.*` prefix does not establish an equivalent VF API. Allocation, data movement/padding, synchronization, scalar control and SIMT remain available. Cube matmul starts with `pl.gemm` / `pl.gemm_mx`, with its [closed exception list](references/patterns/gemm-desugar.md). This is workspace authoring policy, not a claim that tile APIs cannot compile or that every VF implementation is faster. [Static rules](references/tooling/checks.md) enforce the policy and check VF names against the selected source tree. | ||
| 22 | 17 | ||
| 23 | ## Choose the current stage | 18 | ## Choose the current stage |
| 24 | 19 | ||
| 25 | -Before the first kernel-authoring task in a session, read the [DSL primer](references/workflows/getting-started.md) once unless its basics are already in context. Debugging or optimizing an existing kernel needs only the sections resolving a current uncertainty. Then start from the user's artifact and best verified baseline. For an unfamiliar computation, [select the nearest complete example](references/workflows/authoring.md#selecting-an-example), matching its numerical and layout contract; use patterns and API owners for unresolved mechanics. Preserve a suitable complete implementation as the control while adapting it. | 20 | +Start from the user's artifact and best verified baseline. For a new kernel, read the [DSL primer](references/workflows/getting-started.md) unless already in context, then [select a compatible complete example](references/workflows/authoring.md#selecting-an-example). For supplied code, inspect the source and supplied evidence first. Only when the controller supplies a `pypto-task-context/1` JSON inventory, use `query --task manifest.json` to distinguish declared files from inline statements/fixtures; do not search for a separate file representing inline evidence. This checks the inventory; source discovery still uses positional `query TEXT`. A prose task such as `task.txt` is not this inventory. Query a specific unresolved API or capability with positional `query TEXT`; a decision already supported by the workload and source does not need a documentation tour. A validation-only request with a supplied evaluator should obtain its first result before speculative repairs, after checking its loading route. Read any selected section's body; a heading or truncated excerpt does not establish its instructions. |
| 26 | 21 | ||
| 27 | -Before the first supplied-evaluator run, verify its [loading route and public entry](references/verification/board-runs.md#integrate-a-supplied-evaluator). Use that evaluator for the first complete nondegenerate case; an isolated golden call may change dtype promotion or omit criterion branches. Gate device commands with the [source-gated runner](references/tooling/checks.md#run-a-command-after-source-checks). | 22 | +| Current need | Next action | |
| 28 | - | ||
| 29 | -**Score target: finish one complete benchmark case before any full matrix, including a correctness-only stage.** Keep the supplied evaluator's original timing strategy. Require a positive native-task duration and a populated performance contribution in the raw report; a numerical pass alone leaves this gate open. If either is missing, read [capture preflight](references/verification/native-timing.md#verify-capture-before-expanding-performance-coverage) and repair collection/export before expanding. For other timing requests, establish the same capture path before expanding performance coverage. Validate each configuration before timing it; use representative timings to choose the next experiment, then complete the promised correctness matrix before acceptance. A numerical pass and a timing result each belong to their exact source, configuration and toolchain. | ||
| 30 | - | ||
| 31 | -**For a busy or regressed SIMD stage, inspect VF loop form early.** A first/last-block or validity `if` inside a row/chunk loop can prevent hardware-loop and address-generator lowering, even when its condition is constant throughout that invocation. Compare dispatch outside VF with statically specialized bodies before redesigning the algorithm, adding buffers or replacing VF with SIMT. [VF control flow](references/api/vf.md#keep-runtime-dispatch-out-of-vf-loops) owns the mechanism, alternatives and evidence limits; the source checker emits a performance advisory, not a prohibition on branches. | ||
| 32 | - | ||
| 33 | -| Current need | Required next action | | ||
| 34 | | --- | --- | | 23 | | --- | --- | |
| 35 | -| Implement a kernel | Resolve [contract and resources](references/workflows/authoring.md#preflight-decisions), then validate one complete slice; compare plausible paths when the task has a performance target | | 24 | +| Clarify requirements or write a requested specification | Resolve the [mathematical contract](references/workflows/requirements.md); use its optional SPEC tools only when the task or selected generator needs that format | |
| 36 | -| Fix parsing, compilation, wrong results or device failures | [Debugging](references/workflows/debugging.md): symptom → first check → owner | | 25 | +| Locate an existing example or implementation | Query the workload in ordinary words with `query TEXT --kind example --limit 3`, then resolve the selected program for its kernel, independent reference, tests and source hashes. Use catalog/file search for a retrieval miss or an unresolved scope condition | |
| 37 | -| Obtain device time | Validate the exact workload being timed, then use [native-task timing](references/verification/native-timing.md). Full supplied and boundary-case correctness is required for final acceptance, not for an early representative comparison | | 26 | +| Implement or adapt a kernel | Resolve [contract/resources](references/workflows/authoring.md#preflight-decisions) and matching [feature triggers](references/workflows/authoring.md#feature-triggers); validate one complete slice before extending it | |
| 38 | -| Optimize or refactor a correct kernel | Read [Choose the implementation experiment](references/workflows/optimization.md#choose-the-implementation-experiment) and the [source-bound comparison](references/diagnostics/performance.md#test-a-mechanism-with-source-bound-evidence) before selecting the first candidate. An existing runtime plan answers budget setup, not mechanism selection | | 27 | +| Fix a parse, compile, numerical or device failure | Read the original diagnostic and query its unresolved operation; use [debugging](references/workflows/debugging.md) when the boundary still needs classification | |
| 39 | -| Finalize an optimization result | Meet the [exit criteria](references/workflows/optimization.md#exit-criteria): check the final winner's neighbors or resource bounds and resolve remaining cost-driven comparisons within budget | | 28 | +| Optimize a correct kernel | For SIMT, select one [mechanism-specific comparison](references/patterns/simt-first.md#choose-a-simt-experiment); otherwise use the [cost-driven workflow](references/workflows/optimization.md#choose-the-implementation-experiment). Consult the general workflow for unresolved budget or acceptance questions; preserve the best verified baseline | |
| 40 | -| Deliver an operator package | Follow the [five-file delivery format](references/workflows/delivery.md): README, one implementation module with an internal tiling-key entry, CPU golden, executable test and precision comparator; no kernel factories | | 29 | +| Run a supplied evaluator or measure time | Verify its [loading route](references/verification/board-runs.md#integrate-a-supplied-evaluator), then [capture and scoring](references/verification/native-timing.md#verify-capture-before-expanding-performance-coverage) on one complete nondegenerate case; for a score target, do this before any full matrix | |
| 30 | +| Deliver an operator package | Use the [five-file format](references/workflows/delivery.md), with a module-level kernel and internal tiling-key dispatch | | ||
| 41 | 31 | ||
| 42 | -These feature gates apply before choosing an implementation or validator: | 32 | +For an explicitly provided performance-card library, enable the [optional card source](references/tooling/optimization.md#optional-performance-card-source). Query the bottleneck, technique or stable card ID, read the original applicability/API gates and follow declared relationships to the owning contract. Check card coverage before treating a miss as complete. Cards add conditional references and relationships; they do not change authoring policy, establish runtime support or activate another skill's workflow. |
| 43 | 33 | ||
| 44 | -| Feature | Required decision and owner | | 34 | +Open only the rows matching the current uncertainty. The [reference index](references/index.md) routes other patterns and APIs. |
| 45 | -| --- | --- | | ||
| 46 | -| A bandwidth-floor claim would rule out another implementation or end the search | Read [Distinguish bandwidth quantities](references/diagnostics/performance.md#distinguish-bandwidth-quantities) and identify the independent evidence for the claimed limit before using it as a stopping reason | | ||
| 47 | -| Grouped GEMM or per-group row processing | Count actual work per worker across all groups, compare [continuous ownership](references/api/gemm.md#distribute-tiles-across-runtime-groups), and guard [empty local consumers](references/diagnostics/validation-traps.md#empty-consumer-loops-need-their-own-reuse-check); launch size and total tile count alone do not establish coverage or balance | | ||
| 48 | -| Very small M with wide matrix weights, or several BF16 products representing an FP32 activation | Consider [thin-row arithmetic and transport alternatives](references/api/gemm.md#thin-row-contractions-compare-arithmetic-and-transport-paths) alongside the Cube control; choose a bounded comparison using the actual precision contract, live state and busiest worker's work | | ||
| 49 | -| VF loads or stores cross FP16/BF16 and FP32 element widths | Verify the complete [load/cast/pack/store map](references/api/vf.md#map-physical-containers-before-composing-conversions), including [order-preserving FP16 widening](references/api/vf.md#213-the-fp32-path-for-fp16-source-data-order-preserving-widening-with-unpk-required-reading); dtype alone does not establish lane order or dense writes | | ||
| 50 | -| An indexed copy/packing phase dominates, including already grouped SIMT code | Compare [tuned flat and grouped transport](references/patterns/simt-payload.md#compare-flat-and-grouped-mappings); retain the flat control when starting from grouped code and retune after carrier changes | | ||
| 51 | -| Independent load→VF→store chunks reuse local buffers | Choose [row batching](references/patterns/vf-row-reduce.md#batch-independent-rows-even-when-each-row-fits) and [local buffering](references/api/memory-allocation.md#independent-buffers-and-slot-depth) separately, accounting for all operands and slots | | ||
| 52 | -| VF register state, scalar broadcasts or fused updates | Preserve [bindings and independent copies](references/api/vf.md#vf-register-aliasing-and-copying); fused updates need [seeded destinations](references/api/vf.md#destination-registers-used-as-inputs), while first/last decisions need the [loop-form comparison](references/api/vf.md#keep-runtime-dispatch-out-of-vf-loops) | | ||
| 53 | -| Exponential normalization or softmax-weighted aggregation, including indexed/segmented payloads | Select a [contract-compatible anchor](references/patterns/normalized-contractions.md#select-a-correctness-anchor); compare residency and streaming after checking the producer, normalizer and consumer's realized work | | ||
| 54 | -| Refactoring manual synchronization into auto_mutex/pipeline | Preserve geometry and arithmetic first; verify [mutex IDs, cross-core edges and slot lifetimes](references/api/crosscore-sync.md), then change stage placement or overlap separately | | ||
| 55 | -| Repeated dense dot products or weighted contractions, including backward and runtime-indexed phases | Probe a [regular VF/Cube block](references/patterns/normalized-contractions.md#choose-a-native-paradigm-per-phase) before scalar SIMT tuning; a full-matrix storage ban still permits [streamed reverse contractions](references/patterns/normalized-contractions.md#stream-reverse-contractions-with-bounded-state) | | ||
| 56 | -| A computed statistic becomes a normalizing divisor | Check the consumer with [range propagation and discriminating inputs](references/api/numerics.md#2-small-magnitudes-in-normalized-ratios), beyond zero/uniform controls | | ||
| 57 | -| A GEMM accumulator's dtype differs from its final output dtype | Choose the [final output path](references/api/fixpipe.md#choose-the-final-output-path-before-adding-a-conversion-kernel) before allocating an intermediate tensor or adding a cast kernel | | ||
| 58 | -| Adapting a padded Cube kernel to fewer logical rows, heads or channels | Separate [useful rows, producer extent and receiving capacity](references/api/crosscore-sync.md#logical-validity-is-not-transfer-capacity); numerical agreement does not prove the write footprint fits | | ||
| 59 | -| A reinterpreted or transposed tile feeds VF loads | Verify its [physical address map](references/api/datamove.md#verify-a-vf-consumers-address-map-after-reinterpretation) on coordinate-distinct data; metadata views do not move bytes | | ||
| 60 | -| VF produces a Cube operand and the task permits fusion | Compare [format, residency and repeated producer work](references/api/gemm.md#transformed-operands-format-residency-and-repeated-work) on complete paths; capacity alone does not decide fusion | | ||
| 61 | 35 | ||
| 62 | -## Targeted lookup and local checks | 36 | +## Query, check, execute, decide |
| 63 | 37 | ||
| 64 | -Shell examples run from the skill root (`pypto-pro-kernel/`). From another directory, invoke `scripts/check.py` by its absolute path; explicit input paths follow the caller's directory. Examples are bundled and need no path override. Set `PYPTO_SRC` to the absolute path of the matching PyPTO checkout or pass `--pypto-root` before the subcommand for source-dependent checks; `--examples-root` selects a different example library. See [tool usage](references/tooling/checks.md). | 38 | +CLI is the base interface; MCP is an optional adapter to the same implementation and knowledge. Use exposed, authorized `kernel_*` tools, or invoke `scripts/check.py` directly when MCP is unavailable. The [mode and fallback contract](references/tooling/checks.md#cli-and-mcp-modes) preserves interpreter, paths and permissions. An approval denial is not an availability failure. Use [bounded search/read and existing-request status](references/tooling/checks.md#bounded-context-io-and-existing-execution-status) when available; continue a partial read using its source hash rather than assuming it is complete. For long checks, wait about 20–30 seconds on the existing session or pinned receipt; a running request is still pending. After timeout/disconnection, inspect state and artifacts before any retry. |
| 39 | + | ||
| 40 | +Shell examples below run from this skill's root; elsewhere use the check script's absolute path. Bundled examples need no path override; select matching framework source with `PYPTO_SRC` or `--pypto-root`. Global `--pypto-root` / `--examples-root` options precede the subcommand. | ||
| 65 | 41 | ||
| 66 | ```bash | 42 | ```bash |
| 67 | -python scripts/check.py rules <file-or-dir> | 43 | +python scripts/check.py query 'UB to L1' --source candidate.py |
| 68 | -python scripts/check.py run --source <trial-dir> -- python -m pytest <test> -q | 44 | +python scripts/check.py search --path /path/to/relevant/module --pattern SYMBOL |
| 69 | -python scripts/check.py # examples rules + coverage + catalog | 45 | +python scripts/check.py read --path /path/to/owner.md --start-line 180 --max-lines 40 |
| 70 | -python scripts/check.py --pypto-root /path/to/pypto api vf # also: pl, pl.simt | 46 | +python scripts/check.py rules candidate.py --format json |
| 71 | -python scripts/check.py surface # basic_api examples only | 47 | +python scripts/check.py native --spec /path/to/native-spec.json |
| 48 | +python scripts/check.py run --source candidate.py --source test.py -- python -m pytest test.py -q | ||
| 49 | +python scripts/check.py suggest --source candidate.py | ||
| 72 | ``` | 50 | ``` |
| 73 | 51 | ||
| 74 | -| Question | Owner | | 52 | +1. Query the operation at the unresolved boundary, for example `python scripts/check.py query 'vf.reduce_sum' --source candidate.py` from this skill’s root. Use the returned body or conditional route first; broaden to [API lookup](references/api/pypto_pro_language.pyi), a linked owner or [example selection](references/tooling/examples.md) only for facts it leaves unresolved. A missing match is not API absence. |
| 75 | -| --- | --- | | 53 | +2. Check the changed sources, then use [native preflight](references/tooling/checks.md#scenario-query-and-native-preflight) with concrete metadata. Unknown scope and advisories require review; exit zero does not establish numerical correctness. |
| 76 | -| What parameters, defaults and enum choices does an API expose? | Search the generated [language API reference](references/api/pypto_pro_language.pyi); [check or regenerate it](references/tooling/checks.md#generated-api-reference) against the selected source | | 54 | +3. Gate device commands with `run` and the [board discipline](references/verification/board-runs.md). Read the [feedback](references/diagnostics/messages.md#tool-feedback-contract), including the original exit status and unresolved evidence. For MCP also check `delivery`; incomplete delivery leaves the result unresolved. |
| 77 | -| Which computation pattern or API topic fits? | [Reference index](references/index.md) and authoring's feature triggers | | 55 | +4. For optimization, use [suggestions and current experiment state](references/tooling/optimization.md) to choose one testable hypothesis and retain or restore the best source. For a supplied performance assertion or a positive speedup claim, [check its exact evidence scope](references/tooling/optimization.md#performance-claim-consistency); a decision making no speedup claim needs no extra claim-tool tour. A suggestion is conditional; no match does not end the search. Two unsuccessful fixes at one boundary without new evidence require revisiting its contract. |
| 78 | -| What does this exact error mean? | Search [constraints](references/api/constraints.md); for framework defects, use [diagnostics](references/index.md#troubleshooting) | | ||
| 79 | -| Which runnable example should I open? | [Example catalog](references/tooling/examples.md); read one nearest kernel/test header before its code | | ||
| 80 | -| What did a static check establish? | [Check contracts and limits](references/tooling/checks.md); exit 0 is not a numerical pass, and advisories need review | | ||
| 81 | -| Can I trust a supplied evaluator or a reduced diagnostic kernel? | [Reference and evaluator calibration](references/workflows/authoring.md#reference-and-evaluator); [diagnostic probe controls](references/verification/board-runs.md#diagnostic-probes) | | ||
| 82 | -| How should I run on a shared device? | [Board runs](references/verification/board-runs.md); machine configuration stays outside the skill | | ||
| 83 | 56 | ||
| 84 | ## Reading and maintenance | 57 | ## Reading and maintenance |
| 85 | 58 | ||
| 86 | -Read only the owner of the current uncertainty. Existing context counts as read; prefer a signature query or focused probe to another broad API tour. Do not turn the routing tables into a mandatory reading sequence. | 59 | +Reuse context already read. On resuming, retain the contract, selected pattern, current source identity, best verified baseline and next unresolved check. Detailed facts have one owner under `references/`; keep scripts in [scripts](scripts/), kernels in [examples](examples/). Follow the [admission rules](references/index.md#admission-rules); keep this entry short and do not accumulate per-attempt histories. |
| 87 | - | ||
| 88 | -When resuming after context compression, retain the selected pattern, VF authoring policy, numerical/layout contract, current source identity and next unpassed gate. Treat earlier successful probes and unresolved mechanism hypotheses separately; neither establishes that the current submission passes. | ||
| 89 | - | ||
| 90 | -Detailed API facts, mechanisms, diagnostics and procedures each have one owner under `references/`. Runnable kernels stay in [examples](examples/) and tools in [scripts](scripts/). Follow the [maintenance rules](references/index.md#admission-rules); keep this entry short and do not create experiment ledgers, JSON reports or per-attempt histories unless requested. | ||
| @@ -462,7 +462,8 @@ def attn_epilogue_kernel( | |||
| 462 | # L0A/B use (256//K0) panels, each BM/max(BN1,BN)*K0 bytes. Each | 462 | # L0A/B use (256//K0) panels, each BM/max(BN1,BN)*K0 bytes. Each |
| 463 | # accumulator uses 4*BM*N bytes with the largest fitting depth, at most two. | 463 | # accumulator uses 4*BM*N bytes with the largest fitting depth, at most two. |
| 464 | # The first weight tile of GEMM2 reuses L1 address 2*BM*BK, after GEMM1's | 464 | # The first weight tile of GEMM2 reuses L1 address 2*BM*BK, after GEMM1's |
| 465 | - # final reads. The inter-phase barrier drains it before new mutex IDs apply. | 465 | + # final reads. Both phases retain the slot's mutex identity; the barrier |
| 466 | + # drains all Cube work before the second phase reuses local storage. | ||
| 466 | # On 32 cores, AQ is published in two immutable 2048-column slabs. Events | 467 | # On 32 cores, AQ is published in two immutable 2048-column slabs. Events |
| 467 | # 5/6 globally order AIV stores before events 3/4 notify each paired AIC. | 468 | # 5/6 globally order AIV stores before events 3/4 notify each paired AIC. |
| 468 | # Each AIC consumes both once on MTE2. C->V uses automatic events 0/1. | 469 | # Each AIC consumes both once on MTE2. C->V uses automatic events 0/1. |
| @@ -482,8 +483,9 @@ def attn_epilogue_kernel( | |||
| 482 | # Byte offsets preserve the L1 prefetch alias and the C->V buffer lifetime. | 483 | # Byte offsets preserve the L1 prefetch alias and the C->V buffer lifetime. |
| 483 | # Vec mutex IDs 0..8 belong to inverse RoPE; these groups start at ID 9. | 484 | # Vec mutex IDs 0..8 belong to inverse RoPE; these groups start at ID 9. |
| 484 | l0_slots = 256 // K0 | 485 | l0_slots = 256 // K0 |
| 486 | + max_n = max(BN1, BN) | ||
| 485 | acc_id = 6 + 4 * l0_slots | 487 | acc_id = 6 + 4 * l0_slots |
| 486 | - acc_slots = min(2, 65536 // (BM * BN1)) | 488 | + acc_slots = min(2, 65536 // (BM * max_n)) |
| 487 | q_rows = Q_ROWS if BN1 == 256 else BM // 2 | 489 | q_rows = Q_ROWS if BN1 == 256 else BM // 2 |
| 488 | scale_cols = 64 if BN1 == 256 else 128 | 490 | scale_cols = 64 if BN1 == 256 else 128 |
| 489 | vec_bf = 32768 + 2 * BM * BN1 * VSlots | 491 | vec_bf = 32768 + 2 * BM * BN1 * VSlots |
| @@ -515,11 +517,12 @@ def attn_epilogue_kernel( | |||
| 515 | addrs=[2 * (BM + max(BN1, BN)) * BK], | 517 | addrs=[2 * (BM + max(BN1, BN)) * BK], |
| 516 | mutex_ids=[4], | 518 | mutex_ids=[4], |
| 517 | ) | 519 | ) |
| 520 | + # Reserve 256 A-scale columns for the second projection at the same base. | ||
| 518 | bsg = pl.make_tile_group( | 521 | bsg = pl.make_tile_group( |
| 519 | type=pl.TileType( | 522 | type=pl.TileType( |
| 520 | shape=[128, BN1], dtype=E8, target_memory=pl.MemorySpace.Mat, layout=pl.NN | 523 | shape=[128, BN1], dtype=E8, target_memory=pl.MemorySpace.Mat, layout=pl.NN |
| 521 | ), | 524 | ), |
| 522 | - addrs=[2 * (BM + max(BN1, BN)) * BK + BM * scale_cols], | 525 | + addrs=[2 * (BM + max_n) * BK + BM * 256], |
| 523 | mutex_ids=[5], | 526 | mutex_ids=[5], |
| 524 | ) | 527 | ) |
| 525 | al = pl.make_tile_group( | 528 | al = pl.make_tile_group( |
| @@ -533,7 +536,7 @@ def attn_epilogue_kernel( | |||
| 533 | type=pl.TileType( | 536 | type=pl.TileType( |
| 534 | shape=[K0, BN1], dtype=FP8, target_memory=pl.MemorySpace.Right, compact=1 | 537 | shape=[K0, BN1], dtype=FP8, target_memory=pl.MemorySpace.Right, compact=1 |
| 535 | ), | 538 | ), |
| 536 | - addrs=[0, BN1 * K0][:l0_slots], | 539 | + addrs=[0, max_n * K0][:l0_slots], |
| 537 | mutex_ids=[6 + l0_slots, 7 + l0_slots][:l0_slots], | 540 | mutex_ids=[6 + l0_slots, 7 + l0_slots][:l0_slots], |
| 538 | ) | 541 | ) |
| 539 | als = pl.make_tile_group( | 542 | als = pl.make_tile_group( |
| @@ -553,7 +556,7 @@ def attn_epilogue_kernel( | |||
| 553 | target_memory=pl.MemorySpace.ScaleRight, | 556 | target_memory=pl.MemorySpace.ScaleRight, |
| 554 | compact=1, | 557 | compact=1, |
| 555 | ), | 558 | ), |
| 556 | - addrs=[0, BN1 * K0 // 16][:l0_slots], | 559 | + addrs=[0, max_n * K0 // 16][:l0_slots], |
| 557 | mutex_ids=[6 + 3 * l0_slots, 7 + 3 * l0_slots][:l0_slots], | 560 | mutex_ids=[6 + 3 * l0_slots, 7 + 3 * l0_slots][:l0_slots], |
| 558 | ) | 561 | ) |
| 559 | accg = pl.make_tile_group( | 562 | accg = pl.make_tile_group( |
| @@ -563,7 +566,7 @@ def attn_epilogue_kernel( | |||
| 563 | target_memory=pl.MemorySpace.Acc, | 566 | target_memory=pl.MemorySpace.Acc, |
| 564 | compact=1, | 567 | compact=1, |
| 565 | ), | 568 | ), |
| 566 | - addrs=[0, 4 * BM * BN1][:acc_slots], | 569 | + addrs=[0, 4 * BM * max_n][:acc_slots], |
| 567 | mutex_ids=[acc_id, acc_id + 1][:acc_slots], | 570 | mutex_ids=[acc_id, acc_id + 1][:acc_slots], |
| 568 | ) | 571 | ) |
| 569 | # Cross-core IDs are literal lists selected by the compile-time slot count. | 572 | # Cross-core IDs are literal lists selected by the compile-time slot count. |
| @@ -961,19 +964,21 @@ def _project_b(yq_ptr, ys_ptr, wb_ptr, sb_ptr, out_ptr, t, padded): | |||
| 961 | sb = pl.make_tensor(sb_ptr, [n, k // 64, 2], dtype=E8) | 964 | sb = pl.make_tensor(sb_ptr, [n, k // 64, 2], dtype=E8) |
| 962 | output = pl.make_tensor(out_ptr, [padded, n], dtype=pl.DT_BF16) | 965 | output = pl.make_tensor(out_ptr, [padded, n], dtype=pl.DT_BF16) |
| 963 | # The Cube pipe barrier drains the first projection before address reuse. | 966 | # The Cube pipe barrier drains the first projection before address reuse. |
| 964 | - # Continue its Cube mutex numbering; L0 scale planes follow data address >> 4. | 967 | + # Match GEMM1 slot pitches and mutex owners, including reserved scale space. |
| 968 | + # Scale-plane addresses remain the corresponding L0 data address >> 4. | ||
| 965 | l0_slots = 256 // K0 | 969 | l0_slots = 256 // K0 |
| 966 | - cube_id = 6 + 4 * l0_slots + min(2, 65536 // (BM * BN1)) | 970 | + max_n = max(BN1, BN) |
| 967 | - acc_slots = min(2, 65536 // (BM * BN)) | 971 | + acc_id = 6 + 4 * l0_slots |
| 972 | + acc_slots = min(2, 65536 // (BM * max_n)) | ||
| 968 | ag = pl.make_tile_group( | 973 | ag = pl.make_tile_group( |
| 969 | type=pl.TileType(shape=[BM, BK], dtype=FP8, target_memory=pl.MemorySpace.Mat), | 974 | type=pl.TileType(shape=[BM, BK], dtype=FP8, target_memory=pl.MemorySpace.Mat), |
| 970 | addrs=[0, BM * BK], | 975 | addrs=[0, BM * BK], |
| 971 | - mutex_ids=[cube_id, cube_id + 1], | 976 | + mutex_ids=[0, 1], |
| 972 | ) | 977 | ) |
| 973 | bg = pl.make_tile_group( | 978 | bg = pl.make_tile_group( |
| 974 | type=pl.TileType(shape=[BN, BK], dtype=FP8, target_memory=pl.MemorySpace.Mat), | 979 | type=pl.TileType(shape=[BN, BK], dtype=FP8, target_memory=pl.MemorySpace.Mat), |
| 975 | - addrs=[2 * BM * BK, (2 * BM + BN) * BK], | 980 | + addrs=[2 * BM * BK, (2 * BM + max_n) * BK], |
| 976 | - mutex_ids=[cube_id + 2, cube_id + 3], | 981 | + mutex_ids=[2, 3], |
| 977 | ) | 982 | ) |
| 978 | asg = pl.make_tile_group( | 983 | asg = pl.make_tile_group( |
| 979 | type=pl.TileType( | 984 | type=pl.TileType( |
| @@ -982,8 +987,8 @@ def _project_b(yq_ptr, ys_ptr, wb_ptr, sb_ptr, out_ptr, t, padded): | |||
| 982 | target_memory=pl.MemorySpace.Mat, | 987 | target_memory=pl.MemorySpace.Mat, |
| 983 | layout=pl.ZZ, | 988 | layout=pl.ZZ, |
| 984 | ), | 989 | ), |
| 985 | - addrs=[2 * (BM + BN) * BK], | 990 | + addrs=[2 * (BM + max_n) * BK], |
| 986 | - mutex_ids=[cube_id + 4], | 991 | + mutex_ids=[4], |
| 987 | ) | 992 | ) |
| 988 | bsg = pl.make_tile_group( | 993 | bsg = pl.make_tile_group( |
| 989 | type=pl.TileType( | 994 | type=pl.TileType( |
| @@ -992,22 +997,22 @@ def _project_b(yq_ptr, ys_ptr, wb_ptr, sb_ptr, out_ptr, t, padded): | |||
| 992 | target_memory=pl.MemorySpace.Mat, | 997 | target_memory=pl.MemorySpace.Mat, |
| 993 | layout=pl.NN, | 998 | layout=pl.NN, |
| 994 | ), | 999 | ), |
| 995 | - addrs=[2 * (BM + BN) * BK + BM * (k // 32)], | 1000 | + addrs=[2 * (BM + max_n) * BK + BM * (k // 32)], |
| 996 | - mutex_ids=[cube_id + 5], | 1001 | + mutex_ids=[5], |
| 997 | ) | 1002 | ) |
| 998 | al = pl.make_tile_group( | 1003 | al = pl.make_tile_group( |
| 999 | type=pl.TileType( | 1004 | type=pl.TileType( |
| 1000 | shape=[BM, K0], dtype=FP8, target_memory=pl.MemorySpace.Left, compact=1 | 1005 | shape=[BM, K0], dtype=FP8, target_memory=pl.MemorySpace.Left, compact=1 |
| 1001 | ), | 1006 | ), |
| 1002 | addrs=[0, BM * K0][:l0_slots], | 1007 | addrs=[0, BM * K0][:l0_slots], |
| 1003 | - mutex_ids=[cube_id + 6, cube_id + 7][:l0_slots], | 1008 | + mutex_ids=[6, 7][:l0_slots], |
| 1004 | ) | 1009 | ) |
| 1005 | bl = pl.make_tile_group( | 1010 | bl = pl.make_tile_group( |
| 1006 | type=pl.TileType( | 1011 | type=pl.TileType( |
| 1007 | shape=[K0, BN], dtype=FP8, target_memory=pl.MemorySpace.Right, compact=1 | 1012 | shape=[K0, BN], dtype=FP8, target_memory=pl.MemorySpace.Right, compact=1 |
| 1008 | ), | 1013 | ), |
| 1009 | - addrs=[0, BN * K0][:l0_slots], | 1014 | + addrs=[0, max_n * K0][:l0_slots], |
| 1010 | - mutex_ids=[cube_id + 6 + l0_slots, cube_id + 7 + l0_slots][:l0_slots], | 1015 | + mutex_ids=[6 + l0_slots, 7 + l0_slots][:l0_slots], |
| 1011 | ) | 1016 | ) |
| 1012 | als = pl.make_tile_group( | 1017 | als = pl.make_tile_group( |
| 1013 | type=pl.TileType( | 1018 | type=pl.TileType( |
| @@ -1017,7 +1022,7 @@ def _project_b(yq_ptr, ys_ptr, wb_ptr, sb_ptr, out_ptr, t, padded): | |||
| 1017 | compact=1, | 1022 | compact=1, |
| 1018 | ), | 1023 | ), |
| 1019 | addrs=[0, BM * K0 // 16][:l0_slots], | 1024 | addrs=[0, BM * K0 // 16][:l0_slots], |
| 1020 | - mutex_ids=[cube_id + 6 + 2 * l0_slots, cube_id + 7 + 2 * l0_slots][:l0_slots], | 1025 | + mutex_ids=[6 + 2 * l0_slots, 7 + 2 * l0_slots][:l0_slots], |
| 1021 | ) | 1026 | ) |
| 1022 | bls = pl.make_tile_group( | 1027 | bls = pl.make_tile_group( |
| 1023 | type=pl.TileType( | 1028 | type=pl.TileType( |
| @@ -1026,8 +1031,8 @@ def _project_b(yq_ptr, ys_ptr, wb_ptr, sb_ptr, out_ptr, t, padded): | |||
| 1026 | target_memory=pl.MemorySpace.ScaleRight, | 1031 | target_memory=pl.MemorySpace.ScaleRight, |
| 1027 | compact=1, | 1032 | compact=1, |
| 1028 | ), | 1033 | ), |
| 1029 | - addrs=[0, BN * K0 // 16][:l0_slots], | 1034 | + addrs=[0, max_n * K0 // 16][:l0_slots], |
| 1030 | - mutex_ids=[cube_id + 6 + 3 * l0_slots, cube_id + 7 + 3 * l0_slots][:l0_slots], | 1035 | + mutex_ids=[6 + 3 * l0_slots, 7 + 3 * l0_slots][:l0_slots], |
| 1031 | ) | 1036 | ) |
| 1032 | accg = pl.make_tile_group( | 1037 | accg = pl.make_tile_group( |
| 1033 | type=pl.TileType( | 1038 | type=pl.TileType( |
| @@ -1036,8 +1041,8 @@ def _project_b(yq_ptr, ys_ptr, wb_ptr, sb_ptr, out_ptr, t, padded): | |||
| 1036 | target_memory=pl.MemorySpace.Acc, | 1041 | target_memory=pl.MemorySpace.Acc, |
| 1037 | compact=1, | 1042 | compact=1, |
| 1038 | ), | 1043 | ), |
| 1039 | - addrs=[0, 4 * BM * BN][:acc_slots], | 1044 | + addrs=[0, 4 * BM * max_n][:acc_slots], |
| 1040 | - mutex_ids=[cube_id + 6 + 4 * l0_slots, cube_id + 7 + 4 * l0_slots][:acc_slots], | 1045 | + mutex_ids=[acc_id, acc_id + 1][:acc_slots], |
| 1041 | ) | 1046 | ) |
| 1042 | b_transposed = pl.reinterpret(bg, shape=[BK, BN], layout=pl.ZN) | 1047 | b_transposed = pl.reinterpret(bg, shape=[BK, BN], layout=pl.ZN) |
| 1043 | with pl.section_cube(): | 1048 | with pl.section_cube(): |
| @@ -17,6 +17,11 @@ import sys | |||
| 17 | import pytest | 17 | import pytest |
| 18 | import torch | 18 | import torch |
| 19 | 19 | ||
| 20 | +# Slab publication orders intentional Vec reuse; keep its warning visible. | ||
| 21 | +pytestmark = pytest.mark.filterwarnings( | ||
| 22 | + "error:Tile buffers in (Mat|Left|Right|ScaleLeft|ScaleRight|Acc) overlap:pypto_pro._errors.MutexMismatch" | ||
| 23 | +) | ||
| 24 | + | ||
| 20 | # Support both direct execution and pytest from the repository root. | 25 | # Support both direct execution and pytest from the repository root. |
| 21 | if __package__: | 26 | if __package__: |
| 22 | from .reference import attn_epilogue_golden_cpu, inverse_rope, quantize_mx | 27 | from .reference import attn_epilogue_golden_cpu, inverse_rope, quantize_mx |
| @@ -13,6 +13,8 @@ FP16 输入,FP32 输出;显式地址与自动 mutex ID,单槽五组缓冲 | |||
| 13 | Mat A 从 0 开始,W 紧随 A 的 2*block_m*block_k 字节;Left、Right、Acc 各自从 0 开始。 | 13 | Mat A 从 0 开始,W 紧随 A 的 2*block_m*block_k 字节;Left、Right、Acc 各自从 0 开始。 |
| 14 | 容量由框架检查;运行 test.py 检查批次、尾块、不同核数和输出守卫。 | 14 | 容量由框架检查;运行 test.py 检查批次、尾块、不同核数和输出守卫。 |
| 15 | 无性能结论。 | 15 | 无性能结论。 |
| 16 | + | ||
| 17 | +example-query: {"aliases":["batched transposed GEMM with M tails","带M尾块的批量转置GEMM"],"term_groups":[["batched","批量"],["transposed","transpose","转置"],["gemm","矩阵乘"]],"facets":{"source_dtype":["FP16"],"destination_dtype":["FP32"]},"exclude":[{"term_groups":[["N tail","N tails","N尾块","N 尾块","K tail","K tails","K尾块","K 尾块"]],"reason":"N % 16 == 0 and K % 32 == 0 are required; this example handles M tails only."}]} | ||
| 16 | """ | 18 | """ |
| 17 | 19 | ||
| 18 | import pypto_pro.language as pl | 20 | import pypto_pro.language as pl |
| @@ -8,6 +8,8 @@ | |||
| 8 | 8 | ||
| 9 | """写法:原始。VF 逐列均值与总体方差,每个 lane 对应一个保留的列。 | 9 | """写法:原始。VF 逐列均值与总体方差,每个 lane 对应一个保留的列。 |
| 10 | 10 | ||
| 11 | +example-query: {"aliases": ["per-column statistics", "逐列统计"], "facets": {"source_dtype": ["FP32"], "destination_dtype": ["FP32"]}, "term_groups": [["per-column", "per-channel", "逐列", "逐通道"], ["across rows", "reduce rows", "outer-axis", "沿行归约", "沿 M 归约"], ["statistics", "mean", "variance", "统计", "均值", "方差"]]} | ||
| 12 | + | ||
| 11 | 输入为紧密 FP32 [M,N],输出为两个 FP32 [N];沿 M 归约,方差除以 M。 | 13 | 输入为紧密 FP32 [M,N],输出为两个 FP32 [N];沿 M 归约,方差除以 M。 |
| 12 | 先相对首行中心化求均值,再累加相对均值的平方偏差。 | 14 | 先相对首行中心化求均值,再累加相对均值的平方偏差。 |
| 13 | 每个 worker 独占一段列,单槽 tile group 自动同步,尾列使用有效形状和 VF mask。 | 15 | 每个 worker 独占一段列,单槽 tile group 自动同步,尾列使用有效形状和 VF mask。 |
| @@ -20,6 +20,8 @@ test.py 另外覆盖端点、常数分数和接近抵消的载荷。 | |||
| 20 | 程数来自完整调用测量,其他输入分布或硬件需重新测量。 | 20 | 程数来自完整调用测量,其他输入分布或硬件需重新测量。 |
| 21 | 验证环境:PyPTO 导出行为基线872df763f,CANN 9.2.0、BiSheng 15.0.5、Ascend950PR,torch/torch_npu 2.10.0;当前验收仍需绑定源码哈希和实际工具链。test.py 的 | 21 | 验证环境:PyPTO 导出行为基线872df763f,CANN 9.2.0、BiSheng 15.0.5、Ascend950PR,torch/torch_npu 2.10.0;当前验收仍需绑定源码哈希和实际工具链。test.py 的 |
| 22 | FP64 数学参考不采用实现的固定参考或分块归约顺序。 | 22 | FP64 数学参考不采用实现的固定参考或分块归约顺序。 |
| 23 | + | ||
| 24 | +example-query: {"aliases":["CSR sparse softmax aggregation","CSR稀疏softmax加权聚合"],"term_groups":[["csr","压缩稀疏行"],["softmax"],["aggregate","aggregation","weighted sum","加权聚合","聚合"]],"facets":{"source_dtype":["FP32"],"destination_dtype":["FP32"]},"exclude":[{"term_groups":[["backward","gradient","反向","梯度"]],"reason":"This program implements forward segmented softmax-weighted aggregation only."}]} | ||
| 23 | """ | 25 | """ |
| 24 | 26 | ||
| 25 | from functools import lru_cache | 27 | from functools import lru_cache |
| @@ -0,0 +1,7 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| @@ -0,0 +1,206 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""写法:原始。门控外积更新与查询,矩阵状态在片上跨时间步保留。 | ||
| 10 | + | ||
| 11 | +example-query: {"aliases": ["gated outer-product recurrence", "on-chip recurrent matrix state", "门控外积状态递推"], "facets": {"source_dtype": ["FP16", "FP32"], "destination_dtype": ["FP32"]}} | ||
| 12 | + | ||
| 13 | +q/k/v 为 FP16 [R,T,D],g 为 FP32 [R,T],s0 为 FP32 [R,D,D]。 | ||
| 14 | +状态从 s0 开始,每步先 S = g*S + k[:,None]*v[None,:],再 y = q^T@S。 | ||
| 15 | +返回 FP32 y[R,T,D] 与最终状态;输入不变,Host 仅检查元数据与分配。 | ||
| 16 | +范围为 R=1..33、T=1..257、D∈{16,32,64,128},q/k/v/s0 绝对值<=0.125,g∈[0,1]。 | ||
| 17 | +独立 FP64 参考的 y 容差为 atol=2e-3/rtol=1e-4,最终状态为 atol=rtol=1e-4。 | ||
| 18 | + | ||
| 19 | +worker 独占 r,完整调用只有一次 native launch;每个 r 的状态只读入、写出一次。 | ||
| 20 | +每步输入行及输出累加器使用独立 Vec 缓冲组,auto_mutex 管理跨 VF 调用的读写依赖。 | ||
| 21 | +D 决定状态 tile 的物理容量,R/T 使用运行时元数据;padded_dim=max(64,D)。 | ||
| 22 | +峰值 Vec 字节为 4*D*padded_dim + 10*padded_dim,最大 66816 B,无 GM scratch。 | ||
| 23 | +UNPK 扩精度与后续 FP32 指令复用相同物理谓词。逐状态行的 VF 调用是正确性起点, | ||
| 24 | +调用开销与其他计算映射需要单独计时,此例不声称性能优势。 | ||
| 25 | +验证工具链为 PyPTO cbd3c4a778、CANN 9.2.0、Ascend950PR;运行证据须绑定当前源码与安装身份。 | ||
| 26 | +""" | ||
| 27 | + | ||
| 28 | +from functools import lru_cache | ||
| 29 | + | ||
| 30 | +import torch | ||
| 31 | +import pypto_pro.language as pl | ||
| 32 | +from pypto_pro.language import Vf as vf # noqa: N813 | ||
| 33 | + | ||
| 34 | +FP16 = pl.DT_FP16 | ||
| 35 | +FP32 = pl.DT_FP32 | ||
| 36 | +VECTOR_LANES = 64 | ||
| 37 | +MAX_WORKERS = 32 | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +@pl.vector_function | ||
| 41 | +def _zero_row(tile, cols): | ||
| 42 | + for col in pl.range(0, cols, VECTOR_LANES): | ||
| 43 | + active = pl.min(VECTOR_LANES, cols - col) | ||
| 44 | + mask = vf.update_mask(active, dtype=FP32) | ||
| 45 | + zeros = vf.full(0.0, mask, dtype=FP32) | ||
| 46 | + vf.store_align(tile, zeros, mask, [0, col]) | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +@pl.vector_function | ||
| 50 | +def _update_state_row_chunk(state, v, accum, row, col, active, gate, k_i, q_i): | ||
| 51 | + mask32 = vf.update_mask(active, dtype=FP32) | ||
| 52 | + | ||
| 53 | + old = vf.load_align(state, [row, col]) | ||
| 54 | + raw_v = vf.load_align(v, [0, col], dist=pl.LoadDist.UNPK) | ||
| 55 | + v32 = vf.astype(raw_v, mask32, dtype=FP32, layout=pl.CastLayout.ZERO) | ||
| 56 | + | ||
| 57 | + gated = vf.muls(old, gate, mask32) | ||
| 58 | + outer = vf.muls(v32, k_i, mask32) | ||
| 59 | + updated = vf.add(gated, outer, mask32) | ||
| 60 | + vf.store_align(state, updated, mask32, [row, col]) | ||
| 61 | + | ||
| 62 | + partial = vf.muls(updated, q_i, mask32) | ||
| 63 | + previous_total = vf.load_align(accum, [0, col]) | ||
| 64 | + next_total = vf.add(previous_total, partial, mask32) | ||
| 65 | + vf.store_align(accum, next_total, mask32, [0, col]) | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +@lru_cache(maxsize=4) | ||
| 69 | +def _kernel_for_dim(dim): | ||
| 70 | + if dim not in (16, 32, 64, 128): | ||
| 71 | + raise ValueError(f"unsupported D={dim}") | ||
| 72 | + padded_dim = max(VECTOR_LANES, dim) | ||
| 73 | + state_bytes = dim * padded_dim * 4 | ||
| 74 | + input_bytes = padded_dim * 2 | ||
| 75 | + q_addr = state_bytes | ||
| 76 | + k_addr = q_addr + input_bytes | ||
| 77 | + v_addr = k_addr + input_bytes | ||
| 78 | + accum_addr = v_addr + input_bytes | ||
| 79 | + | ||
| 80 | + @pl.jit(auto_mutex=True, name=f"gated_outer_state_d{dim}") | ||
| 81 | + def kernel( | ||
| 82 | + q: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC, dim], FP16], | ||
| 83 | + k: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC, dim], FP16], | ||
| 84 | + v: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC, dim], FP16], | ||
| 85 | + g: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], FP32], | ||
| 86 | + s0: pl.Tensor[[pl.DYNAMIC, dim, dim], FP32], | ||
| 87 | + y: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC, dim], FP32], | ||
| 88 | + s_final: pl.Tensor[[pl.DYNAMIC, dim, dim], FP32], | ||
| 89 | + ): | ||
| 90 | + state_group = pl.make_tile_group( | ||
| 91 | + type=pl.TileType( | ||
| 92 | + shape=[dim, padded_dim], dtype=FP32, target_memory=pl.MemorySpace.Vec | ||
| 93 | + ), | ||
| 94 | + addrs=0, | ||
| 95 | + mutex_ids="auto", | ||
| 96 | + depth=1, | ||
| 97 | + ) | ||
| 98 | + q_group = pl.make_tile_group( | ||
| 99 | + type=pl.TileType( | ||
| 100 | + shape=[1, padded_dim], dtype=FP16, target_memory=pl.MemorySpace.Vec | ||
| 101 | + ), | ||
| 102 | + addrs=q_addr, | ||
| 103 | + mutex_ids="auto", | ||
| 104 | + depth=1, | ||
| 105 | + ) | ||
| 106 | + k_group = pl.make_tile_group( | ||
| 107 | + type=pl.TileType( | ||
| 108 | + shape=[1, padded_dim], dtype=FP16, target_memory=pl.MemorySpace.Vec | ||
| 109 | + ), | ||
| 110 | + addrs=k_addr, | ||
| 111 | + mutex_ids="auto", | ||
| 112 | + depth=1, | ||
| 113 | + ) | ||
| 114 | + v_group = pl.make_tile_group( | ||
| 115 | + type=pl.TileType( | ||
| 116 | + shape=[1, padded_dim], dtype=FP16, target_memory=pl.MemorySpace.Vec | ||
| 117 | + ), | ||
| 118 | + addrs=v_addr, | ||
| 119 | + mutex_ids="auto", | ||
| 120 | + depth=1, | ||
| 121 | + ) | ||
| 122 | + accum_group = pl.make_tile_group( | ||
| 123 | + type=pl.TileType( | ||
| 124 | + shape=[1, padded_dim], dtype=FP32, target_memory=pl.MemorySpace.Vec | ||
| 125 | + ), | ||
| 126 | + addrs=accum_addr, | ||
| 127 | + mutex_ids="auto", | ||
| 128 | + depth=1, | ||
| 129 | + ) | ||
| 130 | + | ||
| 131 | + with pl.section_vector(): | ||
| 132 | + state = state_group.current() | ||
| 133 | + q_tile = q_group.current() | ||
| 134 | + k_tile = k_group.current() | ||
| 135 | + v_tile = v_group.current() | ||
| 136 | + accum = accum_group.current() | ||
| 137 | + | ||
| 138 | + pl.set_validshape(state, [dim, dim]) | ||
| 139 | + pl.set_validshape(q_tile, [1, dim]) | ||
| 140 | + pl.set_validshape(k_tile, [1, dim]) | ||
| 141 | + pl.set_validshape(v_tile, [1, dim]) | ||
| 142 | + pl.set_validshape(accum, [1, dim]) | ||
| 143 | + | ||
| 144 | + for r in pl.range(pl.get_block_idx(), q.shape[0], pl.get_block_num()): | ||
| 145 | + pl.load(state, s0, [r, 0, 0]) | ||
| 146 | + for t in pl.range(0, q.shape[1]): | ||
| 147 | + pl.load(q_tile, q, [r, t, 0]) | ||
| 148 | + pl.load(k_tile, k, [r, t, 0]) | ||
| 149 | + pl.load(v_tile, v, [r, t, 0]) | ||
| 150 | + _zero_row(accum, dim) | ||
| 151 | + | ||
| 152 | + gate = pl.getval(g, r * q.shape[1] + t) | ||
| 153 | + for i in pl.range(0, dim): | ||
| 154 | + k_i = pl.astype(pl.getval(k_tile, i), FP32) | ||
| 155 | + q_i = pl.astype(pl.getval(q_tile, i), FP32) | ||
| 156 | + for col in pl.range(0, dim, VECTOR_LANES): | ||
| 157 | + active = pl.min(VECTOR_LANES, dim - col) | ||
| 158 | + _update_state_row_chunk( | ||
| 159 | + state, v_tile, accum, i, col, active, gate, k_i, q_i | ||
| 160 | + ) | ||
| 161 | + | ||
| 162 | + pl.store(y, accum, [r, t, 0]) | ||
| 163 | + | ||
| 164 | + pl.store(s_final, state, [r, 0, 0]) | ||
| 165 | + | ||
| 166 | + return kernel | ||
| 167 | + | ||
| 168 | + | ||
| 169 | +def run(q, k, v, g, s0): | ||
| 170 | + """Run the recurrence; host work is metadata validation and output allocation.""" | ||
| 171 | + if q.ndim != 3: | ||
| 172 | + raise ValueError("q must have shape [R,T,D]") | ||
| 173 | + r_count, time_steps, dim = q.shape | ||
| 174 | + if not (1 <= r_count <= 33 and 1 <= time_steps <= 257): | ||
| 175 | + raise ValueError("R and T are outside the supported domain") | ||
| 176 | + if dim not in (16, 32, 64, 128): | ||
| 177 | + raise ValueError("D must be one of 16, 32, 64, 128") | ||
| 178 | + if tuple(k.shape) != tuple(q.shape) or tuple(v.shape) != tuple(q.shape): | ||
| 179 | + raise ValueError("q, k, and v must have matching [R,T,D] shapes") | ||
| 180 | + if tuple(g.shape) != (r_count, time_steps): | ||
| 181 | + raise ValueError("g must have shape [R,T]") | ||
| 182 | + if tuple(s0.shape) != (r_count, dim, dim): | ||
| 183 | + raise ValueError("s0 must have shape [R,D,D]") | ||
| 184 | + | ||
| 185 | + expected_dtypes = ( | ||
| 186 | + torch.float16, | ||
| 187 | + torch.float16, | ||
| 188 | + torch.float16, | ||
| 189 | + torch.float32, | ||
| 190 | + torch.float32, | ||
| 191 | + ) | ||
| 192 | + inputs = (q, k, v, g, s0) | ||
| 193 | + if tuple(t.dtype for t in inputs) != expected_dtypes: | ||
| 194 | + raise TypeError("q/k/v must be FP16 and g/s0 must be FP32") | ||
| 195 | + if any(not tensor.is_contiguous() for tensor in inputs): | ||
| 196 | + raise ValueError("all inputs must be contiguous") | ||
| 197 | + if any(tensor.device != q.device for tensor in inputs): | ||
| 198 | + raise ValueError("all inputs must be on the same device") | ||
| 199 | + if q.device.type != "npu": | ||
| 200 | + raise ValueError("run requires NPU tensors") | ||
| 201 | + | ||
| 202 | + y = torch.empty((r_count, time_steps, dim), dtype=torch.float32, device=q.device) | ||
| 203 | + s_final = torch.empty((r_count, dim, dim), dtype=torch.float32, device=q.device) | ||
| 204 | + workers = min(r_count, MAX_WORKERS) | ||
| 205 | + _kernel_for_dim(dim)[None, workers](q, k, v, g, s0, y, s_final) | ||
| 206 | + return y, s_final | ||
| @@ -0,0 +1,23 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""用实际量化输入求 FP64 状态递推,不复制 kernel 的分块或累加顺序。""" | ||
| 10 | + | ||
| 11 | +import numpy as np | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def reference(q, k, v, g, s0): | ||
| 15 | + q, k, v, g, state = [ | ||
| 16 | + np.asarray(value, dtype=np.float64) for value in (q, k, v, g, s0) | ||
| 17 | + ] | ||
| 18 | + state = state.copy() | ||
| 19 | + result = np.empty(q.shape, dtype=np.float64) | ||
| 20 | + for t in range(q.shape[1]): | ||
| 21 | + state = g[:, t, None, None] * state + k[:, t, :, None] * v[:, t, None, :] | ||
| 22 | + result[:, t] = np.einsum("ri,rij->rj", q[:, t], state) | ||
| 23 | + return result, state | ||
| @@ -0,0 +1,109 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""验证片上矩阵状态的跨时间传播、门控重置、轴方向和改变输入后的完整调用。 | ||
| 10 | + | ||
| 11 | +每个 worker 独占一个状态序列;独立的 Vec 缓冲组由 auto_mutex 管理 VF 调用之间的读写依赖。状态只在开始读入、结束写出,输出按时间步写出。连续偏移输入的前后守卫检查越界写,独立 FP64 数学参考使用实际 FP16/FP32 输入,不模拟分块顺序。此处验证正确性与状态语义,不声称性能优势。 | ||
| 12 | +""" | ||
| 13 | + | ||
| 14 | +import numpy as np | ||
| 15 | +import pytest | ||
| 16 | +import torch | ||
| 17 | + | ||
| 18 | +from .kernel import run | ||
| 19 | +from .reference import reference | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +CASES = [ | ||
| 23 | + (1, 1, 16, "coordinates"), | ||
| 24 | + (2, 2, 32, "zero"), | ||
| 25 | + (3, 5, 64, "one"), | ||
| 26 | + (5, 3, 128, "mixed"), | ||
| 27 | + (33, 1, 16, "coordinates"), | ||
| 28 | + (1, 257, 128, "upper"), | ||
| 29 | + (2, 65, 64, "random"), | ||
| 30 | + (3, 129, 16, "mixed"), | ||
| 31 | + (33, 257, 128, "random"), | ||
| 32 | +] | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def arrays(rows, steps, dim, pattern): | ||
| 36 | + rng = np.random.default_rng(rows * 100003 + steps * 131 + dim) | ||
| 37 | + q, k, v = [ | ||
| 38 | + rng.uniform(-0.125, 0.125, (rows, steps, dim)).astype(np.float16) | ||
| 39 | + for _ in range(3) | ||
| 40 | + ] | ||
| 41 | + g = rng.uniform(0, 1, (rows, steps)).astype(np.float32) | ||
| 42 | + s0 = rng.uniform(-0.125, 0.125, (rows, dim, dim)).astype(np.float32) | ||
| 43 | + if pattern == "zero": | ||
| 44 | + g.fill(0) | ||
| 45 | + elif pattern in ("one", "upper"): | ||
| 46 | + g.fill(1) | ||
| 47 | + if pattern == "upper": | ||
| 48 | + q.fill(0.125) | ||
| 49 | + k.fill(0.125) | ||
| 50 | + v.fill(0.125) | ||
| 51 | + s0.fill(-0.125) | ||
| 52 | + elif pattern == "mixed": | ||
| 53 | + g[:] = (np.arange(rows)[:, None] + np.arange(steps)) % 3 != 0 | ||
| 54 | + g[:, 1::4] = 0.5 | ||
| 55 | + elif pattern == "coordinates": | ||
| 56 | + g.fill(1) | ||
| 57 | + q.fill(0) | ||
| 58 | + k.fill(0) | ||
| 59 | + v.fill(0) | ||
| 60 | + for r in range(rows): | ||
| 61 | + q[r, :, r % dim] = 0.125 | ||
| 62 | + s0[:] = ( | ||
| 63 | + ( | ||
| 64 | + np.arange(dim)[:, None] * 5 | ||
| 65 | + + np.arange(dim) * 3 | ||
| 66 | + + np.arange(rows)[:, None, None] | ||
| 67 | + ) | ||
| 68 | + % 17 | ||
| 69 | + - 8 | ||
| 70 | + ) / 64 | ||
| 71 | + return q, k, v, g, s0 | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +@pytest.mark.parametrize("case", CASES) | ||
| 75 | +def test_recurrence_and_changed_inputs(device, case): | ||
| 76 | + host = arrays(*case) | ||
| 77 | + backings, tensors = [], [] | ||
| 78 | + for value in host: | ||
| 79 | + dtype = torch.float16 if value.dtype == np.float16 else torch.float32 | ||
| 80 | + backing = torch.full((value.size + 64,), -2, dtype=dtype, device=device) | ||
| 81 | + tensor = backing[17 : 17 + value.size].view(value.shape) | ||
| 82 | + backings.append(backing) | ||
| 83 | + tensors.append(tensor) | ||
| 84 | + changed = tuple( | ||
| 85 | + (value * factor).astype(value.dtype) | ||
| 86 | + for value, factor in zip(host[:3], (-0.75, -0.5, 0.25)) | ||
| 87 | + ) | ||
| 88 | + changed += (1 - host[3], -host[4] * np.float32(0.75)) | ||
| 89 | + for current in (host, changed): | ||
| 90 | + for tensor, value in zip(tensors, current): | ||
| 91 | + tensor.copy_(torch.from_numpy(value)) | ||
| 92 | + expected_y, expected_state = reference(*current) | ||
| 93 | + y, state = run(*tensors) | ||
| 94 | + torch.npu.synchronize() | ||
| 95 | + for actual, expected, atol in ( | ||
| 96 | + (y, expected_y, 2e-3), | ||
| 97 | + (state, expected_state, 1e-4), | ||
| 98 | + ): | ||
| 99 | + assert ( | ||
| 100 | + actual.dtype == torch.float32 and tuple(actual.shape) == expected.shape | ||
| 101 | + ) | ||
| 102 | + assert actual.is_contiguous() and actual.device == tensors[0].device | ||
| 103 | + result = actual.cpu().numpy() | ||
| 104 | + assert np.isfinite(result).all() | ||
| 105 | + np.testing.assert_allclose(result, expected, atol=atol, rtol=1e-4) | ||
| 106 | + for tensor, value, backing in zip(tensors, current, backings): | ||
| 107 | + np.testing.assert_array_equal(tensor.cpu().numpy(), value) | ||
| 108 | + assert (backing[:17] == -2).all().item() | ||
| 109 | + assert (backing[17 + value.size :] == -2).all().item() | ||
| @@ -0,0 +1,7 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| @@ -0,0 +1,119 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""写法:原始。Direct-GM grouped dilated 1-D cross-correlation. | ||
| 10 | + | ||
| 11 | +example-query: {"aliases": ["grouped dilated convolution", "grouped conv1d", "分组空洞卷积", "一维分组卷积"]} | ||
| 12 | + | ||
| 13 | +Inputs are contiguous x[B,L,Cin] and w[G,3,Cin/G,Cout/G] in FP16, plus | ||
| 14 | +FP32 bias[Cout]. Output is contiguous FP32 [B,ceil(L/stride),Cout]. Tap r | ||
| 15 | +reads t*stride+(r-1)*dilation; invalid source positions contribute zero. | ||
| 16 | +Each SIMT thread owns an output scalar and traverses its group's input channels. | ||
| 17 | +Both FP16 operands are promoted before FP32 FMA; a FP32 accumulator alone | ||
| 18 | +would not specify the product precision. The host handles metadata/allocation. | ||
| 19 | + | ||
| 20 | +The domain is B=1..3, L=1..4097, Cin/Cout multiples of 16 in [16,128], | ||
| 21 | +G in {1,2,4,8} dividing both channel counts, and stride/dilation in {1,2}. | ||
| 22 | +Inputs/weights are bounded by 1 and bias by 2 in absolute value. The reference | ||
| 23 | +uses the actual quantized inputs in FP64 with atol=rtol=3e-4. | ||
| 24 | +Physical SIMT Tensor shapes are static on the supported frontend, so the factory | ||
| 25 | +specializes them per call. Grid-stride ownership covers the automatic grid. | ||
| 26 | +There is no UB workspace or inter-thread communication. This is a correctness | ||
| 27 | +anchor; repeated input reads and scalar reduction work need their own timing. | ||
| 28 | +The verification toolchain is PyPTO cbd3c4a778, CANN 9.2.0 and Ascend950PR; | ||
| 29 | +current execution evidence must identify the selected source and installation. | ||
| 30 | +""" | ||
| 31 | + | ||
| 32 | +from functools import lru_cache | ||
| 33 | + | ||
| 34 | +import pypto_pro.language as pl | ||
| 35 | + | ||
| 36 | +FP16 = pl.DT_FP16 | ||
| 37 | +FP32 = pl.DT_FP32 | ||
| 38 | +THREADS = 128 | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +@lru_cache(maxsize=None) | ||
| 42 | +def _make_kernel(batch, length, cin, groups, cout, stride, dilation): | ||
| 43 | + """按静态物理形状和采样间距生成原生入口。""" | ||
| 44 | + cin_group = cin // groups | ||
| 45 | + cout_group = cout // groups | ||
| 46 | + out_length = (length + stride - 1) // stride | ||
| 47 | + output_count = batch * out_length * cout | ||
| 48 | + | ||
| 49 | + @pl.vector_function(mode="simt", max_threads=THREADS) | ||
| 50 | + def conv_body(x, w, bias, y): | ||
| 51 | + # 一个线程独占一个 y 标量,再以 grid-stride 覆盖全部输出。 | ||
| 52 | + # 线程保留一个 FP32 累加器,直接读取 3*Cin/G 个输入/权重值;无片上暂存或跨线程同步。 | ||
| 53 | + start = pl.simt.block_idx().x * THREADS + pl.simt.linear_thread_idx() | ||
| 54 | + step = pl.simt.grid_dim().x * pl.simt.block_dim().x | ||
| 55 | + for linear in pl.range(start, output_count, step): | ||
| 56 | + out_c = linear % cout | ||
| 57 | + out_t = (linear // cout) % out_length | ||
| 58 | + out_b = linear // (cout * out_length) | ||
| 59 | + group = out_c // cout_group | ||
| 60 | + out_local = out_c % cout_group | ||
| 61 | + acc = bias[out_c] | ||
| 62 | + for tap in pl.range(0, 3, 1): | ||
| 63 | + source_t = out_t * stride + (tap - 1) * dilation | ||
| 64 | + if source_t >= 0 and source_t < length: | ||
| 65 | + for in_local in pl.range(0, cin_group, 1): | ||
| 66 | + in_c = group * cin_group + in_local | ||
| 67 | + xv = pl.simt.cast(x[out_b, source_t, in_c], FP32) | ||
| 68 | + wv = pl.simt.cast(w[group, tap, in_local, out_local], FP32) | ||
| 69 | + acc = pl.simt.fma(xv, wv, acc) | ||
| 70 | + y[out_b, out_t, out_c] = acc | ||
| 71 | + | ||
| 72 | + @pl.jit() | ||
| 73 | + def kernel( | ||
| 74 | + x: pl.Tensor[[batch, length, cin], FP16], | ||
| 75 | + w: pl.Tensor[[groups, 3, cin_group, cout_group], FP16], | ||
| 76 | + bias: pl.Tensor[[cout], FP32], | ||
| 77 | + y: pl.Tensor[[batch, out_length, cout], FP32], | ||
| 78 | + ): | ||
| 79 | + with pl.section_vector(): | ||
| 80 | + conv_body[THREADS](x, w, bias, y) | ||
| 81 | + | ||
| 82 | + return kernel | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +def run(x, w, bias, stride=1, dilation=1): | ||
| 86 | + """Run the native kernel; input contents remain on device and are never read by Host.""" | ||
| 87 | + import torch | ||
| 88 | + | ||
| 89 | + if x.ndim != 3 or w.ndim != 4 or bias.ndim != 1: | ||
| 90 | + raise ValueError("expected x[B,L,Cin], w[G,3,Cin/G,Cout/G], bias[Cout]") | ||
| 91 | + batch, length, cin = map(int, x.shape) | ||
| 92 | + groups, kernel_width, cin_group, cout_group = map(int, w.shape) | ||
| 93 | + cout = groups * cout_group | ||
| 94 | + if kernel_width != 3 or cin_group * groups != cin or int(bias.shape[0]) != cout: | ||
| 95 | + raise ValueError("incompatible grouped-convolution shapes") | ||
| 96 | + if not 1 <= batch <= 3 or not 1 <= length <= 4097: | ||
| 97 | + raise ValueError("B and L are outside the supported domain") | ||
| 98 | + if not 16 <= cin <= 128 or cin % 16 or not 16 <= cout <= 128 or cout % 16: | ||
| 99 | + raise ValueError("Cin and Cout must be 16..128 in multiples of 16") | ||
| 100 | + if groups not in (1, 2, 4, 8) or cin % groups or cout % groups: | ||
| 101 | + raise ValueError("G must be one of 1, 2, 4, 8 and divide Cin/Cout") | ||
| 102 | + if stride not in (1, 2) or dilation not in (1, 2): | ||
| 103 | + raise ValueError("stride and dilation must be 1 or 2") | ||
| 104 | + if ( | ||
| 105 | + x.dtype != torch.float16 | ||
| 106 | + or w.dtype != torch.float16 | ||
| 107 | + or bias.dtype != torch.float32 | ||
| 108 | + ): | ||
| 109 | + raise TypeError("x and w must be FP16; bias must be FP32") | ||
| 110 | + if not x.is_contiguous() or not w.is_contiguous() or not bias.is_contiguous(): | ||
| 111 | + raise ValueError("inputs must be contiguous") | ||
| 112 | + if x.device != w.device or x.device != bias.device: | ||
| 113 | + raise ValueError("inputs must be on the same device") | ||
| 114 | + | ||
| 115 | + out_length = (length + stride - 1) // stride | ||
| 116 | + y = torch.empty((batch, out_length, cout), dtype=torch.float32, device=x.device) | ||
| 117 | + kernel = _make_kernel(batch, length, cin, groups, cout, stride, dilation) | ||
| 118 | + kernel(x, w, bias, y) | ||
| 119 | + return y | ||
| @@ -0,0 +1,41 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Independent CPU FP64 reference for grouped 1-D dilated cross-correlation.""" | ||
| 10 | + | ||
| 11 | +import numpy as np | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def reference(x, w, bias, stride=1, dilation=1): | ||
| 15 | + """Compute the contract in FP64 from the actual quantized input arrays.""" | ||
| 16 | + x64 = np.asarray(x, dtype=np.float64) | ||
| 17 | + w64 = np.asarray(w, dtype=np.float64) | ||
| 18 | + bias64 = np.asarray(bias, dtype=np.float64) | ||
| 19 | + batch, length, cin = x64.shape | ||
| 20 | + groups, taps, cin_group, cout_group = w64.shape | ||
| 21 | + if taps != 3 or cin != groups * cin_group: | ||
| 22 | + raise ValueError("incompatible input and weight shapes") | ||
| 23 | + cout = groups * cout_group | ||
| 24 | + out_length = (length + stride - 1) // stride | ||
| 25 | + result = np.broadcast_to(bias64, (batch, out_length, cout)).copy() | ||
| 26 | + output_positions = np.arange(out_length, dtype=np.int64) * stride | ||
| 27 | + | ||
| 28 | + for group in range(groups): | ||
| 29 | + in_start = group * cin_group | ||
| 30 | + in_stop = in_start + cin_group | ||
| 31 | + out_start = group * cout_group | ||
| 32 | + out_stop = out_start + cout_group | ||
| 33 | + for tap in range(3): | ||
| 34 | + source_positions = output_positions + (tap - 1) * dilation | ||
| 35 | + valid = (source_positions >= 0) & (source_positions < length) | ||
| 36 | + patch = np.zeros((batch, out_length, cin_group), dtype=np.float64) | ||
| 37 | + patch[:, valid, :] = x64[:, source_positions[valid], in_start:in_stop] | ||
| 38 | + result[:, :, out_start:out_stop] += np.einsum( | ||
| 39 | + "btk,ko->bto", patch, w64[group, tap], optimize=False | ||
| 40 | + ) | ||
| 41 | + return result | ||
| @@ -0,0 +1,94 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Grouped channels, zero extension, FP32 products and changed inputs at reused addresses.""" | ||
| 10 | + | ||
| 11 | +import numpy as np | ||
| 12 | +import pytest | ||
| 13 | +import torch | ||
| 14 | + | ||
| 15 | +from .kernel import run | ||
| 16 | +from .reference import reference | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +CASES = [ | ||
| 20 | + (1, 1, 16, 32, 8, 2, 2), | ||
| 21 | + (2, 3, 16, 16, 4, 1, 2), | ||
| 22 | + (3, 31, 16, 48, 8, 2, 1), | ||
| 23 | + (2, 64, 48, 32, 2, 1, 1), | ||
| 24 | + (1, 65, 128, 16, 1, 2, 2), | ||
| 25 | + (3, 129, 64, 128, 4, 2, 1), | ||
| 26 | + (1, 5, 80, 112, 4, 2, 2), | ||
| 27 | + (2, 4097, 64, 96, 2, 1, 1), | ||
| 28 | + (3, 4097, 128, 128, 1, 1, 2), | ||
| 29 | +] | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def assert_output(actual, expected): | ||
| 33 | + assert actual.dtype == np.float32 and actual.shape == expected.shape | ||
| 34 | + assert np.isfinite(actual).all() | ||
| 35 | + np.testing.assert_allclose(actual, expected, atol=3e-4, rtol=3e-4) | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def arrays(case): | ||
| 39 | + batch, length, cin, cout, groups, _, _ = case | ||
| 40 | + rng = np.random.default_rng(971 + length + cin * cout) | ||
| 41 | + x = rng.uniform(-1, 1, (batch, length, cin)).astype(np.float16) | ||
| 42 | + w = rng.uniform(-1, 1, (groups, 3, cin // groups, cout // groups)).astype( | ||
| 43 | + np.float16 | ||
| 44 | + ) | ||
| 45 | + bias = rng.uniform(-2, 2, cout).astype(np.float32) | ||
| 46 | + return x, w, bias | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +@pytest.mark.parametrize("case", CASES) | ||
| 50 | +def test_contract_and_changed_storage(device, case): | ||
| 51 | + x, w, bias = arrays(case) | ||
| 52 | + stride, dilation = case[-2:] | ||
| 53 | + tensors = [torch.from_numpy(a).to(device) for a in (x, w, bias)] | ||
| 54 | + changed = (-x[:, ::-1, :].copy(), w[:, ::-1, :, :].copy(), -bias) | ||
| 55 | + for host in ((x, w, bias), changed): | ||
| 56 | + for tensor, value in zip(tensors, host): | ||
| 57 | + tensor.copy_(torch.from_numpy(np.ascontiguousarray(value))) | ||
| 58 | + result = run(*tensors, stride=stride, dilation=dilation) | ||
| 59 | + torch.npu.synchronize() | ||
| 60 | + assert result.is_contiguous() and result.device == tensors[0].device | ||
| 61 | + assert_output(result.cpu().numpy(), reference(*host, stride, dilation)) | ||
| 62 | + for tensor, value in zip(tensors, host): | ||
| 63 | + np.testing.assert_array_equal(tensor.cpu().numpy(), value) | ||
| 64 | + | ||
| 65 | + | ||
| 66 | +def test_group_isolation_and_bias(device): | ||
| 67 | + x = np.zeros((2, 7, 32), dtype=np.float16) | ||
| 68 | + x[:, :, 8:16] = np.float16(0.25) | ||
| 69 | + w = np.ones((4, 3, 8, 12), dtype=np.float16) | ||
| 70 | + bias = np.linspace(-0.5, 0.5, 48, dtype=np.float32) | ||
| 71 | + result = run( | ||
| 72 | + *(torch.from_numpy(a).to(device) for a in (x, w, bias)), stride=2, dilation=2 | ||
| 73 | + ) | ||
| 74 | + torch.npu.synchronize() | ||
| 75 | + actual = result.cpu().numpy() | ||
| 76 | + assert_output(actual, reference(x, w, bias, 2, 2)) | ||
| 77 | + untouched = np.r_[0:12, 24:48] | ||
| 78 | + np.testing.assert_array_equal( | ||
| 79 | + actual[:, :, untouched], | ||
| 80 | + np.broadcast_to(bias[untouched], (2, 4, len(untouched))), | ||
| 81 | + ) | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def test_comparison_rejects_corruption(): | ||
| 85 | + expected = reference( | ||
| 86 | + np.ones((1, 1, 16), dtype=np.float16), | ||
| 87 | + np.ones((8, 3, 2, 2), dtype=np.float16), | ||
| 88 | + np.zeros(16, dtype=np.float32), | ||
| 89 | + 1, | ||
| 90 | + 2, | ||
| 91 | + ) | ||
| 92 | + assert_output(expected.astype(np.float32), expected) | ||
| 93 | + with pytest.raises(AssertionError): | ||
| 94 | + assert_output(expected.astype(np.float32) + 1, expected) | ||
| @@ -8,6 +8,8 @@ | |||
| 8 | 8 | ||
| 9 | """写法:语法糖。Stage an indexed matrix operand, then consume it with Cube. | 9 | """写法:语法糖。Stage an indexed matrix operand, then consume it with Cube. |
| 10 | 10 | ||
| 11 | +example-query: {"aliases": ["row selector matrix product", "行选择矩阵乘积"], "facets": {"source_dtype": ["FP16", "BF16"], "destination_dtype": ["FP32"]}} | ||
| 12 | + | ||
| 11 | C[b, m, j] = dot(X[b, m, :], table[b, indices[b, j], :]). | 13 | C[b, m, j] = dot(X[b, m, :], table[b, indices[b, j], :]). |
| 12 | X[B,M,K] and table[B,R,K] are contiguous FP16/BF16; indices[B,N] is INT32 | 14 | X[B,M,K] and table[B,R,K] are contiguous FP16/BF16; indices[B,N] is INT32 |
| 13 | with values in [0,R), including repeats. C[B,M,N] is FP32. M is positive, | 15 | with values in [0,R), including repeats. C[B,M,N] is FP32. M is positive, |
Acannbot-skills/ops/pypto-pro-kernel/examples/algorithms/indexed_batched_gemm_onchip/__init__.py+7-0
| @@ -0,0 +1,7 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
Acannbot-skills/ops/pypto-pro-kernel/examples/algorithms/indexed_batched_gemm_onchip/kernel.py+282-0
| @@ -0,0 +1,282 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""写法:语法糖。SIMT gathers an indexed operand into on-chip Cube storage. | ||
| 10 | + | ||
| 11 | +example-query: {"aliases": ["SIMT Cube fusion", "on-chip indexed contraction", "SIMT Cube 片上交接"], "facets": {"source_dtype": ["FP16", "BF16"], "destination_dtype": ["FP32"]}} | ||
| 12 | + | ||
| 13 | +C[b,m,j] = dot(x[b,m,:], table[b,indices[b,j],:]). Inputs are contiguous, | ||
| 14 | +disjoint FP16/BF16 x[B,M,K], table[B,R,K] and INT32 indices[B,N] in [0,R). | ||
| 15 | +C[B,M,N] is FP32. Values are finite in [-1,1]; the table base is 8-byte | ||
| 16 | +aligned. Reference and tolerance are shared with indexed_batched_gemm. | ||
| 17 | +This bounded example supports B<=3, M<=129, R<=257, N in {128,256,384}, | ||
| 18 | +and K in 64..1024 divisible by 64. Overlap is exposed only for K<=320. | ||
| 19 | + | ||
| 20 | +make_kernel(..., workers=W, depth=1, preload=0) is the serial control; | ||
| 21 | +(depth,preload)=(2,1) uses a two-slot time-shifted pipeline. Launch the kernel | ||
| 22 | +with kernel[None,W](x,table,indices,out): W is part of this factory's | ||
| 23 | +mapping and must match the Host block count. Each mixed block uses one | ||
| 24 | +AIC and two AIVs on the verified A5 path. The two AIVs each own 64 panel | ||
| 25 | +rows. One SIMT invocation has 128 threads and moves 64-bit words into an | ||
| 26 | +ND Vec tile; a low-precision alias and a real ND-to-NZ move prepare insert. | ||
| 27 | + | ||
| 28 | +Both stages receive the declared Mat group. Cube reinterprets its bound | ||
| 29 | +group parameter as ZN before selecting one slot, then uses pl.gemm without | ||
| 30 | +a transpose flag. This preserves pipeline buffer tracking as well as the | ||
| 31 | +backing storage and cursor; passing an untracked external view is unsafe | ||
| 32 | +to assume equivalent on the verified source. The view performs no copy. | ||
| 33 | +Vec uses 16 KiB plus the installed SIMT reservation. Mat uses | ||
| 34 | +2*K*(128*depth+64) bytes: panel slots precede the A tile. Left/Right/Acc | ||
| 35 | +use 8/16/32 KiB, each with one slot; their independent spaces start at zero. | ||
| 36 | +There is no auxiliary GM panel. Each M tile gathers its operand again. | ||
| 37 | + | ||
| 38 | +This is a composition example with explicit alternatives, not a default | ||
| 39 | +replacement for the independently partitioned two-kernel implementation. | ||
| 40 | +Compare complete calls at matched AIC/AIV budgets and preserve the better | ||
| 41 | +path for the actual workload. Source behavior was checked at c46548e; | ||
| 42 | +revalidate synchronization, resources and numerical results after upgrades. | ||
| 43 | +""" | ||
| 44 | + | ||
| 45 | +from functools import lru_cache | ||
| 46 | +import pypto_pro.language as pl | ||
| 47 | + | ||
| 48 | +TM, TN, TK, THREADS = 64, 128, 64, 128 | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +@pl.vector_function(mode="simt", max_threads=THREADS) | ||
| 52 | +def gather_chunk(table, indices, dst, b, n0, k0): | ||
| 53 | + tid = pl.simt.linear_thread_idx() | ||
| 54 | + for linear in pl.range(tid, 64 * (TK // 4), THREADS): | ||
| 55 | + row = linear // (TK // 4) | ||
| 56 | + kk = linear % (TK // 4) | ||
| 57 | + selected = indices[b, n0 + row] | ||
| 58 | + dst[row, kk] = table[b, selected, k0 // 4 + kk] | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +@pl.pipeline.stage | ||
| 62 | +def consume( | ||
| 63 | + step, | ||
| 64 | + batch, | ||
| 65 | + workers, | ||
| 66 | + rows, | ||
| 67 | + mtiles, | ||
| 68 | + ntiles, | ||
| 69 | + x, | ||
| 70 | + out, | ||
| 71 | + a_group, | ||
| 72 | + panel_group, | ||
| 73 | + left, | ||
| 74 | + right, | ||
| 75 | + acc_group, | ||
| 76 | +): | ||
| 77 | + worker = pl.get_block_idx() // pl.get_subblock_num() | ||
| 78 | + task = step * workers + worker | ||
| 79 | + panel_group = pl.reinterpret(panel_group, shape=[x.shape[2], TN], layout=pl.ZN) | ||
| 80 | + panel = panel_group.next() | ||
| 81 | + pl.set_validshape(panel, [x.shape[2], TN]) | ||
| 82 | + if task < batch * mtiles * ntiles: | ||
| 83 | + b = task // (mtiles * ntiles) | ||
| 84 | + m0 = ((task // ntiles) % mtiles) * TM | ||
| 85 | + n0 = (task % ntiles) * TN | ||
| 86 | + valid_m = pl.min(TM, rows - m0) | ||
| 87 | + a = a_group.next() | ||
| 88 | + acc = acc_group.next() | ||
| 89 | + pl.set_validshape(a, [valid_m, x.shape[2]]) | ||
| 90 | + pl.set_validshape(acc, [valid_m, TN]) | ||
| 91 | + pl.load(a, x, [b, m0, 0], order=[1, 2]) | ||
| 92 | + pl.gemm(acc, a, panel, l0a=left, l0b=right, m=valid_m, splitk=TK) | ||
| 93 | + pl.store(out, acc, [b, m0, n0], order=[1, 2]) | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +@lru_cache(None) | ||
| 97 | +def make_kernel( | ||
| 98 | + batch, | ||
| 99 | + rows, | ||
| 100 | + table_rows, | ||
| 101 | + selected_rows, | ||
| 102 | + features, | ||
| 103 | + dtype_name="float16", | ||
| 104 | + workers=1, | ||
| 105 | + depth=1, | ||
| 106 | + preload=0, | ||
| 107 | +): | ||
| 108 | + if any( | ||
| 109 | + type(v) is not int or v <= 0 | ||
| 110 | + for v in (batch, rows, table_rows, selected_rows, features, workers) | ||
| 111 | + ): | ||
| 112 | + raise ValueError("shape dimensions and workers must be positive integers") | ||
| 113 | + if batch > 3 or rows > 129 or table_rows > 257: | ||
| 114 | + raise ValueError("this example requires B<=3, M<=129 and R<=257") | ||
| 115 | + if ( | ||
| 116 | + selected_rows not in (128, 256, 384) | ||
| 117 | + or not 64 <= features <= 1024 | ||
| 118 | + or features % 64 | ||
| 119 | + ): | ||
| 120 | + raise ValueError( | ||
| 121 | + "this example requires N in {128,256,384} and K in 64..1024 divisible by 64" | ||
| 122 | + ) | ||
| 123 | + if dtype_name not in ("float16", "bfloat16"): | ||
| 124 | + raise ValueError("dtype_name must be float16 or bfloat16") | ||
| 125 | + if ( | ||
| 126 | + type(depth) is not int | ||
| 127 | + or type(preload) is not int | ||
| 128 | + or (depth, preload) not in ((1, 0), (2, 1)) | ||
| 129 | + ): | ||
| 130 | + raise ValueError("this example exposes (depth,preload)=(1,0) or (2,1)") | ||
| 131 | + if depth == 2 and features > 320: | ||
| 132 | + raise ValueError("this example's overlap option is bounded to K<=320") | ||
| 133 | + dtype = pl.DT_FP16 if dtype_name == "float16" else pl.DT_BF16 | ||
| 134 | + mtiles, ntiles = (rows + TM - 1) // TM, selected_rows // TN | ||
| 135 | + forward_ids = list(range(depth)) | ||
| 136 | + backward_ids = list(range(depth, 2 * depth)) | ||
| 137 | + | ||
| 138 | + @pl.pipeline.stage | ||
| 139 | + def produce( | ||
| 140 | + step, | ||
| 141 | + batch, | ||
| 142 | + workers, | ||
| 143 | + mtiles, | ||
| 144 | + ntiles, | ||
| 145 | + features, | ||
| 146 | + packed_table, | ||
| 147 | + indices, | ||
| 148 | + nd_group, | ||
| 149 | + nz_group, | ||
| 150 | + panel_group, | ||
| 151 | + ): | ||
| 152 | + worker = pl.get_block_idx() // pl.get_subblock_num() | ||
| 153 | + task = step * workers + worker | ||
| 154 | + shared = panel_group.next() | ||
| 155 | + if task < batch * mtiles * ntiles: | ||
| 156 | + b = task // (mtiles * ntiles) | ||
| 157 | + n0 = (task % ntiles) * TN | ||
| 158 | + sub = pl.get_subblock_idx() | ||
| 159 | + for k0 in pl.range(0, features, TK): | ||
| 160 | + nd = nd_group.next() | ||
| 161 | + nz = nz_group.next() | ||
| 162 | + gather_chunk[THREADS](packed_table, indices, nd, b, n0 + sub * 64, k0) | ||
| 163 | + nd_low = pl.reinterpret(nd, dtype=dtype, shape=[64, TK]) | ||
| 164 | + pl.set_validshape(nd_low, [64, TK]) | ||
| 165 | + pl.move(nz, nd_low) | ||
| 166 | + pl.insert(shared, nz, [sub * 64, k0]) | ||
| 167 | + | ||
| 168 | + @pl.jit( | ||
| 169 | + arch="a5", auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=preload) | ||
| 170 | + ) | ||
| 171 | + def kernel( | ||
| 172 | + x: pl.Tensor[[batch, rows, features], dtype], | ||
| 173 | + table: pl.Tensor[[batch, table_rows, features], dtype], | ||
| 174 | + indices: pl.Tensor[[batch, selected_rows], pl.DT_INT32], | ||
| 175 | + out: pl.Tensor[[batch, rows, selected_rows], pl.DT_FP32], | ||
| 176 | + ): | ||
| 177 | + packed_table = pl.make_tensor( | ||
| 178 | + table, [batch, table_rows, features // 4], dtype=pl.DT_INT64 | ||
| 179 | + ) | ||
| 180 | + nd_group = pl.make_tile_group( | ||
| 181 | + type=pl.TileType( | ||
| 182 | + shape=[64, TK // 4], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Vec | ||
| 183 | + ), | ||
| 184 | + addrs=0, | ||
| 185 | + mutex_ids="auto", | ||
| 186 | + depth=1, | ||
| 187 | + ) | ||
| 188 | + nz_group = pl.make_tile_group( | ||
| 189 | + type=pl.TileType( | ||
| 190 | + shape=[64, TK], | ||
| 191 | + dtype=dtype, | ||
| 192 | + target_memory=pl.MemorySpace.Vec, | ||
| 193 | + layout=pl.NZ, | ||
| 194 | + ), | ||
| 195 | + addrs=64 * TK * 2, | ||
| 196 | + mutex_ids="auto", | ||
| 197 | + depth=1, | ||
| 198 | + ) | ||
| 199 | + panel_group = pl.make_tile_group( | ||
| 200 | + type=pl.TileType( | ||
| 201 | + shape=[TN, features], | ||
| 202 | + dtype=dtype, | ||
| 203 | + target_memory=pl.MemorySpace.Mat, | ||
| 204 | + layout=pl.NZ, | ||
| 205 | + ), | ||
| 206 | + addrs=0, | ||
| 207 | + mutex_ids="auto", | ||
| 208 | + depth=depth, | ||
| 209 | + fwd_ids=forward_ids, | ||
| 210 | + bwd_ids=backward_ids, | ||
| 211 | + ) | ||
| 212 | + a_group = pl.make_tile_group( | ||
| 213 | + type=pl.TileType( | ||
| 214 | + shape=[TM, features], dtype=dtype, target_memory=pl.MemorySpace.Mat | ||
| 215 | + ), | ||
| 216 | + addrs=depth * TN * features * 2, | ||
| 217 | + mutex_ids="auto", | ||
| 218 | + depth=1, | ||
| 219 | + ) | ||
| 220 | + left = pl.make_tile_group( | ||
| 221 | + type=pl.TileType( | ||
| 222 | + shape=[TM, TK], | ||
| 223 | + dtype=dtype, | ||
| 224 | + target_memory=pl.MemorySpace.Left, | ||
| 225 | + compact=1, | ||
| 226 | + ), | ||
| 227 | + addrs=0, | ||
| 228 | + mutex_ids="auto", | ||
| 229 | + depth=1, | ||
| 230 | + ) | ||
| 231 | + right = pl.make_tile_group( | ||
| 232 | + type=pl.TileType( | ||
| 233 | + shape=[TK, TN], dtype=dtype, target_memory=pl.MemorySpace.Right | ||
| 234 | + ), | ||
| 235 | + addrs=0, | ||
| 236 | + mutex_ids="auto", | ||
| 237 | + depth=1, | ||
| 238 | + ) | ||
| 239 | + acc_group = pl.make_tile_group( | ||
| 240 | + type=pl.TileType( | ||
| 241 | + shape=[TM, TN], | ||
| 242 | + dtype=pl.DT_FP32, | ||
| 243 | + target_memory=pl.MemorySpace.Acc, | ||
| 244 | + compact=1, | ||
| 245 | + ), | ||
| 246 | + addrs=0, | ||
| 247 | + mutex_ids="auto", | ||
| 248 | + depth=1, | ||
| 249 | + ) | ||
| 250 | + for step in pl.range((batch * mtiles * ntiles + workers - 1) // workers): | ||
| 251 | + with pl.section_vector(): | ||
| 252 | + produce( | ||
| 253 | + step, | ||
| 254 | + batch, | ||
| 255 | + workers, | ||
| 256 | + mtiles, | ||
| 257 | + ntiles, | ||
| 258 | + features, | ||
| 259 | + packed_table, | ||
| 260 | + indices, | ||
| 261 | + nd_group, | ||
| 262 | + nz_group, | ||
| 263 | + panel_group, | ||
| 264 | + ) | ||
| 265 | + with pl.section_cube(): | ||
| 266 | + consume( | ||
| 267 | + step, | ||
| 268 | + batch, | ||
| 269 | + workers, | ||
| 270 | + rows, | ||
| 271 | + mtiles, | ||
| 272 | + ntiles, | ||
| 273 | + x, | ||
| 274 | + out, | ||
| 275 | + a_group, | ||
| 276 | + panel_group, | ||
| 277 | + left, | ||
| 278 | + right, | ||
| 279 | + acc_group, | ||
| 280 | + ) | ||
| 281 | + | ||
| 282 | + return kernel | ||
Acannbot-skills/ops/pypto-pro-kernel/examples/algorithms/indexed_batched_gemm_onchip/reference.py+11-0
| @@ -0,0 +1,11 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Independent reference shared with the materialized indexed contraction.""" | ||
| 10 | + | ||
| 11 | +from ..indexed_batched_gemm.reference import reference_and_bound as reference_and_bound | ||
| @@ -0,0 +1,55 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Verify slot reuse, both subblocks, tails and changed inputs at fixed addresses.""" | ||
| 10 | + | ||
| 11 | +import pytest | ||
| 12 | +import torch | ||
| 13 | + | ||
| 14 | +from .kernel import make_kernel | ||
| 15 | +from .reference import reference_and_bound | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +CASES = [ | ||
| 19 | + ((1, 1, 37, 128, 64), 1, 1, 0), | ||
| 20 | + ((2, 17, 97, 256, 192), 3, 1, 0), | ||
| 21 | + ((3, 129, 193, 384, 320), 7, 1, 0), | ||
| 22 | + ((3, 65, 257, 128, 1024), 3, 1, 0), | ||
| 23 | + ((2, 17, 37, 128, 64), 1, 2, 1), | ||
| 24 | + ((3, 129, 193, 384, 320), 7, 2, 1), | ||
| 25 | +] | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) | ||
| 29 | +@pytest.mark.parametrize("shape,workers,depth,preload", CASES) | ||
| 30 | +def test_indexed_onchip(shape, workers, depth, preload, dtype, device): | ||
| 31 | + b, m, r, n, k = shape | ||
| 32 | + generator = torch.Generator().manual_seed(18371 + k + m) | ||
| 33 | + x = torch.rand((b, m, k), generator=generator).mul(2).sub(1).to(dtype) | ||
| 34 | + table = torch.rand((b, r, k), generator=generator).mul(2).sub(1).to(dtype) | ||
| 35 | + indices = torch.randint(r, (b, n), generator=generator, dtype=torch.int32) | ||
| 36 | + dx, dt, di = x.to(device), table.to(device), indices.to(device) | ||
| 37 | + backing = torch.full((b * m * n + 128,), 23, dtype=torch.float32, device=device) | ||
| 38 | + out = backing[64:-64].view(b, m, n) | ||
| 39 | + kernel = make_kernel(*shape, str(dtype).split(".")[-1], workers, depth, preload) | ||
| 40 | + pointers = [t.data_ptr() for t in (dx, dt, di, out)] | ||
| 41 | + for repeat in range(2): | ||
| 42 | + current = (indices + 7 * repeat) % r | ||
| 43 | + values = table if repeat == 0 else -table | ||
| 44 | + dt.copy_(values) | ||
| 45 | + di.copy_(current) | ||
| 46 | + out.fill_(float("nan")) | ||
| 47 | + kernel[None, workers](dx, dt, di, out) | ||
| 48 | + torch.npu.synchronize() | ||
| 49 | + expected, bound = reference_and_bound(x, values, current) | ||
| 50 | + got = out.cpu().double() | ||
| 51 | + assert torch.isfinite(got).all() and ((got - expected).abs() <= bound).all() | ||
| 52 | + assert torch.equal(dx.cpu(), x) and torch.equal(dt.cpu(), values) | ||
| 53 | + assert torch.equal(di.cpu(), current) | ||
| 54 | + assert (backing[:64] == 23).all() and (backing[-64:] == 23).all() | ||
| 55 | + assert [t.data_ptr() for t in (dx, dt, di, out)] == pointers | ||
| @@ -18,6 +18,8 @@ | |||
| 18 | 18 | ||
| 19 | 验证边界:行为版本 872df763f,CANN 9.2.0,Ascend950PR。 | 19 | 验证边界:行为版本 872df763f,CANN 9.2.0,Ascend950PR。 |
| 20 | 容差与边界由 test.py 固定,不代表性能已优化。 | 20 | 容差与边界由 test.py 固定,不代表性能已优化。 |
| 21 | + | ||
| 22 | +example-query: {"aliases":["runtime prefix softmax","运行期前缀softmax"],"term_groups":[["softmax"],["runtime prefix","prefix length","runtime length","有效前缀","有效长度"]],"facets":{"source_dtype":["FP32"],"destination_dtype":["FP32"]}} | ||
| 21 | """ | 23 | """ |
| 22 | 24 | ||
| 23 | import pypto_pro.language as pl | 25 | import pypto_pro.language as pl |
| @@ -0,0 +1,7 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| @@ -0,0 +1,267 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""写法:原始。FP16 向量的两两平方距离,差值、乘法与归约使用 FP32。 | ||
| 10 | + | ||
| 11 | +example-query: {"aliases": ["pairwise squared distance", "squared Euclidean distance", "两两平方欧氏距离"], "facets": {"source_dtype": ["FP16"], "destination_dtype": ["FP32"]}} | ||
| 12 | + | ||
| 13 | +输入为连续 x[P,D]、z[Q,D];输出 FP32 y[P,Q] = sum_d (x-z)^2。 | ||
| 14 | +范围为 P/Q=1..257、D=1..1025,输入绝对值<=8;相同向量返回精确零。 | ||
| 15 | +FP64 参考使用实际量化输入,容差为 atol=1e-5、rtol=2e-5。 | ||
| 16 | +逐项扩精度后计算差值,避免近邻数据中范数展开的消减误差。 | ||
| 17 | + | ||
| 18 | +run_rows 每个 pair 读取一行 z 并调用 VF,打包 8 个标量结果后写回; | ||
| 19 | +run_batched 一次搬运最多 16 行 z,共享当前 x 行并在一个 VF 调用内计算。 | ||
| 20 | +两种路径均以 UNPK 和 FP32 谓词扩精度,以 FIRST_ELEMENT_B32 打包标量输出。 | ||
| 21 | +各 worker 独占输出片段,三个单槽缓冲组使用独立地址与 mutex IDs。 | ||
| 22 | +最大 Vec 有效分配为 37056 B,最高地址端点为 0xA040,无 GM scratch。 | ||
| 23 | + | ||
| 24 | +run 使用当前平台 vector_core_num 限制 worker 数;批量路径的工作组不足以覆盖 | ||
| 25 | +这些 worker 时采用逐行路径,避免输入复用缩减并行度。此规则只是一种配置选择, | ||
| 26 | +不同设备和工作负载仍需完整调用计时。原生接口与配置在 PyPTO cbd3c4a778、 | ||
| 27 | +CANN 9.2.0、Ascend950PR 验证,当前证据须绑定源码与安装身份。 | ||
| 28 | +""" | ||
| 29 | + | ||
| 30 | +import torch | ||
| 31 | +import torch_npu # noqa: F401 | ||
| 32 | +import pypto_pro.language as pl | ||
| 33 | +from pypto_pro.language import Vf as vf | ||
| 34 | +from pypto_pro.runtime.platform import get_platform_info | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +FP16 = pl.DT_FP16 | ||
| 38 | +FP32 = pl.DT_FP32 | ||
| 39 | +VL = 64 | ||
| 40 | +PAD_D = 1088 | ||
| 41 | +ROW_Q_BLOCK = 8 | ||
| 42 | +BATCH_Q_BLOCK = 16 | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +@pl.vector_function | ||
| 46 | +def _distance_pair(x_tile, z_tile, out_tile, dim: pl.DT_INT64, q_slot: pl.DT_INT64): | ||
| 47 | + """Compute one pair into a slot of the current output tile.""" | ||
| 48 | + all_lanes = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=FP32) | ||
| 49 | + total = vf.full(0.0, all_lanes, dtype=FP32) | ||
| 50 | + for d in pl.range(0, dim, VL): | ||
| 51 | + active = pl.min(VL, dim - d) | ||
| 52 | + mask = vf.update_mask(active, dtype=FP32) | ||
| 53 | + x16 = vf.load_align(x_tile, d, dist=pl.LoadDist.UNPK) | ||
| 54 | + z16 = vf.load_align(z_tile, d, dist=pl.LoadDist.UNPK) | ||
| 55 | + xv = vf.astype(x16, mask, dtype=FP32, layout=pl.CastLayout.ZERO) | ||
| 56 | + zv = vf.astype(z16, mask, dtype=FP32, layout=pl.CastLayout.ZERO) | ||
| 57 | + delta = vf.sub(xv, zv, mask) | ||
| 58 | + square = vf.mul(delta, delta, mask) | ||
| 59 | + part = vf.reduce_sum(square, mask) | ||
| 60 | + total = vf.add(total, part, all_lanes) | ||
| 61 | + | ||
| 62 | + first = vf.update_mask(1, dtype=FP32) | ||
| 63 | + vf.store_align( | ||
| 64 | + out_tile, | ||
| 65 | + total, | ||
| 66 | + first, | ||
| 67 | + [0, q_slot], | ||
| 68 | + dist=pl.StoreDist.FIRST_ELEMENT_B32, | ||
| 69 | + ) | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +@pl.vector_function | ||
| 73 | +def _distance_batch(x_tile, z_tile, out_tile, dim: pl.DT_INT64, q_count: pl.DT_INT64): | ||
| 74 | + """Reduce a loaded block of right-hand rows against one resident row.""" | ||
| 75 | + all_lanes = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=FP32) | ||
| 76 | + first = vf.update_mask(1, dtype=FP32) | ||
| 77 | + for q in pl.range(q_count): | ||
| 78 | + total = vf.full(0.0, all_lanes, dtype=FP32) | ||
| 79 | + for d in pl.range(0, dim, VL): | ||
| 80 | + active = pl.min(VL, dim - d) | ||
| 81 | + mask = vf.update_mask(active, dtype=FP32) | ||
| 82 | + x16 = vf.load_align(x_tile, d, dist=pl.LoadDist.UNPK) | ||
| 83 | + z16 = vf.load_align(z_tile, [q, d], dist=pl.LoadDist.UNPK) | ||
| 84 | + xv = vf.astype(x16, mask, dtype=FP32, layout=pl.CastLayout.ZERO) | ||
| 85 | + zv = vf.astype(z16, mask, dtype=FP32, layout=pl.CastLayout.ZERO) | ||
| 86 | + delta = vf.sub(xv, zv, mask) | ||
| 87 | + square = vf.mul(delta, delta, mask) | ||
| 88 | + part = vf.reduce_sum(square, mask) | ||
| 89 | + total = vf.add(total, part, all_lanes) | ||
| 90 | + vf.store_align( | ||
| 91 | + out_tile, | ||
| 92 | + total, | ||
| 93 | + first, | ||
| 94 | + [0, q], | ||
| 95 | + dist=pl.StoreDist.FIRST_ELEMENT_B32, | ||
| 96 | + ) | ||
| 97 | + | ||
| 98 | + | ||
| 99 | +@pl.jit(auto_mutex=True, name="pairwise_distance_rows_q8") | ||
| 100 | +def _rows_kernel( | ||
| 101 | + x: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], FP16], | ||
| 102 | + z: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], FP16], | ||
| 103 | + y: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], FP32], | ||
| 104 | +): | ||
| 105 | + x_group = pl.make_tile_group( | ||
| 106 | + type=pl.TileType( | ||
| 107 | + shape=[1, PAD_D], | ||
| 108 | + dtype=FP16, | ||
| 109 | + target_memory=pl.MemorySpace.Vec, | ||
| 110 | + valid_shape=[-1, -1], | ||
| 111 | + ), | ||
| 112 | + addrs=[0x0000], | ||
| 113 | + mutex_ids=[0], | ||
| 114 | + ) | ||
| 115 | + z_group = pl.make_tile_group( | ||
| 116 | + type=pl.TileType( | ||
| 117 | + shape=[1, PAD_D], | ||
| 118 | + dtype=FP16, | ||
| 119 | + target_memory=pl.MemorySpace.Vec, | ||
| 120 | + valid_shape=[-1, -1], | ||
| 121 | + ), | ||
| 122 | + addrs=[0x1000], | ||
| 123 | + mutex_ids=[1], | ||
| 124 | + ) | ||
| 125 | + out_group = pl.make_tile_group( | ||
| 126 | + type=pl.TileType( | ||
| 127 | + shape=[1, ROW_Q_BLOCK], | ||
| 128 | + dtype=FP32, | ||
| 129 | + target_memory=pl.MemorySpace.Vec, | ||
| 130 | + valid_shape=[-1, -1], | ||
| 131 | + ), | ||
| 132 | + addrs=[0x2000], | ||
| 133 | + mutex_ids=[2], | ||
| 134 | + ) | ||
| 135 | + | ||
| 136 | + with pl.section_vector(): | ||
| 137 | + p = x.shape[0] | ||
| 138 | + q = z.shape[0] | ||
| 139 | + dim = x.shape[1] | ||
| 140 | + q_groups = (q + ROW_Q_BLOCK - 1) // ROW_Q_BLOCK | ||
| 141 | + total_groups = p * q_groups | ||
| 142 | + for task in pl.range(pl.get_block_idx(), total_groups, pl.get_block_num()): | ||
| 143 | + row = task // q_groups | ||
| 144 | + q_group = task % q_groups | ||
| 145 | + q_start = q_group * ROW_Q_BLOCK | ||
| 146 | + q_count = pl.min(ROW_Q_BLOCK, q - q_start) | ||
| 147 | + | ||
| 148 | + x_tile = x_group.next() | ||
| 149 | + pl.set_validshape(x_tile, [1, dim]) | ||
| 150 | + pl.load(x_tile, x, [row, 0]) | ||
| 151 | + out_tile = out_group.next() | ||
| 152 | + pl.set_validshape(out_tile, [1, q_count]) | ||
| 153 | + for q_local in pl.range(q_count): | ||
| 154 | + z_tile = z_group.next() | ||
| 155 | + pl.set_validshape(z_tile, [1, dim]) | ||
| 156 | + pl.load(z_tile, z, [q_start + q_local, 0]) | ||
| 157 | + _distance_pair(x_tile, z_tile, out_tile, dim, q_local) | ||
| 158 | + pl.store(y, out_tile, [row, q_start]) | ||
| 159 | + | ||
| 160 | + | ||
| 161 | +@pl.jit(auto_mutex=True, name="pairwise_distance_batched_q16") | ||
| 162 | +def _batched_kernel( | ||
| 163 | + x: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], FP16], | ||
| 164 | + z: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], FP16], | ||
| 165 | + y: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], FP32], | ||
| 166 | +): | ||
| 167 | + x_group = pl.make_tile_group( | ||
| 168 | + type=pl.TileType( | ||
| 169 | + shape=[1, PAD_D], | ||
| 170 | + dtype=FP16, | ||
| 171 | + target_memory=pl.MemorySpace.Vec, | ||
| 172 | + valid_shape=[-1, -1], | ||
| 173 | + ), | ||
| 174 | + addrs=[0x0000], | ||
| 175 | + mutex_ids=[0], | ||
| 176 | + ) | ||
| 177 | + z_group = pl.make_tile_group( | ||
| 178 | + type=pl.TileType( | ||
| 179 | + shape=[BATCH_Q_BLOCK, PAD_D], | ||
| 180 | + dtype=FP16, | ||
| 181 | + target_memory=pl.MemorySpace.Vec, | ||
| 182 | + valid_shape=[-1, -1], | ||
| 183 | + ), | ||
| 184 | + addrs=[0x1000], | ||
| 185 | + mutex_ids=[1], | ||
| 186 | + ) | ||
| 187 | + out_group = pl.make_tile_group( | ||
| 188 | + type=pl.TileType( | ||
| 189 | + shape=[1, BATCH_Q_BLOCK], | ||
| 190 | + dtype=FP32, | ||
| 191 | + target_memory=pl.MemorySpace.Vec, | ||
| 192 | + valid_shape=[-1, -1], | ||
| 193 | + ), | ||
| 194 | + addrs=[0xA000], | ||
| 195 | + mutex_ids=[2], | ||
| 196 | + ) | ||
| 197 | + | ||
| 198 | + with pl.section_vector(): | ||
| 199 | + p = x.shape[0] | ||
| 200 | + q = z.shape[0] | ||
| 201 | + dim = x.shape[1] | ||
| 202 | + q_groups = (q + BATCH_Q_BLOCK - 1) // BATCH_Q_BLOCK | ||
| 203 | + total_groups = p * q_groups | ||
| 204 | + for task in pl.range(pl.get_block_idx(), total_groups, pl.get_block_num()): | ||
| 205 | + row = task // q_groups | ||
| 206 | + q_group = task % q_groups | ||
| 207 | + q_start = q_group * BATCH_Q_BLOCK | ||
| 208 | + q_count = pl.min(BATCH_Q_BLOCK, q - q_start) | ||
| 209 | + | ||
| 210 | + x_tile = x_group.next() | ||
| 211 | + pl.set_validshape(x_tile, [1, dim]) | ||
| 212 | + pl.load(x_tile, x, [row, 0]) | ||
| 213 | + z_tile = z_group.next() | ||
| 214 | + pl.set_validshape(z_tile, [q_count, dim]) | ||
| 215 | + pl.load(z_tile, z, [q_start, 0]) | ||
| 216 | + out_tile = out_group.next() | ||
| 217 | + pl.set_validshape(out_tile, [1, q_count]) | ||
| 218 | + _distance_batch(x_tile, z_tile, out_tile, dim, q_count) | ||
| 219 | + pl.store(y, out_tile, [row, q_start]) | ||
| 220 | + | ||
| 221 | + | ||
| 222 | +def _validate_inputs(x, z): | ||
| 223 | + if x.device.type != "npu" or z.device != x.device: | ||
| 224 | + raise ValueError("x and z must be on the same NPU") | ||
| 225 | + if x.dtype != torch.float16 or z.dtype != torch.float16: | ||
| 226 | + raise ValueError("x and z must be FP16") | ||
| 227 | + if x.ndim != 2 or z.ndim != 2 or x.shape[1] != z.shape[1]: | ||
| 228 | + raise ValueError("x and z must be rank-2 with the same feature width") | ||
| 229 | + if not x.is_contiguous() or not z.is_contiguous(): | ||
| 230 | + raise ValueError("x and z must be contiguous") | ||
| 231 | + p, dim = x.shape | ||
| 232 | + q = z.shape[0] | ||
| 233 | + if not (1 <= p <= 257 and 1 <= q <= 257 and 1 <= dim <= 1025): | ||
| 234 | + raise ValueError("supported shapes: 1<=P,Q<=257 and 1<=D<=1025") | ||
| 235 | + | ||
| 236 | + | ||
| 237 | +def _run_with(kernel, q_block, x, z): | ||
| 238 | + _validate_inputs(x, z) | ||
| 239 | + p, dim = x.shape | ||
| 240 | + q = z.shape[0] | ||
| 241 | + y = torch.empty((p, q), dtype=torch.float32, device=x.device) | ||
| 242 | + groups = (q + q_block - 1) // q_block | ||
| 243 | + workers = min(int(get_platform_info().vector_core_num), p * groups) | ||
| 244 | + kernel[None, workers](x, z, y) | ||
| 245 | + return y | ||
| 246 | + | ||
| 247 | + | ||
| 248 | +def run_rows(x, z): | ||
| 249 | + """Read one z row and invoke VF per pair, packing row outputs.""" | ||
| 250 | + return _run_with(_rows_kernel, ROW_Q_BLOCK, x, z) | ||
| 251 | + | ||
| 252 | + | ||
| 253 | +def run_batched(x, z): | ||
| 254 | + """Load and compute a Q16 batch of right-hand rows.""" | ||
| 255 | + return _run_with(_batched_kernel, BATCH_Q_BLOCK, x, z) | ||
| 256 | + | ||
| 257 | + | ||
| 258 | +def run(x, z): | ||
| 259 | + """Return FP32 distances, batching only when enough groups remain active.""" | ||
| 260 | + _validate_inputs(x, z) | ||
| 261 | + p, _ = x.shape | ||
| 262 | + q = z.shape[0] | ||
| 263 | + cores = int(get_platform_info().vector_core_num) | ||
| 264 | + candidate_groups = p * ((q + BATCH_Q_BLOCK - 1) // BATCH_Q_BLOCK) | ||
| 265 | + if candidate_groups < cores: | ||
| 266 | + return _run_with(_rows_kernel, ROW_Q_BLOCK, x, z) | ||
| 267 | + return _run_with(_batched_kernel, BATCH_Q_BLOCK, x, z) | ||
Acannbot-skills/ops/pypto-pro-kernel/examples/algorithms/pairwise_squared_distance/reference.py+22-0
| @@ -0,0 +1,22 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""从实际 FP16 输入直接求 FP64 差平方和,不使用范数展开或 kernel 的分块顺序。""" | ||
| 10 | + | ||
| 11 | +import numpy as np | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def reference(x, z): | ||
| 15 | + x = np.asarray(x, dtype=np.float64) | ||
| 16 | + z = np.asarray(z, dtype=np.float64) | ||
| 17 | + result = np.empty((x.shape[0], z.shape[0]), dtype=np.float64) | ||
| 18 | + for begin in range(0, len(x), 16): | ||
| 19 | + result[begin : begin + 16] = ( | ||
| 20 | + (x[begin : begin + 16, None, :] - z[None, :, :]) ** 2 | ||
| 21 | + ).sum(-1) | ||
| 22 | + return result | ||
| @@ -0,0 +1,97 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""验证直接差平方、近邻、FP16 算术舍入陷阱、尾部和原地址输入变化。 | ||
| 10 | + | ||
| 11 | +worker 独占输出区域,输入和输出 tile 用独立缓冲组同步;FIRST_ELEMENT_B32 在 UB 内打包单值,GM 每次写入完整有效片段。输入从非零存储偏移开始,前后守卫检查越界写。FP64 参考独立于 VF 分块与搬运顺序;三条公开路径都受同一数学契约约束。 | ||
| 12 | +""" | ||
| 13 | + | ||
| 14 | +import numpy as np | ||
| 15 | +import pytest | ||
| 16 | +import torch | ||
| 17 | + | ||
| 18 | +from .kernel import run, run_rows, run_batched | ||
| 19 | +from .reference import reference | ||
| 20 | + | ||
| 21 | +CASES = [ | ||
| 22 | + (1, 1, 1, "same"), | ||
| 23 | + (3, 5, 17, "random"), | ||
| 24 | + (7, 3, 63, "coordinates"), | ||
| 25 | + (2, 33, 65, "close"), | ||
| 26 | + (33, 2, 127, "same"), | ||
| 27 | + (1, 257, 1025, "close"), | ||
| 28 | + (129, 257, 512, "random"), | ||
| 29 | + (257, 129, 1025, "same"), | ||
| 30 | + (5, 7, 513, "extreme"), | ||
| 31 | + (257, 257, 1025, "random"), | ||
| 32 | + (3, 5, 1025, "subnormal"), | ||
| 33 | +] | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def arrays(p, q, d, pattern): | ||
| 37 | + rng = np.random.default_rng(p * 100003 + q * 131 + d) | ||
| 38 | + x = rng.uniform(-8, 8, (p, d)).astype(np.float16) | ||
| 39 | + z = rng.uniform(-8, 8, (q, d)).astype(np.float16) | ||
| 40 | + if pattern == "same": | ||
| 41 | + z[:] = x[np.arange(q) % p] | ||
| 42 | + elif pattern == "close": | ||
| 43 | + x[:] = rng.uniform(2, 6, (1, d)).astype(np.float16) | ||
| 44 | + z[:] = x[0] | ||
| 45 | + for j in range(1, q): | ||
| 46 | + cols = (j * 7 + np.arange(min(d, 33))) % d | ||
| 47 | + z[j, cols] = np.nextafter(z[j, cols], np.float16(np.inf)) | ||
| 48 | + elif pattern == "coordinates": | ||
| 49 | + x[:] = ((np.arange(p)[:, None] * 7 + np.arange(d) * 3) % 31 - 15) / 2 | ||
| 50 | + z[:] = ((np.arange(q)[:, None] * 5 + np.arange(d) * 2) % 29 - 14) / 2 | ||
| 51 | + elif pattern == "extreme": | ||
| 52 | + x[:, ::2] = 8 | ||
| 53 | + x[:, 1::2] = -8 | ||
| 54 | + z[:] = x[0] | ||
| 55 | + z[1::2] *= -1 | ||
| 56 | + x[-1].fill(1.1) | ||
| 57 | + z[-1].fill(0) | ||
| 58 | + elif pattern == "subnormal": | ||
| 59 | + x.fill(2**-14 - 2**-24) | ||
| 60 | + z[:] = -x[0] | ||
| 61 | + z[0] = x[0] | ||
| 62 | + return x, z | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +@pytest.mark.parametrize("case", CASES) | ||
| 66 | +def test_contract_and_reused_addresses(device, case): | ||
| 67 | + host = arrays(*case) | ||
| 68 | + backings = [ | ||
| 69 | + torch.full((a.size + 64,), -13, dtype=torch.float16, device=device) | ||
| 70 | + for a in host | ||
| 71 | + ] | ||
| 72 | + tensors = [b[16 : 16 + a.size].view(a.shape) for a, b in zip(host, backings)] | ||
| 73 | + changed = tuple( | ||
| 74 | + (a * np.float16(-0.5) + np.float16(0.25)).astype(np.float16) for a in host | ||
| 75 | + ) | ||
| 76 | + variants = ( | ||
| 77 | + (run, run_rows, run_batched) | ||
| 78 | + if case[:3] in ((2, 33, 65), (129, 257, 512), (1, 257, 1025)) | ||
| 79 | + else (run,) | ||
| 80 | + ) | ||
| 81 | + for values in (host, changed): | ||
| 82 | + for tensor, value in zip(tensors, values): | ||
| 83 | + tensor.copy_(torch.from_numpy(value)) | ||
| 84 | + golden = reference(*values) | ||
| 85 | + for invoke in variants: | ||
| 86 | + actual = invoke(*tensors) | ||
| 87 | + torch.npu.synchronize() | ||
| 88 | + assert actual.dtype == torch.float32 and tuple(actual.shape) == golden.shape | ||
| 89 | + assert actual.is_contiguous() and actual.device == tensors[0].device | ||
| 90 | + got = actual.cpu().numpy() | ||
| 91 | + assert np.isfinite(got).all() and (got >= 0).all() | ||
| 92 | + assert (got[golden == 0] == 0).all() | ||
| 93 | + np.testing.assert_allclose(got, golden, atol=1e-5, rtol=2e-5) | ||
| 94 | + for tensor, value, backing in zip(tensors, values, backings): | ||
| 95 | + np.testing.assert_array_equal(tensor.cpu().numpy(), value) | ||
| 96 | + assert (backing[:16] == -13).all().item() | ||
| 97 | + assert (backing[16 + value.size :] == -13).all().item() | ||
| @@ -28,6 +28,8 @@ covers all errors. See references/diagnostics/check-coverage.md for their limits | |||
| 28 | 28 | ||
| 29 | The sanitizer variant uses name=None so the program and entry-function names match. Each variant is built and run | 29 | The sanitizer variant uses name=None so the program and entry-function names match. Each variant is built and run |
| 30 | separately; this example makes no performance claim. | 30 | separately; this example makes no performance claim. |
| 31 | + | ||
| 32 | +example-query: {"aliases":["RMS normalization and GEMM with M tails","带M尾块的RMSNorm矩阵乘"],"term_groups":[["rmsnorm","rms normalization","均方根归一化"],["gemm","矩阵乘"]],"facets":{"source_dtype":["FP16"],"destination_dtype":["FP32"]},"exclude":[{"term_groups":[["N tail","N tails","N尾块","N 尾块","K tail","K tails","K尾块","K 尾块"]],"reason":"This fixed K=N=256 program demonstrates M tails only."},{"term_groups":[["backward","gradient","反向","梯度"]],"reason":"This program implements the forward RMSNorm-to-GEMM composition only."}]} | ||
| 31 | """ | 33 | """ |
| 32 | 34 | ||
| 33 | import pypto_pro.language as pl | 35 | import pypto_pro.language as pl |
| @@ -0,0 +1,7 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| @@ -0,0 +1,142 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""写法:原始。UINT8 直方图:直接 GM 原子与每 block 的 UB 局部聚合。 | ||
| 10 | + | ||
| 11 | +输入是连续 UINT8[N],输出是连续 INT32[256],二者不重叠,要求 N <= INT32_MAX。 | ||
| 12 | +每次调用先用独立原生 kernel 清零输出,同一 Stream 后续更新无需全网格屏障。 | ||
| 13 | +local=True 时,每 block 初始化自己的 256 个 UB 计数,再累加并汇总到 GM。 | ||
| 14 | +两个线程块屏障均位于线程控制流之外;没有输入的线程也必须到达。 | ||
| 15 | +local=False 保留直接 GM 原子对照,combine_runs=True 则合并同一线程遍历中的连续相同目标。 | ||
| 16 | +三条路径都使用两个原生调用,空输入只清零;线程内合并不引入共享状态或额外屏障。 | ||
| 17 | +线程数和 worker 数为显式配置;默认值不是性能最优声明。 | ||
| 18 | +来源机制:Ascend 950 SIMT 原子优化指南;接口事实和数值验收以当前 PyPTO 安装为准。 | ||
| 19 | +接口核对源码 c46548e;数值验证安装源码 cbd3c4a 的相关实现相同,CANN 9.2.0 / Ascend950PR。 | ||
| 20 | +example-query: {"aliases":["SIMT local histogram","SIMT local counters"],"term_groups":[["simt","ub","block-local"],["histogram","counters","categorical","直方图"]]} | ||
| 21 | +""" | ||
| 22 | + | ||
| 23 | +from functools import lru_cache | ||
| 24 | + | ||
| 25 | +import pypto_pro.language as pl | ||
| 26 | + | ||
| 27 | +I32 = pl.DT_INT32 | ||
| 28 | +U8 = pl.DT_UINT8 | ||
| 29 | +BINS = 256 | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +@lru_cache(None) | ||
| 33 | +def make_histogram(n, threads=256, local=True, combine_runs=False): | ||
| 34 | + """Return native initialization and update kernels for one physical shape.""" | ||
| 35 | + if not 0 <= n <= 2**31 - 1 or threads not in (64, 128, 256, 512): | ||
| 36 | + raise ValueError("require 0 <= N <= INT32_MAX and threads in 64/128/256/512") | ||
| 37 | + if local and combine_runs: | ||
| 38 | + raise ValueError("run combining is a direct-GM alternative; use local=False") | ||
| 39 | + | ||
| 40 | + @pl.vector_function(mode="simt", max_threads=threads) | ||
| 41 | + def clear_body(out): | ||
| 42 | + first = pl.simt.block_idx().x * threads + pl.simt.linear_thread_idx() | ||
| 43 | + step = pl.simt.grid_dim().x * threads | ||
| 44 | + for j in pl.range(first, BINS, step): | ||
| 45 | + out[j] = pl.simt.cast(0, I32) | ||
| 46 | + | ||
| 47 | + @pl.jit() | ||
| 48 | + def initialize(out: pl.Tensor[[BINS], I32]): | ||
| 49 | + with pl.section_vector(): | ||
| 50 | + clear_body[threads](out) | ||
| 51 | + | ||
| 52 | + if n == 0: | ||
| 53 | + return initialize, None | ||
| 54 | + | ||
| 55 | + @pl.vector_function(mode="simt", max_threads=threads) | ||
| 56 | + def global_body(x, out): | ||
| 57 | + first = pl.simt.block_idx().x * threads + pl.simt.linear_thread_idx() | ||
| 58 | + step = pl.simt.grid_dim().x * threads | ||
| 59 | + one = pl.simt.cast(1, I32) | ||
| 60 | + for i in pl.range(first, n, step): | ||
| 61 | + pl.simt.atomic_add(out[x[i]], one) | ||
| 62 | + | ||
| 63 | + @pl.vector_function(mode="simt", max_threads=threads) | ||
| 64 | + def runs_body(x, out): | ||
| 65 | + first = pl.simt.block_idx().x * threads + pl.simt.linear_thread_idx() | ||
| 66 | + step = pl.simt.grid_dim().x * threads | ||
| 67 | + one = pl.simt.cast(1, I32) | ||
| 68 | + if first < n: | ||
| 69 | + key = x[first] | ||
| 70 | + count = one | ||
| 71 | + for i in pl.range(first + step, n, step): | ||
| 72 | + next_key = x[i] | ||
| 73 | + if next_key == key: | ||
| 74 | + count = count + one | ||
| 75 | + else: | ||
| 76 | + pl.simt.atomic_add(out[key], count) | ||
| 77 | + key = next_key | ||
| 78 | + count = one | ||
| 79 | + pl.simt.atomic_add(out[key], count) | ||
| 80 | + | ||
| 81 | + @pl.vector_function(mode="simt", max_threads=threads) | ||
| 82 | + def local_body(x, counts, out): | ||
| 83 | + tid = pl.simt.linear_thread_idx() | ||
| 84 | + for j in pl.range(tid, BINS, threads): | ||
| 85 | + counts[0, j] = pl.simt.cast(0, I32) | ||
| 86 | + pl.simt.syncthreads() | ||
| 87 | + first = pl.simt.block_idx().x * threads + tid | ||
| 88 | + step = pl.simt.grid_dim().x * threads | ||
| 89 | + one = pl.simt.cast(1, I32) | ||
| 90 | + for i in pl.range(first, n, step): | ||
| 91 | + pl.simt.atomic_add(counts[0, x[i]], one) | ||
| 92 | + pl.simt.syncthreads() | ||
| 93 | + for j in pl.range(tid, BINS, threads): | ||
| 94 | + pl.simt.atomic_add(out[j], counts[0, j]) | ||
| 95 | + | ||
| 96 | + if local: | ||
| 97 | + | ||
| 98 | + @pl.jit(auto_mutex=False) | ||
| 99 | + def accumulate(x: pl.Tensor[[n], U8], out: pl.Tensor[[BINS], I32]): | ||
| 100 | + counts = pl.make_tile( | ||
| 101 | + pl.TileType( | ||
| 102 | + shape=[1, BINS], dtype=I32, target_memory=pl.MemorySpace.Vec | ||
| 103 | + ), | ||
| 104 | + addr=0, | ||
| 105 | + ) | ||
| 106 | + with pl.section_vector(): | ||
| 107 | + local_body[threads](x, counts, out) | ||
| 108 | + elif combine_runs: | ||
| 109 | + | ||
| 110 | + @pl.jit() | ||
| 111 | + def accumulate(x: pl.Tensor[[n], U8], out: pl.Tensor[[BINS], I32]): | ||
| 112 | + with pl.section_vector(): | ||
| 113 | + runs_body[threads](x, out) | ||
| 114 | + else: | ||
| 115 | + | ||
| 116 | + @pl.jit() | ||
| 117 | + def accumulate(x: pl.Tensor[[n], U8], out: pl.Tensor[[BINS], I32]): | ||
| 118 | + with pl.section_vector(): | ||
| 119 | + global_body[threads](x, out) | ||
| 120 | + | ||
| 121 | + return initialize, accumulate | ||
| 122 | + | ||
| 123 | + | ||
| 124 | +def run(x, out, *, workers=4, threads=256, local=True, combine_runs=False): | ||
| 125 | + """Overwrite every bin; Host reads only shape, dtype and layout metadata.""" | ||
| 126 | + if str(x.dtype) != "torch.uint8" or str(out.dtype) != "torch.int32": | ||
| 127 | + raise TypeError("require UINT8 input and INT32 output") | ||
| 128 | + if ( | ||
| 129 | + x.ndim != 1 | ||
| 130 | + or tuple(out.shape) != (BINS,) | ||
| 131 | + or not x.is_contiguous() | ||
| 132 | + or not out.is_contiguous() | ||
| 133 | + ): | ||
| 134 | + raise ValueError("require contiguous input[N] and output[256]") | ||
| 135 | + if type(workers) is not int or workers <= 0: | ||
| 136 | + raise ValueError("workers must be a positive legal Stream block count") | ||
| 137 | + initialize, accumulate = make_histogram( | ||
| 138 | + int(x.shape[0]), threads, local, combine_runs | ||
| 139 | + ) | ||
| 140 | + initialize[None, workers](out) | ||
| 141 | + if accumulate is not None: | ||
| 142 | + accumulate[None, workers](x, out) | ||
| @@ -0,0 +1,18 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""独立数学参考:每个字节值出现的次数,不复用设备分块顺序。""" | ||
| 10 | + | ||
| 11 | +import numpy as np | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def reference(x): | ||
| 15 | + values = np.asarray(x) | ||
| 16 | + if values.dtype != np.uint8 or values.ndim != 1 or values.size > 2**31 - 1: | ||
| 17 | + raise ValueError("require UINT8[N] with N <= INT32_MAX") | ||
| 18 | + return np.bincount(values, minlength=256).astype(np.int32) | ||
| @@ -0,0 +1,67 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""验证完整直方图:两阶段初始化顺序、局部屏障、尾部和空输入。 | ||
| 10 | + | ||
| 11 | +独立 bincount 判据为逐元素精确相等;每次更换输入并毒化旧输出,检查输入和两侧守卫。 | ||
| 12 | +直接 GM、线程内合并与 UB 聚合都必须通过。性能使用共享计时器另测,不作为默认 pytest 的阈值。 | ||
| 13 | +""" | ||
| 14 | + | ||
| 15 | +import numpy as np | ||
| 16 | +import pytest | ||
| 17 | +import torch | ||
| 18 | + | ||
| 19 | +from .kernel import run | ||
| 20 | +from .reference import reference | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +@pytest.mark.parametrize( | ||
| 24 | + "n,kind", | ||
| 25 | + [ | ||
| 26 | + (0, "random"), | ||
| 27 | + (1, "hot"), | ||
| 28 | + (257, "random"), | ||
| 29 | + (4099, "edge"), | ||
| 30 | + (65537, "hot"), | ||
| 31 | + (131101, "skewed"), | ||
| 32 | + (8197, "runs"), | ||
| 33 | + ], | ||
| 34 | +) | ||
| 35 | +@pytest.mark.parametrize( | ||
| 36 | + "local,combine_runs,workers,threads", | ||
| 37 | + [(False, False, 1, 128), (False, True, 3, 128), (True, False, 3, 256)], | ||
| 38 | +) | ||
| 39 | +def test_histogram(device, n, kind, local, combine_runs, workers, threads): | ||
| 40 | + rng = np.random.default_rng(74081 + n) | ||
| 41 | + raw = torch.full((384,), -123456789, dtype=torch.int32, device=device) | ||
| 42 | + out = raw[64:-64] | ||
| 43 | + for repeat in range(2): | ||
| 44 | + values = rng.integers(0, 256, n, dtype=np.uint8) | ||
| 45 | + if kind == "hot": | ||
| 46 | + values[:] = 0 if repeat == 0 else 255 | ||
| 47 | + elif kind == "edge": | ||
| 48 | + values[:] = np.where(np.arange(n) % 2, 0, 255) | ||
| 49 | + elif kind == "skewed": | ||
| 50 | + values[np.arange(n) % 8 != 0] = 127 + repeat | ||
| 51 | + elif kind == "runs": | ||
| 52 | + values[:] = (np.arange(n) // (3 * workers * threads) + repeat) % 256 | ||
| 53 | + x = torch.from_numpy(values).to(device) | ||
| 54 | + out.fill_(10000 + repeat) | ||
| 55 | + run( | ||
| 56 | + x, | ||
| 57 | + out, | ||
| 58 | + workers=workers, | ||
| 59 | + threads=threads, | ||
| 60 | + local=local, | ||
| 61 | + combine_runs=combine_runs, | ||
| 62 | + ) | ||
| 63 | + torch.npu.synchronize() | ||
| 64 | + np.testing.assert_array_equal(out.cpu().numpy(), reference(values)) | ||
| 65 | + np.testing.assert_array_equal(x.cpu().numpy(), values) | ||
| 66 | + assert torch.all(raw[:64].cpu() == -123456789) | ||
| 67 | + assert torch.all(raw[-64:].cpu() == -123456789) | ||
| @@ -0,0 +1,7 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| @@ -0,0 +1,135 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""写法:原始。SIMT 单元素预留与线程内批量 ticket 预留。 | ||
| 10 | + | ||
| 11 | +契约:连续 INT32 keys[N],0<=keys[i]<B,1<=B<=256,0<=N<=INT32_MAX。 | ||
| 12 | +counts[B] 和 tickets[N] 均覆盖旧内容,输入与两个输出互不重叠。 | ||
| 13 | +每个 key 的 tickets 是 0..counts[key]-1 的排列,不承诺输入顺序或跨线程顺序。 | ||
| 14 | +先以独立原生调用清零 counts,同一 Stream 后续预留;N=0 时只清零。 | ||
| 15 | +combine_runs=True 合并同一线程实际 grid-stride 遍历中的相同 key 连续段。 | ||
| 16 | +atomic_add 返回该段的起点,再回访段内位置写 base+rank;不需要线程私有数组。 | ||
| 17 | +每个元素的 ticket 语义仍被保留;不支持观察逐项中间状态或更强顺序的调用者。 | ||
| 18 | +接口依据 c46548e;目标 CANN 9.2.0 / Ascend950PR,数值验收见 test.py。 | ||
| 19 | +example-query: {"aliases":["SIMT ticket ranges","SIMT batched reservation"],"term_groups":[["simt","atomic"],["ticket","reservation","票据"]]} | ||
| 20 | +""" | ||
| 21 | + | ||
| 22 | +from functools import lru_cache | ||
| 23 | + | ||
| 24 | +import pypto_pro.language as pl | ||
| 25 | + | ||
| 26 | +I32 = pl.DT_INT32 | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +@lru_cache(None) | ||
| 30 | +def make_reservation(n, bins, threads=128, combine_runs=True): | ||
| 31 | + if ( | ||
| 32 | + not 0 <= n <= 2**31 - 1 | ||
| 33 | + or not 1 <= bins <= 256 | ||
| 34 | + or threads not in (64, 128, 256, 512) | ||
| 35 | + ): | ||
| 36 | + raise ValueError("require bounded N, 1<=B<=256 and threads 64/128/256/512") | ||
| 37 | + | ||
| 38 | + @pl.vector_function(mode="simt", max_threads=threads) | ||
| 39 | + def clear_body(counts): | ||
| 40 | + first = pl.simt.block_idx().x * threads + pl.simt.linear_thread_idx() | ||
| 41 | + step = pl.simt.grid_dim().x * threads | ||
| 42 | + for key in pl.range(first, bins, step): | ||
| 43 | + counts[key] = pl.simt.cast(0, I32) | ||
| 44 | + | ||
| 45 | + @pl.jit() | ||
| 46 | + def initialize(counts: pl.Tensor[[bins], I32]): | ||
| 47 | + with pl.section_vector(): | ||
| 48 | + clear_body[threads](counts) | ||
| 49 | + | ||
| 50 | + if n == 0: | ||
| 51 | + return initialize, None | ||
| 52 | + | ||
| 53 | + @pl.vector_function(mode="simt", max_threads=threads) | ||
| 54 | + def direct_body(keys, counts, tickets): | ||
| 55 | + first = pl.simt.block_idx().x * threads + pl.simt.linear_thread_idx() | ||
| 56 | + step = pl.simt.grid_dim().x * threads | ||
| 57 | + one = pl.simt.cast(1, I32) | ||
| 58 | + for i in pl.range(first, n, step): | ||
| 59 | + tickets[i] = pl.simt.atomic_add(counts[keys[i]], one) | ||
| 60 | + | ||
| 61 | + @pl.vector_function(mode="simt", max_threads=threads) | ||
| 62 | + def range_body(keys, counts, tickets): | ||
| 63 | + first = pl.simt.block_idx().x * threads + pl.simt.linear_thread_idx() | ||
| 64 | + step = pl.simt.grid_dim().x * threads | ||
| 65 | + one = pl.simt.cast(1, I32) | ||
| 66 | + if first < n: | ||
| 67 | + run_key = keys[first] | ||
| 68 | + run_start = first | ||
| 69 | + run_count = one | ||
| 70 | + for i in pl.range(first + step, n, step): | ||
| 71 | + key = keys[i] | ||
| 72 | + if key == run_key: | ||
| 73 | + run_count = run_count + one | ||
| 74 | + else: | ||
| 75 | + base = pl.simt.atomic_add(counts[run_key], run_count) | ||
| 76 | + pos = run_start | ||
| 77 | + ticket = base | ||
| 78 | + while pos < i: | ||
| 79 | + tickets[pos] = ticket | ||
| 80 | + pos = pos + step | ||
| 81 | + ticket = ticket + one | ||
| 82 | + run_key = key | ||
| 83 | + run_start = i | ||
| 84 | + run_count = one | ||
| 85 | + base = pl.simt.atomic_add(counts[run_key], run_count) | ||
| 86 | + pos = run_start | ||
| 87 | + ticket = base | ||
| 88 | + while pos < n: | ||
| 89 | + tickets[pos] = ticket | ||
| 90 | + pos = pos + step | ||
| 91 | + ticket = ticket + one | ||
| 92 | + | ||
| 93 | + if combine_runs: | ||
| 94 | + | ||
| 95 | + @pl.jit() | ||
| 96 | + def reserve( | ||
| 97 | + keys: pl.Tensor[[n], I32], | ||
| 98 | + counts: pl.Tensor[[bins], I32], | ||
| 99 | + tickets: pl.Tensor[[n], I32], | ||
| 100 | + ): | ||
| 101 | + with pl.section_vector(): | ||
| 102 | + range_body[threads](keys, counts, tickets) | ||
| 103 | + else: | ||
| 104 | + | ||
| 105 | + @pl.jit() | ||
| 106 | + def reserve( | ||
| 107 | + keys: pl.Tensor[[n], I32], | ||
| 108 | + counts: pl.Tensor[[bins], I32], | ||
| 109 | + tickets: pl.Tensor[[n], I32], | ||
| 110 | + ): | ||
| 111 | + with pl.section_vector(): | ||
| 112 | + direct_body[threads](keys, counts, tickets) | ||
| 113 | + | ||
| 114 | + return initialize, reserve | ||
| 115 | + | ||
| 116 | + | ||
| 117 | +def run(keys, counts, tickets, *, workers=4, threads=128, combine_runs=True): | ||
| 118 | + """Use metadata only on Host; every reservation remains a native SIMT update.""" | ||
| 119 | + if any(str(x.dtype) != "torch.int32" for x in (keys, counts, tickets)): | ||
| 120 | + raise TypeError("require INT32 input and outputs") | ||
| 121 | + if ( | ||
| 122 | + keys.ndim != 1 | ||
| 123 | + or counts.ndim != 1 | ||
| 124 | + or tuple(tickets.shape) != tuple(keys.shape) | ||
| 125 | + or not all(x.is_contiguous() for x in (keys, counts, tickets)) | ||
| 126 | + ): | ||
| 127 | + raise ValueError("require contiguous keys[N], counts[B] and tickets[N]") | ||
| 128 | + if type(workers) is not int or workers <= 0: | ||
| 129 | + raise ValueError("workers must be a positive legal Stream block count") | ||
| 130 | + initialize, reserve = make_reservation( | ||
| 131 | + keys.shape[0], counts.shape[0], threads, combine_runs | ||
| 132 | + ) | ||
| 133 | + initialize[None, workers](counts) | ||
| 134 | + if reserve is not None: | ||
| 135 | + reserve[None, workers](keys, counts, tickets) | ||
| @@ -0,0 +1,35 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Independent per-key counts and unordered ticket-set contract.""" | ||
| 10 | + | ||
| 11 | +import numpy as np | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def reference(keys, bins): | ||
| 15 | + keys = np.asarray(keys) | ||
| 16 | + if ( | ||
| 17 | + keys.dtype != np.int32 | ||
| 18 | + or keys.ndim != 1 | ||
| 19 | + or not 1 <= bins <= 256 | ||
| 20 | + or np.any(keys < 0) | ||
| 21 | + or np.any(keys >= bins) | ||
| 22 | + ): | ||
| 23 | + raise ValueError("require valid INT32 keys and 1<=B<=256") | ||
| 24 | + return np.bincount(keys, minlength=bins).astype(np.int32) | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def validate(keys, counts, tickets): | ||
| 28 | + expected = reference(keys, len(counts)) | ||
| 29 | + assert counts.dtype == tickets.dtype == np.int32 | ||
| 30 | + np.testing.assert_array_equal(counts, expected) | ||
| 31 | + assert tickets.shape == keys.shape | ||
| 32 | + for key, count in enumerate(expected): | ||
| 33 | + np.testing.assert_array_equal( | ||
| 34 | + np.sort(tickets[keys == key]), np.arange(count, dtype=np.int32) | ||
| 35 | + ) | ||
| @@ -0,0 +1,63 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""验证独立频数、逐 key 唯一 ticket、输出覆盖、输入不变和两侧守卫。""" | ||
| 10 | + | ||
| 11 | +import numpy as np | ||
| 12 | +import pytest | ||
| 13 | +import torch | ||
| 14 | + | ||
| 15 | +from .kernel import run | ||
| 16 | +from .reference import validate | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +@pytest.mark.parametrize( | ||
| 20 | + "n,bins,kind", | ||
| 21 | + [ | ||
| 22 | + (0, 7, "random"), | ||
| 23 | + (1, 1, "hot"), | ||
| 24 | + (259, 17, "random"), | ||
| 25 | + (8197, 31, "runs"), | ||
| 26 | + (65539, 17, "hot"), | ||
| 27 | + (131101, 63, "no_runs"), | ||
| 28 | + ], | ||
| 29 | +) | ||
| 30 | +@pytest.mark.parametrize( | ||
| 31 | + "combine_runs,workers,threads", [(False, 1, 128), (True, 3, 256)] | ||
| 32 | +) | ||
| 33 | +def test_ticket_reservation(device, n, bins, kind, combine_runs, workers, threads): | ||
| 34 | + rng = np.random.default_rng(90419 + n) | ||
| 35 | + raw_counts = torch.full((bins + 128,), -9876543, dtype=torch.int32, device=device) | ||
| 36 | + raw_tickets = torch.full((n + 128,), -9876543, dtype=torch.int32, device=device) | ||
| 37 | + counts, tickets = raw_counts[64:-64], raw_tickets[64:-64] | ||
| 38 | + for repeat in range(2): | ||
| 39 | + values = rng.integers(0, bins, n, dtype=np.int32) | ||
| 40 | + if kind == "hot": | ||
| 41 | + values[:] = bins - 1 if repeat == 0 else 0 | ||
| 42 | + elif kind == "runs": | ||
| 43 | + values[:] = (np.arange(n) // (3 * workers * threads) + repeat) % bins | ||
| 44 | + elif kind == "no_runs": | ||
| 45 | + values[:] = (np.arange(n) // (workers * threads) + repeat) % bins | ||
| 46 | + keys = torch.from_numpy(values).to(device) | ||
| 47 | + counts.fill_(313 + repeat) | ||
| 48 | + tickets.fill_(313 + repeat) | ||
| 49 | + run( | ||
| 50 | + keys, | ||
| 51 | + counts, | ||
| 52 | + tickets, | ||
| 53 | + workers=workers, | ||
| 54 | + threads=threads, | ||
| 55 | + combine_runs=combine_runs, | ||
| 56 | + ) | ||
| 57 | + torch.npu.synchronize() | ||
| 58 | + validate(values, counts.cpu().numpy(), tickets.cpu().numpy()) | ||
| 59 | + np.testing.assert_array_equal(keys.cpu().numpy(), values) | ||
| 60 | + for raw in (raw_counts, raw_tickets): | ||
| 61 | + assert (raw[:64].cpu() == -9876543).all() and ( | ||
| 62 | + raw[-64:].cpu() == -9876543 | ||
| 63 | + ).all() | ||
| @@ -0,0 +1,7 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| @@ -0,0 +1,93 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""写法:原始。SIMT 的连续 GM 读写与共享 UB 转置。 | ||
| 10 | + | ||
| 11 | +契约:非空连续 FP32[R,C] 输入、连续 FP32[C,R] 输出,二者不重叠。 | ||
| 12 | +每个外层 worker 认领互不重叠的 32x32 tile;SIMT 线程协作加载和转置写回。 | ||
| 13 | +GM 两侧按相邻线程的连续列访问,UB 的列读使用可选物理 padding。 | ||
| 14 | +padding 改变 UB 行跨度,不改变外部布局;默认 2 是实验配置,不是全平台最优规则。 | ||
| 15 | +共享 UB 用满足 Tile 行对齐的一维物理容器,显式元素偏移表示 32×pitch 布局。 | ||
| 16 | +每次 VF 调用的两个 block 屏障都位于线程控制流之外,尾线程也参与。 | ||
| 17 | +支持有限 FP32 位模式,包括 signed zero 与 subnormal;独立参考按元素转置。 | ||
| 18 | +接口核对源码 c46548e;数值验证安装源码 cbd3c4a 的相关实现相同,CANN 9.2.0 / Ascend950PR。 | ||
| 19 | +example-query: {"aliases":["SIMT shared UB transpose","SIMT tiled permutation"],"term_groups":[["transpose","rotation","permutation","转置","旋转"],["simt","ub","tile","tensor","layout","张量"]],"exclude":[{"term_groups":[["noncontiguous input","non-contiguous input","arbitrary positive row","arbitrary input strides","非连续输入"]],"reason":"This program requires contiguous input. Resolve example:algorithms/strided_transpose/kernel.py for the separate positive-stride physical-view contract."}]} | ||
| 20 | +""" | ||
| 21 | + | ||
| 22 | +from functools import lru_cache | ||
| 23 | + | ||
| 24 | +import pypto_pro.language as pl | ||
| 25 | + | ||
| 26 | +F32 = pl.DT_FP32 | ||
| 27 | +TILE = 32 | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +@lru_cache(None) | ||
| 31 | +def make_transpose(rows, cols, threads=256, padding=2): | ||
| 32 | + if ( | ||
| 33 | + rows <= 0 | ||
| 34 | + or cols <= 0 | ||
| 35 | + or threads not in (128, 256, 512) | ||
| 36 | + or padding not in (0, 1, 2, 4) | ||
| 37 | + ): | ||
| 38 | + raise ValueError( | ||
| 39 | + "require positive dimensions, threads 128/256/512 and padding 0/1/2/4" | ||
| 40 | + ) | ||
| 41 | + tile_cols = (cols + TILE - 1) // TILE | ||
| 42 | + tiles = ((rows + TILE - 1) // TILE) * tile_cols | ||
| 43 | + pitch = TILE + padding | ||
| 44 | + | ||
| 45 | + @pl.vector_function(mode="simt", max_threads=threads) | ||
| 46 | + def transpose_body(x, out, scratch, tile_id): | ||
| 47 | + tid = pl.simt.linear_thread_idx() | ||
| 48 | + row_base = (tile_id // tile_cols) * TILE | ||
| 49 | + col_base = (tile_id % tile_cols) * TILE | ||
| 50 | + for i in pl.range(tid, TILE * TILE, threads): | ||
| 51 | + r = i // TILE | ||
| 52 | + c = i % TILE | ||
| 53 | + if row_base + r < rows and col_base + c < cols: | ||
| 54 | + scratch[0, r * pitch + c] = x[row_base + r, col_base + c] | ||
| 55 | + else: | ||
| 56 | + scratch[0, r * pitch + c] = pl.simt.cast(0, F32) | ||
| 57 | + pl.simt.syncthreads() | ||
| 58 | + for i in pl.range(tid, TILE * TILE, threads): | ||
| 59 | + r = i // TILE | ||
| 60 | + c = i % TILE | ||
| 61 | + if col_base + r < cols and row_base + c < rows: | ||
| 62 | + out[col_base + r, row_base + c] = scratch[0, c * pitch + r] | ||
| 63 | + pl.simt.syncthreads() | ||
| 64 | + | ||
| 65 | + @pl.jit(auto_mutex=False) | ||
| 66 | + def kernel(x: pl.Tensor[[rows, cols], F32], out: pl.Tensor[[cols, rows], F32]): | ||
| 67 | + scratch = pl.make_tile( | ||
| 68 | + pl.TileType( | ||
| 69 | + shape=[1, TILE * pitch], dtype=F32, target_memory=pl.MemorySpace.Vec | ||
| 70 | + ), | ||
| 71 | + addr=0, | ||
| 72 | + ) | ||
| 73 | + with pl.section_vector(): | ||
| 74 | + for tile_id in pl.range(pl.get_block_idx(), tiles, pl.get_block_num()): | ||
| 75 | + transpose_body[threads](x, out, scratch, tile_id) | ||
| 76 | + | ||
| 77 | + return kernel | ||
| 78 | + | ||
| 79 | + | ||
| 80 | +def run(x, out, *, workers=4, threads=256, padding=2): | ||
| 81 | + """Write an ordinary contiguous transpose through native tile ownership.""" | ||
| 82 | + if str(x.dtype) != "torch.float32" or str(out.dtype) != "torch.float32": | ||
| 83 | + raise TypeError("require FP32 input/output") | ||
| 84 | + if ( | ||
| 85 | + x.ndim != 2 | ||
| 86 | + or tuple(out.shape) != (x.shape[1], x.shape[0]) | ||
| 87 | + or not x.is_contiguous() | ||
| 88 | + or not out.is_contiguous() | ||
| 89 | + ): | ||
| 90 | + raise ValueError("require contiguous input[R,C] and output[C,R]") | ||
| 91 | + if type(workers) is not int or workers <= 0: | ||
| 92 | + raise ValueError("workers must be a positive legal Stream block count") | ||
| 93 | + make_transpose(*x.shape, threads, padding)[None, workers](x, out) | ||
| @@ -0,0 +1,15 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""独立参考按数学轴交换,不复用 tile 坐标或线程映射。""" | ||
| 10 | + | ||
| 11 | +import numpy as np | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def reference(x): | ||
| 15 | + return np.asarray(x).T.copy() | ||
| @@ -0,0 +1,53 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""验证连续 GM 与共享 UB 转置:双屏障、tile 尾部、多 worker 和不同 UB 行跨度。 | ||
| 10 | + | ||
| 11 | +独立参考逐位比较,包含正负零、subnormal;重复调用更换输入并毒化输出。 | ||
| 12 | +输入和输出 storage 的前后守卫均检查,padding 的性能差异用共享计时器另测。 | ||
| 13 | +""" | ||
| 14 | + | ||
| 15 | +import numpy as np | ||
| 16 | +import pytest | ||
| 17 | +import torch | ||
| 18 | + | ||
| 19 | +from .kernel import run | ||
| 20 | +from .reference import reference | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +@pytest.mark.parametrize( | ||
| 24 | + "rows,cols", [(1, 1), (17, 33), (64, 96), (65, 97), (129, 257)] | ||
| 25 | +) | ||
| 26 | +@pytest.mark.parametrize("padding,workers,threads", [(0, 1, 128), (2, 3, 256)]) | ||
| 27 | +def test_transpose(device, rows, cols, padding, workers, threads): | ||
| 28 | + rng = np.random.default_rng(78101 + rows * cols) | ||
| 29 | + for repeat in range(2): | ||
| 30 | + bits = rng.integers(0, 0x7F000000, rows * cols, dtype=np.int32) | ||
| 31 | + bits[::3] |= np.int32(-2147483648) | ||
| 32 | + special = np.array([0, -2147483648, 1, -2147483647, 0x00800000], dtype=np.int32) | ||
| 33 | + bits[: min(bits.size, special.size)] = special[: min(bits.size, special.size)] | ||
| 34 | + values = bits.view(np.float32).reshape(rows, cols) | ||
| 35 | + source_raw = torch.full( | ||
| 36 | + (rows * cols + 128,), -777, dtype=torch.float32, device=device | ||
| 37 | + ) | ||
| 38 | + x = source_raw[64:-64].reshape(rows, cols) | ||
| 39 | + x.copy_(torch.from_numpy(values).to(device)) | ||
| 40 | + out_raw = torch.full_like(source_raw, -777) | ||
| 41 | + out = out_raw[64:-64].reshape(cols, rows) | ||
| 42 | + out.fill_(123 + repeat) | ||
| 43 | + run(x, out, workers=workers, threads=threads, padding=padding) | ||
| 44 | + torch.npu.synchronize() | ||
| 45 | + np.testing.assert_array_equal( | ||
| 46 | + out.cpu().numpy().view(np.int32), reference(values).view(np.int32) | ||
| 47 | + ) | ||
| 48 | + np.testing.assert_array_equal( | ||
| 49 | + x.cpu().numpy().view(np.int32), bits.reshape(rows, cols) | ||
| 50 | + ) | ||
| 51 | + for raw in (source_raw, out_raw): | ||
| 52 | + assert torch.all(raw[:64].cpu() == -777) | ||
| 53 | + assert torch.all(raw[-64:].cpu() == -777) | ||
| @@ -8,6 +8,8 @@ | |||
| 8 | 8 | ||
| 9 | """写法:原始。超出 UB 容量的一维 INT32 inclusive segmented scan。 | 9 | """写法:原始。超出 UB 容量的一维 INT32 inclusive segmented scan。 |
| 10 | 10 | ||
| 11 | +example-query: {"aliases": ["流式分段前缀和"]} | ||
| 12 | + | ||
| 11 | 契约:连续 x/heads/out[N],1<=N<=1048576,x 在[-4,4],heads 为0/1。 | 13 | 契约:连续 x/heads/out[N],1<=N<=1048576,x 在[-4,4],heads 为0/1。 |
| 12 | i=0或heads[i]=1时输出x[i],否则累加前一输出;输入保持不变,输出精确INT32。 | 14 | i=0或heads[i]=1时输出x[i],否则累加前一输出;输入保持不变,输出精确INT32。 |
| 13 | 三次原生调用分别扫描独立块、计算块摘要的前缀、补入每块的外部carry。 | 15 | 三次原生调用分别扫描独立块、计算块摘要的前缀、补入每块的外部carry。 |
| @@ -94,9 +94,8 @@ PadValue::Zero>` 也是 0。于是写成了「根因在 ISA 头的映射与硬 | |||
| 94 | 94 | ||
| 95 | 留下三样东西: | 95 | 留下三样东西: |
| 96 | 96 | ||
| 97 | -1. **`check.py` 的第五条规则** `auto-mutex-needs-tile-group`——`auto_mutex=True` 的 kernel | 97 | +1. `auto-mutex-needs-tile-group`: its hard findings and unresolved cases follow the |
| 98 | - 里出现裸 `pl.make_tile` 而没有 `make_tile_group`,静态就能判。文档纠正不了这类错误, | 98 | + [current checker scope](../../../../references/tooling/checks.md#scope-and-known-limits). |
| 99 | - 因为它的症状会伪装成别的东西(按 [skill constraints](../../../../SKILL.md#constraints-and-workspace-policy) 的判据,这该落在工具里)。 | ||
| 100 | 2. **`references/verification/board-runs.md` §五点十一**:UB 不是零初始化的,"数值不重要"这句话在你 | 99 | 2. **`references/verification/board-runs.md` §五点十一**:UB 不是零初始化的,"数值不重要"这句话在你 |
| 101 | 把数值打印出来的那一刻就不再成立。 | 100 | 把数值打印出来的那一刻就不再成立。 |
| 102 | 3. **`references/verification/evidence.md` #16**:四次一致的测量不构成可重复性证据——四次里如果每次 | 101 | 3. **`references/verification/evidence.md` #16**:四次一致的测量不构成可重复性证据——四次里如果每次 |
| @@ -0,0 +1,7 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| @@ -0,0 +1,77 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""写法:原始。Native device-side row selection followed by an MTE payload copy. | ||
| 10 | + | ||
| 11 | +Contract: contiguous, disjoint FP32 table[R,C], INT32 indices[N], FP32 out[N,C]; | ||
| 12 | +positive N/R, 1<=C<=4096, valid indices in [0,R), 32-byte aligned tensor bases. | ||
| 13 | +Host uses metadata only. The outer JIT scalar read selects a row on device; | ||
| 14 | +MTE copies its bytes through one padded Tile with automatic reuse ordering. | ||
| 15 | +No SIMT or arithmetic is needed for the payload. Short rows remain a separate | ||
| 16 | +performance control; this example does not promise a general gather speedup. | ||
| 17 | +API scope: source c46548e, CANN 9.2.0 / Ascend950PR; tests check current behavior. | ||
| 18 | +example-query: {"aliases":["device scalar indexed row copy","MTE indirect row payload"],"term_groups":[["indexed row","indirect row","整行间接搬运"],["copy","mte","搬运"]],"exclude":[{"term_groups":[["noncontiguous input","non-contiguous input","noncontiguous output","non-contiguous output","arbitrary input strides","arbitrary output strides","非连续输入","非连续输出","任意输入步长","任意输出步长"]],"reason":"This program requires contiguous FP32 input and output; arbitrary physical strides need a separately verified implementation."}]} | ||
| 19 | +""" | ||
| 20 | + | ||
| 21 | +from functools import lru_cache | ||
| 22 | + | ||
| 23 | +import pypto_pro.language as pl | ||
| 24 | + | ||
| 25 | +F32 = pl.DT_FP32 | ||
| 26 | +I32 = pl.DT_INT32 | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +@lru_cache(None) | ||
| 30 | +def make_copy(rows, columns, count): | ||
| 31 | + if rows <= 0 or count <= 0 or not 1 <= columns <= 4096: | ||
| 32 | + raise ValueError("require positive rows/count and 1<=columns<=4096") | ||
| 33 | + physical_columns = (columns + 7) // 8 * 8 | ||
| 34 | + | ||
| 35 | + @pl.jit(auto_mutex=True) | ||
| 36 | + def kernel( | ||
| 37 | + table: pl.Tensor[[rows, columns], F32], | ||
| 38 | + indices: pl.Tensor[[count], I32], | ||
| 39 | + out: pl.Tensor[[count, columns], F32], | ||
| 40 | + ): | ||
| 41 | + group = pl.make_tile_group( | ||
| 42 | + type=pl.TileType( | ||
| 43 | + shape=[1, physical_columns], dtype=F32, target_memory=pl.MemorySpace.Vec | ||
| 44 | + ), | ||
| 45 | + addrs=[0], | ||
| 46 | + mutex_ids=[0], | ||
| 47 | + ) | ||
| 48 | + with pl.section_vector(): | ||
| 49 | + for row in pl.range(pl.get_block_idx(), count, pl.get_block_num()): | ||
| 50 | + selected = indices[row] | ||
| 51 | + tile = group.next() | ||
| 52 | + pl.set_validshape(tile, [1, columns]) | ||
| 53 | + pl.load(tile, table, [selected, 0]) | ||
| 54 | + pl.store(out, tile, [row, 0]) | ||
| 55 | + | ||
| 56 | + return kernel | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def run(table, indices, out, *, workers=8): | ||
| 60 | + """Copy complete selected rows; callers supply valid indices and disjoint storage.""" | ||
| 61 | + if ( | ||
| 62 | + str(table.dtype) != "torch.float32" | ||
| 63 | + or str(indices.dtype) != "torch.int32" | ||
| 64 | + or str(out.dtype) != "torch.float32" | ||
| 65 | + ): | ||
| 66 | + raise TypeError("require FP32 table/output and INT32 indices") | ||
| 67 | + if ( | ||
| 68 | + table.ndim != 2 | ||
| 69 | + or indices.ndim != 1 | ||
| 70 | + or tuple(out.shape) != (indices.shape[0], table.shape[1]) | ||
| 71 | + ): | ||
| 72 | + raise ValueError("require table[R,C], indices[N] and out[N,C]") | ||
| 73 | + if not all(t.is_contiguous() for t in (table, indices, out)): | ||
| 74 | + raise ValueError("require contiguous tensors") | ||
| 75 | + if type(workers) is not int or workers <= 0: | ||
| 76 | + raise ValueError("workers must be a positive legal Stream block count") | ||
| 77 | + make_copy(*table.shape, indices.shape[0])[None, workers](table, indices, out) | ||
| @@ -0,0 +1,13 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Independent selection in the original FP32 storage units.""" | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +def reference(table, indices): | ||
| 13 | + return table[indices] | ||
| @@ -0,0 +1,74 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Bit-preserving MTE rows: special values, tails, guards and same-pointer updates.""" | ||
| 10 | + | ||
| 11 | +import numpy as np | ||
| 12 | +import pytest | ||
| 13 | +import torch | ||
| 14 | + | ||
| 15 | +from .kernel import run | ||
| 16 | +from .reference import reference | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +@pytest.mark.parametrize( | ||
| 20 | + "count,rows,columns", [(3, 7, 1), (19, 13, 17), (67, 23, 4096)] | ||
| 21 | +) | ||
| 22 | +@pytest.mark.parametrize("workers", [1, 8]) | ||
| 23 | +def test_indexed_rows(device, count, rows, columns, workers): | ||
| 24 | + rng = np.random.default_rng(40817 + columns) | ||
| 25 | + source_raw = torch.full( | ||
| 26 | + (rows * columns + 128,), -777, dtype=torch.float32, device=device | ||
| 27 | + ) | ||
| 28 | + index_raw = torch.full((count + 128,), -777, dtype=torch.int32, device=device) | ||
| 29 | + output_raw = torch.full( | ||
| 30 | + (count * columns + 128,), -777, dtype=torch.float32, device=device | ||
| 31 | + ) | ||
| 32 | + table = source_raw[64:-64].reshape(rows, columns) | ||
| 33 | + indices = index_raw[64:-64] | ||
| 34 | + out = output_raw[64:-64].reshape(count, columns) | ||
| 35 | + for repeat in range(2): | ||
| 36 | + bits = rng.integers(0, 0x7F000000, (rows, columns), dtype=np.int32) | ||
| 37 | + bits.flat[::3] |= np.int32(-2147483648) | ||
| 38 | + special = np.array( | ||
| 39 | + [ | ||
| 40 | + 0x00000000, | ||
| 41 | + 0x80000000, | ||
| 42 | + 0x00000001, | ||
| 43 | + 0x80000001, | ||
| 44 | + 0x7F800000, | ||
| 45 | + 0xFF800000, | ||
| 46 | + 0x7FC12345, | ||
| 47 | + 0xFFC54321, | ||
| 48 | + 0x7FA12345, | ||
| 49 | + 0x7F7FFFFF, | ||
| 50 | + 0xFF7FFFFF, | ||
| 51 | + ], | ||
| 52 | + dtype=np.uint32, | ||
| 53 | + ).view(np.int32) | ||
| 54 | + special[6] ^= np.int32(repeat) | ||
| 55 | + bits.flat[: min(bits.size, special.size)] = special[ | ||
| 56 | + : min(bits.size, special.size) | ||
| 57 | + ] | ||
| 58 | + selected = rng.integers(0, rows, count, dtype=np.int32) | ||
| 59 | + selected[:3] = [0, rows - 1, 0] | ||
| 60 | + values = bits.view(np.float32) | ||
| 61 | + table.copy_(torch.from_numpy(values).to(device)) | ||
| 62 | + indices.copy_(torch.from_numpy(selected).to(device)) | ||
| 63 | + out.fill_(123 + repeat) | ||
| 64 | + run(table, indices, out, workers=workers) | ||
| 65 | + torch.npu.synchronize() | ||
| 66 | + np.testing.assert_array_equal( | ||
| 67 | + out.cpu().numpy().view(np.int32), reference(values, selected).view(np.int32) | ||
| 68 | + ) | ||
| 69 | + np.testing.assert_array_equal(table.cpu().numpy().view(np.int32), bits) | ||
| 70 | + np.testing.assert_array_equal(indices.cpu().numpy(), selected) | ||
| 71 | + for raw in (source_raw, index_raw, output_raw): | ||
| 72 | + assert bool((raw[:64].cpu() == -777).all()) and bool( | ||
| 73 | + (raw[-64:].cpu() == -777).all() | ||
| 74 | + ) | ||
| @@ -0,0 +1,9 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Bundled PyPTO-Pro examples package.""" | ||
| @@ -0,0 +1,171 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""写法:混合。One-shot VF → UB NZ → L1 → Cube handover. | ||
| 10 | + | ||
| 11 | +Each AIV owns ROWS rows, with ROWS in {8, 16, 32}. DIRECT=0 converts an | ||
| 12 | +aligned ND backing to NZ with move; DIRECT=1 writes an exact ROWS+1 pitch | ||
| 13 | +with cursor-based VF stores. Both insert disjoint row regions into L1. | ||
| 14 | +Local group mutexes protect MTE2/V/MTE3 work. The explicit cross-core edge | ||
| 15 | +orders MTE3 production before the Cube MTE1 consumer; there is no slot reuse. | ||
| 16 | +No performance ordering between the two variants is assumed. | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +import pypto_pro.language as pl | ||
| 20 | +from pypto_pro.language import Vf as vf | ||
| 21 | +from pypto_pro.runtime.tilingkey import TilingKeyField | ||
| 22 | + | ||
| 23 | +COLS = 128 | ||
| 24 | +OUT_COLS = 16 | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +class HandoverKey: | ||
| 28 | + ROWS = TilingKeyField(bits=2, values=[8, 16, 32]) | ||
| 29 | + DIRECT = TilingKeyField(bits=1, values=[0, 1]) | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +@pl.vector_function | ||
| 33 | +def increment_nd(tile, rows: pl.DT_INT32): | ||
| 34 | + mask = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=pl.DT_FP16) | ||
| 35 | + one = vf.full(1.0, mask, dtype=pl.DT_FP16) | ||
| 36 | + for row in pl.range(rows): | ||
| 37 | + values = vf.load_align(tile, [row, 0]) | ||
| 38 | + result = vf.add(values, one, mask) | ||
| 39 | + vf.store_align(tile, result, mask, [row, 0]) | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +@pl.vector_function | ||
| 43 | +def increment_nz(src, dst, rows: pl.DT_INT32, pitch: pl.DT_INT32): | ||
| 44 | + mask = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=pl.DT_FP16) | ||
| 45 | + one = vf.full(1.0, mask, dtype=pl.DT_FP16) | ||
| 46 | + for row in pl.range(rows): | ||
| 47 | + values = vf.load_align(src, [row, 0]) | ||
| 48 | + result = vf.add(values, one, mask) | ||
| 49 | + vf.store_align( | ||
| 50 | + dst, | ||
| 51 | + result, | ||
| 52 | + mask, | ||
| 53 | + data_copy_mode=pl.DataCopyMode.DATA_BLOCK_COPY, | ||
| 54 | + block_stride=pitch, | ||
| 55 | + repeat_stride=1, | ||
| 56 | + post_update=True, | ||
| 57 | + ) | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +@pl.jit(arch="a5", auto_mutex=True, tiling_key=HandoverKey) | ||
| 61 | +def handover( | ||
| 62 | + x: pl.Tensor[[pl.DYNAMIC, COLS], pl.DT_FP16], | ||
| 63 | + rhs: pl.Tensor[[COLS, OUT_COLS], pl.DT_FP16], | ||
| 64 | + out: pl.Tensor[[pl.DYNAMIC, OUT_COLS], pl.DT_FP32], | ||
| 65 | +): | ||
| 66 | + shared = pl.make_tile_group( | ||
| 67 | + type=pl.TileType( | ||
| 68 | + shape=[2 * ROWS, COLS], # noqa: F821 - DSL tiling-key fields. | ||
| 69 | + dtype=pl.DT_FP16, | ||
| 70 | + target_memory=pl.MemorySpace.Mat, | ||
| 71 | + layout=pl.NZ, | ||
| 72 | + ), | ||
| 73 | + addrs=0, | ||
| 74 | + mutex_ids="auto", | ||
| 75 | + depth=1, | ||
| 76 | + ) | ||
| 77 | + with pl.section_vector(): | ||
| 78 | + physical_rows = (ROWS + 15) // 16 * 16 # noqa: F821 - DSL tiling-key fields. | ||
| 79 | + pitch = ROWS + 1 if DIRECT else physical_rows # noqa: F821 - DSL tiling-key fields. | ||
| 80 | + nd_group = pl.make_tile_group( | ||
| 81 | + type=pl.TileType( | ||
| 82 | + shape=[physical_rows, COLS], | ||
| 83 | + valid_shape=[ROWS, COLS], # noqa: F821 - DSL tiling-key fields. | ||
| 84 | + dtype=pl.DT_FP16, | ||
| 85 | + target_memory=pl.MemorySpace.Vec, | ||
| 86 | + layout=pl.ND, | ||
| 87 | + ), | ||
| 88 | + addrs=0, | ||
| 89 | + mutex_ids="auto", | ||
| 90 | + depth=1, | ||
| 91 | + ) | ||
| 92 | + nz_group = pl.make_tile_group( | ||
| 93 | + type=pl.TileType( | ||
| 94 | + shape=[pitch, COLS], | ||
| 95 | + valid_shape=[ROWS, COLS], # noqa: F821 - DSL tiling-key fields. | ||
| 96 | + dtype=pl.DT_FP16, | ||
| 97 | + target_memory=pl.MemorySpace.Vec, | ||
| 98 | + layout=pl.NZ, | ||
| 99 | + ), | ||
| 100 | + addrs=0x4000, | ||
| 101 | + mutex_ids="auto", | ||
| 102 | + depth=1, | ||
| 103 | + ) | ||
| 104 | + nd, nz = nd_group.current(), nz_group.current() | ||
| 105 | + row_offset = pl.get_subblock_idx() * ROWS # noqa: F821 - DSL tiling-key fields. | ||
| 106 | + pl.load(nd, x, [row_offset, 0]) | ||
| 107 | + if DIRECT: # noqa: F821 - DSL tiling-key fields. | ||
| 108 | + increment_nz(nd, nz, ROWS, pitch) # noqa: F821 - DSL tiling-key fields. | ||
| 109 | + else: | ||
| 110 | + increment_nd(nd, ROWS) # noqa: F821 - DSL tiling-key fields. | ||
| 111 | + pl.move(nz, nd) | ||
| 112 | + l1 = shared.current() | ||
| 113 | + pl.insert(l1, nz, [row_offset, 0]) | ||
| 114 | + pl.system.set_cross_core(pipe=pl.PipeType.MTE3, event_id=2) | ||
| 115 | + with pl.section_cube(): | ||
| 116 | + weights = pl.make_tile_group( | ||
| 117 | + type=pl.TileType( | ||
| 118 | + shape=[COLS, OUT_COLS], | ||
| 119 | + dtype=pl.DT_FP16, | ||
| 120 | + target_memory=pl.MemorySpace.Mat, | ||
| 121 | + layout=pl.NZ, | ||
| 122 | + ), | ||
| 123 | + addrs=0x8000, | ||
| 124 | + mutex_ids="auto", | ||
| 125 | + depth=1, | ||
| 126 | + ) | ||
| 127 | + left = pl.make_tile_group( | ||
| 128 | + type=pl.TileType( | ||
| 129 | + shape=[2 * ROWS, COLS], # noqa: F821 - DSL tiling-key fields. | ||
| 130 | + dtype=pl.DT_FP16, | ||
| 131 | + target_memory=pl.MemorySpace.Left, | ||
| 132 | + layout=pl.NZ, | ||
| 133 | + ), | ||
| 134 | + addrs=0, | ||
| 135 | + mutex_ids="auto", | ||
| 136 | + depth=1, | ||
| 137 | + ) | ||
| 138 | + right = pl.make_tile_group( | ||
| 139 | + type=pl.TileType( | ||
| 140 | + shape=[COLS, OUT_COLS], | ||
| 141 | + dtype=pl.DT_FP16, | ||
| 142 | + target_memory=pl.MemorySpace.Right, | ||
| 143 | + layout=pl.ZN, | ||
| 144 | + ), | ||
| 145 | + addrs=0, | ||
| 146 | + mutex_ids="auto", | ||
| 147 | + depth=1, | ||
| 148 | + ) | ||
| 149 | + accumulator = pl.make_tile_group( | ||
| 150 | + type=pl.TileType( | ||
| 151 | + shape=[2 * ROWS, OUT_COLS], # noqa: F821 - DSL tiling-key fields. | ||
| 152 | + dtype=pl.DT_FP32, | ||
| 153 | + target_memory=pl.MemorySpace.Acc, | ||
| 154 | + layout=pl.NZ, | ||
| 155 | + fractal=1024, | ||
| 156 | + ), | ||
| 157 | + addrs=0, | ||
| 158 | + mutex_ids="auto", | ||
| 159 | + depth=1, | ||
| 160 | + ) | ||
| 161 | + b = weights.current() | ||
| 162 | + pl.load(b, rhs, [0, 0]) | ||
| 163 | + pl.system.wait_cross_core( | ||
| 164 | + pipe=pl.PipeType.MTE1, | ||
| 165 | + event_id=2, | ||
| 166 | + sync_mode=pl.CrossCoreSyncMode.INTRA_BLOCK, | ||
| 167 | + ) | ||
| 168 | + a = shared.current() | ||
| 169 | + acc = accumulator.current() | ||
| 170 | + pl.gemm(acc, a, b, l0a=left, l0b=right, splitk=COLS) | ||
| 171 | + pl.store(out, acc, [0, 0]) | ||
| @@ -0,0 +1,18 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Independent CPU arithmetic for the VF increment and FP16 Cube operands.""" | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +def reference(x, rhs): | ||
| 13 | + import torch | ||
| 14 | + | ||
| 15 | + values = ( | ||
| 16 | + (x.detach().cpu().to(torch.float32) + 1).to(torch.float16).to(torch.float32) | ||
| 17 | + ) | ||
| 18 | + return values @ rhs.detach().cpu().to(torch.float32) | ||
| @@ -0,0 +1,50 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Consume both UB packing paths through Cube with exact quarter-valued inputs. | ||
| 10 | + | ||
| 11 | +Changed inputs, non-square geometry, both AIVs and output guards distinguish | ||
| 12 | +layout mistakes and stale handovers. These tests establish no timing result. | ||
| 13 | +""" | ||
| 14 | + | ||
| 15 | +import os | ||
| 16 | + | ||
| 17 | +import pytest | ||
| 18 | +import torch | ||
| 19 | +import torch_npu # noqa: F401 | ||
| 20 | + | ||
| 21 | +from .kernel import COLS, OUT_COLS, handover | ||
| 22 | +from .reference import reference | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +@pytest.mark.parametrize("rows", [8, 16, 32]) | ||
| 26 | +@pytest.mark.parametrize("direct", [0, 1]) | ||
| 27 | +def test_handover(rows, direct): | ||
| 28 | + device = f"npu:{int(os.environ.get('TILE_FWK_DEVICE_ID', 0))}" | ||
| 29 | + torch.npu.set_device(device) | ||
| 30 | + for seed in (0, 3): | ||
| 31 | + x_cpu = ( | ||
| 32 | + (torch.arange(2 * rows * COLS).reshape(2 * rows, COLS) + seed) % 31 - 15 | ||
| 33 | + ).half() / 4 | ||
| 34 | + rhs_cpu = ( | ||
| 35 | + (torch.arange(COLS * OUT_COLS).reshape(COLS, OUT_COLS) * 3 + seed) % 7 - 3 | ||
| 36 | + ).half() / 4 | ||
| 37 | + x, rhs = x_cpu.to(device), rhs_cpu.to(device) | ||
| 38 | + backing = torch.full( | ||
| 39 | + (2 * rows + 2, OUT_COLS), -12345.0, dtype=torch.float32, device=device | ||
| 40 | + ) | ||
| 41 | + out = backing[1:-1] | ||
| 42 | + handover[torch.npu.current_stream(), 1, {"ROWS": rows, "DIRECT": direct}]( | ||
| 43 | + x, rhs, out | ||
| 44 | + ) | ||
| 45 | + torch.npu.synchronize() | ||
| 46 | + torch.testing.assert_close(out.cpu(), reference(x_cpu, rhs_cpu), rtol=0, atol=0) | ||
| 47 | + assert torch.all(backing[0] == -12345.0).item() | ||
| 48 | + assert torch.all(backing[-1] == -12345.0).item() | ||
| 49 | + assert torch.equal(x.cpu(), x_cpu) | ||
| 50 | + assert torch.equal(rhs.cpu(), rhs_cpu) | ||
| @@ -140,7 +140,7 @@ def probe_scalar_gm_writes(out: pl.Tensor[[128], I32]): | |||
| 140 | 140 | ||
| 141 | 141 | ||
| 142 | # --------------------------------------------------------------------------- | 142 | # --------------------------------------------------------------------------- |
| 143 | -# 六、pto_assert:条件不成立就中止 | 143 | +# 6. pto_assert: logging and subsequent control flow |
| 144 | # --------------------------------------------------------------------------- | 144 | # --------------------------------------------------------------------------- |
| 145 | # | 145 | # |
| 146 | # **接口名是 `pl.pto_assert`,不是 `assert_` 也不是 `assert`**(`assert` 是 Python 关键字, | 146 | # **接口名是 `pl.pto_assert`,不是 `assert_` 也不是 `assert`**(`assert` 是 Python 关键字, |
| @@ -170,8 +170,8 @@ def _assert_failing_kernel(out: pl.Tensor[[1], I32], offset: pl.DT_INT32): | |||
| 170 | 设备日志打的是**条件的源码文本**:`Assertion failed: offset == 12345`,随后是格式化消息。 | 170 | 设备日志打的是**条件的源码文本**:`Assertion failed: offset == 12345`,随后是格式化消息。 |
| 171 | 每个核各打一份。 | 171 | 每个核各打一份。 |
| 172 | 172 | ||
| 173 | - `_api.py` 的 docstring 说 *"abort if condition is false"*,那句是错的;官方文档 | 173 | + The current assertion contract and installation boundaries belong to `references/api/support.md`. |
| 174 | - `pto_assert.md:20` 和框架自己的 ST 都写明只打日志、不中止。要真的停用 `pl.trap()`。 | 174 | + This probe writes only valid output addresses to observe continuation; it does not guard indexed access. |
| 175 | """ | 175 | """ |
| 176 | with pl.section_vector(): | 176 | with pl.section_vector(): |
| 177 | out[0] = 7 | 177 | out[0] = 7 |
| @@ -12,6 +12,8 @@ | |||
| 12 | KiB、Acc双槽合计64 KiB。B只读且在两个matmul间不被覆盖,tile-group IDs让auto_mutex看见全部真实读写。 | 12 | KiB、Acc双槽合计64 KiB。B只读且在两个matmul间不被覆盖,tile-group IDs让auto_mutex看见全部真实读写。 |
| 13 | 手写链仅用于gemm-desugar的“保留L0操作数”例外:reuse=True在循环前move B一次;False每次gemm都重新搬B。A搬运、两个matmul、drain和算术完全相同。生成代码中的B搬运次数是结构证据,数值测试或减 | 13 | 手写链仅用于gemm-desugar的“保留L0操作数”例外:reuse=True在循环前move B一次;False每次gemm都重新搬B。A搬运、两个matmul、drain和算术完全相同。生成代码中的B搬运次数是结构证据,数值测试或减 |
| 14 | 少一次move都不代表硬件加速。 | 14 | 少一次move都不代表硬件加速。 |
| 15 | + | ||
| 16 | +example-query: {"aliases":["L0 operand reuse","保留L0操作数"],"term_groups":[["L0B reuse","L0 operand reuse","retained L0B","retain L0B","复用L0B","保留L0B"]],"facets":{"source_dtype":["FP16"],"destination_dtype":["FP32"]}} | ||
| 15 | """ | 17 | """ |
| 16 | 18 | ||
| 17 | from functools import lru_cache | 19 | from functools import lru_cache |
| @@ -6,7 +6,7 @@ These restrictions are easy to work around, but each encounter costs a compilati | |||
| 6 | 6 | ||
| 7 | --- | 7 | --- |
| 8 | 8 | ||
| 9 | -## Type aliases cannot be used as annotations | 9 | +## Spell out complete Tensor annotations |
| 10 | 10 | ||
| 11 | ```python | 11 | ```python |
| 12 | T_A = pl.Tensor[[M, K], pl.DT_FP16] | 12 | T_A = pl.Tensor[[M, K], pl.DT_FP16] |
| @@ -15,7 +15,7 @@ T_A = pl.Tensor[[M, K], pl.DT_FP16] | |||
| 15 | def kernel(a: T_A): # InvalidType: Unsupported type annotation | 15 | def kernel(a: T_A): # InvalidType: Unsupported type annotation |
| 16 | ``` | 16 | ``` |
| 17 | 17 | ||
| 18 | -Annotations must spell out `pl.Tensor[[...], ...]` literally. **Module-level int constants can** appear in shapes (`[M, 2 * K]` works); the alias itself is what gets rejected. | 18 | +The selected parameter parser requires the complete `pl.Tensor[[...], ...]` form rather than a name holding that Tensor declaration. **Module-level int constants can** appear in shapes (`[M, 2 * K]` works). This does not reject aliases inside the Tensor's dtype position; [scalar annotations and dtype subexpressions](#annotate-scalar-parameters-directly-with-a-dtype) have different resolution paths. First establish that the selected callable reached this parser. |
| 19 | 19 | ||
| 20 | ## Inline helpers accept only positional arguments | 20 | ## Inline helpers accept only positional arguments |
| 21 | 21 | ||
| @@ -79,6 +79,7 @@ inner box cols (16), got remainder 8. Pad Cols to a multiple of 16. | |||
| 79 | 79 | ||
| 80 | When slicing an accumulator into strips by address, **round the last strip's width up to 16** rather than declaring the exact remaining column count. Extra columns outside the valid region do not affect the result: store reads the narrowed parent handle. | 80 | When slicing an accumulator into strips by address, **round the last strip's width up to 16** rather than declaring the exact remaining column count. Extra columns outside the valid region do not affect the result: store reads the narrowed parent handle. |
| 81 | 81 | ||
| 82 | +<!-- kernel-query: {"id":"jit-annotation-types","aliases":["jit-annotation-types","JIT scalar annotation","scalar parameter annotation"],"when":"The selected parser reports an unsupported or incomplete parameter annotation.","rules":["jit-scalar-dtype-alias","jit-annotation-type"]} --> | ||
| 82 | ## Annotate scalar parameters directly with a dtype | 83 | ## Annotate scalar parameters directly with a dtype |
| 83 | 84 | ||
| 84 | Use a concrete dtype for `@pl.jit` scalar parameters, such as `scale: pl.DT_FP32` or `count: pl.DT_INT64`. `pl.Scalar` is the DSL scalar value class; using it alone as a parameter annotation raises `Incomplete type annotation: pl.Scalar`. Do not change it to `pl.Scalar[...]` either. Tensor and Ptr parameters use complete declarations of `pl.Tensor[[shape], dtype]` and `pl.Ptr[dtype]`, respectively. | 85 | Use a concrete dtype for `@pl.jit` scalar parameters, such as `scale: pl.DT_FP32` or `count: pl.DT_INT64`. `pl.Scalar` is the DSL scalar value class; using it alone as a parameter annotation raises `Incomplete type annotation: pl.Scalar`. Do not change it to `pl.Scalar[...]` either. Tensor and Ptr parameters use complete declarations of `pl.Tensor[[shape], dtype]` and `pl.Ptr[dtype]`, respectively. |
| @@ -87,6 +88,17 @@ Distinguish the complete parameter annotation from its dtype subexpression: even | |||
| 87 | 88 | ||
| 88 | The official kernel parameter documentation (`pypto/docs/zh/guide/programming_guide/pro/development/kernel_function.md`) shows the dtype form. The installed parser's `_type_resolver.py::resolve_type` at behavior version `872df763f` agrees with actual parameter calls. Scalar values produced inside a kernel by `getval`, shape, or block APIs are a different use case and do not replace parameter declarations for caller-supplied scalars. | 89 | The official kernel parameter documentation (`pypto/docs/zh/guide/programming_guide/pro/development/kernel_function.md`) shows the dtype form. The installed parser's `_type_resolver.py::resolve_type` at behavior version `872df763f` agrees with actual parameter calls. Scalar values produced inside a kernel by `getval`, shape, or block APIs are a different use case and do not replace parameter declarations for caller-supplied scalars. |
| 89 | 90 | ||
| 91 | +<!-- kernel-query: {"id":"jit-entry-kind","aliases":["jit-entry-kind","jit-postponed-entry","native entry classification","postponed Tensor annotations","legacy JIT entry"],"symbols":["pl.jit"],"when":"Native capture rejects the imported entry's kind; inspect its observed callable type and annotation values.","rules":["native-entry-kind","jit-postponed-entry"]} --> | ||
| 92 | +## Check the imported entry before changing its layout | ||
| 93 | + | ||
| 94 | +`Expected a native @pl.jit Pro kernel` is an entry-classification boundary. Inspect the reported callable type, selected declaration and `string_annotations`; a host wrapper or legacy dispatch is not a native capture result. Native preflight preserves the source module's own future flags and reads fresh source bytes, so the inspection must have the same annotation semantics as ordinary Python loading. | ||
| 95 | + | ||
| 96 | +`declaration` identifies the selected callable's own code, while `wrapped_declaration`, when available, identifies its separately unwrapped function. Each available declaration binds its original file SHA. A wrapper's `__wrapped__` or copied annotations do not change which object was selected for capture. Native preflight reports this rejection as `entry_classification` with native parsing `not_established`; an entry-import or argument-binding failure must be resolved before a kernel-body parser or layout hypothesis. Plain output logs retain an unknown stage unless the caller supplies separate stage evidence. | ||
| 97 | + | ||
| 98 | +`jit-postponed-entry` brings this entry check forward when all supplied parameter annotations are strings and the selected recognizer cannot identify their Tensor/Ptr spellings. It is an advisory bound to the complete `_is_tile_kernel` source SHA256; changed or missing recognizers remain outside the check. Another recognized dtype parameter, eager annotation, wrapper or annotation rewrite has a different dispatch boundary. The check does not import the candidate or prove native parsing. | ||
| 99 | + | ||
| 100 | +On the selected `cbd3c4a778` frontend, CPU capture accepted eager Tensor annotations containing a dtype alias and accepted postponed Tensor annotations spelling `pl.DT_FP32` explicitly. Postponed Tensor annotations containing the alias instead produced a plain function rejected by native capture. Current JIT recognition (`pypto/python/pypto_pro/runtime/jit.py` in the matching source checkout) and a minimal paired probe establish this boundary; it is not an unconditional prohibition of `from __future__ import annotations` or of aliases inside Tensor/Ptr dtype positions. Inspect current installed behavior before choosing an eager annotation form or an explicit dtype spelling, then revalidate the unchanged numerical contract. A successful CPU capture is neither compilation nor numerical/performance evidence. | ||
| 101 | + | ||
| 90 | ## Bind `pl.gemm` operands to variables first | 102 | ## Bind `pl.gemm` operands to variables first |
| 91 | 103 | ||
| 92 | ``` | 104 | ``` |
| @@ -183,17 +195,7 @@ The first entry in the official `wait_cross_core.md` parameter table defines `pi | |||
| 183 | 195 | ||
| 184 | The [INT8/INT16 probe in Fixpipe §15](fixpipe.md#15-the-hf8-cell-neither-of-two-failures-was-an-hf8-problem) observed zeros for nonzero layouts, but its recorded conditions do not establish a general layout restriction. Check the supported conversion pair, loaded register arrangement and selected predicate bits before diagnosing unavailable lanes. | 196 | The [INT8/INT16 probe in Fixpipe §15](fixpipe.md#15-the-hf8-cell-neither-of-two-failures-was-an-hf8-problem) observed zeros for nonzero layouts, but its recorded conditions do not establish a general layout restriction. Check the supported conversion pair, loaded register arrangement and selected predicate bits before diagnosing unavailable lanes. |
| 185 | 197 | ||
| 186 | -For narrowed outputs, choose the store from its physical container map: [port packing](vf.md#distinguish-numerical-conversion-from-port-bit-packing-first) can emit dense ND output directly, while [de-interleave packing](vf.md#210-narrowing-astype-occupies-only-half-the-width-pair-two-chunks-and-de_interleave-before-storing) serves consumers needing a dense register. A valid layout selector alone does not establish a dense write. | 198 | +For narrowed outputs, choose the store from its [physical container map](vf.md#210-narrowing-fp32-to-fp16-choose-port-packing-or-a-dense-register): port packing can emit dense ND output directly, while de-interleave packing serves consumers needing a dense register. A valid layout selector alone does not establish a dense write. |
| 187 | - | ||
| 188 | -## Kernel definition modules cannot use `from __future__ import annotations` | ||
| 189 | - | ||
| 190 | -```python | ||
| 191 | -from __future__ import annotations # ✗ Turns every annotation into a string | ||
| 192 | -... | ||
| 193 | -kernel[None, 1](a, b, out) # TypeError: 'function' object is not subscriptable | ||
| 194 | -``` | ||
| 195 | - | ||
| 196 | -`pl.jit` identifies Tile kernels through **actual objects** in parameter annotations (`_is_tile_kernel`'s isinstance check). Once future annotations turn them into strings, jit **silently returns an ordinary function wrapper** through the legacy path; only bracket launch fails. The symptom and root cause are one layer apart; hardware evidence dated 2026-09-29. It is fine in test/bench files, but **not in modules defining `@pl.jit` kernels**. | ||
| 197 | 199 | ||
| 198 | ## Variable names inside `@pl.vector_function` have a single type environment; masks and data cannot share names | 200 | ## Variable names inside `@pl.vector_function` have a single type environment; masks and data cannot share names |
| 199 | 201 | ||
| @@ -315,6 +315,8 @@ The official documentation says: | |||
| 315 | 315 | ||
| 316 | A one-shot handover that writes once and reads once, outside a loop, needs only forward synchronization. | 316 | A one-shot handover that writes once and reads once, outside a loop, needs only forward synchronization. |
| 317 | 317 | ||
| 318 | +For a manually chosen one-slot Cube→Vector READY/FREE protocol, each participating AIV publishes one initial FREE credit, waits for READY per task and returns FREE only after its last use of that slot. If that last use is a GM store, release on MTE3 after the conditional store, including when the AIV's useful share is empty; a V-pipe release does not retire the store. Cube consumes both AIV FREE credits before overwriting the shared slot, publishes READY after FIX completes the transfer and drains the final FREE pair. For `T` tasks, each AIV contributes `T+1` FREE credits and consumes `T` READY credits. Check actual event mapping and emitted ordering on the target; this accounting describes this one-slot protocol, not arbitrary preload depths or the generated Layer B schedule. | ||
| 319 | + | ||
| 318 | For a hand-written protocol whose event state spans a whole-core MIX barrier, balanced dynamic set/wait counts do not by themselves establish the token's lifetime through `sync_all`. Before relying on that composition, probe its actual `seed -> first wave -> MIX barrier -> second wave` sequence on the matching target, retaining producer/consumer participation, empty-lane paths, slot reuse and final drain. Check bounded completion separately from numerical values, tail coverage and guards. A barrier-free primitive probe omits the boundary under investigation. | 320 | For a hand-written protocol whose event state spans a whole-core MIX barrier, balanced dynamic set/wait counts do not by themselves establish the token's lifetime through `sync_all`. Before relying on that composition, probe its actual `seed -> first wave -> MIX barrier -> second wave` sequence on the matching target, retaining producer/consumer participation, empty-lane paths, slot reuse and final drain. Check bounded completion separately from numerical values, tail coverage and guards. A barrier-free primitive probe omits the boundary under investigation. |
| 319 | 321 | ||
| 320 | This is a validation requirement for an unestablished composition, not a claim that the barrier resets events or that every such protocol is unsupported. B-layer transformed loops and the [drained pipeline followed by a MIX merge](#part--sync_all--part-two-phase-mega-kernel-board-evidence-2026-09-30) have their own lifetime argument; neither route proves a different C-layer protocol's event state survives across the barrier. Keep a verified ordered handover while the new protocol remains unresolved, and use the existing [device-fault isolation](../verification/board-runs.md#isolating-device-faults) rules for its probe. | 322 | This is a validation requirement for an unestablished composition, not a claim that the barrier resets events or that every such protocol is unsupported. B-layer transformed loops and the [drained pipeline followed by a MIX merge](#part--sync_all--part-two-phase-mega-kernel-board-evidence-2026-09-30) have their own lifetime argument; neither route proves a different C-layer protocol's event state survives across the barrier. Keep a verified ordered handover while the new protocol remains unresolved, and use the existing [device-fault isolation](../verification/board-runs.md#isolating-device-faults) rules for its probe. |
Rcannbot-skills/ops/pypto-pro-intent-understand/scripts/exit_criteria.py→cannbot-skills/ops/pypto-pro-kernel/scripts/exit_criteria.py+8-0
Rcannbot-skills/plugins-official/pypto-pro-op-orchestrator/tests/test_exit_criteria.py→cannbot-skills/ops/pypto-pro-kernel/scripts/tests/test_exit_criteria.py+1-2
Rcannbot-skills/ops/pypto-pro-intent-understand/scripts/test_validate_spec.py→cannbot-skills/ops/pypto-pro-kernel/scripts/tests/test_validate_spec.py+10-1
Rcannbot-skills/ops/pypto-pro-intent-understand/scripts/validate_spec.py→cannbot-skills/ops/pypto-pro-kernel/scripts/validate_spec.py+1-1