已合并
[feat] PyPTO Pro Agent 知识库与模版能力更新 #501
lim-jiunnbin创建于 8月17日
[feat] PyPTO Pro Agent 知识库与模版能力更新 #501
已合并
lim-jiunnbin创建于 8月17日
共 53 个文件变更+4326-1371
@@ -67,7 +67,7 @@ opencode
67| 验证与检视 | `pypto-op-verify`、`pypto-op-review`、`pypto-kernel-validate` | 算子功能验证、代码检视与产物校验(反作弊 + 精度 + 性能) |67| 验证与检视 | `pypto-op-verify`、`pypto-op-review`、`pypto-kernel-validate` | 算子功能验证、代码检视与产物校验(反作弊 + 精度 + 性能) |
68| 性能调优 | `pypto-op-perf-tune` | 算子性能采集、分析与自动调优 |68| 性能调优 | `pypto-op-perf-tune` | 算子性能采集、分析与自动调优 |
69| 监控与调试 | `pypto-op-monitor`、`pypto-general-debug` | 任务进度监控与通用问题诊断 |69| 监控与调试 | `pypto-op-monitor`、`pypto-general-debug` | 任务进度监控与通用问题诊断 |
70-| **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 精简流程的九项专属技能,含 CANN Bench 提交与评测 |70+| **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 精简流程的八项专属技能 |
71 71 
72**模型适配**(model/,共 3 个)72**模型适配**(model/,共 3 个)
73 73 
@@ -189,7 +189,7 @@ python scripts/derive_design_params.py \
189 189 
190当算子的数学形式是「带前导批次轴的 2D contraction」(前导若干 batch 轴 + 一次 matmul,如 `out[..., m, n] = Σ_k a[..., m, k] * w[k, n]`)时:190当算子的数学形式是「带前导批次轴的 2D contraction」(前导若干 batch 轴 + 一次 matmul,如 `out[..., m, n] = Σ_k a[..., m, k] * w[k, n]`)时:
191 191 
192-- 折叠前导 batch 轴让 `pypto.matmul` 保持 2D `[M,K]@[K,N]`。**优先在 kernel 内**按真实 shape 计算扁平偏移完成折叠;只有当输入已连续、host 侧 `reshape` 确认是纯 view(profile 中不出现 `aclnn*`)时,才可在 Layer K 做 reshape 并在输出侧还原。会 materialize 的 `.contiguous()` / dtype 转换属于被计入分数的 device 算子,见 [`pypto-pro-op-kb/constraints/wrapper-boundary.md`](../../pypto-pro-op-kb/constraints/wrapper-boundary.md)。192+- 折叠前导 batch 轴让 `pypto.matmul` 保持 2D `[M,K]@[K,N]`。**优先在 kernel 内**按真实 shape 计算扁平偏移完成折叠;只有当输入已连续、host 侧 `reshape` 确认是纯 view(profile 中不出现 `aclnn*`)时,才可在 Layer K 做 reshape 并在输出侧还原。会 materialize 的 `.contiguous()` / dtype 转换属于被计入分数的 device 算子,见 [`pypto-pro-op-kb/constraints/wrapper-boundary.md`](../pypto-pro-op-kb/constraints/wrapper-boundary.md)。
193- **不要**把另一个 operand `unsqueeze` 升到和输入一样的高 rank 去「凑维度」——那会逼出退化的 `[1, 1, ...]` 高 rank matmul 和多层嵌套动态 loop,得不偿失。193- **不要**把另一个 operand `unsqueeze` 升到和输入一样的高 rank 去「凑维度」——那会逼出退化的 `[1, 1, ...]` 高 rank matmul 和多层嵌套动态 loop,得不偿失。
194- 行主序连续张量折叠前导维是 no-copy view,输出 reshape 是其逆操作,语义可逆。194- 行主序连续张量折叠前导维是 no-copy view,输出 reshape 是其逆操作,语义可逆。
195 195 
@@ -141,7 +141,7 @@ export PTO_TILE_LIB_CODE_PATH=./pto_isa/pto-isa/
141 - **Layer J**(JIT 入口):`@pypto.frontend.jit`,纯类型签名 + `runtime_options`,body 一行委托 Layer I141 - **Layer J**(JIT 入口):`@pypto.frontend.jit`,纯类型签名 + `runtime_options`,body 一行委托 Layer I
142 - **Layer K**(host wrapper):仅 4 个职责(layout / 分配输出 / 单次调用 JIT / reshape 还原),**禁止 Python `for ... in range(...)` 循环驱动 kernel**(OL45)142 - **Layer K**(host wrapper):仅 4 个职责(layout / 分配输出 / 单次调用 JIT / reshape 还原),**禁止 Python `for ... in range(...)` 循环驱动 kernel**(OL45)
143 143 
144- > ⚠️ **host 端的 layout/reshape 是被计入分数的 device kernel**(`aclnn*Cast` / `*Transpose` / `*Slice` 等),CANN-Bench 计时覆盖整个提交入口。已连续张量的纯 view reshape 不产生 device 算子,可以保留;任何会 materialize 的整形(`.contiguous()` / dtype 转换 / transpose)应移入 kernel,无法移入时必须在设计文档中记录原因与实测代价。统一口径见 [`pypto-pro-op-kb/constraints/wrapper-boundary.md`](../../pypto-pro-op-kb/constraints/wrapper-boundary.md)。144+ > ⚠️ **host 端的 layout/reshape 会作为 device kernel 被计入耗时**(`aclnn*Cast` / `*Transpose` / `*Slice` 等),因为计时覆盖整个交付入口,而不只是 kernel 本身。已连续张量的纯 view reshape 不产生 device 算子,可以保留;任何会 materialize 的整形(`.contiguous()` / dtype 转换 / transpose)应移入 kernel,无法移入时必须在设计文档中记录原因与实测代价。统一口径见 [`pypto-pro-op-kb/constraints/wrapper-boundary.md`](../pypto-pro-op-kb/constraints/wrapper-boundary.md)。
145 145 
1464. 完成后停止;不要继续生成 M_{k+1} 或 test 文件。1464. 完成后停止;不要继续生成 M_{k+1} 或 test 文件。
147 147 
@@ -135,7 +135,7 @@ HANG_CONFIRMED 后,**跑一次 Step 2 的 `env_preflight.py`** 拿可用卡列
135上面的三段式由**超时 / 无响应**触发。但坏卡还有一条**不触发任何超时**的表现形式,135上面的三段式由**超时 / 无响应**触发。但坏卡还有一条**不触发任何超时**的表现形式,
136且更危险:**运行正常结束,干净地报出 `TOTAL 0/N passed`**。136且更危险:**运行正常结束,干净地报出 `TOTAL 0/N passed`**。
137 137 
138-这在现场发生过:一次完整评测跑完,代码生成阶段成功(数十个 kernel、模块正常 parse),随后全部 case "失败"。按"以 `passed` 为准"的规则,138+这在现场发生过:一次完整回归跑完,代码生成阶段成功(数十个 kernel、模块正常 parse),随后全部 case "失败"。按"以 `passed` 为准"的规则,
139这读起来就是灾难性回归,其预先登记的响应是 **revert 两个 commit**——而那两个 commit139这读起来就是灾难性回归,其预先登记的响应是 **revert 两个 commit**——而那两个 commit
140毫无问题,坏的是卡。140毫无问题,坏的是卡。
141 141 
@@ -33,7 +33,7 @@ description: 实现、调试并自验证 PyPTO-Pro 算子 kernel。用于 Stage
331. 一个交付文件只含一个 `@pl.jit` kernel,核心计算全部在该 kernel 内;wrapper 只启动一次 kernel,且启动不在 host 循环内。331. 一个交付文件只含一个 `@pl.jit` kernel,核心计算全部在该 kernel 内;wrapper 只启动一次 kernel,且启动不在 host 循环内。
342. 严格执行 DESIGN.md 已冻结的 Module 边界、API 序列、tile 属性/地址、循环、同步、尾块和 `vector_selection`。本轮功能或精度测试表明设计有误时返回 `design_violation`,不得在 Stage 4 静默改设计。342. 严格执行 DESIGN.md 已冻结的 Module 边界、API 序列、tile 属性/地址、循环、同步、尾块和 `vector_selection`。本轮功能或精度测试表明设计有误时返回 `design_violation`,不得在 Stage 4 静默改设计。
353. 轮转 tile 使用 `make_tile_group` + `auto_mutex`;`make_tile` 只用于不参与轮转的单次 scratch。不要在 `auto_mutex` 管理的 tile 上叠加手动 `sync_src`/`sync_dst`。353. 轮转 tile 使用 `make_tile_group` + `auto_mutex`;`make_tile` 只用于不参与轮转的单次 scratch。不要在 `auto_mutex` 管理的 tile 上叠加手动 `sync_src`/`sync_dst`。
36-4. wrapper 默认只做参数检查与 Python 形状推导、`torch.empty` 输出分配、一次 kernel 启动。完整边界、迁移方式和例外条件只以 [wrapper-boundary.md](../../pypto-pro-op-kb/constraints/wrapper-boundary.md) 为准。36+4. wrapper 默认只做参数检查与 Python 形状推导、`torch.empty` 输出分配、一次 kernel 启动。完整边界、迁移方式和例外条件只以 [wrapper-boundary.md](../pypto-pro-op-kb/constraints/wrapper-boundary.md) 为准。
375. 测试通过 wrapper 调用 kernel;不得删改 DESIGN.md §8 的 case 来迁就实现,也不得把核心计算移到测试或 host 代码。375. 测试通过 wrapper 调用 kernel;不得删改 DESIGN.md §8 的 case 来迁就实现,也不得把核心计算移到测试或 host 代码。
38 38 
39## 按需读取的资源39## 按需读取的资源
@@ -50,10 +50,10 @@ description: 实现、调试并自验证 PyPTO-Pro 算子 kernel。用于 Stage
50| [references/cv-matmul-direct-buffering.md](references/cv-matmul-direct-buffering.md) | Cube 累加器在同一 launch 内被 Vector epilogue 消费时的轮转缓冲与 `auto_mutex` 形态 | 实现 CV 直连 matmul 时 |50| [references/cv-matmul-direct-buffering.md](references/cv-matmul-direct-buffering.md) | Cube 累加器在同一 launch 内被 Vector epilogue 消费时的轮转缓冲与 `auto_mutex` 形态 | 实现 CV 直连 matmul 时 |
51| [templates/cv_matmul_direct_buffering.py.tmpl](templates/cv_matmul_direct_buffering.py.tmpl) | 上一行的可替换代码骨架 | 同上 |51| [templates/cv_matmul_direct_buffering.py.tmpl](templates/cv_matmul_direct_buffering.py.tmpl) | 上一行的可替换代码骨架 | 同上 |
52| [templates/fp32-chain-precision-fragments.py.tmpl](templates/fp32-chain-precision-fragments.py.tmpl) | fp32 链路的精度安全片段 | 需要与 CPU 参考逐位对齐时 |52| [templates/fp32-chain-precision-fragments.py.tmpl](templates/fp32-chain-precision-fragments.py.tmpl) | fp32 链路的精度安全片段 | 需要与 CPU 参考逐位对齐时 |
53-| [../../pypto-pro-op-kb/ROUTER.md](../../pypto-pro-op-kb/ROUTER.md) | 按任务选择一个补充约束、pattern 或 validated study kernel | API 文档与官方样例不足时 |53+| [../../pypto-pro-op-kb/ROUTER.md](../pypto-pro-op-kb/ROUTER.md) | 按任务选择一个补充约束、pattern 或 validated study kernel | API 文档与官方样例不足时 |
54| [scripts/list_idle_chip_ids.sh](scripts/list_idle_chip_ids.sh) | 查找空闲 NPU chip | 运行前按需执行 |54| [scripts/list_idle_chip_ids.sh](scripts/list_idle_chip_ids.sh) | 查找空闲 NPU chip | 运行前按需执行 |
55| [pypto-pro-op-perf-tune](../pypto-pro-op-perf-tune/SKILL.md) | wrapper 动态反作弊检查:只检查 profile 中的 device op,不评价性能 | 需要验证 wrapper 未绕过 kernel 时 |55| [pypto-pro-op-perf-tune](../pypto-pro-op-perf-tune/SKILL.md) | wrapper 动态反作弊检查:只检查 profile 中的 device op,不评价性能 | 需要验证 wrapper 未绕过 kernel 时 |
56-| [KB CONTRACT](../../pypto-pro-op-kb/CONTRACT.md) | KB 选择与使用格式的完整合同,唯一来源 | 写 `KB_SELECTION.json` / `KB_USAGE.json` 前 |56+| [KB CONTRACT](../pypto-pro-op-kb/CONTRACT.md) | KB 选择与使用格式的完整合同,唯一来源 | 写 `KB_SELECTION.json` / `KB_USAGE.json` 前 |
57 57 
58参考之间是互补关系:DESIGN.md 决定“实现什么”,纯 Vector 模板或 Cube 官方样例提供“如何写”的主要起点,`KB_SELECTION.json` 已选参考补充必须落实的 pattern 和约束;三者不得相互替代。模板和样例不是 API 或性能事实源,使用时仍须核对目标版本 API 文档;与 DESIGN.md 或已选 KB 冲突的参考片段直接弃用,只有上游合同本身无法同时落实时才按根因分流,Stage 4 不自行改合同。标为 conceptual 的片段不得直接复制成交付代码。58参考之间是互补关系:DESIGN.md 决定“实现什么”,纯 Vector 模板或 Cube 官方样例提供“如何写”的主要起点,`KB_SELECTION.json` 已选参考补充必须落实的 pattern 和约束;三者不得相互替代。模板和样例不是 API 或性能事实源,使用时仍须核对目标版本 API 文档;与 DESIGN.md 或已选 KB 冲突的参考片段直接弃用,只有上游合同本身无法同时落实时才按根因分流,Stage 4 不自行改合同。标为 conceptual 的片段不得直接复制成交付代码。
59 59 
@@ -112,7 +112,7 @@ L1 的逐 Module 交付只规定开发与验证顺序,不等于运行时整段
112 112 
113### 6. 编写 wrapper、测试和 KB 使用记录113### 6. 编写 wrapper、测试和 KB 使用记录
114 114 
115-入口命名是硬合同:L0 必须命名为 `<op>_wrapper`,L1 staged 入口必须命名为 `<op>_wrapper_module<suffix_k>`。wrapper 的签名与算子 schema 一致;L1 使用 `primary_inputs`,输出当前 Module 的结果。optional 参数若可被调用方省略,必须提供相应默认值。wrapper 只执行 [wrapper-boundary.md](../../pypto-pro-op-kb/constraints/wrapper-boundary.md) 允许的三类动作;只有 DESIGN.md 已冻结的逐项例外可原样实现,并在 `KB_USAGE.json` 中记录 `deviated` 和理由。115+入口命名是硬合同:L0 必须命名为 `<op>_wrapper`,L1 staged 入口必须命名为 `<op>_wrapper_module<suffix_k>`。wrapper 的签名与算子 schema 一致;L1 使用 `primary_inputs`,输出当前 Module 的结果。optional 参数若可被调用方省略,必须提供相应默认值。wrapper 只执行 [wrapper-boundary.md](../pypto-pro-op-kb/constraints/wrapper-boundary.md) 允许的三类动作;只有 DESIGN.md 已冻结的逐项例外可原样实现,并在 `KB_USAGE.json` 中记录 `deviated` 和理由。
116 116 
117TensorList(`is_list: true`)同样只能启动一次 kernel,且启动不得位于 host 循环内。参数展开、固定 arity、地址/shape 传递与 work-item 映射必须原样执行 DESIGN.md 及 `KB_SELECTION.json` 已选 TensorList pattern;Stage 4 不自行发明新的打包协议或改写支持范围。117TensorList(`is_list: true`)同样只能启动一次 kernel,且启动不得位于 host 循环内。参数展开、固定 arity、地址/shape 传递与 work-item 映射必须原样执行 DESIGN.md 及 `KB_SELECTION.json` 已选 TensorList pattern;Stage 4 不自行发明新的打包协议或改写支持范围。
118 118 
@@ -126,7 +126,7 @@ TensorList(`is_list: true`)同样只能启动一次 kernel,且启动不得
126- `precision_compare` 与 `<op>_golden_cpu` 是 dev-only;import 放在函数体内,保证交付单元仅含 test 与 NPU golden 时可安全导入。126- `precision_compare` 与 `<op>_golden_cpu` 是 dev-only;import 放在函数体内,保证交付单元仅含 test 与 NPU golden 时可安全导入。
127- L1 改为对比当前 `<op>_golden_stage<suffix_k>`;它同样属于 dev-only 依赖,必须在 `_assert_precision` 或测试函数体内 import,禁止顶层 import。127- L1 改为对比当前 `<op>_golden_stage<suffix_k>`;它同样属于 dev-only 依赖,必须在 `_assert_precision` 或测试函数体内 import,禁止顶层 import。
128 128 
129-读取 `KB_SELECTION.json` 中每个 `optional_patterns` 和 `required_constraints`,再按 [KB CONTRACT](../../pypto-pro-op-kb/CONTRACT.md) 生成 `KB_USAGE.json`。本阶段只声明选中参考如何落到真实文件和符号;不得引用未选路径,也不得写 `verified`。`deviated` 或 `not_applicable` 必须说明理由。写完用标准库 `json.load` 做格式预检,verifier 才负责最终裁决。129+读取 `KB_SELECTION.json` 中每个 `optional_patterns` 和 `required_constraints`,再按 [KB CONTRACT](../pypto-pro-op-kb/CONTRACT.md) 生成 `KB_USAGE.json`。本阶段只声明选中参考如何落到真实文件和符号;不得引用未选路径,也不得写 `verified`。`deviated` 或 `not_applicable` 必须说明理由。写完用标准库 `json.load` 做格式预检,verifier 才负责最终裁决。
130 130 
131若实现中发现必须使用未选参考,返回 `kb_selection_invalid` 请求回 Stage 1 更新选择;不得只在 `KB_USAGE.json` 中补路径。131若实现中发现必须使用未选参考,返回 `kb_selection_invalid` 请求回 Stage 1 更新选择;不得只在 `KB_USAGE.json` 中补路径。
132 132 
@@ -26,7 +26,7 @@ Apply the workflow policy in this order:
26 candidates: the reduce primitives are same-type and cannot widen, so a26 candidates: the reduce primitives are same-type and cannot widen, so a
27 narrow-dtype chain whose intermediates exceed the format's range has to be27 narrow-dtype chain whose intermediates exceed the format's range has to be
28 widened by the caller. See28 widened by the caller. See
29- [`pypto-pro-op-kb/constraints/precision.md`](../../../pypto-pro-op-kb/constraints/precision.md).29+ [`pypto-pro-op-kb/constraints/precision.md`](../../pypto-pro-op-kb/constraints/precision.md).
30 A faster candidate that returns `inf` is not a candidate.30 A faster candidate that returns `inf` is not a candidate.
312. **Follow `DESIGN.md §1`.** Implement its single frozen choice. Use tile312. **Follow `DESIGN.md §1`.** Implement its single frozen choice. Use tile
32 operations only when DESIGN cites an explicit selected-KB-template requirement.32 operations only when DESIGN cites an explicit selected-KB-template requirement.
@@ -89,7 +89,7 @@ Write the alternative out of the vector function instead:
89 straight-line and neither needs a condition. The empty range is genuinely89 straight-line and neither needs a condition. The empty range is genuinely
90 empty in pypto-pro: `pl.range(start, 0, step)` executing zero times is90 empty in pypto-pro: `pl.range(start, 0, step)` executing zero times is
91 measured directly in91 measured directly in
92- [`pypto-pro-op-kb/patterns/vec-tensorlist-fixed-arity.md`](../../../pypto-pro-op-kb/patterns/vec-tensorlist-fixed-arity.md).92+ [`pypto-pro-op-kb/patterns/vec-tensorlist-fixed-arity.md`](../../pypto-pro-op-kb/patterns/vec-tensorlist-fixed-arity.md).
93- **A zero-or-one-iteration loop replaces an `if`.** A loop bounded by93- **A zero-or-one-iteration loop replaces an `if`.** A loop bounded by
94 `min(n, 1)` runs its body only when `n > 0`, costs one loop set-up, and does94 `min(n, 1)` runs its body only when `n > 0`, costs one loop set-up, and does
95 not predicate the lanes.95 not predicate the lanes.
@@ -103,11 +103,11 @@ Write the alternative out of the vector function instead:
103## <a id="reviewable-examples"></a>Reviewable examples103## <a id="reviewable-examples"></a>Reviewable examples
104 104 
105- Tile-operation softmax:105- Tile-operation softmax:
106- [`pypto-pro-op-kb/examples/samples/softmax/softmax_impl.py`](../../../pypto-pro-op-kb/examples/samples/softmax/softmax_impl.py)106+ [`pypto-pro-op-kb/examples/samples/softmax/softmax_impl.py`](../../pypto-pro-op-kb/examples/samples/softmax/softmax_impl.py)
107- Vector-function softmax:107- Vector-function softmax:
108- [`pypto-pro-op-kb/examples/samples/vf_vs_tileop/vf_softmax_impl.py`](../../../pypto-pro-op-kb/examples/samples/vf_vs_tileop/vf_softmax_impl.py)108+ [`pypto-pro-op-kb/examples/samples/vf_vs_tileop/vf_softmax_impl.py`](../../pypto-pro-op-kb/examples/samples/vf_vs_tileop/vf_softmax_impl.py)
109- Other validated vector-function compositions:109- Other validated vector-function compositions:
110- [`pypto-pro-op-kb/examples/kernel-index.md`](../../../pypto-pro-op-kb/examples/kernel-index.md)110+ [`pypto-pro-op-kb/examples/kernel-index.md`](../../pypto-pro-op-kb/examples/kernel-index.md)
111 111 
112These examples establish API usage only for their recorded environment. They112These examples establish API usage only for their recorded environment. They
113are not proof that the same implementation level is fastest for another113are not proof that the same implementation level is fastest for another
@@ -34,29 +34,37 @@ always relative to the KB root:
34 34 
35Never record an absolute path or an installation-specific prefix.35Never record an absolute path or an installation-specific prefix.
36 36 
37-### Links into this KB are authored for the installed layout37+### Cross-package links use the sibling form, which resolves in both layouts
38 38 
39-The two roots above sit at different depths relative to a skill, and that difference is39+**The rule: write the path that is correct with the KB as a sibling of each skill**, i.e.
40-not reconcilable: installed, a skill lives at `$CONFIG_ROOT/skills/<skill>/` and reaches40+the `cannbot-skills/ops/` layout — `../pypto-pro-op-kb/…` from `<skill>/SKILL.md`,
41-the KB with `../../pypto-pro-op-kb/`; in a checkout it lives at41+`../../pypto-pro-op-kb/…` from `<skill>/references/`, and the mirror image for KB→skill
42-`cannbot-skills/ops/<skill>/` with the KB as a *sibling*, needing42+links.
43-`../pypto-pro-op-kb/`. One relative path cannot satisfy both.
44 43 
45-**Write the installed form.** That is the one agents actually follow. The accepted44+An earlier revision of this section said the opposite — that a separate "installed form"
46-consequence, decided deliberately rather than overlooked: those links do not resolve when45+(one `../` deeper) had to be written and would not resolve in a checkout. **That was
47-browsing the repository on the web or in an editor. Runtime is unaffected.46+wrong, and 17 links written to follow it were broken everywhere.** Skills are installed as
47+**symlinks** into `cannbot-skills/ops/`, so a `..` traversal out of an installed skill is
48+resolved by the filesystem *physically* — it lands back in `cannbot-skills/ops/`, where
49+the KB is a sibling. The sibling form is therefore correct under both a lexical resolver
50+in a checkout and the physical resolver at runtime; the deeper form is correct under
51+neither.
48 52 
49-Two things follow, and both have already been got wrong once:53+Measured over all 41 cross-package links: sibling form 41/41 resolve repo-relative and
54+41/41 resolve through the installed symlink tree.
50 55 
51-- **Do not "fix" a KB link that looks broken in a checkout.** Rewriting it to the56+Two consequences:
52- checkout-relative form breaks it for every installed agent. Verify against57+ 
53- `$CONFIG_ROOT` before changing any `../../pypto-pro-op-kb/` path.58+- **A cross-package link that does not resolve in a checkout is broken, not "authored for
54-- **Do not extend `check_kb_integrity.py`'s link check to skill or plugin Markdown.** It59+ the installed layout".** The previous instruction not to "fix" such links protected the
55- is KB-internal by design; a repo-relative scan there reports ~35 correct links as60+ defect it was written to prevent.
56- broken. Checking them would require resolving through the install layout.61+- **`check_kb_integrity.py` does traverse cross-package links** (`cross-package links
62+ resolve`). The old prohibition rested on the claim that a repo-relative scan reports
63+ correct links as broken; it does not — every failure it reports is a link that resolves
64+ nowhere.
57 65 
58Links *within* this KB are unaffected — the directory moves as a unit, so relative paths66Links *within* this KB are unaffected — the directory moves as a unit, so relative paths
59-between its own pages hold in either layout, and those are the ones the checker verifies.67+between its own pages hold in either layout.
60 68 
61The orchestrator's `agents/*.md` are a further special case: they install to69The orchestrator's `agents/*.md` are a further special case: they install to
62`$CONFIG_ROOT/agents/`, which bears no fixed relation to their repo path, so no single70`$CONFIG_ROOT/agents/`, which bears no fixed relation to their repo path, so no single
@@ -14,7 +14,8 @@ current decision.
14- Selector usage contract: [examples/README.md](examples/README.md)14- Selector usage contract: [examples/README.md](examples/README.md)
15- Validated implementation selector: [examples/kernel-index.md](examples/kernel-index.md)15- Validated implementation selector: [examples/kernel-index.md](examples/kernel-index.md)
16- Correctness-preserving decomposition: [references/decomposition-primitives.md](references/decomposition-primitives.md)16- Correctness-preserving decomposition: [references/decomposition-primitives.md](references/decomposition-primitives.md)
17-- Measurement workflow: [playbooks/benchmark-scoring.md](playbooks/benchmark-scoring.md)17+- Measurement workflow: [`pypto-pro-op-perf-tune` evidence protocol](../pypto-pro-op-perf-tune/references/evidence-protocol.md)
18+- Integrity checks: `check_kb_integrity.py`, with negative controls in [tests/test_check_kb_integrity.py](tests/test_check_kb_integrity.py) — every case there is a defect that once passed a full green run
18 19 
19## Retention gate20## Retention gate
20 21 
@@ -15,16 +15,18 @@ for signatures and platform-specific behavior.
15| Check dynamic tails | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/tail-validshape.md](constraints/tail-validshape.md) |15| Check dynamic tails | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/tail-validshape.md](constraints/tail-validshape.md) |
16| Select A5 constraints; use limits only after target detection | design/develop/perf skills | [constraints/arch-a5.md](constraints/arch-a5.md) |16| Select A5 constraints; use limits only after target detection | design/develop/perf skills | [constraints/arch-a5.md](constraints/arch-a5.md) |
17| Decide what may run on the host | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/wrapper-boundary.md](constraints/wrapper-boundary.md) |17| Decide what may run on the host | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/wrapper-boundary.md](constraints/wrapper-boundary.md) |
18-| Measure and tune a correct kernel | `pypto-pro-op-perf-tune` | [playbooks/benchmark-scoring.md](playbooks/benchmark-scoring.md) |18+| Measure and tune a correct kernel | `pypto-pro-op-perf-tune` | [`pypto-pro-op-perf-tune` evidence protocol](../pypto-pro-op-perf-tune/references/evidence-protocol.md) |
wangzheng97
wangzheng97wangzheng978月21日

[P1] 新增跨 Skill 链接没有统一的安装解析合同

问题:installer 把 KB 链到 $CONFIG_ROOT/pypto-pro-op-kb,把 skills 链到 $CONFIG_ROOT/skills/*。本 PR 新增的 KB→perf 链接按 checkout 物理布局书写,而 staged-matmul-ab-protocol.md 的反向链接按 installed-logical 布局书写。标准 OpenCode 安装虽然 health PASS,但 lexical resolver 只能解析后者,跟随 symlink 的 physical resolver 只能解析前者。

影响:不存在一种解析策略能让 evidence protocol、staged gate、checklist 和模板双向可达;安装器仍会报告成功,工作流直到加载必选门禁时才失败。

建议:固定一种 installed-root 解析规则,统一 KB→skill 和 skill→KB 的写法;在安装健康检查中按同一规则遍历全部跨边界链接,并覆盖非默认安装目录。

likedislike
19| Localise a numerical error | `pypto-pro-op-develop` | [playbooks/numerical-error-localisation.md](playbooks/numerical-error-localisation.md) |19| Localise a numerical error | `pypto-pro-op-develop` | [playbooks/numerical-error-localisation.md](playbooks/numerical-error-localisation.md) |
20| Quantize per row with a scale that is also an output | `pypto-pro-op-design` | [patterns/vec-per-token-dynamic-quant.md](patterns/vec-per-token-dynamic-quant.md) |20| Quantize per row with a scale that is also an output | `pypto-pro-op-design` | [patterns/vec-per-token-dynamic-quant.md](patterns/vec-per-token-dynamic-quant.md) |
21+| Feed an integer Cube contraction directly into a floating-point epilogue | `pypto-pro-op-design` / `pypto-pro-op-develop` | [patterns/cv-quant-matmul-direct-epilogue.md](patterns/cv-quant-matmul-direct-epilogue.md) |
22+| Changing a staged multi-phase Cube matmul and need target-version precision/performance gates before trusting an alternative | `pypto-pro-op-develop` / `pypto-pro-op-perf-tune` | [references/staged-cube-matmul-gates.md](references/staged-cube-matmul-gates.md) |
23+| Choosing or varying a kernel's per-launch `block_dim` / core count | `pypto-pro-op-develop` / `pypto-pro-op-perf-tune` | [references/pypto-pro-launch-block-dim.md](references/pypto-pro-launch-block-dim.md) |
21| Hit a framework limit, or debug something that makes no sense | any | [references/pypto-pro-framework-findings.md](references/pypto-pro-framework-findings.md) |24| Hit a framework limit, or debug something that makes no sense | any | [references/pypto-pro-framework-findings.md](references/pypto-pro-framework-findings.md) |
22| An API looks unsupported, or a correct-looking call returns stale/wrong data | any | [references/pypto-pro-dsl-limitations-a5.md](references/pypto-pro-dsl-limitations-a5.md) — severity-ordered, silent failures first |25| An API looks unsupported, or a correct-looking call returns stale/wrong data | any | [references/pypto-pro-dsl-limitations-a5.md](references/pypto-pro-dsl-limitations-a5.md) — severity-ordered, silent failures first |
23| An investigation keeps failing to converge, or you are about to trust a measurement | any | [references/investigation-discipline.md](references/investigation-discipline.md) |26| An investigation keeps failing to converge, or you are about to trust a measurement | any | [references/investigation-discipline.md](references/investigation-discipline.md) |
24-| A whole run failed at once (0/N), or a change "did nothing", or a number reproduces suspiciously well | any | [playbooks/benchmark-scoring.md](playbooks/benchmark-scoring.md) § traps, then `pypto-pro-environment-check` |27+| A whole run failed at once (0/N), or a change "did nothing", or a number reproduces suspiciously well | any | [references/investigation-discipline.md](references/investigation-discipline.md) §2, §13, then `pypto-pro-environment-check` |
25| Several agents are working in parallel on one shared record, or you are merging their branches | any | [references/investigation-discipline.md](references/investigation-discipline.md) §10 |28| Several agents are working in parallel on one shared record, or you are merging their branches | any | [references/investigation-discipline.md](references/investigation-discipline.md) §10 |
26| Map a Chinese/English hardware, pipe, tiling, or layout term to its meaning | any | [references/terminology.md](references/terminology.md) |29| Map a Chinese/English hardware, pipe, tiling, or layout term to its meaning | any | [references/terminology.md](references/terminology.md) |
27-| A page carries a cross-DSL claim and you need its provenance, or you are about to re-derive something a sibling DSL already knew | any | [references/easyasc-port-ledger.md](references/easyasc-port-ledger.md) — provenance record, not a selected pattern or constraint |
28 30 
29Load [constraints/arch-a5.md](constraints/arch-a5.md) when runtime/build selects A5 or when31Load [constraints/arch-a5.md](constraints/arch-a5.md) when runtime/build selects A5 or when
30the workflow default A5 applies; do not use its numerical limits until the exact device and source are confirmed.32the workflow default A5 applies; do not use its numerical limits until the exact device and source are confirmed.
@@ -150,22 +150,19 @@ def _links_from(path: Path) -> list[tuple[str, Path]]:
150def check_links() -> list[str]:150def check_links() -> list[str]:
151 """Resolve relative links, KB-internal only.151 """Resolve relative links, KB-internal only.
152 152 
153- **Do not widen this to skill or plugin Markdown.** Links from153+ Cross-package links are checked too, by `check_cross_package_links` -- not here.
154- ``cannbot-skills/ops/<skill>/`` and from the orchestrator's ``agents/`` into this KB
155- are authored against the *installed* layout, not the repo: ``init.sh`` symlinks this
156- directory to the config root (``$CANNBOT_DIR/pypto-pro-op-kb``), so a skill reaches it
157- with ``../../pypto-pro-op-kb/`` once installed but would need ``../pypto-pro-op-kb/``
158- in a checkout. Those two cannot both be satisfied by one relative path, and the
159- installed form is the one that has to work.
160 154 
161- A repo-relative scan over that Markdown therefore reports ~35 correct links as broken.155+ This docstring used to say they must **not** be checked, on the reasoning that a skill
162- That is an accepted tradeoff, decided deliberately: KB links do not resolve when156+ reaches the KB with ``../../pypto-pro-op-kb/`` once installed but ``../pypto-pro-op-kb/``
163- browsing the repo on the web or in an editor. Runtime is unaffected. If this ever157+ in a checkout, so a repo-relative scan would report ~35 correct links as broken. That
164- needs checking, the checker has to resolve through the install layout -- widening the158+ was wrong on the facts: skills install as **symlinks** into ``cannbot-skills/ops/``, so
165- glob is not the fix, it just manufactures false positives.159+ a ``..`` traversal out of an installed skill resolves physically back to the KB's
160+ siblings -- the same place a checkout puts it. The sibling form is correct under both
161+ resolvers, and every link the widened scan reported was genuinely broken. See
162+ `CONTRACT.md`.
166 163 
167- KB-internal links are safe to check because the whole directory moves as a unit, so164+ KB-internal links are safe to check for the separate reason that the directory moves as
168- relative paths between its own pages hold in either layout.165+ a unit, so relative paths between its own pages hold in either layout.
169 """166 """
170 errors: list[str] = []167 errors: list[str] = []
171 for path in _kb_files():168 for path in _kb_files():
@@ -459,13 +456,22 @@ def _citation_resolution_result(
459) -> str | None:456) -> str | None:
460 present, absent = refs457 present, absent = refs
461 parts = _expand(citation)458 parts = _expand(citation)
462- on_disk = any(((page.parent / part) if part.startswith("..") else (REPO_ROOT / part)).exists() for part in parts)459+ # `all`, not `any`. A brace citation names several files and is evidence only for
460+ # what it names; under `any` one present member vouched for every absent one. This
461+ # was fixed in `check_reference_artifact_citations` and missed here, so the hole
462+ # stayed open on the path that guards `validated` rows -- the stronger claim.
463+ on_disk = all(((page.parent / part) if part.startswith("..") else (REPO_ROOT / part)).exists() for part in parts)
463 if on_disk or (present and all(any(_git_has(ref, part) for ref in present) for part in parts)):464 if on_disk or (present and all(any(_git_has(ref, part) for ref in present) for part in parts)):
464 return None465 return None
465 if absent and not present:466 if absent and not present:
466- # Preserve the existing best-effort behaviour for shallow clones: an unfetched467+ # Cannot be settled locally: a named ref may be unfetched (shallow clone) or may
467- # branch cannot be verified locally, but it is not reported as a broken citation.468+ # never have existed. Returning None passed both, so a fabricated branch name
468- return None469+ # plus a path that exists nowhere produced a green run. Report it as SKIP --
470+ # inconclusive, not verified -- which `main` prints as SKIP rather than ok.
471+ return (
472+ f"SKIP: pattern-index.md:{lineno} ({name}) cites {citation!r} against ref(s) {absent} that "
473+ f"are not present locally; fetch them to verify, or the citation is unchecked"
474+ )
469 hint = (475 hint = (
470 f"; it names branch(es) {present} but the path is not in them"476 f"; it names branch(es) {present} but the path is not in them"
471 if present477 if present
@@ -481,8 +487,7 @@ def check_pattern_validated_claims_cite_evidence() -> list[str]:
481 487 
482 `pattern-index.md` defines the status: "validated skeleton: the page links to a488 `pattern-index.md` defines the status: "validated skeleton: the page links to a
483 retained runnable implementation". Enforced only for `kernel-index.md` once, so a489 retained runnable implementation". Enforced only for `kernel-index.md` once, so a
484- pattern could claim validation and cite nothing -- and one did, while the operator490+ pattern could claim validation and cite nothing -- and one did.
485- behind it passed 14 of 20 cases.
486 491 
487 This repo splits the knowledge base from the operator trees that validate it, so an492 This repo splits the knowledge base from the operator trees that validate it, so an
488 artifact may legitimately live on another branch. That is resolved by **looking**:493 artifact may legitimately live on another branch. That is resolved by **looking**:
@@ -735,6 +740,14 @@ def stamp_validation_hashes() -> int:
735 Run this only after a sample has actually been re-validated -- stamping is what740 Run this only after a sample has actually been re-validated -- stamping is what
736 records "this exact code is what produced the result above", so stamping unverified741 records "this exact code is what produced the result above", so stamping unverified
737 code launders it into looking verified.742 code launders it into looking verified.
743+ 
744+ One narrower case is permitted and must be **written into the sample's header**: a
745+ text-only edit (comment or docstring) that provably leaves the executable code
746+ identical -- compare the parsed AST with docstrings stripped, before and after. The
747+ record still describes the same computation, but the stamp then asserts "semantically
748+ the same code", not "just re-validated", and a reader deciding whether to trust the
749+ number needs to know which of the two it is. Anything touching executable code
750+ requires a real re-run; there is no AST argument for it.
738 """751 """
739 changed = 0752 changed = 0
740 for sample in _validated_sample_paths():753 for sample in _validated_sample_paths():
@@ -819,6 +832,85 @@ def check_skill_absolute_paths() -> list[str]:
819 return _absolute_path_errors(paths)832 return _absolute_path_errors(paths)
820 833 
821 834 
835+_CROSS_PACKAGE_LINK = re.compile(r"\[[^\]]*\]\(((?:\.\./)+pypto-[^)]+)\)")
836+ 
837+ 
838+_REPORT_ENTRY = re.compile(r"^### (\d+(?:\.\d+)?\..*)$", re.M)
839+ 
840+ 
841+def check_report_copies_agree() -> list[str]:
842+ """The KB's A5 limitations page and Part I of the consolidated report must agree.
843+ 
844+ They are two copies of the same entries for two audiences: the KB page is routed to
845+ agents, the `docs/` report goes upstream. Nothing kept them in step, and they drifted
846+ exactly as predicted -- one copy called a defect `unexplained` while the other had
847+ already located it, and an entry title said "evaluation server" on one side and
848+ "deployed runtime" on the other. Both were found by review, not by this checker.
849+ 
850+ Entry titles are compared, not prose: the titles carry the entry number and the claim,
851+ so a renumber, a dropped entry or a reworded verdict all show up, while ordinary
852+ editorial differences between the two framings do not.
853+ """
854+ kb_report = KB_ROOT / "references" / "pypto-pro-dsl-limitations-a5.md"
855+ docs_report = REPO_ROOT / "docs" / "pypto-pro-dsl-limitations.md"
856+ if not (kb_report.is_file() and docs_report.is_file()):
857+ return ["SKIP: one of the two report copies is absent"]
858+ docs = _text(docs_report)
859+ if "# Part I" not in docs or "# Part II" not in docs:
860+ return ["SKIP: the consolidated report has no Part I span to compare"]
861+ part_one_start = docs.index("# Part I")
862+ part_one_end = docs.index("# Part II")
863+ part_one = docs[part_one_start:part_one_end]
864+ in_docs = {m.group(1).strip() for m in _REPORT_ENTRY.finditer(part_one)}
865+ in_kb = {m.group(1).strip() for m in _REPORT_ENTRY.finditer(_text(kb_report))}
866+ errors = [
867+ f"{docs_report.relative_to(REPO_ROOT)} Part I has an entry the KB copy lacks: {title!r}"
868+ for title in sorted(in_docs - in_kb)
869+ ]
870+ errors += [
871+ f"{kb_report.relative_to(REPO_ROOT)} has an entry Part I lacks: {title!r}"
872+ for title in sorted(in_kb - in_docs)
873+ ]
874+ return errors
875+ 
876+ 
877+def check_cross_package_links() -> list[str]:
878+ """Every link that leaves its own package must resolve.
879+ 
880+ These are the links between a skill and this KB, in both directions. They were
881+ excluded from checking on the theory that they are "authored for the installed
882+ layout" and only look broken in a checkout. They are not: skills install as
883+ **symlinks** into `cannbot-skills/ops/`, so a `..` traversal out of an installed
884+ skill is resolved physically and lands back among its siblings -- the same place a
885+ checkout puts it. The sibling form is correct under both resolvers, the deeper
886+ "installed" form under neither, and 17 links written to the latter resolved nowhere
887+ while this check did not exist to say so.
888+ 
889+ Scoped to `ops/pypto-*`, matching `check_skill_absolute_paths`.
890+ """
891+ ops_root = KB_ROOT.parent
892+ if not ops_root.is_dir():
893+ return ["SKIP: no ops/ root to scan"]
894+ errors: list[str] = []
895+ seen = 0
896+ for md in sorted(ops_root.glob("pypto-*/**/*.md")):
897+ text = _text(md)
898+ for m in _CROSS_PACKAGE_LINK.finditer(text):
899+ rel = m.group(1)
900+ seen += 1
901+ if (md.parent / rel).exists():
902+ continue
903+ lineno = text[: m.start()].count("\n") + 1
904+ errors.append(
905+ f"{md.relative_to(REPO_ROOT)}:{lineno} links out of its package to "
906+ f"{rel!r}, which resolves nowhere; use the sibling form "
907+ f"(see CONTRACT.md)"
908+ )
909+ if not seen:
910+ return ["SKIP: no cross-package links found"]
911+ return errors
912+ 
913+ 
822def check_tool_absolute_paths() -> list[str]:914def check_tool_absolute_paths() -> list[str]:
823 """``tools/`` must not carry machine-specific paths either.915 """``tools/`` must not carry machine-specific paths either.
824 916 
@@ -917,6 +1009,279 @@ def _module_constants(path: Path) -> dict:
917 return {k: (list(v) if isinstance(v, tuple) else v) for k, v in out.items()}1009 return {k: (list(v) if isinstance(v, tuple) else v) for k, v in out.items()}
918 1010 
919 1011 
1012+_DOCS_ROOT = REPO_ROOT / "docs"
1013+_ARTIFACT_CITE = re.compile(r"`((?:custom|tools)/[\w./{},-]+)`")
1014+# A markdown link to another page. The `§N` it carries may sit **inside** the link text
1015+# (`[ROUTER §99](../ROUTER.md)`) or after it (`[ROUTER](../ROUTER.md) §99`), and there may
1016+# be more than one (`§1, §99`). The first version of this matched only the trailing shape
1017+# and only the first number, so two of the three ways a citation is actually written went
1018+# unchecked -- a gap an audit found, not a control.
1019+_SECTION_LINK = re.compile(r"\[([^\]]*)\]\(([^)#]+?\.md)(?:#[^)]*)?\)")
1020+_SECTION_NUM = re.compile(r"§(\d+(?:\.\d+)?)")
1021+_PART_HEADING = re.compile(r"^# Part ([IVX]+)\b", re.M)
1022+# A bare `entry N` is only ambiguous when the reader has to guess which Part it
1023+# belongs to. `entry 16 of `some-page.md`` already names its target, and that
1024+# target keeps its own numbering, so the lookahead exempts it -- without it this
1025+# check demands a Part prefix for a cross-document citation, which is how a first
1026+# run of it turned a correct reference into a wrong one.
1027+_BARE_ENTRY = re.compile(
1028+ r"(?<![-\w])(?:entry|Entry) (\d+)\b(?!\s+of\s+`[^`]*\.md`)")
1029+# A qualified citation: `entry II-14`, or the bare `II-14` token the consolidated-ask
1030+# lists use. Roman-dash-digit is distinctive enough to match unqualified -- a survey of
1031+# every KB and docs page returned 58 hits, all of them genuine entry references.
1032+_QUALIFIED_ENTRY = re.compile(r"\b([IVX]+)-(\d+)\b")
1033+# Entries are numbered paragraphs in one Part of the merged report and `###` headings in
1034+# another, because the two source reports wrote them differently. Match both, or the Part
1035+# that uses bold paragraphs reads as defining no entries at all and every citation into it
1036+# is reported missing.
1037+_ENTRY_HEADING = re.compile(r"^(?:\*\*|#{2,4} )(\d+)\. ", re.M)
1038+ 
1039+ 
1040+def _paragraphs(text: str):
1041+ """(start_lineno, block) for each blank-line-delimited block, 1-indexed."""
1042+ lineno, block, start = 1, [], 1
1043+ for line in text.split("\n"):
1044+ if line.strip():
1045+ if not block:
1046+ start = lineno
1047+ block.append(line)
1048+ elif block:
1049+ yield start, "\n".join(block)
1050+ block = []
1051+ lineno += 1
1052+ if block:
1053+ yield start, "\n".join(block)
1054+ 
1055+ 
1056+def _heading_numbers(text: str) -> set[str]:
1057+ """Section numbers a page actually defines, as strings ('14', '14.2')."""
1058+ return {
1059+ m.group(1)
1060+ for m in re.finditer(r"^#{1,4} +(?:§)?(\d+(?:\.\d+)?)[.\s]", text, re.M)
1061+ }
1062+ 
1063+ 
1064+def check_reference_artifact_citations() -> list[str]:
1065+ """Any KB page citing `custom/...` or `tools/...` must cite something that RESOLVES.
1066+ 
1067+ This rule already existed for `validated` rows in `patterns/pattern-index.md`, and
1068+ nowhere else -- so `references/` and `playbooks/` pages could cite a retained artifact
1069+ in exactly the form the KB reserves for evidence, on the one page class where nothing
1070+ checked retention. Three such citations shipped: two naming files that exist on no ref
1071+ at all, carrying a page's entire measured sweep, and the page named no branch.
1072+ 
1073+ The failure is not cosmetic. A citation a reader cannot open invites re-running a
1074+ measurement that was already paid for -- which is the reason this KB gives elsewhere
1075+ for deleting dangling pointers.
1076+ 
1077+ The `on branch <name>` escape hatch is honoured, but scoped to the **paragraph** that
1078+ carries the citation. Searching the whole page for the keyword is how an unrelated
1079+ sentence once laundered a broken path (see
1080+ `check_pattern_validated_claims_cite_evidence`), and a page-wide scope would reopen it.
1081+ """
1082+ errors: list[str] = []
1083+ # `docs/` is scanned too. Leaving it out is how a dangling `custom/...` path in the
1084+ # merged DSL report survived a full green run: the citation rule existed, but not for
1085+ # the directory that carried the citation.
1086+ pages = list(_kb_files()) + (
1087+ sorted(_DOCS_ROOT.glob("*.md")) if _DOCS_ROOT.is_dir() else []
1088+ )
1089+ for page in pages:
1090+ if page.suffix == ".md" and page.name != "pattern-index.md":
1091+ errors.extend(_artifact_citation_errors(page))
1092+ return errors
1093+ 
1094+ 
1095+def _artifact_citation_errors(page: Path) -> list[str]:
1096+ """Unresolved `custom/`/`tools/` citations on one page.
1097+ 
1098+ Split out so neither function nests more than four deep.
1099+ """
1100+ errors: list[str] = []
1101+ text = _text(page)
1102+ for start, block in _paragraphs(text):
1103+ cites = _ARTIFACT_CITE.findall(block)
1104+ if cites:
1105+ named = _PATTERN_BRANCH.findall(block)
1106+ present = [r for r in named if _ref_exists(r)]
1107+ absent = [r for r in named if not _ref_exists(r)]
1108+ errors.extend(
1109+ _artifact_citation_error(page, start, citation, present, absent)
1110+ for citation in cites
1111+ )
1112+ return [e for e in errors if e]
1113+ 
1114+ 
1115+def _artifact_citation_error(
1116+ page: Path,
1117+ start: int,
1118+ citation: str,
1119+ present: list[str],
1120+ absent: list[str],
1121+) -> str | None:
1122+ """One citation's verdict: an error string, a `SKIP:` note, or None when it resolves."""
1123+ rel = page.relative_to(REPO_ROOT)
1124+ parts = _expand(citation)
1125+ # `all`, not `any`: `{present.py,absent.py}` names two files, and a citation is
1126+ # only evidence for what it names. Under `any` the present member vouched for the
1127+ # absent one -- the same "one member covers the rest" hole `_expand` was written to
1128+ # close, reintroduced one line later.
1129+ if all((REPO_ROOT / part).exists() for part in parts):
1130+ return None
1131+ if present and all(any(_git_has(r, part) for r in present) for part in parts):
1132+ return None
1133+ if absent and not present:
1134+ # Same reasoning as `_citation_resolution_result`: unfetched and never-existed
1135+ # are indistinguishable here, so say "unchecked" rather than passing a citation
1136+ # nothing verified.
1137+ return (
1138+ f"SKIP: {rel}:{start} cites {citation!r} "
1139+ f"against ref(s) {absent} not present locally; fetch to verify"
1140+ )
1141+ hint = (
1142+ f"; it names branch(es) {present} but the path is not in them"
1143+ if present
1144+ else "; retain it, name the branch with `on branch <name>`, or drop the path"
1145+ )
1146+ return f"{rel}:{start} cites {citation!r} which resolves nowhere{hint}"
1147+ 
1148+ 
1149+def _cited_sections(text: str, match: "re.Match[str]") -> list[str]:
1150+ """Section numbers a single markdown link carries.
1151+ 
1152+ Both spellings occur: the number can sit inside the link text
1153+ (``[ROUTER §99](../ROUTER.md)``) or follow the link (``[ROUTER](../ROUTER.md) §99``),
1154+ and a run may name several (``§1, §99``). The trailing window stops at the next ``[``
1155+ so a second link's sections are never attributed to this one.
1156+ """
1157+ tail = text[match.end():match.end() + 40].split("[")[0]
1158+ cited = _SECTION_NUM.findall(match.group(1)) + _SECTION_NUM.findall(tail)
1159+ return list(dict.fromkeys(cited))
1160+ 
1161+ 
1162+def _section_citation_errors(page: Path) -> list[str]:
1163+ """Unresolved `§N` citations on one page.
1164+ 
1165+ Split out of `check_section_citations` so neither function nests more than four
1166+ deep; the loop-inside-loop-inside-loop form tripped the depth limit.
1167+ """
1168+ text = _text(page)
1169+ rel = page.relative_to(REPO_ROOT)
1170+ errors: list[str] = []
1171+ for match in _SECTION_LINK.finditer(text):
1172+ target_rel = match.group(2)
1173+ target = (page.parent / target_rel).resolve()
1174+ if not target.is_file():
1175+ continue # link resolution is check_links's job, not this one
1176+ cited = _cited_sections(text, match)
1177+ if not cited:
1178+ continue
1179+ defined = _heading_numbers(_text(target))
1180+ missing = [section for section in cited if section not in defined]
1181+ lineno = text[: match.start()].count("\n") + 1
1182+ errors.extend(
1183+ f"{rel}:{lineno} cites §{section} of {target_rel}, which defines no "
1184+ f"such section"
1185+ for section in missing
1186+ )
1187+ return errors
1188+ 
1189+ 
1190+def check_section_citations() -> list[str]:
1191+ """A `§N` citation must point at a section the target page actually defines.
1192+ 
1193+ A number is a silent reference: when the target renumbers, the citation keeps
1194+ resolving -- to the wrong section -- and nothing announces it. That happened here: a
1195+ page cited `§15` while the target stopped at `§14.x`, so the link was visibly broken;
1196+ a later commit added a `§15` on an unrelated subject and the citation became quietly
1197+ wrong, which is worse than the dangling version it replaced.
1198+ 
1199+ Only citations of the form `[...](target.md) ... §N` are checked -- the ones that name
1200+ both the page and the number, so both halves can be compared.
1201+ """
1202+ errors: list[str] = []
1203+ pages = list(_kb_files()) + (
1204+ sorted(_DOCS_ROOT.glob("*.md")) if _DOCS_ROOT.is_dir() else []
1205+ )
1206+ for page in pages:
1207+ if page.suffix == ".md":
1208+ errors.extend(_section_citation_errors(page))
1209+ return errors
1210+ 
1211+ 
1212+def _entries_by_part(text: str) -> dict[str, set[str]]:
1213+ """Which entry numbers each `# Part <ROMAN>` actually defines."""
1214+ marks = [(m.group(1), m.start()) for m in _PART_HEADING.finditer(text)]
1215+ parts: dict[str, set[str]] = {}
1216+ for i, (roman, start) in enumerate(marks):
1217+ end = marks[i + 1][1] if i + 1 < len(marks) else len(text)
1218+ parts[roman] = {m.group(1) for m in _ENTRY_HEADING.finditer(text[start:end])}
1219+ return parts
1220+ 
1221+ 
1222+def check_multi_part_entry_citations() -> list[str]:
1223+ """In a report with numbered Parts, `entry N` must say which Part.
1224+ 
1225+ Merging two separately-numbered reports into one document makes every bare `entry N`
1226+ ambiguous, and the reader lands on whichever Part comes first -- a wrong-number defect
1227+ that never announces itself. One such document here carries two entries numbered 20,
1228+ two numbered 24, and so on; thirteen bare citations pointed at the wrong one.
1229+ 
1230+ Applies only to documents that declare `# Part <ROMAN>` headings more than once, since
1231+ that is what makes a bare number ambiguous. A citation that names an external page --
1232+ ``entry 16 of `pypto-pro-framework-findings.md` `` -- is exempt: the number indexes that
1233+ page's numbering, not this document's Parts, and demanding a Part prefix there produces
1234+ a citation that points at the wrong entry.
1235+ 
1236+ A citation that *is* qualified is then resolved: `II-14` must be an entry Part II
1237+ actually defines. Checking only that a prefix is present would accept any number.
1238+ The limit is worth stating: resolution rejects an out-of-range prefix, not one
1239+ that lands on a real but unrelated entry. No static rule reaches that.
1240+ """
1241+ errors: list[str] = []
1242+ pages = list(_kb_files()) + (
1243+ sorted(_DOCS_ROOT.glob("*.md")) if _DOCS_ROOT.is_dir() else []
1244+ )
1245+ for page in pages:
1246+ if page.suffix != ".md":
1247+ continue
1248+ text = _text(page)
1249+ if len(_PART_HEADING.findall(text)) < 2:
1250+ continue
1251+ rel = page.relative_to(REPO_ROOT)
1252+ for m in _BARE_ENTRY.finditer(text):
1253+ lineno = text[: m.start()].count("\n") + 1
1254+ errors.append(
1255+ f"{rel}:{lineno} cites bare 'entry {m.group(1)}' in a multi-part report; "
1256+ f"say which part (e.g. 'entry II-{m.group(1)}')"
1257+ )
1258+ # Qualifying a citation is not the same as it resolving: the rule above demands a
1259+ # Part prefix, and any number satisfies it. This catches a prefix that names an
1260+ # entry the Part does not have. It does NOT catch a prefix that is in range and
1261+ # still wrong -- `entry I-16` resolves, because Part I does define an entry 16;
1262+ # that one is caught upstream by exempting citations which name a target file.
1263+ parts = _entries_by_part(text)
1264+ for m in _QUALIFIED_ENTRY.finditer(text):
1265+ roman, number = m.groups()
1266+ if number in parts.get(roman, ()):
1267+ continue
1268+ if roman not in parts:
1269+ lineno = text[: m.start()].count("\n") + 1
1270+ errors.append(
1271+ f"{rel}:{lineno} cites {roman}-{number}, but this document defines no "
1272+ f"Part {roman} (it defines {', '.join(sorted(parts))})"
1273+ )
1274+ continue
1275+ lineno = text[: m.start()].count("\n") + 1
1276+ known = sorted(parts[roman], key=int)
1277+ span = f"{known[0]}-{known[-1]}" if known else "none"
1278+ errors.append(
1279+ f"{rel}:{lineno} cites {roman}-{number}, but Part {roman} defines no "
1280+ f"entry {number} (it defines {span})"
1281+ )
1282+ return errors
1283+ 
1284+ 
920CHECKS = (1285CHECKS = (
921 ("links resolve", check_links),1286 ("links resolve", check_links),
922 ("files are reachable", check_reachability),1287 ("files are reachable", check_reachability),
@@ -932,6 +1297,11 @@ CHECKS = (
932 ("every page is routable", check_every_page_is_routable),1297 ("every page is routable", check_every_page_is_routable),
933 ("pypto skill paths are portable", check_skill_absolute_paths),1298 ("pypto skill paths are portable", check_skill_absolute_paths),
934 ("repo tool paths are portable", check_tool_absolute_paths),1299 ("repo tool paths are portable", check_tool_absolute_paths),
1300+ ("cross-package links resolve", check_cross_package_links),
1301+ ("report copies agree", check_report_copies_agree),
1302+ ("reference citations resolve", check_reference_artifact_citations),
1303+ ("section citations resolve", check_section_citations),
1304+ ("multi-part entries are qualified", check_multi_part_entry_citations),
935)1305)
936 1306 
937 1307 
@@ -86,33 +86,6 @@ about A5 UB. So it is a usable cross-check, and the one row it got wrong is the
86one that was quoted most. Verify against the platform file before reusing any row86one that was quoted most. Verify against the platform file before reusing any row
87of it.87of it.
88 88 
89-## Three cross-DSL notes about this silicon
90- 
91-**未在 PyPTO-Pro 上验证——由 EasyASC 移植的假设 (unverified on PyPTO-Pro — an
92-assumption ported from EasyASC).** These are statements about the chip rather than
93-about a DSL, which is why they are here rather than being dropped as another
94-project's platform data. Two are design bounds and one is a negative.
95- 
96-- **A fused-bias contraction is capped at `N` / `Cout` ≤ 512.** The total is
97- anchored — `bt_size=4096` in the SKU's platform file, which is 1024 fp32/int32
98- elements. The **unverified** half is the structure: the bias table is described
99- as two slots, with a shortcut-matmul or conv bias required to fit *one*, which
100- halves the usable width to 512. Check the slot structure before a tiling leans
101- on it, but check it *early* — it caps a dimension tile planning otherwise treats
102- as free. (For scale: A2/A3's BT is 512 B, so the equivalent bound there is 64.)
103-- **The 12-bit `n_burst` field is an A2/A3 restriction that A5 does not inherit.**
104- On C220, padded GM↔UB transfers encode the burst count in `[0, 4095]` and a
105- request for 4096 silently does nothing. This is carried as a **negative**: do
106- not budget around a 4095 burst cap on A5, and do not port an A2-era tiling
107- workaround that exists only to respect it. Recorded because a silent no-op is
108- the kind of rule that gets applied defensively long after it stopped applying.
109-- **950 and 950PR share the C310 instruction and codegen family**, differing in
110- default core count, vector lane count, and the debug SoC string. The platform
111- files corroborate the shared family directly — `950PR_957x.ini` and
112- `950DT_957x.ini` both declare `dav-c310-cube` — which is why a finding measured
113- on one is worth *testing* on the other, and equally why it is not automatically
114- valid there, since anything derived from core count is exactly what differs.
115- 
116## Performance boundary89## Performance boundary
117 90 
118Platform configuration values are roofline inputs, not measured kernel91Platform configuration values are roofline inputs, not measured kernel
@@ -78,17 +78,6 @@ Two consequences worth stating separately:
78 Assert the linear extent, and keep the negative control that shows the78 Assert the linear extent, and keep the negative control that shows the
79 assertion can fire.79 assertion can fire.
80 80 
81-**Provenance.** The two formulas are from EasyASC's runtime footprint guards
82-(`references/simulator-datamove-footprint-guards.md:19,52-55`), where they are
83-enforced in that DSL's bounds checker. They are **shape arithmetic over
84-offsets, spans and strides**, so they hold for any DSL that lets a tile view a
85-sub-region of a wider tensor — which `pl.load` / `pl.load_tile` / `pl.store` all
86-do. Nothing about them is EasyASC-specific and nothing needs re-measuring; what
87-would need checking, if a design depends on it, is which *particular* extent a
88-given PyPTO-Pro call validates internally. The same source also warns against
89-clamping a view to the parent size with `min(...)`: it hides the real
90-out-of-bounds and re-surfaces later as an unrelated-looking footprint failure.
91- 
92## Evidence81## Evidence
93 82 
94- rotating Vec groups:83- rotating Vec groups:
@@ -102,46 +91,3 @@ Use the installed API documentation and matching official example to confirm
102alignment and layout semantics for the target version.91alignment and layout semantics for the target version.
103 92 
104---93---
105- 
106-## A transposing GM→on-chip read has a source-plane alignment cliff
107- 
108-**未在 PyPTO-Pro 上验证——由 EasyASC 移植的假设 (unverified on PyPTO-Pro — an
109-assumption ported from EasyASC).** Board-confirmed on Ascend 950 under EasyASC, a
110-different DSL over the same silicon; the claim below is about the **DMA engine's
111-transposing read path**, which is a property of the hardware rather than of
112-either DSL's spelling of it.
113- 
114-**Trigger — check this against your own kernel.** A load that converts layout on
115-the way in (dense source → fractal destination) *and* whose source plane extent
116-in bytes is not a multiple of 32. In EasyASC's terms that is `gm_to_l1_dn2nz`;
117-in PyPTO-Pro the layout-converting surface is `pl.set_mm_layout_transform` plus
118-the transposing operand load used by the retained
119-[TN matmul sample](../examples/samples/matmul_kmkn_fp32_out/matmul_tn_impl.py).
120- 
121-**The measurement.** When `H*W*sizeof(dtype)` is not a multiple of 32 bytes, the
122-transposing read falls off its fast path: **about 40 GB/s against roughly
123-1.7 TB/s on an aligned plane** — a factor of ~40, enough to turn a MAC-bound
124-kernel into a load-bound one (EasyASC reported `aic_mte2_ratio` 0.978 at the
125-cliff). `W = 127` fp16 and `W = 63` fp32 both hit it. The recorded remedy is to
126-split that branch into a separate dense→fractal conversion pass; on the aligned
127-branch the single fused read stays faster.
128- 
129-**A second, quieter rule from the same source.** EasyASC's dense→fractal copy
130-sets its destination fractal-row stride to `align16(M_dst)` — it rounds the C0
131-stride **up to 16 rows** — so one call may only span several C0 blocks when the
132-destination plane is itself 16-row aligned. With an unaligned plane the C0 blocks
133-drift apart and any consumer assuming a packed stride reads the wrong block.
134-Whether PyPTO-Pro's conversion does the same rounding is unknown.
135- 
136-**Why this is worth carrying despite being unverified.** It is a *cliff*, not a
137-gradient: a design that lands on the wrong side loses more than an order of
138-magnitude and the kernel is still bit-correct, so nothing but a timing
139-measurement reveals it. It also cannot be seen by any simulator that models the
140-transfer as a flat copy.
141- 
142-**Named probe to settle it** (one board session): one transposing operand load of
143-fixed total volume, built twice — once with the source plane extent a multiple of
144-32 bytes, once one element short of it — timed, with the byte counts asserted
145-equal. If the two times differ by an order of magnitude the cliff transfers; if
146-they do not, delete this section. Pair it with a check that the fractal stride
147-the consumer assumes matches what the copy wrote, which is the second rule above.
@@ -127,7 +127,8 @@ elements whose true value happens to land near zero then carry enormous relative
127error. Worse, that same absolute error pushes `|output|` past the cancel-region127error. Worse, that same absolute error pushes `|output|` past the cancel-region
128threshold, so those elements do not even qualify for the cancel region's128threshold, so those elements do not even qualify for the cancel region's
129CPU comparison — they land in the normal region, which must have zero129CPU comparison — they land in the normal region, which must have zero
130-exceedances. Measured on MlaProlog: ~0.1 absolute error on `query`, ~77 elements130+exceedances. Measured on a staged multi-matmul chain: ~0.1 absolute error on one
131+output, ~77 elements
131per case, every case failing.132per case, every case failing.
132 133 
133Two rules follow, and they are separate:134Two rules follow, and they are separate:
@@ -167,7 +168,7 @@ them **pairwise** in the consumer — `(p0+p1) + (p2+p3)` keeps both intermediat
167at half scale so only the final addition rounds at full scale. Four `[64, 128]`168at half scale so only the final addition rounds at full scale. Four `[64, 128]`
168fp32 accumulators cost 128 KB of a 256 KB L0C.169fp32 accumulators cost 128 KB of a 256 KB L0C.
169 170 
170-Measured on MlaProlog's first projection: the inherited error fell 3.51e-6 →171+Measured on the first projection of such a chain: the inherited error fell 3.51e-6 →
1711.68e-6 (2.09x), bringing the chain to parity with the CPU reference1721.68e-6 (2.09x), bringing the chain to parity with the CPU reference
172(2.76e-6 vs 2.74e-6) at **unchanged runtime** — the extra GM traffic was ~19 MB173(2.76e-6 vs 2.74e-6) at **unchanged runtime** — the extra GM traffic was ~19 MB
173against 122 MB of weights. 17/20 → 19/20.174against 122 MB of weights. 17/20 → 19/20.
@@ -213,8 +214,8 @@ Consequences that change design decisions:
213- **The cheap pre-board check** is to replay the kernel's exact arithmetic on CPU214- **The cheap pre-board check** is to replay the kernel's exact arithmetic on CPU
214 against a higher-precision golden and count threshold exceedances per region,215 against a higher-precision golden and count threshold exceedances per region,
215 next to the same counts for the reference. That ratio is what the gate compares.216 next to the same counts for the reference. That ratio is what the gate compares.
216- `tools/precision_oracle.py` does this, including the deterministic input217+ A CPU-side oracle that replays the accuracy gate does this, including
217- generation.218+ the deterministic input generation.
218 219 
219### Integer outputs are not covered by any of that220### Integer outputs are not covered by any of that
220 221 
@@ -18,7 +18,7 @@ this order — the same order the adjudication further down this page arrives at
18 18 
191. **Try the generated pipeline path first.** `fwd_ids`/`bwd_ids` plus191. **Try the generated pipeline path first.** `fwd_ids`/`bwd_ids` plus
20 `@pl.pipeline.stage` plus `PipelineConfig` **does work** here, measured on the20 `@pl.pipeline.stage` plus `PipelineConfig` **does work** here, measured on the
21- reference kernel and on a full MLA kernel21+ reference kernel and on a full staged kernel
22 ([framework-findings §17](../references/pypto-pro-framework-findings.md)).22 ([framework-findings §17](../references/pypto-pro-framework-findings.md)).
232. **Fall back to single-sided launches with GM intermediates** when the fused232. **Fall back to single-sided launches with GM intermediates** when the fused
24 form fails. This is the proven escape, not evidence that fusion is impossible.24 form fails. This is the proven escape, not evidence that fusion is impossible.
@@ -33,9 +33,11 @@ compiles and then dies with `aicore timeout`. One attention kernel was taken
33through **thirteen hypotheses and nine mutation-ladder rungs** on that construct33through **thirteen hypotheses and nine mutation-ladder rungs** on that construct
34and never ran once, even though every ingredient passed in isolation — the cube34and never ran once, even though every ingredient passed in isolation — the cube
35half (including the transposed NT load and a dual-accumulator contraction) and35half (including the transposed NT load and a dual-accumulator contraction) and
36-the register-level softmax were each proven separately. The reference Ascend-C36+the register-level softmax were each proven separately. A reference
37-implementation of a sibling operator hit the identical wall on the identical37+implementation written against a different kernel language hit the identical
38-construct. This says nothing about the generated pipeline path in step 1.38+wall on the identical construct, so the limit is in the construct rather than in
39+one language's lowering. This says nothing about the generated pipeline path in
40+step 1.
39 41 
40### The proven fallback: decompose into single-sided launches42### The proven fallback: decompose into single-sided launches
41 43 
@@ -86,87 +88,144 @@ remain authoritative for pipe/event signatures.
86 88 
87---89---
88 90 
89-## An unresolved conflict: must A5 cube↔vec round-trip GM?91+## A hang is not evidence of a synchronization bug — locate the PC first
90 92 
91-Recorded, not adjudicated. A sibling DSL (EasyASC) targeting the same A5 silicon93+Five ablations of the cross-core edges of one deadlocking kernel all came back
92-states the opposite of this page's headline advice, and both statements rest on94+negative: even-vs-odd loop parity, moving a release to a different pipe, deleting
93-work that was actually run. Leaving the disagreement visible is more useful than95+the guarded cube-side wait, deleting the guarded vector-side wait, and deleting
94-picking a winner, because the two claims are about **different objects**.96+both back edges. Each was a well-formed experiment and each said "not this."
95 97 
96-| | claim | basis |98+They were all aimed at the wrong resource class. Resolving the two stuck PCs to
99+source settled it in one step:
100+ 
101+| core | parked at | pipe |
97|---|---|---|102|---|---|---|
98-| this page, above | a fused single-launch cube+vector kernel with per-tile handoff does not run on A5; decompose into single-sided launches with GM intermediates | measured here, repeatedly — 13 hypotheses, 9 mutation-ladder rungs, never ran once |103+| AIC, all 28 | `get_buf(PIPE_MTE1, b_right/b_l1)` → `TEXTRACT`, inner K sub-block loop | MTE1 |
99-| EasyASC `agent/references/constraints/a5.md` §4 | on A5 the cube↔vec handoff **stays on chip**; no GM workspace bridge is required, unlike the A2 model | asserted as an A5-vs-A2 authoring consequence; that page cites no probe for this specific line |104+| AIV, all 56 | `TSTORE(out_tile)` → `set_loop_size_ubtoout` | MTE3 |
100 105 
101-**They are reconcilable, and the reconciliation is the actionable part.** The106+**Neither is a `wait_intra_block` or a `wait_flag`.** There was no flag id to
102-disagreement is not about whether the silicon has on-chip cube↔vec paths — it107+audit, and no cross-core edge to fix, because the machine was never parked on
103-does, and PyPTO-Pro exposes them: `pl.move`'s documented space table108+one — it was parked on **pipe/buffer resource acquisition**. Every core of both
104-(`pypto_pro/language/_api.py:196-206` in this checkout) carries `Acc (L0C) → Vec109+types at a fixed PC is a structural stall, and `aicore timeout` names the
105-(UB)` on the fix pipe and `Vec (UB) → Mat (L1)` on mte3. What failed here was one110+watchdog, not the mechanism.
106-*construct*: a hand-written per-tile cross-core event sequence inside a single
107-`@pl.jit`. And this KB's own
108-[framework-findings §17](../references/pypto-pro-framework-findings.md) records
109-that the **generated** path — `fwd_ids`/`bwd_ids` plus `@pl.pipeline.stage` plus
110-`PipelineConfig` — does work, on the reference kernel and on a full MLA kernel.
111 111 
112-So the honest three-way statement is:112+**The lesson is about ordering of work.** "All cores hang" invites the
113+synchronization hypothesis, and the vocabulary of the failure (`aicore timeout`,
114+`retCode=0x25`) reinforces it. But a hang localises *exactly* — one address per
115+core type — and that address is cheap to obtain. Get it before enumerating
116+candidate edges; five ablation rounds is a lot to spend re-deriving "not a wait."
113 117 
114-1. on-chip cube↔vec handoff **exists** and is reachable (both DSLs agree);118+### Getting the source line without an ISA disassembler
115-2. the **hand-written** per-tile event sequence hangs here (measured);
116-3. the **generated** pipeline path works here (measured, §17) — and is the thing
117- to try before falling back to GM intermediates.
118 119 
119-Read the "decompose into single-sided launches" advice above as *the proven120+The obstacle looks like tooling and is not. No Ascend disassembler was available
120-escape when the fused form fails*, not as evidence that fusion is impossible.121+(`msobjdump`'s Python module absent, `llvm-objdump -d` prints
121-**Nothing here has been re-measured against EasyASC's claim** — it remains a122+`<not available>` for every instruction, no bisheng toolchain `bin/`). **But the
122-cross-DSL assertion about the same silicon, and the experiment that would settle123+instruction is not what you need — the source line is**, and that needs only
123-it is a PyPTO-Pro kernel built on the generated pipeline path at the tile124+`.debug_line`, which `llvm-symbolizer` and `llvm-dwarfdump --lookup` read without
124-granularity the fused attempt used.125+knowing the ISA.
125 126 
126-## Cube→cube re-feed: EasyASC's on-chip route has no `pl.move` spelling here127+The recipe, with the two checks that make it trustworthy:
127 128 
128-**未在 PyPTO-Pro 上验证——由 EasyASC 移植的假设 (unverified on PyPTO-Pro — an129+1. The device binary is embedded in the built shared library:
129-assumption ported from EasyASC), and the PyPTO-Pro side of it is a checked130+ `objcopy --dump-section .aicore_binary=out.bin <build>/tk_*/call_kernel.so /dev/null`.
130-absence rather than a checked presence.**131+ Load base is reported in the fault dump; `vaddr = PC − base`. **Verify the base**
132+ by checking that the AIV `pc start` equals `base + _mix_aiv` from the symbol
133+ table — do not assume it.
134+2. Rebuild with `-g` appended to the compile flags, then **prove `-g` was
135+ codegen-neutral** before trusting the line table: compare `.text` *bytes*,
136+ `_mix_aic`/`_mix_aiv` offsets, and the generated `kernel.cpp` against the
137+ archived binary that actually hung. Byte-identical `.text` is the gate. If it
138+ shifts, the line table describes different code and the lookup is void.
131 139 
132-EasyASC (`constraints/a5.md` §5) tells an author that when a later cube matmul140+Two practical notes. A frozen config dataclass can be patched in the probe
133-consumes an earlier one's result, the direct on-chip route141+process only (`object.__setattr__` on the flags tuple), so nothing is installed
134-`mmad → L0C → l0c_to_l1 → l1_to_l0 → mmad` should be preferred, and the detour142+on a shared board. And **the rebuild need not reproduce the hang**: a tiny case
135-`L0C → UB → L1` avoided as pure traffic and synchronization with no added143+on the *same tiling key* emits the identical binary, because the key selects the
136-capability. It adds that its `auto_sync()` does **not** create the `FIX → MTE1`144+specialization while shapes are runtime tiling parameters — 1.6 s instead of a
137-edge between the L0C→L1 copy and the next consumer, so that edge must be fenced145+570 s watchdog timeout.
138-by hand.
139 146 
140-**In PyPTO-Pro the recommended route does not appear to exist.** `pl.move`'s147+### What this did *not* establish
141-documented space table (`pypto_pro/language/_api.py:196-206`) lists exactly one
142-path out of `Acc`:
143 148 
144-```149+The investigation that produced the rule above also produced a specific
145-Acc (L0C) → Vec (UB) fix150+geometric hypothesis (one tile group declared outside both sections, shared
146-Mat (L1) → Left (L0A) mte1151+mutex ids), a discriminator that **refuted** it, and a claim about the
147-Mat (L1) → Right (L0B) mte1152+vec-to-cube handshake that was later **withdrawn** under isolation. None of it
148-Mat (L1) → Vec (UB) v153+is carried here: this page is routed as a constraint, and a page an agent reads
149-Vec (UB) → Mat (L1) mte3154+as normative must not also carry the arguments that were overturned on the way.
150-```155+What survives is the rule -- locate the PC before believing a hang is a
156+synchronization bug -- and the technique for doing it without a disassembler.
151 157 
152-There is **no `Acc → Mat` row**. The only on-chip way back from an accumulator to158+## 从累加器回 L1 没有直达路径:`Acc → Vec → Mat`,或走 GM
153-L1 is therefore `Acc → Vec → Mat` — precisely the detour EasyASC says to avoid.
154 159 
155-Two consequences, and one of them is a warning about this very entry:160+`pl.move` 的空间表(本 checkout 的 `pypto_pro/language/_api.py:196-206`)只列出
161+`Acc (L0C) → Vec (UB)`(fix 流水)与 `Vec (UB) → Mat (L1)`(mte3)两条,
162+**没有 `Acc → Mat` 一行**。
156 163 
157-- **Design consequence.** Do not plan a cube→cube on-chip re-feed around an164+> **证据等级:这是关于那张表的陈述,不是一次完整的能力缺失判定。**
158- `L0C → L1` move. Budget either the `Acc → Vec → Mat` round trip (two moves, two165+> 本 KB 自己的
159- spaces, and a vector-pipe touch that the fix→mte3 sequence has to be ordered166+> [absence gate](../references/investigation-discipline.md)(§11「Before claiming a
160- against) or a GM intermediate.167+> capability is absent, run the absence gate」)要求 API 文档、安装源码、可组合原语、
161-- **Do not promote this into a capability claim without running the absence168+> 最小探针与生成代码/板端证据齐备后,才能宣布一项能力不存在。此处只走到了"安装源码里
162- gate.** A missing row in one docstring table is weaker evidence than it looks —169+> 那张空间表没有这一行"。因此下面按"没有直达路径"来规划是**当前最稳妥的默认**,
163- this KB has a standing finding that170+> 而不是已证成的禁令——若你确有理由需要 `Acc → Mat`,先补齐 absence gate 再下结论,
164- [documentation tables under-report](../references/investigation-discipline.md)171+> 不要把这段当作已经替你跑完了那个 gate。
165- (`vf.astype`'s table omits BF16 while the silicon does it). Before recording
166- "PyPTO-Pro cannot re-feed L0C to L1", check the installed `_api.py` for other
167- spellings, grep the official samples under `$PYPTO_DEVKIT_DIR/pro_ops/` with
168- `find -L`, and build the minimal two-matmul probe.
169 172 
170-The `FIX → MTE1` fencing half of EasyASC's advice is untested here and has no173+**设计后果**:不要围绕 `L0C → L1` 直搬来规划 cube→cube 的片上再喂。要么预算
171-obvious PyPTO-Pro counterpart to test, since the edge it fences is on the path174+`Acc → Vec → Mat` 这趟往返——两次 move、两个空间,外加一次向量流水触碰,
172-that appears to be absent.175+且必须与 fix→mte3 的次序对齐——要么走 GM 中转。
176+ 
177+链式收缩(QK^T 后接 PV,或任意两段 GEMM)最容易踩这条:把累加器直接当作下一个
178+matmul 的 L1 操作数在 DESIGN 阶段看起来成立,到 Stage 4 才发现没有对应的 `pl.move`
179+拼写。**在设计期就按上面两条之一预算,不要留到实现期。**
180+ 
181+## `phase=` is a hardware handshake, and only `pl.store` can answer it
182+ 
183+Added after a hang that was misattributed to `Acc→Vec` for weeks. Full entry:
184+`references/pypto-pro-dsl-limitations-a5.md` #28.
185+ 
186+`phase=` on a `matmul` **turns off** the framework's automatic M↔FixPipe
187+synchronization and replaces it with a hardware `unit_flag` that the paired
188+`store(phase=...)` must clear. **`pl.move` has no `phase` parameter**, so a
189+`matmul(phase=Final)` drained by `pl.move(..., acc_to_vec_mode=...)` arms a
190+protocol whose other half cannot reply. Nothing rejects it.
191+ 
192+Checklist item, before diagnosing any Cube-side hang or L0C fault:
193+ 
194+1. For every `matmul` carrying `phase=`, name the drain. If it is not
195+ `pl.store` / `store_tile` **with `phase=`**, that is the defect — stop here.
196+2. Do not read buffer depth as causal. A slot buys one iteration; it does not
197+ clear the flag. Depth 1→2 "fixing" a hang means the test shape stopped
198+ re-entering a dirty block, not that the race is gone.
199+3. Do not treat a hang and an ECC fault as different bugs. `phase.md`'s 案例三
200+ (flag stuck at 1 → the next matmul on that block waits forever) and 案例二
201+ (read not gated on completion → fixpipe reads unwritten L0C → multi-bit ECC
202+ `error 171`) are the **same** violation seen from the writer's and the
203+ reader's side.
204+4. A passing cut is not a cleared cut. Two cuts here carried the violation and
205+ passed because `kv_tiles = 1` against a 2-slot accumulator never re-entered a
206+ dirty block. Re-test at a shape that forces re-entry (`kv_len >= 384`).
207+ 
208+An `error 171` multi-bit ECC on an L0C read also drives the card into
wangzheng97
wangzheng97wangzheng978月18日

[P0] 已知会使板卡进入 Alarm 的探针不能作为常规步骤

问题:本页已经记录该路径可能触发 multi-bit ECC/error 171,并让设备进入需要驱动重置的 Alarm 状态,却仍以“budget cards accordingly”的方式允许继续试探。

影响:在共享环境中可能直接让 NPU 下线、阻塞其他任务;同一调查中已有一次探针导致三张卡中的两张不可用。

证据:本页随后明确写明 error 171 会把卡置入 driver-level Alarm;另一份 staged-matmul gate 又要求首次 device error 后立即关闭候选、不重试,当前规范互相冲突。

建议:将该探针改为默认禁止。只有独占且已排空任务的板卡、负责人批准、明确重置/恢复方案和一次性执行上限同时满足时才允许运行;首次设备告警后立即隔离设备。

likedislike
209+driver-level `Alarm` through the RAS path — `8C4BA00C`, "The software has failed
210+and cannot recover", needing a driver reset. A single probe here cost two of
211+three cards.
212+ 
213+**Do not reproduce a suspected L0C fault on shared hardware.** This is a
214+default prohibition, not a budgeting exercise — an earlier revision of this page
215+said "budget cards accordingly", which reads as permission and is how the two
216+cards were lost. Diagnose from the generated code and the failure signature
217+first; they are usually sufficient, because the hang and the ECC fault are the
218+same violation (point 3 above) and the hang side is not destructive.
219+ 
220+If a live reproduction is genuinely unavoidable, every one of the following must
221+hold before it runs, and the probe is forbidden if any is missing:
222+ 
223+1. written authorization from the hardware owner for this specific probe;
224+2. an explicitly named device from an allowlist, never "whatever is free";
225+3. exclusive possession of that device, with every other job drained first;
226+4. a single attempt with a hard cap — no retry loop, no sweep;
227+5. isolation from any shared scheduler or CI pool;
228+6. a written recovery path (driver reset procedure and who may run it), agreed
229+ before the probe rather than discovered after it.
230+ 
231+Record the outcome so the next reader does not pay for it again.
@@ -39,10 +39,9 @@ Eight fp32 rows is exactly 32 bytes.
39reduction tile `[roundup(TR, 8), 1]` and narrow it with `pl.set_validshape`. That satisfies the39reduction tile `[roundup(TR, 8), 1]` and narrow it with `pl.set_validshape`. That satisfies the
40assertion while leaving the effective `TR` free, including 1.40assertion while leaving the effective `TR` free, including 1.
41 41 
42-Two operators reached this independently and it is the remedy both landed on:42+Two operators reached this independently and it is the remedy both landed on: one verified
43-`rms_norm` verified identical fp32 rounding at effective `TR` = 1, 2, 3, 4, 8, 16; `softmax`43+identical fp32 rounding at effective `TR` = 1, 2, 3, 4, 8, 16; the other declared `[8, 1]` and
44-declared `[8, 1]` and narrowed, which took every public last-axis case from a two-pass kernel44+narrowed, which took every last-axis case from a two-pass kernel to single-pass. Original observation held at `TR = 16` (N=256) and `TR = 8` (N=1024).
45-to single-pass. Original observation held at `TR = 16` (N=256) and `TR = 8` (N=1024).
46 45 
47> **Corrected.** This page first said to "reduce the buffer count rather than dropping TR46> **Corrected.** This page first said to "reduce the buffer count rather than dropping TR
48> below 8". That advice is wrong and was propagated before it was tested: at a long47> below 8". That advice is wrong and was propagated before it was tested: at a long
@@ -148,22 +147,22 @@ used for, and getting this wrong corrupts results silently.**
148this page. `load_align` moves a whole register, so with a non-64-multiple width the extra147this page. `load_align` moves a whole register, so with a non-64-multiple width the extra
149lanes run off the tile and fault at `507035` instead of computing harmless garbage.148lanes run off the tile and fault at `507035` instead of computing harmless garbage.
150 149 
151-**Measured**, swi_glu on Ascend950PR_9579, same body, two separately `stamped()` names in150+**Measured** on Ascend950PR_9579, one elementwise body, two separately `stamped()` names in
152one module so neither could be served the other's binary:151one module so neither could be served the other's binary:
153 152 
154-| case | shape, dtype | per-register mask | hoisted | ratio |153+| shape, dtype | per-register mask | hoisted | ratio |
155-|---|---|---|---|---|154+|---|---|---|---|
156-| 3 | 4096x8192 bf16 | 91.06 us | 14.01 us | **6.5x** |155+| 4096x8192 bf16 | 91.06 us | 14.01 us | **6.5x** |
157-| 18 | 2x1023x4096 fp32 | 19.87 us | 3.85 us | 5.2x |156+| 2x1023x4096 fp32 | 19.87 us | 3.85 us | 5.2x |
158-| 15 | 512x4096 fp32 | 6.58 us | 1.50 us | 4.4x |157+| 512x4096 fp32 | 6.58 us | 1.50 us | 4.4x |
159-| 11 | 3x7x13x1018 fp32 | 2.52 us | 0.93 us | 2.7x |158+| 3x7x13x1018 fp32 | 2.52 us | 0.93 us | 2.7x |
160-| 8 | 1538x1537 fp32, dim 0 | 8.36 us | 3.50 us | 2.4x |159+| 1538x1537 fp32, dim 0 | 8.36 us | 3.50 us | 2.4x |
161-| 5 | 2039x65520 fp32 | 655.86 us | 649.88 us | 1.01x |160+| 2039x65520 fp32 | 655.86 us | 649.88 us | 1.01x |
162 161 
163**The gain scales with how far the kernel is from the DRAM roof, which is why it is easy to162**The gain scales with how far the kernel is from the DRAM roof, which is why it is easy to
164-dismiss.** Case 5 moves 801 MB and is bandwidth-bound at 1.23 TB/s, so the mask costs it 1%;163+dismiss.** The largest row moves 801 MB and is bandwidth-bound at 1.23 TB/s, so the mask costs
165-every case that fits cache pays the full 2.4–6.5x. A kernel tuned only on its largest case164+it 1%; every shape that fits cache pays the full 2.4–6.5x. A kernel tuned only on its largest
166-will conclude the mask is free. cummin measured this lever at 28% on a scan body of ~20 ops;165+case will conclude the mask is free. A scan body of ~20 ops measured this lever at 28%;
167on a 4-op elementwise body the same fix is worth an order of magnitude more, because the166on a 4-op elementwise body the same fix is worth an order of magnitude more, because the
168overhead is fixed per register and the body it is amortised over is not.167overhead is fixed per register and the body it is amortised over is not.
169 168 
@@ -171,7 +170,7 @@ overhead is fixed per register and the body it is amortised over is not.
171only stored — see the criterion above; if it takes part in addressing, keep the tail170only stored — see the criterion above; if it takes part in addressing, keep the tail
172regardless of what these numbers say). An explicitly masked tail register (hoisted mask for171regardless of what these numbers say). An explicitly masked tail register (hoisted mask for
173the full registers, one `update_mask` for the remainder) measured within noise of the no-tail172the full registers, one `update_mask` for the remainder) measured within noise of the no-tail
174-form — 3.65 vs 3.85 us on case 18, 1.54 vs 1.50 on case 15 — **so keeping the tail costs173+form — 3.65 vs 3.85 us on the 2x1023x4096 shape, 1.54 vs 1.50 on 512x4096 — **so keeping the tail costs
175essentially nothing.** These numbers were once written as "the tail path buys nothing and174essentially nothing.** These numbers were once written as "the tail path buys nothing and
176costs a branch", which read as an argument for removing it; measured, it is an argument that175costs a branch", which read as an argument for removing it; measured, it is an argument that
177removing it is not worth the risk.176removing it is not worth the risk.
@@ -185,11 +184,9 @@ fast kernel. Board-only, ~30% in the originating case.
185 184 
186**Cause.** UB is banked, on the store path as on the load path. The *gather*-side rule and185**Cause.** UB is banked, on the store path as on the load path. The *gather*-side rule and
187its pypto-pro measurements (stride 64 = 51.0 µs vs 65 = 7.0 µs) are in186its pypto-pro measurements (stride 64 = 51.0 µs vs 65 = 7.0 µs) are in
188-[vec-scan-prefix-dependent.md](../patterns/vec-scan-prefix-dependent.md); the store side187+[vec-scan-prefix-dependent.md](../patterns/vec-scan-prefix-dependent.md). The store
189-was measured under EasyASC on the same silicon: padding an NZ fractal-row store stride from188+side has not been measured here; treat it as the same bank behaviour and probe it
190-64 to 65 rows took the kernel from **167.67 µs to 128.05 µs**, with the pad row excluded on189+before relying on a particular stride.
191-the copy that publishes the tile onward (the publishing copy takes a separate source
192-stride, so the downstream tile stays compact).
193 190 
194**Rule.** The same pitch rule as the gather side, applied to the tile a scatter/strided191**Rule.** The same pitch rule as the gather side, applied to the tile a scatter/strided
195store writes into: make the row pitch an **odd multiple of 32 bytes** — a tile row must be192store writes into: make the row pitch an **odd multiple of 32 bytes** — a tile row must be
@@ -198,10 +195,20 @@ the tool here — and exclude the pad at the publishing copy via the valid windo
198than carrying it onward. Board-validate the timing of any NZ / strided UB store; this195than carrying it onward. Board-validate the timing of any NZ / strided UB store; this
199class is invisible to flat-UB simulation.196class is invisible to flat-UB simulation.
200 197 
198+## 分发模式的 store 会写整个寄存器,有没有 mask 都一样
199+ 
200+**掩码不缩小写入范围。** 一次 masked distribution store 目标的 scratch,必须按
201+**整个寄存器 256 字节**分配,而不是按活跃 lane 数分配。
202+ 
203+这条给 `references/pypto-pro-dsl-limitations-a5.md` 里那条 workaround 定尺——
204+「不要依赖 `INTLV_B32` 的 predicate;先把数据 mask 掉再 store,或者不带 mask 存进
205+scratch 再显式合并」。按活跃 lane 数给 scratch 定尺,store 会越过末尾写入相邻 UB tile,
206+而症状出现在**另一个** tile 上,定位方向天然是错的。
207+ 
201## A masked *continuous* store may round its active lanes up to a whole 32-byte block208## A masked *continuous* store may round its active lanes up to a whole 32-byte block
202 209 
203-EasyASC board measurement on the same silicon; **unverified for `vf.store_align` — treat210+**Unverified for `vf.store_align` — treat as a hypothesis and run the probe below
204-as a hypothesis and run the probe below before relying on either behavior.**211+before relying on either behavior.**
205 212 
206A masked continuous store rounded its active lane count up to a whole 32-byte block213A masked continuous store rounded its active lane count up to a whole 32-byte block
207(`align8(n)` lanes at b32), so the spill lands past the active lanes. That is harmless214(`align8(n)` lanes at b32), so the spill lands past the active lanes. That is harmless
@@ -226,10 +233,9 @@ and reversing the call order flips which shape "works". `k.__name__ = ...` does
226`co_name` is fixed at `def` — and `exec` breaks `inspect.getsource`. Code-generate each kernel233`co_name` is fixed at `def` — and `exec` breaks `inspect.getsource`. Code-generate each kernel
227to a real file under a unique `def` name.234to a real file under a unique `def` name.
228 235 
229-Use a source-derived unique kernel name; see "Stale binary under an unchanged kernel name" in236+Use a source-derived unique kernel name; see [the build-directory finding](../references/pypto-pro-framework-findings.md)
230-[benchmark-scoring.md](../playbooks/benchmark-scoring.md) for the quieter converse, where an237+for the quieter converse, where an edited body under an unchanged name is served a *stale*
231-edited body under an unchanged name is served a *stale* binary and the run comes back238+binary and the run comes back byte-identical. (This pointer previously named a per-operator findings file that is not in this
232-byte-identical. (This pointer previously named a per-operator findings file that is not in this
233repo, cited by an entry number -- which this KB's own convention forbids, because the numbering239repo, cited by an entry number -- which this KB's own convention forbids, because the numbering
234collides across operator trees. Cite in-repo pages by title.) The diagnostic is worth240collides across operator trees. Cite in-repo pages by title.) The diagnostic is worth
235keeping: **an unchanged module-level reference kernel passing at the same shape where a241keeping: **an unchanged module-level reference kernel passing at the same shape where a
@@ -240,79 +246,3 @@ One myth was busted in the same investigation and should not be reintroduced: `i
240out-of-bounds access, misattributed.246out-of-bounds access, misattributed.
241 247 
242---248---
243- 
244-## Per-token scalar staging wants one whole 32-byte row per token
245- 
246-**Cross-DSL: EasyASC board measurement on Ascend 950. 未在 PyPTO-Pro 上验证——由
247-EasyASC 移植的假设 (unverified on PyPTO-Pro).** It does **not** override the
248-PyPTO-Pro measurement it sits next to; read that one first.
249- 
250-**What this KB already measured, and which stays authoritative.** An FP16
251-scalar-Tensor store is not safe at a 32-byte ownership boundary — accuracy 0.90
252-overall and 0.90625 at `block_dim=32`, while **64 B and 128 B boundaries were
253-exact** and a whole-tile `pl.store` was exact at all three
254-([framework-findings, A5 probe session](../references/pypto-pro-framework-findings.md)).
255-The conclusion there is: prefer the beat-complete tile store.
256- 
257-**What EasyASC adds, from the staging side rather than the store side.** Its
258-`constraints/a5.md` §12 reports that repeatedly moving *one scalar per token*
259-between GM and UB — `m > 1`, `n == 1` — into a compact `[1, L]` or `[L, 1]` UB
260-layout **can misaddress later rows on hardware while its Python simulator
261-passes**. Its prescription is to give each token one physical 32-byte UB row and
262-use only the first element of it:
263- 
264-```
265-scalar_ub : [L, C0] # C0 = 32 B / sizeof(dtype); 16 for bf16, 8 for fp32
266- # logical slice stays [L, 1]; the backing stays [L, C0]
267-```
268- 
269-EasyASC is explicit that this is a **burst-pitch** requirement — a property of the
270-repeated one-element transfer — and *not* a general ban on unaligned scalar
271-addressing, which it says is fine for an isolated access.
272- 
273-**Why it is worth carrying.** It is the same 32-byte quantum as the measured
274-PyPTO-Pro finding above, reached from a different direction (staging pitch rather
275-than concurrent-store ownership), by a different DSL, on the same silicon. Two
276-independent arrivals at "give the scalar a whole beat" is the kind of agreement
277-that should raise your prior before you spend a board session. It also predicts
278-something the PyPTO-Pro measurement did not test: that the hazard survives even
279-with a single writer, because it is about burst addressing rather than about two
280-cores sharing a beat.
281- 
282-**Named probe:** stage `L` per-token fp32 scalars into a `[L, 1]` UB tile and into
283-an `[L, 8]` tile whose column 0 carries the payload, read both back, and compare
284-against the host values at `L` large enough to need several bursts. A clean `[L,
285-1]` result retires this section; a mismatch that appears only past the first burst
286-confirms it. Note the control requirement — the probe is void unless the same run
287-shows the checker can report a mismatch
288-([investigation-discipline §13](../references/investigation-discipline.md)).
289- 
290-## A distribution-mode store writes the whole register, mask or no mask
291- 
292-Independent corroboration, from a second DSL, of a silent failure this KB already
293-records — and a constructive consequence the original entry does not state.
294- 
295-**Already measured here.** A masked `vf.store_align(dist=INTLV_B32)` **ignores its
296-predicate entirely**, writing every lane; the store succeeds and the data is wrong
297-only in the lanes the mask was supposed to protect
298-([framework-findings, A5 probe session](../references/pypto-pro-framework-findings.md)).
299- 
300-**The corroboration.** EasyASC's `constraints/a5.md` §6.2 reports, on the same
301-silicon, that its `DIST_NORM_B8` store "writes the full 256-byte register even
302-when only a prefix mask is active". Same shape of defect, a different DSL, a
303-different distribution mode, and a *different* mask (a prefix rather than a
304-scatter pattern). Two arrivals make this look like a property of the
305-distribution-mode store path rather than an artifact of one lowering.
306- 
307-**The consequence worth acting on, which is about allocation rather than
308-correctness.** EasyASC states it as a sizing rule: the scratch a masked
309-distribution store targets must be allocated for the **whole register**, 256
310-bytes, not for the active lane count. That is the constructive form — the
311-PyPTO-Pro entry tells you the data will be wrong; this tells you the buffer will
312-also be too small, which is the failure that shows up as corruption of whatever
313-was allocated next to it.
314- 
315-**未在 PyPTO-Pro 上验证 for the sizing rule specifically** (the mask-is-ignored
316-half *is* measured here). To verify: place a sentinel immediately after a scratch
317-tile sized to the active lane count, issue a masked distribution store into it,
318-and read the sentinel back.
@@ -1,8 +1,8 @@
1# Converting a mask between element widths1# Converting a mask between element widths
2 2 
3-A `MaskReg` can be converted to a different element width in **one instruction**. Two operators3+A `MaskReg` can be converted to a different element width in **one instruction**. Two separate
4-independently concluded it could not be, and between them that cost roughly **+8 OperatorScore**4+efforts independently concluded it could not be, and between them that cost several development
5-and several development rounds. This page exists because the capability is real but undiscoverable5+rounds of avoidable work. This page exists because the capability is real but undiscoverable
6from the place you would look for it.6from the place you would look for it.
7 7 
8## Why it is missed8## Why it is missed
@@ -70,19 +70,18 @@ Two details worth copying, both non-obvious: the destinations are pre-declared a
70| `interleave`/`de_interleave` take MaskRegs; `dtype` selects `pintlv/pdintlv_b8/16/32` | **documented** (`_vf_api.py:687,1312`; `de_interleave.md:31,111`) |70| `interleave`/`de_interleave` take MaskRegs; `dtype` selects `pintlv/pdintlv_b8/16/32` | **documented** (`_vf_api.py:687,1312`; `de_interleave.md:31,111`) |
71| `dst0` = lower part, `dst1` = higher part | **documented figure + numeric golden** (`test_vf_basic_ops.py:3865-3867` round-trips and recovers both 64-lane inputs) |71| `dst0` = lower part, `dst1` = higher part | **documented figure + numeric golden** (`test_vf_basic_ops.py:3865-3867` round-trips and recovers both 64-lane inputs) |
72| **narrowing** b32 → b16 | **sample-backed, shipped** |72| **narrowing** b32 → b16 | **sample-backed, shipped** |
73-| **widening** b16 → b32 | **measured on device** — `cummin/probe/probe_mask.py`, 128/128 lanes correct with `dtype=pl.DT_UINT16`; `dtype=pl.DT_UINT32` is wrong on 32/128, confirming `dtype=` names the *finer* width |73+| **widening** b16 → b32 | **measured on device** — a retained lane-mask probe, 128/128 lanes correct with `dtype=pl.DT_UINT16`; `dtype=pl.DT_UINT32` is wrong on 32/128, confirming `dtype=` names the *finer* width |
74| b32 ↔ b8 in three ops | **derived only** |74| b32 ↔ b8 in three ops | **derived only** |
75 75 
76## It working does not mean it pays76## It working does not mean it pays
77 77 
78-`cummin` verified the widening on device, built its native fp16/bf16 path on it, got a **correct**78+One effort verified the widening on device, built a native fp16/bf16 path on it, got a **correct**
79-kernel (253/253) — and measured it **slower on all four target cases** (0.322 → 0.245, 0.530 →79+kernel — and measured it **slower on every target case it was meant to help**. Reverted.
80-0.480, 0.377 → 0.368, 0.322 → 0.314). Reverted.
81 80 
82-The projected gain had been **+5.8 OperatorScore across 11 of 16 cases**, carried for three rounds.81+A substantial gain had been projected for it and carried for several rounds. It was void, and it
83-It was void, and it was **its own earlier fix that voided it**: a round before, `cummin` found the82+was **that effort's own earlier fix that voided it**: a round before, it had found the narrow-dtype
84-narrow-dtype penalty was mostly a UB bank conflict on the *work tile's* pitch rather than the fp3283+penalty was mostly a UB bank conflict on the *work tile's* pitch rather than the fp32 round trip,
85-round trip, and fixing the pitch collected that value. What remained of the round trip costs less84+and fixing the pitch had already collected that value. What remained of the round trip costs less
86than two `vf.interleave` calls plus doubled index-register traffic — the native step is 20 vector85than two `vf.interleave` calls plus doubled index-register traffic — the native step is 20 vector
87ops per 128 elements against 26-plus-a-cast, and still measures 1.18–1.44× worse.86ops per 128 elements against 26-plus-a-cast, and still measures 1.18–1.44× worse.
88 87 
@@ -29,10 +29,8 @@ CANN 9.1.0 vs dev 9.2.0), and its operator inventory is not a superset: a
29wrapper `.to(torch.float32)` that ran fine locally raised29wrapper `.to(torch.float32)` that ran fine locally raised
30`aclnnInplaceCopy failed, error code is 561103` (`EZ1013:30`aclnnInplaceCopy failed, error code is 561103` (`EZ1013:
31aclnnInplaceCopy_1_CastAiCore cannot be found`) on every fp16/bf16 case of a31aclnnInplaceCopy_1_CastAiCore cannot be found`) on every fp16/bf16 case of a
32-real submission, scoring 7/20 with all fp32 cases passing (job_cb400c1718cb,32+real delivery, where only the fp32 cases passed. A wrapper that dispatches no
33-2026-08-06). A wrapper that dispatches no device op has no such dependency.33+device op has no such dependency.
34-See the eval-runner trap entry in
35-[../playbooks/benchmark-scoring.md](../playbooks/benchmark-scoring.md).
36 34 
37Two consequences follow, and they are the durable part:35Two consequences follow, and they are the durable part:
38 36 
@@ -108,11 +106,30 @@ appear in the profile — it is `.contiguous()`, `.to()` and the movement ops
108that are charged. If in doubt, read the profile: anything named `aclnn*` in106that are charged. If in doubt, read the profile: anything named `aclnn*` in
109`op_times.device_kernels` is wrapper time.107`op_times.device_kernels` is wrapper time.
110 108 
111-## The one legitimate exception109+## What this boundary governs
112 110 
113-If a transformation genuinely cannot be expressed in the kernel, keep it, and111+It governs the **delivered wrapper** — the `{op}_wrapper` in `custom/<op>/test_{op}.py`
114-**record why** in `DESIGN.md` with the measured cost of the op you kept. An112+that ships with the operator and whose host time is measured.
115-unexplained host-side shaping op is a defect, not a trade-off.113+ 
114+It does **not** govern the driver functions in this KB's study samples under
115+`examples/samples/`. Those exist to make a sample runnable on its own, and they allocate,
116+reshape and synchronize to do that. They are harnesses, not delivery shapes — see
117+[examples/README.md](../examples/README.md). Do not copy one into a delivery and do not
118+read one as evidence that a call is permitted here.
119+ 
120+## There is no pre-approval exception
121+ 
122+`torch.empty` for output allocation is the only Torch call a delivered wrapper
123+may make. Nothing in `DESIGN.md` can widen that: an earlier revision of this
124+page let a transformation stay if the reason was recorded, which turns a hard
125+boundary into a promise and is how host-side `.t().contiguous()`, `torch.zeros`
126+and `torch.npu.synchronize` reached delivered wrappers.
127+ 
128+If a transformation appears impossible to express in the kernel, that is a
129+design problem to escalate at Stage 3, not something a wrapper may absorb.
130+Record the blocker and the measured cost of the alternative in `DESIGN.md` so it
131+can be judged -- but the recording is the escalation, never the authorization,
132+and the wrapper stays inside the boundary while it is judged.
116 133 
117### A bit reinterpretation is never that exception134### A bit reinterpretation is never that exception
118 135 
@@ -123,12 +140,11 @@ tile, an int64 pair viewed as two 32-bit words — happens **inside** the kernel
123and the wrapper needs no `.view()`.140and the wrapper needs no `.view()`.
124 141 
125This matters beyond tidiness. A host-side `.view()` or `.to()` is measured142This matters beyond tidiness. A host-side `.view()` or `.to()` is measured
126-time, and, as the runner-inventory trap in143+time, and an `aclnn`-dispatching host op is also a **compatibility** risk on any
127-[../playbooks/benchmark-scoring.md](../playbooks/benchmark-scoring.md) shows, an144+machine whose CANN inventory differs from the dev box -- the op set is not
128-`aclnn`-dispatching host op is also a **compatibility** risk on an evaluation145+guaranteed to be a superset. A kernel-side reinterpretation
129-runner whose CANN differs from the dev box. A kernel-side reinterpretation146+depends on nothing outside the delivered kernel itself. (Measured on
130-depends on nothing outside the submission. (Measured on Ascend950PR / CANN147+Ascend950PR / CANN 9.2.0.)
131-9.2.0.)
132 148 
133## How this is checked149## How this is checked
134 150 
@@ -12,3 +12,20 @@ Do not add failed, work-in-progress, diagnostic, or benchmark-only probes to
12the selector. Re-run the retained validation on the actual target before12the selector. Re-run the retained validation on the actual target before
13adopting a sample in production; a historical validation does not establish13adopting a sample in production; a historical validation does not establish
14compatibility with a different PyPTO/CANN version or platform.14compatibility with a different PyPTO/CANN version or platform.
15+ 
16+## What to copy from a sample, and what not to
17+ 
18+**Copy the kernel. Do not copy the driver.**
19+ 
20+A sample's value is the `@pl.jit` kernel body and the dataflow around it. Some samples
21+also define a `*_wrapper` (or a `__main__` block) whose job is to make the file runnable
22+by itself: it allocates an output, reshapes an operand into the layout the kernel expects,
23+and calls `torch.npu.synchronize()` so a smoke test measures something. Those are
24+**harness** calls.
25+ 
26+A delivered wrapper is held to a much narrower rule — `torch.empty` for output allocation
27+and nothing else, with layout work inside the kernel. See
28+[constraints/wrapper-boundary.md](../constraints/wrapper-boundary.md). A sample driver is
29+not an example of that rule and must not be read as one; copying its shape into
30+`custom/<op>/test_{op}.py` produces a boundary violation that the sample never claimed to
31+license.
@@ -20,7 +20,7 @@
20# output written with pl.AtomicType.AtomicAdd. The atomic is the new capability under test:20# output written with pl.AtomicType.AtomicAdd. The atomic is the new capability under test:
21# both vector sub-blocks accumulate their own 32-row slab into the SAME [0,0] region, so a21# both vector sub-blocks accumulate their own 32-row slab into the SAME [0,0] region, so a
22# correct result requires the atomic accumulate to serialize the two concurrent writes.22# correct result requires the atomic accumulate to serialize the two concurrent writes.
23-# Convention note: siblings compute q@k (not q@k.t()); easyasc golden is x@y.t() — the23+# Convention note: siblings compute q@k (not q@k.t()); the reference golden is x@y.t() — the
24# transpose convention is already proven separately by k4 (TN). Kept q@k to stay a pure24# transpose convention is already proven separately by k4 (TN). Kept q@k to stay a pure
25# delta on the proven template.25# delta on the proven template.
26import logging26import logging
@@ -7,16 +7,19 @@
7# See LICENSE in the root of the software repository for the full text of the License.7# See LICENSE in the root of the software repository for the full text of the License.
8# -----------------------------------------------------------------------------------------------------------8# -----------------------------------------------------------------------------------------------------------
9# Golden for the matmul_float_mmad transfer (pure torch, NO pypto — lint D3).9# Golden for the matmul_float_mmad transfer (pure torch, NO pypto — lint D3).
10-# twin_of: easyasc:kernels/a5/matmul/matmul_float_mmad.py
11#10#
12-# Oracle demonstrated on Tier 1 (Mac) via
13-# python tools/agent/easyasc_oracle_dump.py \
14-# ../easyasc/kernels/a5/matmul/matmul_float_mmad.py --out oracle/
15# SAMPLE PROVENANCE -- describes THIS reference implementation only.11# SAMPLE PROVENANCE -- describes THIS reference implementation only.
16# Do not copy this header into generated code: a generated kernel inherits12# Do not copy this header into generated code: a generated kernel inherits
17# no validation from the sample it was modelled on.13# no validation from the sample it was modelled on.
18# The oracle and simulator artifacts matched exactly; the reference performance target is 1,483 cycles.14# The oracle and simulator artifacts matched exactly; the reference performance target is 1,483 cycles.
19-# VALIDATED-CODE-SHA256: ed7722de58bb8cb621265fd66ec9dac1b1fc950b6c1d58f2bd245c0be032b83915+# RE-STAMP BASIS (this PR): the edit that moved this hash was **text only** -- a
16+# docstring/comment change with no executable difference, proved by comparing the
17+# parsed AST with docstrings stripped before and after. The recorded result above was
18+# NOT re-measured on a board. So this stamp asserts "semantically the same code as the
19+# one that produced that record", which is weaker than `--stamp-validation-hashes`'s
20+# normal meaning ("this exact code was just re-validated"). Re-run on target before
21+# relying on it as a fresh result.
22+# VALIDATED-CODE-SHA256: c4c115ec3421995800cb8e62e55da51165126e492400f8c157f90e49946038c2
20import logging23import logging
21 24 
22import torch25import torch
@@ -28,7 +31,7 @@ def matmul_float_mmad_golden(x, y):
28 """z = x @ y.T with FP32 accumulation.31 """z = x @ y.T with FP32 accumulation.
29 32 
30 x: [M, K] float32, y: [N, K] float32 -> z: [M, N] float32.33 x: [M, K] float32, y: [N, K] float32 -> z: [M, N] float32.
31- Matches the easyasc kernel's embedded reference `z_ref = x @ y.t()`.34+ Matches the reference implementation's `z_ref = x @ y.t()`.
32 The `.float()` is load-bearing: the pypto twin accumulates in FP32 in L0C35 The `.float()` is load-bearing: the pypto twin accumulates in FP32 in L0C
33 (constraints/precision.md), so the golden must accumulate in FP32 too.36 (constraints/precision.md), so the golden must accumulate in FP32 too.
34 """37 """
@@ -11,21 +11,27 @@
11# no validation from the sample it was modelled on.11# no validation from the sample it was modelled on.
12# STATUS: VALIDATED on Ascend a5 (950) NPU — 2026-07-17. pl tile DSL (pypto_pro.language).12# STATUS: VALIDATED on Ascend a5 (950) NPU — 2026-07-17. pl tile DSL (pypto_pro.language).
13# FP32 -> max_abs_diff = 0.000e+00 (bit-exact vs golden); FP16 -> 1.9e-06. Both PASS.13# FP32 -> max_abs_diff = 0.000e+00 (bit-exact vs golden); FP16 -> 1.9e-06. Both PASS.
14-# twin_of: easyasc:kernels/a5/matmul/matmul_float_mmad.py (z = x @ y.T, float)
15# Modeled on the real pl matmul test t01 (python/tests/ut/block/frontend/a5/matmul/14# Modeled on the real pl matmul test t01 (python/tests/ut/block/frontend/a5/matmul/
16# test_matmul_api_basic.py:92-125): GM->L1(Mat)->L0A(Left,NZ)/L0B(Right,ZN)->matmul->L0C(Acc)->GM.15# test_matmul_api_basic.py:92-125): GM->L1(Mat)->L0A(Left,NZ)/L0B(Right,ZN)->matmul->L0C(Acc)->GM.
17# pl has NO RunMode.SIM -> validated ONLY on Tier-3 NPU (bisheng compile + run).16# pl has NO RunMode.SIM -> validated ONLY on Tier-3 NPU (bisheng compile + run).
18-# The mapping: easyasc's explicit L1/L0/l0c staging + is_init become pl tile groups +
19-# sections; the cube dataflow is the same. Single-tile (smoke shape); tile the M/N/K
20# loops per test_doc_quickstart.py matmul_example for larger shapes.17# loops per test_doc_quickstart.py matmul_example for larger shapes.
21-# VALIDATED-CODE-SHA256: 20a9f1aac1557566c23e726cd4c9e6066b075e02adfd7ab33387f028ebe6f43018+# NOT A DELIVERY SHAPE: the `*_wrapper` below is this sample's own driver so the
22-# The EasyASC source was used only to verify the data-flow mapping; this sample keeps the19+# file runs standalone. Its host-side allocation, layout and synchronize calls are
23-# equivalent PyPTO tile stages below instead of retaining a second implementation in comments.20+# harness, not a licensed pattern -- a delivered wrapper may call only torch.empty.
21+# See ../../../constraints/wrapper-boundary.md. Copy the kernel, not the driver.
22+# RE-STAMP BASIS (this PR): the edit that moved this hash was **text only** -- a
23+# docstring/comment change with no executable difference, proved by comparing the
24+# parsed AST with docstrings stripped before and after. The recorded result above was
25+# NOT re-measured on a board. So this stamp asserts "semantically the same code as the
26+# one that produced that record", which is weaker than `--stamp-validation-hashes`'s
27+# normal meaning ("this exact code was just re-validated"). Re-run on target before
28+# relying on it as a fresh result.
29+# VALIDATED-CODE-SHA256: 4728b84f81f7e40d8b38f708c3791aef03b730b020064e02985f69c51e631b20
24import pypto_pro.language as pl30import pypto_pro.language as pl
25import torch31import torch
26import torch_npu # noqa: F401 required for NPU device init32import torch_npu # noqa: F401 required for NPU device init
27 33 
28-M, K, N = 32, 16, 48 # easyasc smoke shapes (multiples of the 16 cube fractal)34+M, K, N = 32, 16, 48 # smoke shapes (multiples of the 16 cube fractal)
29 35 
30 36 
31@pl.jit(auto_mutex=True)37@pl.jit(auto_mutex=True)
@@ -71,7 +77,7 @@ def matmul_float_mmad_kernel(
71 77 
72 78 
73def matmul_float_mmad_wrapper(x, y):79def matmul_float_mmad_wrapper(x, y):
74- """easyasc contract z = x @ y.T. x:[M,K], y:[N,K] -> z:[M,N]. Pass y.T as the B operand."""80+ """contract z = x @ y.T. x:[M,K], y:[N,K] -> z:[M,N]. Pass y.T as the B operand."""
wangzheng97
wangzheng97wangzheng978月21日

[P1] 重新盖章的 validated 样例仍越过 Pro wrapper 硬边界

问题:本 PR 修改该 wrapper 的 docstring 并重写 VALIDATED-CODE-SHA256,但返回路径仍执行 y.t().contiguous()、torch.zeros() 和 torch.npu.synchronize()。PyPTO-Pro 返回式 wrapper 唯一允许的 Torch 接口是用 torch.empty 分配输出;同 PR 修改的 wrapper-boundary.md 还保留了通过 DESIGN.md 预批额外 Torch 变换的例外。

影响:production selector 会继续向 material explorer/coder 提供一个“validated”但不满足单 kernel 交付边界的参考实现;复制完整样例会引入额外 device op、同步和兼容性风险。

建议:让 kernel 接收原始 y 并在 kernel 内完成 transpose/layout,wrapper 只用 torch.empty 分配且只 launch 一次;移除显式 synchronize,并删除 DESIGN 预批额外 Torch 接口的例外。验证器也应检查 wrapper 边界,而不只是内容 hash。

likedislike
75 b = y.t().contiguous() # [K, N] = y.T81 b = y.t().contiguous() # [K, N] = y.T
76 out = torch.zeros((x.shape[0], y.shape[0]), dtype=torch.float32, device=x.device)82 out = torch.zeros((x.shape[0], y.shape[0]), dtype=torch.float32, device=x.device)
77 matmul_float_mmad_kernel(x, b, out) # plain call = single default core83 matmul_float_mmad_kernel(x, b, out) # plain call = single default core
@@ -14,7 +14,7 @@
14# Gate A was bit-exact on the 1024-by-1024-by-128 FP32 case. Gate B reached 89.8% cube14# Gate A was bit-exact on the 1024-by-1024-by-128 FP32 case. Gate B reached 89.8% cube
15# utilisation. The implementation uses the proven tiled multicore TN transpose-load pattern.15# utilisation. The implementation uses the proven tiled multicore TN transpose-load pattern.
16# Kernel 4 computes a transposed-left-operand FP32 matmul with reduction dimension 128.16# Kernel 4 computes a transposed-left-operand FP32 matmul with reduction dimension 128.
17-# twin_of easyasc matmul_kmkn_fp32_out (golden x.t()@y fp32, tol 3e-3). Place in a5/matmul dir.17+# Golden is x.t()@y fp32, tol 3e-3.
18import csv18import csv
19import glob19import glob
20import logging20import logging
@@ -15,6 +15,10 @@
15# Modeled on python/tests/ut/block/frontend/a5/tile_vector/test_softmax.py.15# Modeled on python/tests/ut/block/frontend/a5/tile_vector/test_softmax.py.
16# Fully dynamic rows AND cols; row-tiles spread across vector cores; tail handled by16# Fully dynamic rows AND cols; row-tiles spread across vector cores; tail handled by
17# pl.set_validshape. pl has NO RunMode.SIM -> validated ONLY on Tier-3 NPU.17# pl.set_validshape. pl has NO RunMode.SIM -> validated ONLY on Tier-3 NPU.
18+# NOT A DELIVERY SHAPE: the `*_wrapper` below is this sample's own driver so the
19+# file runs standalone. Its host-side allocation, layout and synchronize calls are
20+# harness, not a licensed pattern -- a delivered wrapper may call only torch.empty.
21+# See ../../../constraints/wrapper-boundary.md. Copy the kernel, not the driver.
18# VALIDATED-CODE-SHA256: c3238d2b21879ab4e34a4dfbd570661eee7bed91e406d3eae0f750fb9cae3bb822# VALIDATED-CODE-SHA256: c3238d2b21879ab4e34a4dfbd570661eee7bed91e406d3eae0f750fb9cae3bb8
19import pypto_pro.language as pl23import pypto_pro.language as pl
20import torch24import torch
@@ -8,9 +8,9 @@ evidence, not a substitute for re-running correctness on the current SDK and tar
8|---|---|---|---|---|8|---|---|---|---|---|
9| UB strip gather | Ascend950PR_9579, CANN 9.2.0 | Twelve dtype combinations for the UB-strip gather dataflow | 12/12 combinations bit-exact; fp32 path measured end to end | Other targets and SDK versions require revalidation |9| UB strip gather | Ascend950PR_9579, CANN 9.2.0 | Twelve dtype combinations for the UB-strip gather dataflow | 12/12 combinations bit-exact; fp32 path measured end to end | Other targets and SDK versions require revalidation |
10| TensorList fixed arity | Ascend950PR_9579, CANN 9.2.0 | Generated fixed-arity kernels for list lengths 1–64 over three dtypes | 21 generated kernels compiled; the 64-slot/385-parameter form launched and returned per-slot-correct data | Runtime-variable arity still requires padding to the compiled maximum |10| TensorList fixed arity | Ascend950PR_9579, CANN 9.2.0 | Generated fixed-arity kernels for list lengths 1–64 over three dtypes | 21 generated kernels compiled; the 64-slot/385-parameter form launched and returned per-slot-correct data | Runtime-variable arity still requires padding to the compiled maximum |
11-| Scatter owner model | Ascend950PR_9579 | Inner-tile owner layout with fp32 update mode | Addressing/owner model bit-exact against torch; whole operator passed 14/20 recorded cases | Owner-batch and rank-1 layouts remained conceptual; narrow-dtype accumulation was not validated |11+| Scatter owner model | Ascend950PR_9579 | Inner-tile owner layout with fp32 update mode | Addressing/owner model bit-exact against torch in the recorded fp32 scope | Owner-batch and rank-1 layouts remained conceptual; narrow-dtype accumulation was not validated |
12| Prefix-dependent scan | Ascend950PR_9579 | Both dataflows described by the scan pattern | Both built and compiled; recorded outputs were bit-exact | Performance figures are target-specific and are not reusable targets |12| Prefix-dependent scan | Ascend950PR_9579 | Both dataflows described by the scan pattern | Both built and compiled; recorded outputs were bit-exact | Performance figures are target-specific and are not reusable targets |
13-| Row-reduce broadcast | Ascend950PR_9579 | Tile-operation row reduction, over-declared reduction tile and short-axis measurements | Recorded 20/20 cases; TR 1, 2, 3, 4, 8 and 16 produced the same fp32 rounding as legal TR=8 | Vector-function form and the very-short-axis limitation require separate validation |13+| Row-reduce broadcast | Ascend950PR_9579 | Tile-operation row reduction, over-declared reduction tile and short-axis measurements | Bit-exact across the full recorded case set; TR 1, 2, 3, 4, 8 and 16 produced the same fp32 rounding as legal TR=8 | Vector-function form and the very-short-axis limitation require separate validation |
14| Paired-lane rotation | Ascend950PR_9579 | Retained interleaved fp32 sample: one operand pair, static innermost width, pre-broadcast coefficients | Sample is validated for its multicore row-tile loop | Split-half pairing, runtime divisor/rank and table lookup regimes are not validated by that sample |14| Paired-lane rotation | Ascend950PR_9579 | Retained interleaved fp32 sample: one operand pair, static innermost width, pre-broadcast coefficients | Sample is validated for its multicore row-tile loop | Split-half pairing, runtime divisor/rank and table lookup regimes are not validated by that sample |
15 15 
16When a pattern page claims more than the scope recorded above, the narrower scope wins.16When a pattern page claims more than the scope recorded above, the narrower scope wins.
@@ -68,6 +68,11 @@ tokens as the epilogue drains. **Both sides stay balanced whatever the number
68is**, so a wrong credit count produces no unbalanced-event warning, no assertion,68is**, so a wrong credit count produces no unbalanced-event warning, no assertion,
69and no error. Nothing reports it; the values are simply stale.69and no error. Nothing reports it; the values are simply stale.
70 70 
71+> **未在 PyPTO-Pro 上验证。** 上面这条"错误的 credit 数不会引发任何诊断"是从另一套
72+> DSL 对其自身 prologue/epilogue 的观察迁移过来的,本仓从未复现过。
73+> **本地验证方法**:用两槽 group 搭一个两拍、两角色的轮转,跑一个会回绕的 shape,
74+> 看是否有任何一层报出来。在复现之前,把它当作待验证假设,不要当作 PyPTO-Pro 的既定行为。
75+ 
71Two further non-proofs, from the same source:76Two further non-proofs, from the same source:
72 77 
73- **Source order is not retirement.** That a store appears earlier in the Python78- **Source order is not retirement.** That a store appears earlier in the Python
@@ -97,16 +102,6 @@ from the indexing side.
97core; see102core; see
98[investigation-discipline §13.2](../references/investigation-discipline.md).103[investigation-discipline §13.2](../references/investigation-discipline.md).
99 104 
100-**Provenance.** From EasyASC's `patterns/buffer-slot-lifetime.md`, with its slot
101-types (`DBuff`/`TBuff`/`QBuff` = 2/3/4 slots) and its explicit mutex-`depth`
102-parameter dropped — PyPTO-Pro spells the same thing as the slot count of a
103-`make_tile_group(..., auto_mutex=True)`. The counting law and the
104-credits-are-not-slots distinction transfer as reasoning. **未在 PyPTO-Pro 上验证**
105-for the specific claim that a wrong credit count raises *no* diagnostic here;
106-that is EasyASC's observation about its own prologue/epilogue, and the
107-PyPTO-Pro-side check is to build a two-beat two-role rotation with a two-slot
108-group on a wrapping shape and see whether anything at all complains.
109- 
110## Validation status105## Validation status
111 106 
112The rotating input, output, scratch, and reduction groups in the retained107The rotating input, output, scratch, and reduction groups in the retained
@@ -0,0 +1,102 @@
1+# Quantized matmul with a direct floating-point epilogue
2+ 
3+## Applies when
4+ 
5+**A5 only.** The dataflow below freezes A5 memory capacities, event mapping and
6+width gates; the routing table selects this page by operator class, not by
7+target, so check the target before taking anything here as a constant.
8+ 
9+An integer Cube contraction remains in int32 through the full K reduction, then
10+feeds a floating-point Vector epilogue in the same kernel. The output is
11+fp16/bf16 rather than a clamped integer, so
12+`quant-matmul-scaled-mm.md`'s round/clamp skeleton is not the formula oracle.
13+ 
14+## Invariants
15+ 
16+- Freeze the epilogue order from the golden: integer pre-bias, FP32 scale,
17+ optional offset, optional per-token scale, floating post-bias, final cast.
18+- Keep the compact Acc physical window unchanged from the first matmul through
19+ the handoff. Pin the selected physical family as `[tile_m, tile_n]`; do not
20+ hard-code a baseline `TN` after adding a wider tiling key.
21+- Use `make_tile_group + auto_mutex` for every rotating L1/L0 buffer. Advance
22+ L1 once per non-empty K1 step and L0 once per non-empty K0 step.
23+- For direct Acc-to-Vector TMOV, do not use Acc `Final` phase: there is no
24+ `STPhase.Final` consumer to reset the unit flag.
25+- Prove UB capacity and GM beat ownership for the selected hardware split. Use
26+ a single-AIV fallback when an unaligned output stride makes sibling stores
27+ share a 32-byte beat.
28+- Balance cross-core READY/FREE credits for repeated same-core reuse; one-tile
29+ success is insufficient. On the validated direct path, prime and return FREE
30+ on MTE3, and place the per-task return after the conditional output store.
31+ 
32+## Reusable gated-width pattern
33+ 
34+Keep the common TN256 path and add TN512 as a compile-time tiling-key family,
35+not as a global width change. The retained A5 gate requires all of:
36+ 
37+```text
38+M >= 257
39+K >= 3584
40+N % 512 == 0
41+per-token scale is absent
42+baseline P0 tile count >= 56
43+```
44+ 
45+The selected `tile_n` must flow through L1/L0B/Acc shapes, offsets, valid
46+shapes, UB capacity checks and the JIT key. The validated high-water marks are
47+L1 393216 B, L0A 16384 B, L0B 65536 B, L0C 262144 B and UB 203264 B on A5.
48+Small/decode TN512 is a negative template: it passed codegen inspection and was
49+bit-exact on every case it was run against, yet the decode-shaped subset measured
50+**slower than the baseline** — roughly a third slower in geometric mean, and worse
51+still on the narrowest shapes. Exactness plus a clean CCE does not imply the tile
52+choice pays on small shapes.
53+ 
54+For FP16/BF16 output, two adjacent row stores of 256 columns are universally
55+32-byte-beat disjoint when their byte gap is at least 32:
56+ 
57+```text
58+gap_bytes = (N - 256) * 2
59+```
60+ 
61+判据只有这一条不等式:**`gap_bytes >= 32` 才有不相交的 32B beat**。按它推:
62+N=272 给出 `gap_bytes = 32`,**满足**判据;N=271 只有 30 字节,不满足,且有具体的
63+边界对齐使相邻 AIV store 落在同一 beat 上。
64+ 
65+因此可接纳的最小宽度是 **N=272**,不是 273——早前写成 273 是把"不满足判据"与
66+"恰好落在判据边界"混为一谈。若某个目标上要额外留出余量,把余量写进不等式
67+(例如要求 `gap_bytes > 32`)并说明理由,不要在正文里另立一个与不等式不一致的门限。
68+ 
69+用 dual-AIV SplitM 只限已验证的非 decode family 且 `gap_bytes >= 32`;
70+更窄的尾巴与 decode 留在单 AIV 回退路径上。
71+ 
72+本仓不保留该 A5 study 的 kernel,因此这里不给出可点开的产物路径。**相应地,
73+上面的相对加速比按 study 证据读——量级可用于判断方向,绝对数值不可复核,
74+不要当作目标或验收线。** 可复现的是它覆盖到什么程度:4×L1/2×L0 轮转在 K=1/63/64/65/127/128/129/257/513、M/N 尾块、多 tile 复用
75+与 batch 上通过逐位比较——**覆盖面本身是可检查的判据**(跨越轮转的每个边界),
76+按这个覆盖面在自己的目标上重做,比引用一个打不开的文件有用。
77+Use [the develop-skill reference](../../pypto-pro-op-develop/references/cv-matmul-direct-buffering.md)
wangzheng97
wangzheng97wangzheng978月18日

[P1] PR #501 单独合入时存在 7 个跨 PR 断链

问题:这个引用以及同一 PR 中另外 6 个引用只在 PR #444 中存在;#501 与 #444 都以同一基线为目标,且 #501 没有声明为 stacked PR。

影响:#501 单独合入后 KB 导航、模板和验证材料不可用,完整性检查直接失败。

证据:在当前 #501 head 运行 check_kb_integrity.py 返回 1,断链覆盖 direct-buffering、staged checklist、stage-task、tiling-key、EasyAsc、cube-shared 和 typed-tilegroup;只有把 #444 内容叠加后才通过。

建议:让 #501 自包含,或明确声明依赖 #444,并在 #444 合入后 rebase;CI 必须针对每个 PR 的独立结果运行完整性检查。

likedislike
78+for resource formulas, synchronization details and promotion gates.
79+ 
80+## Validation boundary
81+ 
82+The dataflow is an A5 study whose kernel is not retained in this repository,
83+not a universal code template. Recheck
84+the target SDK's Acc-to-Vector modes, auto-mutex lowering, event mapping and
85+memory capacities. Tile width/depth changes require fresh codegen, locked
86+device exactness and kernel-only profiling.
87+ 
88+Do not infer that a target is met from a local geometric speedup alone. In one
89+recorded run, a ~1.4x local kernel gain on three shapes read as a ~1.5x gain across
90+the full shape set, yet the end-to-end result improved far less, because startup,
91+handshake and underfilled-wave costs still dominated several shapes. Quantify that
92+gap before choosing the next experiment.
93+ 
94+The subsequent gated WideN/N-tail study reinforces the same rule. Its ten
95+selected main paths improved by 1.071656x under the A5 lock and 1.061559x when
96+compared with the preceding kernel's device times; the N-tail case improved by
97+1.497716x locally and 1.381942x on the target. Despite that agreement, the
98+end-to-end figure moved less than the kernel gain, because the baseline it is
99+measured against is not under your control and can change between runs. Compare
100+device kernel times for candidate bytes, and use a geometric speedup only
101+against the baseline measured in the same run. Correctness closure does not
102+imply a performance target is closed.
@@ -54,12 +54,6 @@ The requirement above — "exclude padding lanes from both `row_max` and
54`row_sum`" — is correct but under-specified, and the under-specification has a54`row_sum`" — is correct but under-specified, and the under-specification has a
55name. This section says *where* in the recurrence each mask lands.55name. This section says *where* in the recurrence each mask lands.
56 56 
57-**Provenance.** The ordering and the failure chain are from EasyASC
58-(`patterns/online-softmax-tail.md`, board-exercised there on A2 flash-attention
59-kernels): **未在 PyPTO-Pro 上验证——由 EasyASC 移植的假设**. The sentinel rule
60-below has an independent PyPTO-Pro anchor and is not merely assumed. This page is
61-conceptual-only either way, so nothing here is an implementation skeleton.
62- 
63### Padding zeros are not neutral for a maximum57### Padding zeros are not neutral for a maximum
64 58 
65When the final score chunk has `valid_n < TILE_N`, the padded columns of the59When the final score chunk has `valid_n < TILE_N`, the padded columns of the
@@ -119,13 +113,11 @@ NEG_LARGE = -1.0e30
119and initialise the running row-max `m` to it as well, so the first chunk's113and initialise the running row-max `m` to it as well, so the first chunk's
120`max(m_old, m_chunk)` is a no-op rather than a special case.114`max(m_old, m_chunk)` is a no-op rather than a special case.
121 115 
122-**This one has a local anchor, and it is stronger than the cross-DSL reason.**116+**This one has a local anchor.** In PyPTO-Pro a module-level
123-EasyASC's stated reason is that true `-inf` is not reliably representable across
124-all vector paths — unverified here. But in PyPTO-Pro a module-level
125`float("inf")` **does not even compile**: it renders as the undeclared C++117`float("inf")` **does not even compile**: it renders as the undeclared C++
126identifier `inff` and bisheng rejects the generated `kernel.cpp`118identifier `inff` and bisheng rejects the generated `kernel.cpp`
127([pypto-pro-dsl-limitations-a5.md](../references/pypto-pro-dsl-limitations-a5.md)119([pypto-pro-dsl-limitations-a5.md](../references/pypto-pro-dsl-limitations-a5.md)
128-#19, measured on cummin). So the finite sentinel is the route here regardless of120+#19, measured on a scan kernel). So the finite sentinel is the route here regardless of
129whether the representability claim transfers.121whether the representability claim transfers.
130 122 
131**The sentinel has one hazard, and it is the all-invalid row.** On a row where123**The sentinel has one hazard, and it is the all-invalid row.** On a row where
@@ -19,6 +19,7 @@ The validation column controls how a pattern may be used:
19| [buffer-reuse-lifetime.md](buffer-reuse-lifetime.md) | tile groups rotate or persist across iterations | validated skeleton for the indexed rotating groups; conceptual for other loop-carried state |19| [buffer-reuse-lifetime.md](buffer-reuse-lifetime.md) | tile groups rotate or persist across iterations | validated skeleton for the indexed rotating groups; conceptual for other loop-carried state |
20| [batched-2d-contraction.md](batched-2d-contraction.md) | host reshaping can reduce a batched contraction to 2-D | conceptual only |20| [batched-2d-contraction.md](batched-2d-contraction.md) | host reshaping can reduce a batched contraction to 2-D | conceptual only |
21| [quant-matmul-scaled-mm.md](quant-matmul-scaled-mm.md) | a quantized matmul uses explicit scale/round/clamp semantics | validated skeleton for the indexed int8 path |21| [quant-matmul-scaled-mm.md](quant-matmul-scaled-mm.md) | a quantized matmul uses explicit scale/round/clamp semantics | validated skeleton for the indexed int8 path |
22+| [cv-quant-matmul-direct-epilogue.md](cv-quant-matmul-direct-epilogue.md) | an integer Cube contraction feeds a floating-point Vector epilogue directly | conceptual only |
22| [vec-per-token-dynamic-quant.md](vec-per-token-dynamic-quant.md) | each row is quantized by a scale derived from that row, and the scale is an output | conceptual only |23| [vec-per-token-dynamic-quant.md](vec-per-token-dynamic-quant.md) | each row is quantized by a scale derived from that row, and the scale is an output | conceptual only |
23| [online-softmax-tail.md](online-softmax-tail.md) | a softmax reduction streams across multiple score chunks | conceptual only |24| [online-softmax-tail.md](online-softmax-tail.md) | a softmax reduction streams across multiple score chunks | conceptual only |
24| [vec-scan-prefix-dependent.md](vec-scan-prefix-dependent.md) | element i of the output depends on elements 0..i along one axis | validated skeleton for both dataflows, measured on Ascend950PR_9579 |25| [vec-scan-prefix-dependent.md](vec-scan-prefix-dependent.md) | element i of the output depends on elements 0..i along one axis | validated skeleton for both dataflows, measured on Ascend950PR_9579 |
@@ -110,12 +110,12 @@ absolute error of each product can exceed the magnitude of their difference, and
110relative-error gates fail on the positions where the result is near zero.110relative-error gates fail on the positions where the result is near zero.
111 111 
112Before reaching for compensated arithmetic, establish **which references the gate112Before reaching for compensated arithmetic, establish **which references the gate
113-actually compares against**. A grader that supplies a same-precision reference113+actually compares against**. An accuracy gate that supplies a same-precision
114-alongside its high-precision oracle typically grades the normal range as a *ratio*114+reference alongside its high-precision oracle typically judges the normal range as
115-against that reference, in which case reproducing the reference's operation order115+a *ratio* against that reference, in which case reproducing the reference's
116-in the operand's own precision already passes, and compensated arithmetic buys116+operation order in the operand's own precision already passes, and compensated
117-nothing. A grader that supplies only the oracle grades absolutely, and then117+arithmetic buys nothing. A gate that supplies only the oracle judges absolutely,
118-compensation is required.118+and then compensation is required.
119 119 
120Getting this backwards is expensive in both directions, and it is not usually120Getting this backwards is expensive in both directions, and it is not usually
121documented in the task package — read the evaluator. A worked instance, including121documented in the task package — read the evaluator. A worked instance, including
@@ -78,8 +78,8 @@ from the toolbox for a very short axis.
78 78 
79## Where the time goes79## Where the time goes
80 80 
81-Measured on `Ascend950PR_9579` for `rms_norm`, which is this pattern with the81+Measured on `Ascend950PR_9579` for a row normalization, which is this pattern
82-`max`/`sub`/`exp` steps removed:82+with the `max`/`sub`/`exp` steps removed:
83 83 
84* **The fp32 form is memory-bound and the arithmetic is free.** At a 268 MB84* **The fp32 form is memory-bound and the arithmetic is free.** At a 268 MB
85 working set a pure copy ran 217.0 us and the full reduce-and-broadcast chain85 working set a pure copy ran 217.0 us and the full reduce-and-broadcast chain
@@ -105,8 +105,8 @@ load contiguous but destroys the per-row reduction, and the compact re-view that
105would restore it is blocked by the Cols alignment rule above. Record the cost105would restore it is blocked by the Cols alignment rule above. Record the cost
106rather than assuming a tiling escape exists.106rather than assuming a tiling escape exists.
107 107 
108-**Measured escapes now exist for the vf form** (rms_norm, Ascend950PR_9579,108+**Measured escapes now exist for the vf form** (Ascend950PR_9579, 2026-08-06,
109-2026-08-06, 20/20 public + 19/19 hidden-guess): keep the reduction in109+bit-exact across the whole measured domain): keep the reduction in
110*registers* instead of re-viewing tiles — load rows contiguously and restore110*registers* instead of re-viewing tiles — load rows contiguously and restore
111per-row sums with in-register shuffles, one kernel family per D band.111per-row sums with in-register shuffles, one kernel family per D band.
112- D=2: de-interleave even/odd lanes (`DINTLV_B32` for fp32; `vf.astype`112- D=2: de-interleave even/odd lanes (`DINTLV_B32` for fp32; `vf.astype`
@@ -133,10 +133,10 @@ form is a separate implementation choice and must be validated against the
133target SDK's current API.133target SDK's current API.
134 134 
135The sizing rules, the over-declared reduction tile and the measurements above135The sizing rules, the over-declared reduction tile and the measurements above
136-are preserved in the [retained validation record](../examples/validation-records.md): 20/20 cases136+are preserved in the [retained validation record](../examples/validation-records.md): bit-exact
137-passing at TR ranging 1..128. The over-declaration is verified at TR = 1, 2, 3,137+across the full recorded case set at TR ranging 1..128. The over-declaration is verified at TR = 1, 2, 3,
1384, 8 and 16 producing the same fp32 rounding as the legal TR=8 form, not merely a1384, 8 and 16 producing the same fp32 rounding as the legal TR=8 form, not merely a
139close one. The "very short axis" section's degradation is measured; its139close one. The "very short axis" section's degradation is measured; its
140-register-shuffle escapes above are also measured (on branch `bench/rms_norm-a5`,140+register-shuffle escapes above are also measured (verifier-rerun 2026-08-06,
141-`custom/rms_norm/{DESIGN.md,test_rms_norm.py}`, verifier-rerun 2026-08-06) —141+against a retained row-normalization implementation) — port the family
142-port the family structure, not the numbers.142+structure, not the numbers.
@@ -146,6 +146,37 @@ read of the same address inside a vector function requires
146`vf.mem_bar(mode=pl.MemBarMode.VST_VLD)`** — omit it and the kernel faults the146`vf.mem_bar(mode=pl.MemBarMode.VST_VLD)`** — omit it and the kernel faults the
147vector core — and the barrier, not the store or the load, is what costs.147vector core — and the barrier, not the store or the load, is what costs.
148 148 
149+**屏障不是全部——但这条的证据等级低于上一条,必须分开读。**
150+ 
151+*源码级(本 checkout 可核对)*:`vf.mem_bar` 的模式为 `VST_VLD` / `VST_VST` / `VV_ALL`
152+(`pypto_pro/language/_vf_api.py:242-252`),它排序的是本地内存流。源码只确立模式集合,
153+**不足以确立**下面这条更强的结论。
154+ 
155+> **未在 PyPTO-Pro 上验证——由另一套 tile DSL 移植的假设。** 在那套 DSL 下于
156+> Ascend 950 实测过,此处**未**复现。carry 它的理由是它把本 KB 已有的规则往
157+> **不安全**方向收窄,而这个方向的修正自己踩出来代价很高。
158+ 
159+被移植的结论有两条,都保持假设状态:
160+ 
161+- **不要在同一个 vector-function 循环里,把一个 UB tensor 同时用作"逐元素基值来源"
162+ 和"prefix / reverse-prefix 目的地"。** 那套 DSL 的记述是:store→load 屏障
163+ "orders local memory streams, but it does not turn that UB read/write alias into
164+ scalar program order on hardware"——屏障在场,别名递推依然错。
165+- **"换成两个 UB tensor"并未被确立为与寄存器累加等价。** 这条同样值得带过来:
166+ 别名规则的显而易见的修法(基值放一个 tensor、结果写另一个)在那套 DSL 的
167+ 随机输入硬件探针上**也失败了**。其保留立场是把 staged UB 递推当作需要硬件验证的例外,
168+ 而不是默认写法。
169+ 
170+**要在 PyPTO-Pro 上把它升级为硬规则,需要的探针**:同一 vector-function 循环内做别名
171+递推,加满 `vf.mem_bar(VST_VLD)`,用**随机**输入在目标板上与 golden 逐位比较;再用
172+分离 src/dst 的版本重跑一次。在此之前按假设处理——写法上仍建议把 loop-carried 状态
173+放寄存器(成本低),但不要据此判定某个实现"必然错"。
174+ 
175+**为什么输入分布是关键**:该失败只在*随机*输入上出现。用 ramp、常量或小整数探到的 scan
176+可能是"构造上正确"——结构化数据下递推的错误中间值与正确值重合的概率远高于随机数据。
177+见 [investigation-discipline §13](../references/investigation-discipline.md)。
178+ 
179+ 
149Per 64-lane register on this SKU: `vf.gather` ~20 ns, `vf.scatter` ~18 ns, a180Per 64-lane register on this SKU: `vf.gather` ~20 ns, `vf.scatter` ~18 ns, a
150barriered UB round trip ~16 ns, an aligned `load_align`/`store_align` under181barriered UB round trip ~16 ns, an aligned `load_align`/`store_align` under
1511 ns, the arithmetic ~0.3 ns. **Every way of moving data across lanes costs1821 ns, the arithmetic ~0.3 ns. **Every way of moving data across lanes costs
@@ -306,61 +337,6 @@ jobs" from "slow per element", which look identical in a score column.
306 and medium cases are therefore **vector-issue-bound**, and op count — not337 and medium cases are therefore **vector-issue-bound**, and op count — not
307 traffic — is what to minimise. Check before tuning tiles.338 traffic — is what to minimise. Check before tuning tiles.
308 339 
309-## Keep the recurrence in registers — the barrier is not the whole story
310- 
311-**未在 PyPTO-Pro 上验证——由 EasyASC 移植的假设 (unverified on PyPTO-Pro — an
312-assumption ported from EasyASC).** Board-probed under EasyASC on Ascend 950. It is
313-carried here because it **narrows** a rule this KB already states, and narrowing a
314-rule in the unsafe direction is the kind of correction that is expensive to
315-discover for yourself.
316- 
317-**What this KB already says.** A scratch store must be fenced before the next
318-vector load reads it
319-(`ops/pypto-pro-op-develop/references/vf-reduction-perf.md` § "Scratch stores need
320-a barrier before the next vector load"). The local fence is `vf.mem_bar`, whose
321-modes are `VST_VLD`, `VST_VST` and `VV_ALL`
322-(`pypto_pro/language/_vf_api.py:242-252`). Read on its own, that section implies
323-the barrier is *sufficient* — put the fence in and the round trip is safe.
324- 
325-**What EasyASC reports, and it is the stronger claim.** For a scan, cumsum, or
326-row-wise recurrence inside a vector function, keep the loop-carried state in
327-registers. Specifically (`constraints/a5.md` §1, `facts-authoring.md:147`):
328- 
329-- **Do not use one UB tensor as both the per-element base-value source and the
330- prefix / reverse-prefix destination inside the same vector-function loop.** A
331- `vf_barrier(STORE, LOAD)` "orders local memory streams, but it does not turn
332- that UB read/write alias into scalar program order on hardware." The fence is
333- present and the aliased recurrence is still wrong.
334-- **Separate source and destination UB tensors are not established as equivalent
335- to register accumulation either.** That is the part worth carrying: the obvious
336- fix for the aliasing rule — stage the base values in one tensor, write results
337- to another — **also failed the random-input hardware probe.** EasyASC's retained
338- position is to treat a staged UB recurrence as a hardware-validated exception,
339- never as a default.
340- 
341-**Why the input distribution is load-bearing here.** The failure was seen on
342-*random* inputs. A scan probed on a ramp, a constant, or small integers can be
343-right by construction — the recurrence's wrong intermediate and its right one
344-coincide for structured data far more often than they do for random data. This is
345-[investigation-discipline §13](../references/investigation-discipline.md) in its
346-data form: a green probe on a friendly input is not a green probe. Any test of a
347-staged recurrence has to run random inputs, and has to show the checker going red.
348- 
349-**Design consequence, in this DSL's terms.** Where the scan state can live in
350-`vf` registers across the loop, keep it there and do not stage it through UB for
351-readability or for register pressure without measuring. Where the base vector
352-genuinely must be staged, use distinct source and destination tiles — that
353-remains the least-bad staged form — and treat the result as unvalidated until it
354-has been run on the board against random inputs.
355- 
356-**Named probe to settle it here:** one `vf` scan over a tile, built three ways —
357-register-carried accumulator; one UB tile as both source and destination with
358-`vf.mem_bar(VST_VLD)` between; separate source and destination UB tiles with the
359-same fence — all three run against a CPU reference on uniform random input at a
360-length that needs several loop iterations. If the two staged forms match the
361-register form bit-for-bit, this section is retired for PyPTO-Pro; if either
362-diverges, it is promoted to a measurement.
363- 
364## Where this was built340## Where this was built
365 341 
366The [retained validation record](../examples/validation-records.md) covers both dataflows342The [retained validation record](../examples/validation-records.md) covers both dataflows
@@ -13,13 +13,12 @@ owner-batch and rank-1 layouts.
13**Evidence:** [retained validation record](../examples/validation-records.md), which keeps13**Evidence:** [retained validation record](../examples/validation-records.md), which keeps
14the fp32 inner-tile result and its explicit exclusions separate from the conceptual layouts.14the fp32 inner-tile result and its explicit exclusions separate from the conceptual layouts.
15 15 
16-**Read the scope literally.** The operator as a whole scored **14 of 20 cases**, and the16+**Read the scope literally.** The record validates **the owner model and the inner-tile
17-known failures are narrow-dtype accumulation — `float16` `add` misses the gate on MARE17+addressing**, in fp32. It does **not** validate narrow-dtype accumulation: `float16` `add`
18-while its MERE stays small, which is accumulation order, not addressing. So this page18+misses the gate on MARE while its MERE stays small, which is accumulation order, not
19-validates **the owner model and the inner-tile addressing**, in fp32. It does **not**19+addressing. Nor does a bit-exactness figure recorded against a **golden** transfer to the
20-validate narrow-dtype accumulation, and the "bit-exact on all 20 public cases" figure20+kernel — a golden settled offline before any kernel existed says nothing about the kernel
21-recorded in `MEMORY.md` §1 belongs to the **golden**, which was settled offline before21+that later consumes it. Match every claim to the artifact it was measured on.
22-any kernel existed — not to the kernel.
23 22 
24---23---
25 24 
@@ -51,7 +50,7 @@ at once:
51 50 
52Do not guard on rank or on a shape. Guard on the relationship — `indices.rank ==51Do not guard on rank or on a shape. Guard on the relationship — `indices.rank ==
53data.rank`, `indices.shape[a] <= data.shape[a]` — because the declared range is52data.rank`, `indices.shape[a] <= data.shape[a]` — because the declared range is
54-routinely wider than the public cases and has been observed wider than the53+routinely wider than the cases you can see, and has been observed wider than the
55documentation.54documentation.
56 55 
57## 2. `vf.scatter` writes UB, so the whole indexed axis must be resident56## 2. `vf.scatter` writes UB, so the whole indexed axis must be resident
@@ -109,7 +108,8 @@ Ascend950PR_9579 with `K=4, U=16` so that every column carried duplicates:
109plain scatter left **3 of 256** elements holding the earlier write; the same108plain scatter left **3 of 256** elements holding the earlier write; the same
110kernel with `vf.mem_bar()` after each scatter was **0 of 256**. On realistic109kernel with `vf.mem_bar()` after each scatter was **0 of 256**. On realistic
111index draws the error rate is around 1 in 1000 — low enough to survive a casual110index draws the error rate is around 1 in 1000 — low enough to survive a casual
112-check and lose hidden cases, which is precisely why it belongs in a pattern page.111+check and still fail on inputs you never inspect, which is precisely why it
112+belongs in a pattern page.
113 113 
114For `amax` / `amin` the combine collapses into the mask itself, which is both114For `amax` / `amin` the combine collapses into the mask itself, which is both
115faster and avoids `vf.select` entirely:115faster and avoids `vf.select` entirely:
@@ -179,41 +179,3 @@ and keep control of the addressing.
179 `outer`/`K`/`inner` factorisation is host-side *metadata* arithmetic over179 `outer`/`K`/`inner` factorisation is host-side *metadata* arithmetic over
180 shapes, and the reshape it implies is a pure view of a contiguous tensor.180 shapes, and the reshape it implies is a pure view of a contiguous tensor.
181 Anything that moves data stays in the kernel.181 Anything that moves data stays in the kernel.
182- 
183-## 10. An 8-bit scatter consumes only the even source lanes
184- 
185-**未在 PyPTO-Pro 上验证——由 EasyASC 移植的假设 (unverified on PyPTO-Pro — an
186-assumption ported from EasyASC).** Board-verified under EasyASC on Ascend 950; §6
187-above stops at b16 and states no b8 row, so this fills a real hole in the table
188-rather than restating it.
189- 
190-EasyASC (`constraints/a5.md` §8) records that a register→UB scatter of **8-bit**
191-data writes `dst_flat[index[k]] = src[2k]` for its 128 `uint16` indices — the
192-**odd source bytes are ignored**. Its remedy for placing a dense 8-bit payload:
193-cast even and odd logical rows separately, pack each group, then interleave and
194-scatter through a `uint16` carrier view.
195- 
196-**Why to expect this to transfer.** It is the write-side mirror of a rule this KB
197-already holds on the read side. The
198-[gather page](vec-ub-strip-gather.md) records that an 8-bit *gather* is a
199-`b8 → b16` zero-extend — the byte arrives in the low half of a 16-bit lane. If the
200-gather unit addresses 8-bit data through 16-bit lanes, a scatter addressing the
201-same data through the same `uint16` index register has nowhere to put the odd
202-byte. The two statements are one mechanism seen from both ends, which is the main
203-reason to trust the ported half before measuring it.
204- 
205-**Practical reading.** This is *why* the gather page's int8 route declares
206-`DT_UINT8` and widens to `DT_UINT16` in UB rather than working at native width —
207-that widening is not a convenience, it is the layout the index register imposes.
208-Expect a dense int8 output to cost an explicit compaction stage on the way out,
209-and budget it at design time rather than discovering it as half-empty output.
210- 
211-The same EasyASC section also states that the **scatter's mask is lane-wise**,
212-unlike the continuous store paths whose masks round up to whole 32-byte blocks
213-(board-verified 2026-07-29 there). That half is already carried, with its
214-PyPTO-Pro caveats, in
215-[constraints/vec-alignment-and-rotation.md](../constraints/vec-alignment-and-rotation.md).
216- 
217-**Named probe:** scatter 128 known b8 values through a `uint16` carrier into a
218-zeroed UB tile at known indices and read the tile back. If exactly the even source
219-lanes landed, the rule transfers.
@@ -72,9 +72,9 @@ Two readings, and the second is the one that generalises:
72 loop costs nothing; at 64 items of 4,096 elements it costs 6.2x.72 loop costs nothing; at 64 items of 4,096 elements it costs 6.2x.
73* **A host loop does not look obviously wrong on small-`L` cases.** At `L <= 4`73* **A host loop does not look obviously wrong on small-`L` cases.** At `L <= 4`
74 the penalty is 1.0–1.8x, well inside the range an ordinary tuning change moves74 the penalty is 1.0–1.8x, well inside the range an ordinary tuning change moves
75- — and in the task this was measured on, 18 of 20 public cases have `L <= 2`.75+ — and in the task this was measured on, nearly every visible case sat at
76- The rule earns its keep on the cases a public run never reaches, which is76+ `L <= 2`. The rule earns its keep on the cases a visible run never reaches,
77- exactly why it has to be a rule rather than a measurement.77+ which is exactly why it has to be a rule rather than a measurement.
78 78 
79## The shape that works: fixed arity, padded slots, one launch79## The shape that works: fixed arity, padded slots, one launch
80 80 
@@ -17,9 +17,8 @@ that is a segment copy, not this.
17## The constraint that determines everything17## The constraint that determines everything
18 18 
19**`vf.gather` reads UB only.** There is no GM random-access primitive, and19**`vf.gather` reads UB only.** There is no GM random-access primitive, and
20-pypto-pro has no SIMT, so an implementation ported from a framework that indexes20+pypto-pro has no SIMT, so an approach that indexes GM per element does not
21-GM per element (easyasc's `x[source_idx]` inside `@simt`) has nothing to port21+translate here at all. Every element a tile needs must already be in UB.
22-except its flattening. Every element a tile needs must already be in UB.
23 22 
24## The shape23## The shape
25 24 
@@ -143,10 +142,10 @@ viewed as UINT32 with the inner extent doubled, the source word for output word
143`p` is `idx[p/2]*2C + (p mod 2C)`, the same expression with each index value142`p` is `idx[p/2]*2C + (p mod 2C)`, the same expression with each index value
144duplicated.143duplicated.
145 144 
146-## Coverage the public cases will not exercise145+## Coverage the cases you can see will not exercise
147 146 
148The map from index coordinates to source coordinates is the identity only under147The map from index coordinates to source coordinates is the identity only under
149-two conditions, and a benchmark's public draws routinely satisfy both while the148+two conditions, and the draws you can inspect routinely satisfy both while the
150declared range does not:149declared range does not:
151 150 
152* **prefix identity** — extents agree on every axis before `k` except the151* **prefix identity** — extents agree on every axis before `k` except the
@@ -168,34 +167,3 @@ case and an inf case precisely because they are cheap to generate. Compare
168floats through `.view()` on an integer of the same width so NaN payloads and167floats through `.view()` on an integer of the same width so NaN payloads and
169signed zeros are compared as bits, and keep the official gate as the formal168signed zeros are compared as bits, and keep the official gate as the formal
170second verdict rather than the first.169second verdict rather than the first.
171- 
172-## Independent corroboration from a second DSL on the same silicon
173- 
174-Two rules on this page were reached independently under EasyASC on Ascend 950 and
175-board-validated there (dates are EasyASC's). This adds no new instruction to the
176-page; it raises confidence that both are **CANN-level properties of the gather
177-unit** rather than artifacts of how PyPTO-Pro lowers it — which matters when
178-deciding whether they survive a toolchain or SDK bump.
179- 
180-- **Index width is bound to data width.** EasyASC records `uint16` indices for
181- 8-bit *and* 16-bit data, `uint32` for 32-bit, and `uint32` or `uint64` for
182- 64-bit — "all combinations sim + Ascend950 board-validated (2026-07-21)". That
183- matches §6 of [the scatter page](vec-scatter-owner-model.md) and the dtype table
184- above, and it extends both with the 8-bit row, which neither states explicitly.
185- 
186-- **The 8-bit gather zero-extends into 16 bits.** EasyASC: an 8-bit-source gather
187- "is a `b8 -> b16` byte zero-extend: the source byte lands in the low 8 bits of a
188- 16-bit `dst`, high 8 bits zeroed (`int8` `0xFF` -> `255`, not `-1`)", and the
189- same-width `b8 -> b8` case is what the hardware rejects. That is exactly the
190- mechanism behind this page's int8 row — declare `DT_UINT8`, widen to `DT_UINT16`
191- in UB, and narrow the offsets with a **truncating** `vf.pack` because "`-1`
192- arrives as `0x00FF` and a saturating cast returns `127`". Two DSLs, one
193- mechanism, same remedy.
194- 
195-**One EasyASC claim from the same section is deliberately not carried:** that a
196-gather prices the same as an ordinary load (it measured 0.995–1.001x). This DSL's
197-own scan measurements put `vf.gather` at 20–35x an aligned `vf.load_align` at real
198-dependency depth
199-([vec-scan-prefix-dependent.md](vec-scan-prefix-dependent.md)). The measurements
200-were taken in different loop structures and are not necessarily in contradiction,
201-but the local one governs designs built here, and it is the one to design against.
@@ -1,364 +0,0 @@
1-# Measure and tune a correct kernel
2- 
3-Use this playbook only after correctness passes on the target platform. PyPTO-Gym owns
4-kernel correctness and reproducible profiling; packaging, scoring formulas and submission
5-contracts belong to whichever external driver consumes the kernel.
6- 
7-1. Record the device, architecture, CANN/PyPTO versions, kernel commit, shapes, dtypes,
8- launch geometry and profiler command.
9-2. Establish a baseline for the same inputs and numerical contract.
10-3. Warm up both paths and collect repeated measurements under the same conditions.
11-4. Retain the profiler artifact and parser output used for every claim.
12-5. Change one implementation factor, re-run correctness and profile again.
13-6. Accept the change only when the selected target metric improves without violating the
14- numerical contract.
15- 
16-Use
17-[`../../ops/pypto-pro-op-perf-tune/SKILL.md`](../../pypto-pro-op-perf-tune/SKILL.md)
18-for collection and analysis. Apply its target-specific roofline references only after target
19-detection confirms the matching architecture.
20- 
21-Do not treat a utilization threshold, externally reported score or result from another
22-shape/platform/version as a universal performance target.
23- 
24-## Traps that silently invalidate a measurement
25- 
26-Each of these can produce a plausible number rather than an error.
27- 
28-- **Stale profiler cache.** The evaluator archives each run under
29- `reports/prof_data/<level>/<op>/<case>/` and locates `kernel_details.csv` by
30- taking the first `os.listdir` entry rather than the newest — and the
31- `trace_view.json` path is derived from that CSV's directory, so it inherits the
32- same staleness. Left uncleaned, a score freezes at the kernel version that
33- produced the surviving archive. **Current cann-bench clears it itself**:
34- `perf_eval.py` calls `_clean_prof_dir_contents` before the first attempt and
35- between retries, and the PyPTO-Pro child removes leftover timestamp
36- subdirectories. Do not add a routine `rm -rf` for it. Keep the tell-tale
37- instead — an overall score reproducing to ~1e-13 across independent runs is
38- not something real hardware timing does; on a checkout predating that cleanup,
39- clear the directory by hand.
40-- **Skipped rebuild.** The runner skips building when a wheel is already in
41- `dist/`. Clear `dist/` and `build/` when the kernel changed.
42-- **Wall-clock fallback.** Running without performance collection times the host
43- call, including dispatch and framework overhead, and is largely insensitive to
44- kernel changes. Do not compare such numbers against profiled ones.
45-- **Host-side timing in the wrapper.** The benchmark times the wrapper, so every
46- tensor operation there becomes a measured device kernel. Synchronising inside
47- the wrapper additionally charges the whole stream's wait to the measurement.
48-- **A wrapper op that runs on the dev box can be absent on the eval runner.**
49- The eval container ships its own CANN, and its operator inventory is not a
50- superset of the dev box's: observed runner `950pr` = Ascend950PR_957c with
51- CANN 9.1.0 (docker cake-ci CANN 9.0.0, torch_npu 2.10.0.post4) against a dev
52- box on CANN 9.2.0. A submission whose wrapper called `.to(torch.float32)`
53- scored 7/20 there: **every** fp16/bf16 case raised `RuntimeError: call
54- aclnnInplaceCopy failed, error code is 561103` with `Config_Error(EZ1013):
55- ... aclnnInplaceCopy_1_CastAiCore cannot be found` at the wrapper's cast
56- line, while every fp32 case — which never took that path — passed
57- (job_cb400c1718cb, 2026-08-06; full per-case JSON archived beside the op).
58- The failure signature is easy to misread as a broken kernel or a polluted
59- runner; the tell is that the failing set partitions exactly by which cases
60- execute the host-side op. **Treat every aclnn-dispatching host op in the
61- wrapper as correctness-critical, not merely as measured time** — the
62- boundary in `constraints/wrapper-boundary.md` is also the compatibility
63- boundary, because a kernel-only submission depends on nothing from the
64- runner's op inventory. Version skew cuts the other way too: constructs the
65- dev toolchain accepts may not exist for the eval toolchain, so keep the
66- submission's dependency surface (host ops *and* DSL constructs) to what the
67- eval environment is known to provide.
68-- **A dispatcher that enumerates public signatures fails the hidden set, and the
69- error reads like a kernel bug.** A `transpose` submission routed on an exact
70- `(rank, dtype)` table built from the 20 public cases: public scored 20/20 at
71- 72.40, and the hidden set failed **20 of 80** — every failure the same
72- `no transpose class for signature [[3, 'float32']]`-style `ValueError` from
73- the dispatcher, never reaching a kernel. The hidden set legitimately spans
74- ranks and dtypes the public cases never show (here ranks 2-8 x fp16/bf16/fp32/
75- int8/int16/int32/int64). The fix cost **ten lines**: route an unmatched
76- signature to the generic class instead of raising, since each class's kernel
77- already generalised — hidden went to **80/80** and public *rose* to 73.33
78- (job_e813540ee6f2, 2026-08-07). Two rules follow: **an unmatched input must
79- fall through to a working path, never to an exception** (the same
80- no-host-guard rule as `constraints/wrapper-boundary.md`, applied to
81- dispatch), and **a public-only score cannot detect this class of defect at
82- all** — the dispatch table is exactly as complete as the case list it was
83- written from. Test dispatch against the *declared* domain, not the observed
84- cases.
85-- **The local copy of a submission is not what scored — download the archive.**
86- A resubmission built from the on-disk package directory scored **0/20** with
87- `jit() got unexpected keyword argument(s): timeout` on every case, while the
88- *same* operator's earlier submission had scored 70.73. Downloading the
89- archive that actually scored (`/api/jobs/<id>/submission/download`) settled
90- it in one grep: the shipped file had **no** `timeout=` kwarg; the local copy
91- had acquired one after that submission, from another session. Everything
92- derived from the local copy inherited a kwarg the evaluator's pypto rejects,
93- and it failed at kernel-compile entry before any case ran. Two rules:
94- **diff against the downloaded archive, not the local directory, before
95- claiming "kernel byte-identical to what scored"**, and note that a *sibling*
96- kwarg may be fine — `compile_timeout=` is accepted on the same fleet, so
97- "it's just a timeout hint" is not a safe assumption about which spelling
98- survives. Also drop `dist/` from the archive: a prebuilt wheel can be
99- installed in place of the source you just edited.
100-- **A uniform slowdown across every case is not automatically the runner — check
101- the launch width.** A resubmission measured **1.900x median / 1.997x max**
102- slower than the prior one across 77 shared cases, and the first reading
103- (same runner, ten hours apart) invited a contention story. Re-measuring on a
104- *second* runner killed that story outright: the two runners agreed to
105- **median 1.000, p90 1.007**. The slowdown was in the code — the local copy
106- had `block_dim = min(get_platform_info().core_num, row_blocks)` where the
107- archive that scored used `vector_core_num`, so the kernel launched on 28 of
108- 56 vector cores. The ratio distribution was the tell it was not
109- environmental: **bimodal at 1.02 and 1.99** (cases whose `row_blocks` fell
110- below 28 were unaffected), where contention is flat. Procedure: before
111- attributing a uniform slowdown to a runner, (a) re-measure on a different
112- runner — agreement to ~1% indicts the code, and (b) read the *shape* of the
113- per-case ratios, not just the median. Corrects an earlier version of this
114- entry that recorded the contention reading as fact.
115- See the `vector_core_num` entry in
116- [../references/pypto-pro-framework-findings.md](../references/pypto-pro-framework-findings.md).
117-- **Board contention.** A byte-identical package has been measured 12.9–15.9x
118- slower at a busy time of day. **Ship a control variant in every comparison
119- run**; if the control moves by tens of percent, the run is noise and must be
120- repeated rather than interpreted.
121-- **A degraded device, disguised by a healthy-looking reference.** Devices on a
122- shared board degrade independently, and the vendor op being compared against
123- is not a health check: on one contended device a vector-only A5 kernel ran
124- **15x** slower while the CANN built-in beside it moved under 2% — the
125- built-in was not competing for the same vector cores. When a number
126- collapses, sweep every visible `/dev/davinci*` before believing any
127- per-kernel conclusion. (Measured under another DSL on the same silicon; the
128- trap is board-level, not DSL-level.)
129-- **Timing the wrong device.** `torch_npu.npu.synchronize()` and
130- `torch_npu.npu.Event` act on the **current** device, not on the device the
131- tensors live on. A harness with a `--device` flag must call
132- `torch_npu.npu.set_device(index)` before timing, or it silently reports
133- launch overhead instead of kernel time.
134-- **The `trace_view` metric strategy zeroes an eager-mode pypto_pro
135- submission.** `--perf-metric-strategy trace_view` takes its time from
136- tilefwk/PYPTO-named trace events and nothing else, with no fallback
137- (`TraceViewStrategy` / `parse_tilefwk_metrics` in
138- `src/kernel_eval/base/perf_strategy.py`: the name filter accepts only
139- `tilefwk`/`PYPTO`). Eager-mode pypto_pro launches appear as plain `AI_CORE`
140- events, so the strategy finds nothing, the run is flagged as suspected CPU
141- fallback (anti-cheat), and the operator scores **0 with accuracy passing** —
142- while `kernel_details.csv` from the same run holds the real device rows.
143- Measured 2026-08-06, identical submissions with only the strategy changed:
144- `foreach_addcdiv_scalar` 0.00 vs 121.67, `apply_rotary_pos_emb` 0.00 vs
145- 80.78. **Choose the strategy from the implementation type**: tilefwk-event-
146- emitting implementations (PYPTO graph mode) need `trace_view`; eager-mode
147- pypto_pro needs the framework default (`kernel_details`). The older
148- "trace_view is mandatory for PyPTO" guidance applies to the former only.
149-- **`trace_view` is *structurally* unreachable on the isolated-subprocess
150- path** — a second, independent mechanism producing the same zero.
151- `pypto_pro_child.py` hardcodes `profiler_level` to `ProfilerLevel.Level1`,
152- while `trace_view` requires **Level2** (`bench_registry.py:64`), and
153- `--profiler-level` is plumbed only into `perf_eval.py` and
154- `mc2_distributed_runner.py` — **it never reaches the isolated child**. So the
155- artifact `trace_view` needs is not merely unmatched, it is never produced.
156- Symptoms: `elapsed_us = 0.0`, `score_error_code:
157- 'no_npu_kernel_detected'`, composite score zeroed by anti-cheat, on a kernel
158- that ran correctly. No flag combination fixes this from the CLI. *Inference,
159- flagged as such:* the evaluation server runs the same unpatched child, so it
160- should behave identically — that part is read from shared source, not
161- measured server-side, and is worth reporting upstream rather than designing
162- around.
163-- **A `pl.jit` kwarg the target runtime does not accept kills the submission
164- with no attributable error.** The evaluation server's pypto_pro raised
165- `TypeError: jit() got unexpected keyword argument(s): timeout` on a module
166- our own box compiles fine. Since the submission imports its kernel module at
167- package import, the exception fired inside the evaluator's import and
168- surfaced only as `staged_rc_1_missing_report` — a successful wheel build
169- followed by nothing, reproducible on three different runners and easy to
170- misread as pool flakiness. **Grep the shipped module for jit kwargs before
171- packaging**, and make the forwarder import the kernel module *lazily*
172- (inside the entry function): it converts an opaque infra-stage death into a
173- per-case traceback you can read. Removing the kwarg took the operator from a
174- hard server failure to 82.51. (foreach_addcdiv_scalar, 2026-08-07.)
175-- **Provenance.** Confirm the profiler output actually contains the submitted
176- kernel's rows, and that vendor-library rows total zero. A result produced by a
177- fallback path is not a result.
178-- **Stale binary under an unchanged kernel name.** pypto keys its build directory
179- on the kernel's `co_name`, so an edited body compiled under the same name can be
180- served the previous binary. The run then reproduces **byte-identically**, which
181- reads as "my change did nothing" and is indistinguishable from it. Name kernels
182- by a hash of their own source, and make sure the hash covers **what the compiler
183- sees** — a generator that hashed only the rendered `@pl.jit` wrapper left the
184- guard inert for exactly the edits it existed to catch, because the wrapper
185- template interpolates the vector function's *name*, not its source. Hash the
186- header, the called body and the wrapper together.
187-- **A per-case-scored benchmark is not optimized by a mean.** An optimisation
188- measured at **−2.23% mean over the 13 cases it touched, with no case slower**,
189- scored **−0.22 on the server** (69.6082 → 69.3886, same archive, same runner,
190- and server readings reproduce to ~0.01 so that is signal). The mean was real;
191- it was the wrong statistic. `OperatorScore` sums a *per-case* term, and the
192- four smallest cases regressed 4.5–11% while the large ones gained 1–2% — the
193- losses cost −0.095 of summed score against +0.017 of wins. Convert every
194- candidate result into **per-case score deltas weighted the way the grader
195- weights them** before deciding to ship; a percentage on wall time, however
196- carefully controlled, does not answer the question being scored.
197-- **On a degraded board the *sign* flips first for fixed-overhead-dominated
198- cases.** The same change measured −0.79%, −2.35%, −0.62%, −2.83% on four small
199- cases locally and **+11.1%, +11.1%, +9.3%, +4.5%** on the server. Those four
200- are the ones where a fixed per-launch cost dominates, and a board that is slow
201- on fixed-overhead-heavy paths inflates the variable part they are being
202- compared against. A same-session ratio with a null control is a real defence
203- for the *large* cases and buys much less than it appears to for the small
204- ones — so when a change trades a fixed cost against a variable one, get the
205- small cases measured somewhere trustworthy before shipping.
206-- **A board can degrade by multiples between days, and the drift check will not
207- tell you.** Measured 2026-08-07: byte-identical shipped code, cached binaries,
208- the same script, the same metadata and the same card read OperatorScore
209- **70.02 one day and 61.21 the next** — mean SOL 0.400 → 0.224, every one of
210- twenty cases slower, the DMA-bound strided cases worst (9.79x, 8.71x, 5.83x)
211- against about 2x on the contiguous ones. A descriptor probe on that second day
212- read 6.81 where the recorded value was 0.488, a **14x** miss.
213- **The before/after control drift check passed on both days** — 19.2% and 10.6%,
214- both inside the 20% band — because it compares a control to itself *within*
215- the run and therefore cannot see a floor that moved between runs. Two defences
216- actually work, and they are cheap: (a) re-run one **recorded absolute** (a
217- probe whose ns/element you have written down) and refuse to interpret anything
218- until it reproduces; (b) shape the experiment as a **same-session contrast**
219- with an untouched arm, so the arm you did not change reads the noise floor for
220- you. On the day above, (b) still licensed a 2.2% A/B result — the changed arm
221- moved −0.62…−3.27% on all 13 cases while the untouched arm sat within ±0.1% on
222- 6 of 7 — while (a) correctly voided an absolute pricing decision.
223- A within-run *ratio* is not automatically safe either: the same pair of
224- descriptor variants was 3.03x apart on the good day and 14.8x apart on the bad
225- one.
226-- **A partial profiler export under-reports deterministically.** Where a helper
227- divides surviving rows by an expected step count, a dropped launch scales the
228- answer by `rows/expected` — two rows of five read as 40 % of the true time.
229- **This survives every defence built for noise**: it reproduces to ~1 %, so a
230- second pass confirms it, and the control variant passes because the control was
231- not affected. It once produced a clean, control-checked 3.67× for a change worth
232- 1.59×. Only an invariant catches it: **print the profiler row count next to every
233- timing, and have something compare it to what was expected.** A printed
234- invariant nobody checks is not a check.
235-- **A device fault reported as a total accuracy failure.** A wedged accelerator can
236- let a run complete and report `TOTAL 0/N passed` — no timeout, no hang, a clean
237- verdict that reads as a catastrophic regression and invites a revert. The tell is
238- that **no comparison ran**: failures arrive as `RuntimeError` from device
239- synchronise/copy entry points rather than as an error metric against a threshold.
240- See the discrimination procedure in `pypto-pro-environment-check`. **Before acting
241- on a total failure, require positive evidence that the comparison executed.**
242-- **A green run the public data cannot fail.** An optimisation that removes an
243- operation can validate 20/20 and still be wrong, when the public cases cannot
244- reach the inputs the removed operation was handling. One case generator lays
245- special values in contiguous blocks of `numel//20`; where that block size is even
246- and the reduction is 2 wide, no public row ever mixes `+inf` with a finite
247- element, so a collapse that breaks exactly that pairing passes everything. **When
248- an optimisation deletes an operation, ask what it was doing for the special
249- values, then check whether the public data can even reach that case.**
250- 
251-- **`PYTHONPATH=src` *replaces* the overlay instead of extending it, and a
252- correct kernel becomes 20/20 compile failures.** The documented invocation
253- `env PYTHONPATH=src python -m kernel_eval.cli …` discards whatever
254- `env_setup.sh` put on the path, so the eval child imports the **older**
255- `pypto_pro` from the conda environment rather than the overlay. That older
256- codegen passes a `MaskReg` predicate into an int32 `vand`, and every case
257- dies with `error: no matching function for call to 'vand'` /
258- `no known conversion from 'pto::MaskReg' (aka 'vector_bool') to
259- 'vector_s32'`. The failure reads as a broken kernel — it is a resolution
260- problem, and the kernel is fine. **Always append, with absolute paths and the
261- overlay first:**
262- 
263- ```bash
264- PYTHONPATH="$OVERLAY:$BENCH/src" python -m kernel_eval.cli eval ...
265- ```
266- 
267- and **verify what actually resolved** before trusting any verdict:
268- 
269- ```bash
270- python -c "import pypto_pro; print(pypto_pro.__file__)"
271- ```
272- 
273- This is a specific instance of the whole-run-fails-at-once signature: when
274- every case fails identically at *compile*, suspect resolution before code.
275-- **`--source-dir` force-reinstalls into the shared environment.** It runs
276- `pip install --force-reinstall --no-deps`
277- (`package_manager.py:474-508`), which **evicts the previously installed
278- operator's submission**. Evaluating two operators alternately in one conda
279- environment therefore measures whichever was installed last, with no warning.
280- Re-install before each evaluation, or give each operator its own environment.
281-- **Bare-metal single-card device binding is broken, and the workaround needs
282- its own proof.** `evaluator.py:1102` writes the **physical** chip id into
283- `ASCEND_RT_VISIBLE_DEVICES` *and* passes the same integer to `set_device()`.
284- But `ASCEND_RT_VISIBLE_DEVICES` names an absolute physical chip while
285- renumbering the visible set from 0 — the two agree **only at 0**. So
286- `--device-id 4` raises `RuntimeError 107001`, and passing 0 to dodge that is
287- overwritten back to physical npu0. It never shows on k8s, where the device
288- plugin has already renumbered the allocated card to physical 0. Workaround:
289- keep an inherited value that is already a single chip
290- (`ASCEND_RT_VISIBLE_DEVICES=4` with `--device-id 0`) — and because the
291- binding cannot be trusted, **prove in the log which physical card ran the
292- work**, via an HBM fingerprint or the `npu-smi` process table. A workaround
293- for a device-selection bug that does not verify device selection is not a
294- workaround.
295-- **Score the run, not the summary line.** A suite of 20 test functions in
296- which some functions sweep several modes must print **more than 20** accuracy
297- verdicts. The expected count is `Σ (modes per function)`, and any shortfall
298- means a function short-circuited — returned early, skipped a mode, reused a
299- previous result. **The "20/20 PASS" summary is exactly what hides this**: it
300- counts functions that did not raise, not comparisons that ran. Compute the
301- expected line count before the run and check the actual against it, the same
302- way the profiler-row-count invariant above catches a partial export.
303- 
304-## Choosing the metric
305- 
306-Prefer the profiler's device-side end-to-end figure over host wall-clock; on a
307-representative case the two have differed by roughly a factor of two on the same
308-kernel, and only the former reflects what the kernel did. On CANN Bench the
309-metric *strategy* is itself implementation-conditional — see the `trace_view`
310-trap above before passing `--perf-metric-strategy`.
311- 
312-Report kernel time and wrapper/device-library time separately so an apparent kernel
313-improvement cannot hide a slower public callable.
314- 
315-**`kernel_details` is a device measurement, not a host-overhead fallback.**
316-Some older evaluation guidance describes the default `kernel_details` caliber as host wall-clock including
317-Python dispatch and framework overhead, and mandates `trace_view` as the only
318-true device figure. **Neither half of that holds on this checkout**, and no
319-page in this KB has ever claimed it — the stale text is in the skill only. `KernelDetailsStrategy` (`perf_strategy.py:590-608`) takes
320-the **median** of the device kernel `Duration` column in `kernel_details.csv` —
321-a device-side measurement carrying no host or framework time. Verified on a case
322-whose CSV held five rows: their median equalled the scoring `elapsed_us`
323-exactly, and the file contained only that kernel's rows with zero non-kernel
324-rows. Meanwhile `TraceViewStrategy` (`:724`) carries a
325-`PendingDeprecationWarning` stating that `KernelDetailsStrategy`'s metadata will
326-subsume `aicore_e2e` and that it — the default — should be used instead.
327- 
328-Two consequences. The `kernel_details` number does **not** need a
329-host-overhead discount applied to it. And the "`trace_view` or the score is
330-meaningless" framing is obsolete on this checkout; combined with the
331-structural unreachability of `trace_view` on the isolated-subprocess path
332-above, `kernel_details` is frequently the *only* caliber available.
333- 
334-What does not change: **state the caliber in the report, every time.** Two
335-numbers from different strategies are not comparable, the default has already
336-shifted once, and a figure whose caliber is unrecorded cannot be re-checked
337-later.
338- 
339-## BenchSite server operations
340- 
341-Operational facts about the remote submission service, recorded 2026-08.
342-They are service-side and can change without notice; when an interaction
343-contradicts one, believe the service and update this list.
344- 
345-- **Names differ by direction.** A submission's `selected_operators` takes
346- snake_case function names (`swi_glu`) while `get_benchmark_task` takes
347- CamelCase operator names (`SwiGlu`). Neither errors on the other's
348- spelling; the mismatch surfaces as an empty selection.
349-- **`infra_error` jobs are auto-refunded** — the job record's charges/refunds
350- fields show it. Do not re-budget an infrastructure failure as spent quota.
351-- **Quota is per-token and daily**: base 10/day plus an earnable bonus,
352- resetting at 16:00Z. Plan sweeps against the reset time, not the calendar
353- day.
354-- **At most 3 active jobs per user** (`active_job_cap`); a fourth submission
355- is rejected, not queued.
356-- **A runner claim can lag the queue by over an hour under pool congestion.**
357- A job sitting unclaimed is not stuck; check pool load before resubmitting —
358- a resubmission spends quota and joins the same queue.
359-- **Runners are not interchangeable for timing.** `multi-0` and `multi-2` have
360- produced consistent numbers; `multi-1` has produced uniform ~15x slowdowns
361- (every case, same factor — the fingerprint of a contended or degraded box;
362- see the degraded-device trap above), and `simen-0` runs ~10% conservative.
363- Compare timings only within one trusted runner, and record which runner
364- produced every number.
@@ -4,9 +4,9 @@ Use this when a kernel is structurally correct — it runs, most cases pass —
4a graded output misses the accuracy gate and you do not know which stage is4a graded output misses the accuracy gate and you do not know which stage is
5responsible.5responsible.
6 6 
7-It exists because on one operator (MlaProlog) the obvious statistic pointed at7+It exists because on one staged multi-matmul kernel the obvious statistic
8-the wrong stage **twice**, costing two full build-measure-revert cycles. The8+pointed at the wrong stage **twice**, costing two full build-measure-revert
9-technique below found it in one run.9+cycles. The technique below found it in one run.
10 10 
11---11---
12 12 
@@ -20,7 +20,7 @@ Two checks first, both cheap, both of which have produced false failures:
20 fine**, by getting four things wrong at once — the flag threshold (`10 ×20 fine**, by getting four things wrong at once — the flag threshold (`10 ×
21 threshold`, not `threshold`), the bf16 small-value boundary (`2**-8`, not the21 threshold`, not `threshold`), the bf16 small-value boundary (`2**-8`, not the
22 fp16 `2**-11`), the cancel region (absent), and the CPU baseline (absent).22 fp16 `2**-11`), the cancel region (absent), and the CPU baseline (absent).
23- See [benchmark-scoring.md](benchmark-scoring.md).23+ See [the accuracy-gate model](../constraints/precision.md).
24- **Judge with the harness verdict, not a summary statistic.** `MARE` is a max24- **Judge with the harness verdict, not a summary statistic.** `MARE` is a max
25 dominated by the smallest `|golden|`, so it moves *non-monotonically* with25 dominated by the smallest `|golden|`, so it moves *non-monotonically* with
26 real accuracy: a strictly more accurate scheme measured a **worse** MARE on26 real accuracy: a strictly more accurate scheme measured a **worse** MARE on
@@ -40,7 +40,7 @@ single most common way to chase the wrong stage.
40| relative error in a normal region | **relative** error |40| relative error in a normal region | **relative** error |
41| an absolute bound on near-zero outputs (small-value / cancel regions) | **absolute** error |41| an absolute bound on near-zero outputs (small-value / cancel regions) | **absolute** error |
42 42 
43-On MlaProlog every failure was in the small-value region — an absolute43+In that case every failure was in the small-value region — an absolute
44`2**-16` bound on cancellation-born near-zeros — while the diagnostic reported a44`2**-16` bound on cancellation-born near-zeros — while the diagnostic reported a
45*relative* error cut at `0.1 ×` the tensor RMS to stop cancellation dominating45*relative* error cut at `0.1 ×` the tensor RMS to stop cancellation dominating
46the statistic. That cut is reasonable for describing a tensor's bulk and46the statistic. That cut is reasonable for describing a tensor's bulk and
@@ -71,9 +71,9 @@ Independent rounding sources add in quadrature, so
71total² ≈ inherited² + own²71total² ≈ inherited² + own²
72```72```
73 73 
74-**That identity is the check that the decomposition is trustworthy.** On74+**That identity is the check that the decomposition is trustworthy.** There it
75-MlaProlog it held to three digits — `3.51² + 2.43² = 4.27²` — which is what made75+held to three digits — `3.51² + 2.43² = 4.27²` — which is what made it safe to
76-it safe to act on after two earlier misdiagnoses.76+act on after two earlier misdiagnoses.
77 77 
78Then compare each component against the same decomposition of the CPU reference.78Then compare each component against the same decomposition of the CPU reference.
79The measured table:79The measured table:
@@ -98,10 +98,18 @@ gain = Σ_newly_passing (0.3 + 0.5·score_i) / N · 100
98cost = Σ_all_cases 0.5·Δscore_i / N · 10098cost = Σ_all_cases 0.5·Δscore_i / N · 100
99```99```
100 100 
101-Worked example: converting the last failing MlaProlog case needed a matmul in101+Worked example, **under the two formulas above and nothing more general**:
102-the cube's fp32 mode, which gains one case (**+1.7 points**) and costs ~2×102+converting the last failing case needed a matmul in the cube's fp32 mode. That
103-runtime across all twenty (**−5 points**). **Net −3.3.** The right call was to103+gains the one case, but costs roughly 2x runtime on **every** case; substituting
104-ship 19/20 and record the arithmetic, not to chase the case count.104+into `gain` and `cost` above, the many small regressions outweigh the single win
105+by a wide margin, so the right call was to ship with that case failing and record
106+the arithmetic.
107+ 
108+**Do not read that as a law.** It is arithmetic in one weighting, not a
109+statement about per-case-weighted metrics in general: raise the pass bonus,
110+weight cases unequally, or make the regression sublinear and the sign flips.
111+The transferable part is the *procedure* — write down the metric's own formula,
112+substitute both sides, and compare — not this instance's answer.
105 113 
106---114---
107 115 
@@ -142,9 +150,9 @@ acted on without one were both wrong.
142 150 
143Choosing *which* scheme to build needs no accelerator. Replay the kernel's151Choosing *which* scheme to build needs no accelerator. Replay the kernel's
144dataflow in torch with the GM dtype and the operand split depth as parameters,152dataflow in torch with the GM dtype and the operand split depth as parameters,
145-and grade with the benchmark's real comparator. The whole scheme comparison for153+and grade with the real comparator. One such whole-scheme comparison — five
146-MlaProlog — five candidates across three problem sizes — ran on a laptop with no154+candidates across three problem sizes — ran on a laptop with no NPU and picked
147-NPU and picked the one that worked:155+the one that worked:
148 156 
149| scheme | M=1 | M=128 | M=512 |157| scheme | M=1 | M=128 | M=512 |
150|---|---|---|---|158|---|---|---|---|
@@ -162,8 +170,41 @@ mean.
162## Evidence170## Evidence
163 171 
164All figures were measured on Ascend A5 with the comparator recorded by that run,172All figures were measured on Ascend A5 with the comparator recorded by that run,
165-on MlaProlog and MLA. Results over the session: MlaProlog 0/20 → 19/20173+在两个分阶段 attention 类算子上应用后,一个从"几乎全错"到"仅剩一个 case 不过",
166-(57.96 → 61.84), MLA never-ran → 20/20. Per-stage numbers in174+另一个从"从未跑通"到全部通过。逐阶段的机理见
167-`custom/mla_prolog/DESIGN.md` §9.2–9.8 and
168[../references/pypto-pro-framework-findings.md](../references/pypto-pro-framework-findings.md)175[../references/pypto-pro-framework-findings.md](../references/pypto-pro-framework-findings.md)
169-findings 21–24.176+中 fp32 链路与 phase 相关的条目(按标题查,不按编号)。
177+ 
178+## Two proxies that lie, and the discriminator for each
179+ 
180+Both produced a confident wrong diagnosis in the same campaign, in opposite directions, from a
181+single-axis reading while two axes had moved.
182+ 
183+- **`import_s` cannot see device, driver or compiler-subprocess contention.** A launch measured at
184+ 184 s against 24 s for the same tuple was called "ambient" because `import_s` had risen
185+ 6.5 → 36.1 s; a later run showed `import_s` back at 4.9 s with the launch *worse* at 478 s, and
186+ it was then called geometry-borne. Both over-read the same proxy. **Discriminator:** re-run the
187+ same geometry on the same arm, beside a base-arm run at those exact axes — which converts "is
188+ this slow?" into "did my change do this?". The answer was 15.47 s versus 15.94 s: nothing slow,
189+ nothing introduced.
190+- **A result differing from an older one on *two* axes tells you nothing about either.** A build
191+ lost 11 of 20 performance measurements on a machine it had never run on before, and the loss was
192+ attributed to the build. The byte-identical archive on a different machine measured 20/20 at the
193+ normal score. **Discriminator:** buy the control that varies exactly one axis *before* doing any
194+ engineering. It cost one credit and saved a diff plus a board session.
195+ 
196+General form: **before diagnosing, count how many things changed.** If more than one did, the first
197+move is a control that changes one — not a hypothesis about which one mattered.
198+ 
199+## An internal control beats an external threshold
200+ 
201+When repairing a numerical defect, find the leaf that *should not move* and prove it didn't.
202+Repairing an RMS reciprocal improved `c_kv` 43× and `query` 5.7×, and left `k_rope` — the one output
203+with no reciprocal in its path — identical to the digit at every geometry. That unmoved leaf is
204+stronger evidence the edit stayed in scope than any tolerance check on the leaves that moved.
205+ 
206+**And a passing threshold can be luck rather than accuracy.** One geometry's `mare` went from
207+passing 0.055 to failing 0.19 while its `mere` improved 16.6×. The fp32 host golden at that
208+geometry sits at 0.164 and fails the same threshold in **both** arms — so the original pass was
209+margin the arithmetic never earned. Read a threshold beside the same-precision host control, never
210+alone.
@@ -1,170 +0,0 @@
1-# EasyASC port ledger
2- 
3-EasyASC is a sibling Ascend DSL (`easyascv2`) with its own agent knowledge base, developed
4-against the same silicon this repository targets — A2/A3 and A5 (C310). Its knowledge was
5-swept and, where it transfers, moved onto these pages. This file is the inventory: every
6-source item, what happened to it, and why.
7- 
8-**Coverage is the point.** The rows that say *not ported* carry as much information as the
9-rows that say ported — they record that an item was examined and rejected for a stated
10-reason, so nobody re-derives the same rejection.
11- 
12-## The two rules the port runs under
13- 
14-**1. Cross-DSL claims are hypotheses until this stack says otherwise.** Every ported claim
15-carries one of two provenances, and it is visible in the text on the page:
16- 
17-- a **PyPTO-Pro anchor** — an installed `pypto_pro` source line, a
18- `$PYPTO_DEVKIT_DIR/docs/pypto_pro/` page, a `$PYPTO_DEVKIT_DIR/pro_ops/` sample, or a
19- measurement recorded in this KB; or
20-- the marker **`未在 PyPTO-Pro 上验证——由 EasyASC 移植的假设`** plus a named probe that
21- would settle it.
22- 
23-A cross-DSL statement written in this KB's ordinary declarative voice would be read by the
24-next agent as measured here. That is the failure this rule exists to prevent.
25- 
26-**2. "Simulator passes, board fails" needs translating, because there is no simulator here.**
27-A large share of EasyASC's highest-value material is framed against its Python simulator.
28-PyPTO-Pro has no equivalent, so that framing does not transfer literally. What transfers is
29-the **class**: *the cheap check passes and the board fails* — where the cheap check here is a
30-successful compile, a host/eager replay, or a small-shape run. Items whose only content was
31-"the simulator models this differently" are marked not-applicable rather than ported.
32- 
33-## Provenance states
34- 
35-| State | Meaning |
36-|---|---|
37-| **ported (earlier)** | landed in the first sweep, commit `ce6251f` |
38-| **ported (made durable)** | written in a session that ended before committing; committed as `2d69e4b` |
39-| **ported (this session)** | added in the sweep this ledger was written for |
40-| **already held** | this KB reached the same rule independently; EasyASC adds corroboration at most |
41-| **not ported** | examined and rejected — reason given |
42-| **conflict** | both sides recorded, neither promoted |
43- 
44----
45- 
46-## 1. Ported earlier — `ce6251f`
47- 
48-| EasyASC source | Landed in | Provenance |
49-|---|---|---|
50-| branchless authoring inside a vector function | `ops/pypto-pro-op-develop/references/vf-reduction-perf.md` § "Do not branch inside a vector function" | ported (earlier) |
51-| per-call overhead and loop form | same file, § "Per-call overhead and loop form" | ported (earlier) |
52-| load-issue cost model | same file, § "Load-issue cost model" — labelled a hypothesis with a re-probe recipe | ported (earlier), unverified |
53-| capability-absence gate (six required records) | [`investigation-discipline.md`](investigation-discipline.md) §11 | ported (earlier), credentialed by a local +8 OperatorScore miss |
54-| wall-vs-plateau evidence standard | `ops/pypto-pro-op-perf-tune/references/a5-roofline-and-levers.md` § "When the local levers plateau" | ported (earlier) |
55-| structural levers; degraded-device and current-device timing traps | same file; [`../playbooks/benchmark-scoring.md`](../playbooks/benchmark-scoring.md) § traps | ported (earlier) |
56-| store-side UB bank serialisation (odd 32-byte-block pitch) | [`../constraints/vec-alignment-and-rotation.md`](../constraints/vec-alignment-and-rotation.md) | ported (earlier) |
57-| CN/EN hardware and tiling glossary | [`terminology.md`](terminology.md) | ported (earlier), DSL-neutral terms only |
58-| gather prices the same as an ordinary load (0.995–1.001x) | — | **not ported**: contradicted by this DSL's own measurement of `vf.gather` at 20–35x an aligned load at real dependency depth ([`../patterns/vec-scan-prefix-dependent.md`](../patterns/vec-scan-prefix-dependent.md)) |
59- 
60-## 2. Ported but uncommitted, made durable — `2d69e4b`
61- 
62-| EasyASC source | Landed in | Provenance |
63-|---|---|---|
64-| `a5.md` — transposing dense→fractal read alignment cliff (~40 GB/s vs ~1.7 TB/s off a 32-byte source plane) | [`../constraints/memory-layout.md`](../constraints/memory-layout.md) | ported (made durable), **unverified** + named probe |
65-| `a5.md` — dense→fractal copy rounds its destination C0 stride to `align16(M_dst)` | same page | ported (made durable), **unverified** |
66-| `a5.md` §4 — on A5 the cube↔vec handoff stays on chip; no GM bridge needed | [`../constraints/sync-stitch.md`](../constraints/sync-stitch.md) | **conflict**, recorded not adjudicated — it contradicts a repeated local measurement |
67-| `a5.md` §5 — prefer the on-chip `L0C → L1 → L0` cube→cube re-feed | same page | ported (made durable) as a **checked absence**: `pl.move`'s space table (`pypto_pro/language/_api.py:196-206`) has no `Acc → Mat` row |
68-| `a5.md` §12 — per-token scalar staging needs one 32-byte UB row per token | [`../constraints/vec-alignment-and-rotation.md`](../constraints/vec-alignment-and-rotation.md) | ported (made durable), **unverified**; sits beside a local measurement it corroborates |
69-| `a5.md` §6.2 — `DIST_NORM_B8` writes its full 256-byte register under a prefix mask | same page | ported (made durable); the mask-ignored half is measured here, the **sizing** consequence is unverified |
70-| `a5.md` §8 — an 8-bit register→UB scatter consumes only even source lanes | [`../patterns/vec-scatter-owner-model.md`](../patterns/vec-scatter-owner-model.md) §10 | ported (made durable), **unverified**; write-side mirror of a rule held here on the read side |
71-| `a5.md` — gather index width bound to data width; 8-bit gather zero-extends to b16 | [`../patterns/vec-ub-strip-gather.md`](../patterns/vec-ub-strip-gather.md) | **already held** — carried as cross-DSL corroboration, which is what makes it a CANN-level rather than a lowering property |
72-| `a5.md` §6.1 — a BF16→FP4 cast requires one of `RegLayout.ZERO/ONE/TWO/THREE` (`vcvt` `P0..P3`) | [`pypto-pro-framework-findings.md`](pypto-pro-framework-findings.md) § EasyASC cross-port | ported (made durable) with a **PyPTO-Pro anchor**: the prediction was checked and `_vf_api.py:655` declares four `CastLayout` members where the docs show two |
73- 
74----
75- 
76-## 3. Ported this session
77- 
78-| EasyASC source | Landed in | Provenance |
79-|---|---|---|
80-| `facts-authoring.md:147` / `constraints/a5.md` §1 — keep a `@vf` scan's loop-carried accumulator in registers; a UB round trip failed a random-input hardware probe **even with `vf_barrier(STORE, LOAD)`** | [`../patterns/vec-scan-prefix-dependent.md`](../patterns/vec-scan-prefix-dependent.md) | ported, **unverified**; the barrier-is-not-enough half is the new content — this KB already required the barrier |
81-| `simulator-datamove-footprint-guards.md:19,52-55` — burst footprint is `(n_burst-1)*step + burst_len`; GM slice coverage is `1 + Σ(span_i-1)*stride_i`, **not** `Π spans` | [`../constraints/memory-layout.md`](../constraints/memory-layout.md) | ported as **shape arithmetic**, which is DSL-independent; feeds the overlap check that [`investigation-discipline.md`](investigation-discipline.md) §12 already mandates |
82-| `facts-authoring.md:180` / `patterns/online-softmax-tail.md` — use the finite sentinel `-1.0e30`, not `float("-inf")` | [`../patterns/online-softmax-tail.md`](../patterns/online-softmax-tail.md) | ported with a **PyPTO-Pro anchor**: a module-level `float("inf")` renders as the undeclared C++ identifier `inff` and fails to compile here ([`pypto-pro-dsl-limitations-a5.md`](pypto-pro-dsl-limitations-a5.md) #19) |
83-| `patterns/online-softmax-tail.md:262` / `a5-mixed-pipeline.md:228` — the tail mask must land **before** `rowmax`, not in the p-domain; padded zeros inflate the running max and corrupt `alpha` and `l` | [`../patterns/online-softmax-tail.md`](../patterns/online-softmax-tail.md) | ported as **ordering** guidance on a page that is already conceptual-only; the failure chain is the new content |
84-| `authoring-preflight.md:58-61`, `pitfall-records.md:23` — same-core reuse stress gate: `ceil(BH*ceil(S1/TILE_M)/core_count) > 1`; "a passing single-tile simulation is not a reuse proof" | [`investigation-discipline.md`](investigation-discipline.md) §13.2 | ported as a **shape precondition**, mechanically checkable; generalises §13's existing geometry rule to reuse |
85-| `patterns/buffer-slot-lifetime.md` — required slots ≥ (overlapped beats) × (simultaneously live roles); and the reason a wrong credit count is silent (prologue and epilogue stay balanced) | [`../patterns/buffer-reuse-lifetime.md`](../patterns/buffer-reuse-lifetime.md) | ported as a **sizing law**, API dropped; connects to the local finding that a wrong slot stride aliases two buffers while the event machinery still issues two credits |
86-| `authoring-preflight.md:62-63` — treat the ownership checker's warnings as correctness signals; resolve the model or make a concrete proposal, do not waive them | [`investigation-discipline.md`](investigation-discipline.md) §13.2, closing paragraph | ported **generalised** — EasyASC names its own `auto_sync` warnings; the transferable form is that a passing result with an unresolved ownership warning is not a passing result |
87-| `simulator-datamove-footprint-guards.md:64-66` — do not clamp an out-of-range view to the parent size with `min(...)`; it hides the real out-of-bounds and re-surfaces as an unrelated footprint failure | [`../constraints/memory-layout.md`](../constraints/memory-layout.md), with the extent formulas | ported as a **diagnostic** rule; it is about how a bounds check should fail, which is DSL-independent |
88-| `facts-device-runtime.md` — a BT slot holds 512 fp32/int32 elements on A5 (64 on A2/A3), and a shortcut-matmul or conv bias must fit one slot | [`../constraints/arch-a5.md`](../constraints/arch-a5.md) | ported as a **derived design bound** (tile N/Cout ≤ 512), not as a capacity number. **Half-anchored**: `bt_size=4096` is in the SKU platform file; the two-slot structure that halves 1024 elements to 512 is the unverified half |
89-| `facts-device-runtime.md` — the 12-bit `n_burst` field (`[0, 4095]`, 4096 silently no-ops) is a C220 restriction A5 does **not** inherit | [`../constraints/arch-a5.md`](../constraints/arch-a5.md) | ported as a **negative** result — it says do not budget for it on A5 |
90-| `facts-device-runtime.md` — 950 and 950pr share the C310 instruction and codegen family | [`../constraints/arch-a5.md`](../constraints/arch-a5.md) | ported, **unverified**; it is the reason a 950 finding is worth testing on 950PR at all |
91- 
92-## 4. Conflicts
93- 
94-| Subject | EasyASC | Here | Outcome |
95-|---|---|---|---|
96-| A5 UB capacity | 256 KB, 216 KB when the kernel contains SIMT | 248 KB, stated twice in the installed tutorial for Ascend 950PR/950DT | **Resolved in our favour.** `ub_size=253952` (= 248 KB exactly) in `950PR_957x.ini`, and identically in `950DT_957x`, `950PR_958x`, `950DT_958x`. Recorded at [`../constraints/arch-a5.md`](../constraints/arch-a5.md) together with *how* it was settled: the search that first concluded "no source decides this" had grepped `python/pypto_pro`, which has no UB constant, and not the platform `.ini` that arch-a5's own primary-source list names |
97-| cube↔vec must round-trip GM on A5 | no — the handoff stays on chip | the hand-written per-tile fused construct never ran; the generated pipeline path does | [`../constraints/sync-stitch.md`](../constraints/sync-stitch.md) — reconciled into a three-way statement rather than a winner |
98-| `splitk` / `splitn` minimum 32 | `decomposition-primitives.md` P5 calls 32 a hard minimum; two other files in the same corpus call it a tuning heuristic | — | **not ported in either form.** The source contradicts itself, so there is nothing to port; a reader who needs the bound must measure it |
99- 
100-## 5. Not ported — and why
101- 
102-Grouped by the reason, because the reasons repeat.
103- 
104-### 5a. The construct does not exist in PyPTO-Pro
105- 
106-| EasyASC item | Why not |
107-|---|---|
108-| `Var(existing_var)` is a fresh alias, not a snapshot — the C++ backend may fold it into its uses so a "saved" value reads the new one, and **the simulator snapshots it so this passes every simulator case and only fails on board** | No PyPTO-Pro construct has this shape. There is no re-binding assignment operator on a kernel value (`language/typing/scalar.py` exposes `Scalar`; there is no `__ilshift__` or equivalent). The hazard needs an aliasing declaration form the DSL does not offer |
109-| nonzero L0C row offset: simulator passes, hardware leaves part of L0C uninitialized | Not expressible. `pl.matmul(dst_tile, lhs, rhs)` and `pl.matmul_acc` take a whole accumulator Tile (`language/_api.py:569,581`); there is no destination-offset parameter, so a matmul cannot target a nonzero row offset in the first place |
110-| MX matmul geometry (`splitk % 64`, `splitn % 16`) | No MX surface here — `matmul_mx`, `MxType` and any `_mx` entry point are absent from the installed `pypto_pro` |
111-| `CvMutex` / `VcMutex` spellings, `depth=`, `DBuff`/`TBuff`/`QBuff`, `auto_sync()`, `@vf`/`@simt`/`@func` decorators, `GMTensor` subscripting, `OpExec`, `sim_print` | EasyASC API surface. PyPTO-Pro's equivalents (`make_tile_group(auto_mutex=True)`, sections, `@pl.pipeline.stage`, `vf.mem_bar`) are different objects with different semantics. The *shape* of the mutex-depth argument was ported (§3); the API was not |
112-| A5 pipe legality details — CrossCore set/ready rejecting `Pipe.S`/`Pipe.ALL`, cube-side ready not using `Pipe.MTE3`, barrier side ownership | Stated against EasyASC's explicit per-pipe event API. PyPTO-Pro does not expose hand-placed CrossCore pipe events at this level; there is no call site at which the rule would be checked |
113-| pipe→op mapping table (`gm_to_l1_nd2nz` → MTE2, …) | The pipe *names* are already in [`terminology.md`](terminology.md); the op names are EasyASC's. PyPTO-Pro documents its own pipe per API page, which is the version-correct source |
114-| A2 `SelectMode.TENSOR_SCALAR` silently rewrites NaN lanes | A2-only, and an EasyASC API name |
115- 
116-### 5b. A2/A3-only, explicitly not inherited by A5
117- 
118-| EasyASC item | Why not |
119-|---|---|
120-| `DataCopyPad` at `n_burst = 4096` silently does no work | A2/A3 C220 restriction; the source itself states A5 does not inherit it. Carried onto [`../constraints/arch-a5.md`](../constraints/arch-a5.md) only as the negative statement |
121-| A2 fixed sub-block split (`sb_row = sb*HALF_M`, ownership pinned to rows [0:64)/[64:128)) vs the A5 compact split | Both are EasyASC sub-block authoring models. PyPTO-Pro does not expose the vec sub-block as an addressable half in this form |
122-| A2/A3 capacity rows of the device table | Not our target |
123- 
124-### 5c. Already held here, usually with a stronger local anchor
125- 
126-| EasyASC item | What we already have |
127-|---|---|
128-| matmul accumulation is fp32 except integer paths (int32); L0C is not implicitly zeroed, so dropping the init flag accumulates the previous tile | [`pypto-pro-framework-findings.md`](pypto-pro-framework-findings.md) §18 — measured here in the local spelling: the last matmul of a K loop needs `AccPhase.Final`, and `Partial` throughout faults the device |
129-| local buffers stay full-tile sized; `valid_*` applies only at GM boundaries | [`../constraints/tail-validshape.md`](../constraints/tail-validshape.md), plus the local `compact=1` carve-out, which is more specific than the EasyASC rule and contradicts it for compact accumulators |
130-| decomposition legality tiers P / L / A / F | [`decomposition-primitives.md`](decomposition-primitives.md) — the same four tiers as exact / lossy / algorithmic / forbidden |
131-| UB second dimension must be 32-byte aligned | [`../constraints/vec-alignment-and-rotation.md`](../constraints/vec-alignment-and-rotation.md), measured here |
132-| "do not infer a device rule from a sample alone" | [`../constraints/sync-stitch.md`](../constraints/sync-stitch.md): "These samples demonstrate their recorded environment only"; and [`investigation-discipline.md`](investigation-discipline.md) §11's evidence order |
133-| `@vf` hardware overlaps store / load / compute streams even when the body reads sequentially | `ops/pypto-pro-op-develop/references/vf-reduction-perf.md` § "Scratch stores need a barrier before the next vector load", against the local `vf.mem_bar` (`language/_vf_api.py:242`). Only the *simulator treats the barrier as a no-op* half is untranslatable |
134-| `c220 vgatherb` needs uint16 operands for 16-bit data | [`../patterns/vec-ub-strip-gather.md`](../patterns/vec-ub-strip-gather.md) index-width rule. The "simulator accepts `half`, the on-box compiler rejects it" half has no local counterpart |
135-| bounded search budget — three candidates, at most two fixes at one boundary, counters in a state file | The orchestrator state machine already bounds this (`max_cycles_per_module`, the `capability_gap` → verifier adjudication path) |
136-| signed zero survives into FP4 (a negative rounding to zero emits nibble `0x8`) | Already recorded, explicitly as unverified, in [`pypto-pro-framework-findings.md`](pypto-pro-framework-findings.md) § EasyASC cross-port, alongside the cast-mask-width claim from the same section |
137-| a5pr = 28 cube / 56 vector cores | Independently measured here (`vector_core_num=56`); a cross-check, not a port |
138- 
139-### 5d. Numbers this KB is not allowed to transcribe
140- 
141-[`../constraints/arch-a5.md`](../constraints/arch-a5.md) states the rule: platform capacities are
142-read from the installed platform files at design time and **not duplicated into this KB**,
143-because a duplicated number detaches from the version that produced it.
144- 
145-| EasyASC item | Why not |
146-|---|---|
147-| the device capacity table (cube/vec core counts, L0A/L0B/L0C, L1, BT bytes, UB per SKU across a2/a3/a5/a5pr) | Transcription ban. What was portable from it is the *derived* content — the BT-slot bound and the `n_burst` negative, both in §3. **It was checked anyway**, row by row against `950PR_957x.ini`, because a table that can be checked cheaply should be: it is right about L0A/L0B, L0C, L1, BT, the 28/56 split and A2/A3's 192 KB UB, and wrong only about A5 UB. Usable as a cross-check; not as a source |
148-| estimator quick-models: L0C double-buffer bytes, `MAX_L0C_TILE_ELEMENTS_DBUF = 32*1024`, the "stable large-K point" `TILE_M=128, TILE_N=256, TILE_K=256, SPLIT_K=64` | Another DSL's estimator constants, unmeasured here. [`investigation-discipline.md`](investigation-discipline.md) §6 is explicit that a model ranks candidates and is not evidence; a transcribed tuning point would be read as a starting configuration |
149-| NZ panel footprint `ceil(N/C0)*stride_m*C0`, ZZ footprint `ceil(M/row_block)*align_N*row_block` | Layout-specific and partly in vocabulary this KB does not use (`ZZ`). The general principle — a strided footprint is not the product of its extents — was ported in §3 in its DSL-independent form |
150- 
151-### 5e. Process content belonging to the other project
152- 
153-EasyASC's workflow-state, repository-maintenance, and pattern-page-contract playbooks, its
154-`tools/` scripts, and its `refs/` decomposition layout are 100% that project's process. This
155-repository has its own equivalents (the four-stage orchestrator, `CONTRACT.md`, the pattern
156-index).
157- 
158-Its rule to **run simulator tests sequentially**, because concurrent simulator processes can
159-corrupt each other, has no counterpart — there is no simulator. The nearest live analogue,
160-serializing parallel agents against one board, is already held at
161-[`investigation-discipline.md`](investigation-discipline.md) §10.
162- 
163----
164- 
165-## Re-reading this ledger later
166- 
167-A row that says *unverified* is an invitation, not a closed question. Each such claim carries
168-a named probe on its own page; running one converts the row to a measurement or deletes the
169-section. If you settle one, update both the page and this ledger — a ledger that still lists a
170-retired hypothesis is how a refuted claim gets re-adopted.
@@ -228,10 +228,10 @@ share not just a record but a board, and three operational facts govern that:
228 228 
229"The framework cannot express X" is a much stronger claim than "I have not229"The framework cannot express X" is a much stronger claim than "I have not
230found a composition that expresses X", and collapsing the second into the first230found a composition that expresses X", and collapsing the second into the first
231-has a measured price: two operators independently concluded a mask could not be231+has a measured price: two separate efforts independently concluded a mask could
232-converted between element widths, designed their kernels around the absence,232+not be converted between element widths, designed their kernels around the
233-and paid roughly **+8 OperatorScore** between them — the capability existed,233+absence, and each carried avoidable cost for several rounds — the capability
234-filed under a name neither search reached234+existed, filed under a name neither search reached
235([mask-width conversion](../constraints/vec-mask-width.md)).235([mask-width conversion](../constraints/vec-mask-width.md)).
236 236 
237Before promoting a candidate's failure into a capability claim, record all of:237Before promoting a candidate's failure into a capability claim, record all of:
@@ -307,9 +307,9 @@ second.
307Related, in a different register: **grade a test run by the number of307Related, in a different register: **grade a test run by the number of
308comparisons that ran**, not by its summary line. Expected verdict lines =308comparisons that ran**, not by its summary line. Expected verdict lines =
309`Σ (modes per test function)`; a shortfall means something short-circuited, and309`Σ (modes per test function)`; a shortfall means something short-circuited, and
310-a "20/20 PASS" summary counts functions that did not raise rather than310+an all-pass summary counts functions that did not raise rather than
311-comparisons that executed. The procedure is in311+comparisons that executed. Count the verdict lines and compare against the
312-[../playbooks/benchmark-scoring.md](../playbooks/benchmark-scoring.md) § traps.312+expected total before reading the summary as coverage.
313 313 
314If the gate is incomplete, report **"the current candidate has not found a314If the gate is incomplete, report **"the current candidate has not found a
315valid composition"** — a statement that invites the next search — not "the DSL315valid composition"** — a statement that invites the next search — not "the DSL
@@ -339,6 +339,27 @@ the thing under test**. A wrong shape is caught by reading the shape; a shared
339flag is caught only by asking what the control would have to emit if the339flag is caught only by asking what the control would have to emit if the
340implementation were broken, and then checking that it does.340implementation were broken, and then checking that it does.
341 341 
342+### 13.0 The negative control has its own mechanism, and that mechanism can fail
343+ 
344+One level below §13. A checker was validated by perturbing the source it guards
345+and confirming it went red. The perturbation appeared to pass — and the *test* was
346+broken, not the checker: the `sed` pattern matched 20-space indentation while the
347+code under test now sat at 24, so it edited nothing. A no-op perturbation produces
348+a green result that looks exactly like a checker correctly accepting valid input.
349+ 
350+> **A negative control must prove it changed something before its result carries
351+> information.** Diff the perturbed artifact against the original, or assert the
352+> edit count, and only then read the verdict.
353+ 
354+The same session produced two related failures in the same script, both of which
355+make a naive checker lie while looking healthy. Anchoring a block comparison on
356+the first occurrence of its opening line, when that line occurs four times, diffed
357+one section against a different one and printed 80 lines that read as catastrophic
358+deviation. And widening an alignment window to absorb length changes made the
359+*next* section's lines score as deletions — 16 phantom deletions, including
360+another module's preamble. Both were caught only because someone read the diff
361+instead of the exit code.
362+ 
342So state the expectation as what a correct implementation must produce,363So state the expectation as what a correct implementation must produce,
343unconditionally — never as a function of the switch being tested — and make the364unconditionally — never as a function of the switch being tested — and make the
344control's required output a number written down in advance. `checker-is-live:365control's required output a number written down in advance. `checker-is-live:
@@ -424,20 +445,8 @@ verdict, the way §13 requires the control's mismatch count next to it. "It pass
424with a reuse factor of 1 is the same non-statement as "no mismatches" from a445with a reuse factor of 1 is the same non-statement as "no mismatches" from a
425checker never shown to go red.446checker never shown to go red.
426 447 
427-**Provenance.** The predicate and the phrase "a passing single-tile simulation is
428-not a reuse proof" are EasyASC's
429-(`references/authoring-preflight.md:58-61`, `references/pitfall-records.md:23`,
430-where it is a mandatory regression); its own analysis puts the invariant as
431-`slots > lookahead` and notes that shapes at or under the pipeline lookahead pass
432-while undersized. The reasoning is about ring wrap-around and work distribution,
433-not about either DSL's API, and the discipline it expresses is §13's — which is
434-why it lives here rather than being marked as an unverified port. What is *not*
435-established for PyPTO-Pro is any specific lookahead depth.
436- 
437One rule travels with it, in the same register: **the ownership checker's448One rule travels with it, in the same register: **the ownership checker's
438-warnings are correctness signals.** EasyASC's form is "treat `auto_sync` warnings449+warnings are correctness signals.** When the machinery that manages buffer ownership
439-as correctness signals — resolve the ownership model or make a concrete proposal;
440-do not waive them." Generalised: when the machinery that manages buffer ownership
441for you emits a warning and the run passes anyway, you have a passing result with450for you emits a warning and the run passes anyway, you have a passing result with
442an unresolved warning, which is not a passing result. Read it before shipping.451an unresolved warning, which is not a passing result. Read it before shipping.
443 452 
@@ -539,9 +548,8 @@ a wrong-copy error at the point of failure.
539 548 
540### 14.2 Run the artifact you are shipping, once, before it costs anything549### 14.2 Run the artifact you are shipping, once, before it costs anything
541 550 
542-An operator was submitted and scored **0/20 — every case a compile error**. The551+A delivery failed **every case with a compile error**. The post-mortem first
543-post-mortem first blamed a toolchain version gap between the grader and the552+blamed a toolchain version gap between the build host and the board. That was wrong, and the truth is duller: **the submitted file had never
544-board. That was wrong, and the truth is duller: **the submitted file had never
545been executed anywhere.** It reproduced the failure on the first board run,553been executed anywhere.** It reproduced the failure on the first board run,
546byte-for-byte, in seconds.554byte-for-byte, in seconds.
547 555 
@@ -566,10 +574,10 @@ Two rules, and the second is the one that was missing:
566 "couldn't have affected."574 "couldn't have affected."
567- **Before any irreversible spend, execute the exact artifact.** Not the staged575- **Before any irreversible spend, execute the exact artifact.** Not the staged
568 source it came from, not the version the gate saw — the bytes being shipped.576 source it came from, not the version the gate saw — the bytes being shipped.
569- One run, one command. It costs seconds against a credit and a zero.577+ One run, one command. It costs seconds, against losing the whole delivery.
570 578 
571A note on how the wrong post-mortem happened, since it wasted a round. The579A note on how the wrong post-mortem happened, since it wasted a round. The
572-version difference between grader and board was real and independently580+version difference between build host and board was real and independently
573documented, so it was *available* as an explanation and it fit the shape of the581documented, so it was *available* as an explanation and it fit the shape of the
574failure. Reaching for it meant the cheap decisive test — run the shipped file on582failure. Reaching for it meant the cheap decisive test — run the shipped file on
575the board — went unrun for another cycle. **When a plausible systemic cause and583the board — went unrun for another cycle. **When a plausible systemic cause and
@@ -598,3 +606,69 @@ names, KB-root-relative paths, a source root declared at the top of the
598document). An audit's first red is as likely to indict the audit as the606document). An audit's first red is as likely to indict the audit as the
599artifact — repair the resolver, then re-confirm it still rejects a fabricated607artifact — repair the resolver, then re-confirm it still rejects a fabricated
600path before believing the green.608path before believing the green.
609+ 
610+## 15. The premise is the thing to test first, not the candidates within it
611+ 
612+Three optimisation directions were dispatched on one kernel in one session. All three
613+premises were wrong, and each was refuted by a measurement that cost far less
614+than the work it prevented:
615+ 
616+1. *"The deficit is prefill traffic."* A pipe-utilisation profile showed
617+ `aic_mac 0.08-0.18` and `aiv_time == kernel duration` — the Cube idle, the
618+ vector core always critical, GM traffic never binding. Two candidates modelled
619+ at 2.04x and 1.45x were aimed at an idle resource.
620+2. *"Band A's cost is per-KV-column iteration overhead, so pack columns."*
621+ Refuted from the **same profile that produced the attribution**, by tabulating
622+ ns per loop-iteration across a 35x range and finding it monotone — the
623+ signature of fixed cost.
624+3. *"`TQ_PREFILL=128` gives 2x."* It gives 1.45x, because the bound expression
625+ `kv_lim_i = S_kv - S + (i+1)*TQ` contains `TQ`, so a previously shipped lever
626+ had already consumed those iterations.
627+ 
628+The pattern: each premise was inherited from a document (a DESIGN section, a
629+prior agent's report) that was internally rigorous but rested on an unmeasured
630+assumption about *what the binding resource is*. Rigour downstream of a wrong
631+premise produces confident wrong direction, and it is indistinguishable from
632+rigour downstream of a right one.
633+ 
634+**Rule.** Before commissioning work against a model, spend one measurement on
635+the model's own load-bearing assumption. "Which resource is saturated" is
636+usually one profile away and it invalidates or confirms every candidate at once.
637+Prefer that to adjudicating candidates more carefully within the model.
638+ 
639+**Corollary — a rejected candidate must be re-examined when the premise changes.**
640+`TQ_PREFILL=128` had been rejected for "zero traffic benefit". Once traffic was
641+measured not to be the constraint, that rejection carried no information, and the
642+candidate turned out to be both the cheapest to build (zero extra UB — the tile
643+groups were *already* declared at 64 lanes and narrowed at runtime) and the best
644+remaining. Rejections inherit the premise they were made under; re-derive them
645+rather than trusting the earlier verdict. The same re-examination found the
646+recorded capacity obstacle ("L0A over by 32,768 B") was arithmetic for a
647+*different* candidate's double-buffered tile, not this one's single slot.
648+ 
649+## 16. Fixing an underflow is not fixing the empty case
650+ 
651+A data-dependent loop bound was found by review to go negative
652+(`min(128, 0+64+128-512) = -320`) and was clamped at zero. The clamp was correct
653+and insufficient: the zero-iteration loop it produced **hung the AI Core**,
654+because a consumer outside the bound waited on a handshake its producer, inside
655+the bound, never performed. The pre-clamp code had been slow but correct — it ran
656+the full loop with every lane masked.
657+ 
658+Two transferable pieces:
659+ 
660+- **A range fix has three cases, not two.** Negative, empty, and non-empty.
661+ Clamping merges the first into the second; if the second is unsafe, the fix
662+ moves the defect rather than removing it. Enumerate all three explicitly.
663+- **Localize a hang by flooring one participant at a time.** Flooring only the
664+ suspected loop, while deliberately *leaving* zero bounds on the other three
665+ sites carrying the same expression, both proved which site owned the hang and
666+ refuted the competing "the primitive mishandles an empty range" theory in one
667+ run. A positive control — reverting the fix and confirming the hang returns
668+ with the same log signature — is what separates "I changed something and it
669+ stopped" from "I fixed the cause".
670+ 
671+Related: a safety argument of the form "no in-contract input can reach this" must
672+be re-derived per tile size when the threshold contains the tile size. Here the
673+condition is `S >= S_kv + QTile`, and one contract case sits exactly on it,
674+protected only by carrying `is_causal=False`.
@@ -101,19 +101,19 @@ Three cheap checks, in the order they would have caught it:
101A control that only exercises the harness — re-measuring the same variant twice101A control that only exercises the harness — re-measuring the same variant twice
102— cannot catch this. The control has to distinguish the variants.102— cannot catch this. The control has to distinguish the variants.
103 103 
104-### 1c. `precision_compare` is stricter on integers than the benchmark104+### 1c. `precision_compare` is stricter on integers than the accuracy contract
105 105 
106The dev-side helper compares integer outputs for **exact equality**, while the106The dev-side helper compares integer outputs for **exact equality**, while the
107-benchmark applies the operator's `proto.yaml` tolerance — commonly `int8: 1`,107+contract applies the operator's `proto.yaml` tolerance — commonly `int8: 1`,
108i.e. every element within ±1. A kernel can therefore fail the local check and108i.e. every element within ±1. A kernel can therefore fail the local check and
109pass the real gate.109pass the real gate.
110 110 
111Measured on a quantizing operator: 1281 of 262144 int8 elements differed, **all111Measured on a quantizing operator: 1281 of 262144 int8 elements differed, **all
112-by exactly 1**, `max|diff| = 1`. Local check FAIL, benchmark rule PASS.112+by exactly 1**, `max|diff| = 1`. Local check FAIL, contract rule PASS.
113 113 
114So when the local check reports an integer mismatch, get the distribution before114So when the local check reports an integer mismatch, get the distribution before
115changing anything — `max|diff|` and the off-by-one count. Chasing exact equality115changing anything — `max|diff|` and the off-by-one count. Chasing exact equality
116-that the benchmark never required costs real time, and the two-step116+that the contract never required costs real time, and the two-step
117`fp32 → fp16 → int8` convert (necessary, see below) inherently produces117`fp32 → fp16 → int8` convert (necessary, see below) inherently produces
118off-by-one drift near rounding boundaries.118off-by-one drift near rounding boundaries.
119 119 
@@ -181,7 +181,7 @@ taking the device lock. Use it as the fast gate before every on-board run.
181**Observed.** `ValueError: no <op> class for signature []` on every case of any181**Observed.** `ValueError: no <op> class for signature []` on every case of any
182operator with more than one class.182operator with more than one class.
183 183 
184-**Established.** The evaluator calls the candidate as `func(**params)` — keyword184+**Established.** The caller invokes the candidate as `func(**params)` — keyword
185arguments only, with keys taken from `signature(golden_func)`. The generated185arguments only, with keys taken from `signature(golden_func)`. The generated
186PyPTO-Pro dispatcher builds its lookup key from positional `args` alone, so the186PyPTO-Pro dispatcher builds its lookup key from positional `args` alone, so the
187key is empty and matches nothing. Reproduced directly by reimplementing the187key is empty and matches nothing. Reproduced directly by reimplementing the
@@ -189,7 +189,7 @@ matcher: it returns the right class for `stock(x)` and raises for `stock(x=x)`.
189The non-Pro dispatcher in the sibling generator is correct — it falls back to189The non-Pro dispatcher in the sibling generator is correct — it falls back to
190keyword values and prefix-matches.190keyword values and prefix-matches.
191 191 
192-**Cost.** The operator scores zero on routing, before any kernel runs.192+**Cost.** The operator fails on routing, before any kernel runs.
193 193 
194**Workaround.** Emit a dispatcher that binds positional *and* keyword arguments194**Workaround.** Emit a dispatcher that binds positional *and* keyword arguments
195against the golden's parameter order before keying, and that skips absent-or-None195against the golden's parameter order before keying, and that skips absent-or-None
@@ -302,13 +302,14 @@ Whether that matters depends on which pipes the two accesses sit on:
302 MTE2→V barrier is never emitted, and the broadcast reads whatever was at the302 MTE2→V barrier is never emitted, and the broadcast reads whatever was at the
303 address before the transfer landed.303 address before the transfer landed.
304 304 
305-Measured on DequantSwigluQuant: loading the per-token `activation_scale` into305+Measured on a fused dequant/activation/quant kernel: loading the per-token
306-the row-major alias and broadcasting through the DN view corrupted 1,071,046 of306+`activation_scale` into the row-major alias and broadcasting through the DN view
307-8,388,608 elements on case 20 and produced scale errors of 1e7 relative. It is307+corrupted about an eighth of the output elements on the largest case and
308-a *latent* failure — it only appears once a block runs more than one tile, so308+produced scale errors of 1e7 relative. It is a *latent* failure — it only
309-every case whose token count fit in a single tile per core passed, and a test309+appears once a block runs more than one tile, so every case whose token count
310-set built from small shapes would have shipped it. Four of the twenty public310+fit in a single tile per core passed, and a test set built from small shapes
311-cases hid it; the four that exposed it were the largest.311+would have shipped it. Only a handful of the contract cases exposed it, and
312+those were the largest.
312 313 
313**Rule.** Never DMA into an address that is read through a different tile-group314**Rule.** Never DMA into an address that is read through a different tile-group
314view. Land the transfer in its own tile with its own `mutex_id`, then copy it315view. Land the transfer in its own tile with its own `mutex_id`, then copy it
@@ -359,7 +360,7 @@ illegal in the cube section, so the same enum passes one half of the compile and
359fails the other.360fails the other.
360 361 
361**This is narrower than it first appeared.** The auto path emits the correct362**This is narrower than it first appeared.** The auto path emits the correct
362-`PIPE_FIX` for the reference kernel *and* for a full MLA kernel whose vector363+`PIPE_FIX` for the reference kernel *and* for a full staged kernel whose vector
363stage consumes the buffer with `pl.mul`. Only the DMA-consumer probe broke. So364stage consumes the buffer with `pl.mul`. Only the DMA-consumer probe broke. So
364the rule is: **have the consuming stage touch a cross-core buffer with a vector365the rule is: **have the consuming stage touch a cross-core buffer with a vector
365op first**. If a stage only wants to forward the buffer to GM, copy it into a366op first**. If a stage only wants to forward the buffer to GM, copy it into a
@@ -413,8 +414,8 @@ groups throughout, checked against torch:
413| 4 | 56 | 7168 | 8.7e-04 |414| 4 | 56 | 7168 | 8.7e-04 |
414 415 
415So **two slots suffice at any depth** — `auto_mutex` does order slot reuse416So **two slots suffice at any depth** — `auto_mutex` does order slot reuse
416-against the matmul still reading it, and a 56-block contraction (which417+against the matmul still reading it, and a 56-block contraction (which a
417-MlaProlog's `He = 7168` requires) is fine. Extra slots buy nothing for418+7168-wide hidden extent requires) is fine. Extra slots buy nothing for
418correctness.419correctness.
419 420 
420**This finding previously said the opposite** — that slots must be >= blocks,421**This finding previously said the opposite** — that slots must be >= blocks,
@@ -501,7 +502,7 @@ leaving an architect to reason about a roofline with no numbers available. The
501right fix is not to paste constants — the platform constraints page explicitly502right fix is not to paste constants — the platform constraints page explicitly
502forbids that, since transcribed numbers detach from the installed version — but503forbids that, since transcribed numbers detach from the installed version — but
503to supply a tool that derives them from the installed platform file, plus the504to supply a tool that derives them from the installed platform file, plus the
504-knowledge that no platform file contains: which SKU applies, how the scoring505+knowledge that no platform file contains: which SKU applies, how a comparison
505anchor relates to the hardware roofline, and what fraction of peak is actually506anchor relates to the hardware roofline, and what fraction of peak is actually
506reachable.507reachable.
507 508 
@@ -515,9 +516,9 @@ sent this operator's development down a blind alley for a full cycle: a
515reimplemented checker reported **0/20** on kernels whose real verdict was mixed,516reimplemented checker reported **0/20** on kernels whose real verdict was mixed,
516and it did so by being wrong in four independent ways at once.517and it did so by being wrong in four independent ways at once.
517 518 
518-Measured against `src/kernel_eval/utils/compare.py` (identical on the A5 box and519+Measured against the configured comparator (identical on the A5 box and in the
519-in the local checkout; the box's copy simply predates the normal-region520+local checkout; the box's copy simply predates the normal-region relaxation and
520-relaxation and is therefore the stricter of the two):521+is therefore the stricter of the two):
521 522 
522| what | the real rule | what a plausible paraphrase gets wrong |523| what | the real rule | what a plausible paraphrase gets wrong |
523|---|---|---|524|---|---|---|
@@ -543,10 +544,11 @@ to a local approximation reintroduces exactly the bug it is meant to prevent.
543 544 
544### 22. A bf16 GM intermediate is not a free choice in a multi-matmul chain545### 22. A bf16 GM intermediate is not a free choice in a multi-matmul chain
545 546 
546-MlaProlog's golden upcasts every input to fp32, carries the whole chain in fp32,547+Consider a golden that upcasts every input to fp32, carries the whole chain in
547-and rounds only its four outputs. A kernel that instead rounds each GM548+fp32, and rounds only its final outputs. A kernel that instead rounds each GM
548-intermediate to bf16 — the obvious tiling, and the one this operator shipped549+intermediate to bf16 — the obvious tiling, and the one commonly reached for
549-first — fails every case on `query` and `query_rope`.550+first — fails every case on the outputs fed by the longest accumulation
551+chain.
550 552 
551The mechanism is not accumulated relative error, which stays near `2e-3` and553The mechanism is not accumulated relative error, which stays near `2e-3` and
552would pass. It is that `query` is a 128-term signed sum, so its elements are554would pass. It is that `query` is a 128-term signed sum, so its elements are
@@ -590,7 +592,7 @@ widen to fp32.
590 592 
591**The cheap way to find this:** the whole table above was produced on a laptop593**The cheap way to find this:** the whole table above was produced on a laptop
592with no NPU, by replaying the kernel's dataflow in torch with `store` and594with no NPU, by replaying the kernel's dataflow in torch with `store` and
593-`terms` as parameters and grading with the bench's own comparator. A precision595+`terms` as parameters and checking with the configured comparator. A precision
594plan is settleable offline; only the kernel that implements it needs hardware.596plan is settleable offline; only the kernel that implements it needs hardware.
595 597 
596### 23. Vector-kernel throughput is set by DMA granularity and task striding598### 23. Vector-kernel throughput is set by DMA granularity and task striding
@@ -643,8 +645,8 @@ contraction pairwise. For a 7168-deep contraction (N = 56) that is a ~3x gap,
643and on an operator whose graded outputs include catastrophically cancelled645and on an operator whose graded outputs include catastrophically cancelled
644near-zeros it is the difference between passing and failing.646near-zeros it is the difference between passing and failing.
645 647 
646-Measured on MlaProlog's first projection, decomposing `qr`'s absolute error by648+Measured on the first projection of a staged multi-matmul chain, decomposing
647-substituting each stage with its exact value:649+one output's absolute error by substituting each stage with its exact value:
648 650 
649| contribution | 1 accumulator | 4 accumulators | CPU |651| contribution | 1 accumulator | 4 accumulators | CPU |
650|---|---|---|---|652|---|---|---|---|
@@ -658,7 +660,7 @@ and recombine them **pairwise** in the consumer: `(p0+p1) + (p2+p3)` keeps both
658intermediates at half scale so only the final addition rounds at full scale.660intermediates at half scale so only the final addition rounds at full scale.
659Four `[64, 128]` fp32 accumulators cost 128 KB of the 256 KB L0C, and the extra661Four `[64, 128]` fp32 accumulators cost 128 KB of the 256 KB L0C, and the extra
660GM traffic was ~19 MB against 122 MB of weights -- runtime did not move.662GM traffic was ~19 MB against 122 MB of weights -- runtime did not move.
661-17/20 -> 19/20, operator score 57.96 -> 61.84.663+17/20 -> 19/20 correct.
662 664 
663Practical notes: unroll the K loop by the accumulator count rather than665Practical notes: unroll the K loop by the accumulator count rather than
664branching on `k % 4`, so the Partial/Final phase conditions stay simple (`q == 0`666branching on `k % 4`, so the Partial/Final phase conditions stay simple (`q == 0`
@@ -702,9 +704,8 @@ Read them under these conditions:
702 704 
703## Consolidated DSL limitations — the four-operator sweep (2026-08)705## Consolidated DSL limitations — the four-operator sweep (2026-08)
704 706 
705-One pass across four CANN Bench operators built in this DSL on707+One pass across four operators built in this DSL on
706-Ascend950PR_9579 (CANN 9.2.0, bisheng 15.0.5): `foreach_addcdiv_scalar`,708+Ascend950PR_9579 (CANN 9.2.0, bisheng 15.0.5). The upstream-facing report with
707-`swi_glu`, `apply_rotary_pos_emb`, `cummin`. The upstream-facing report with
708full text and citations for every entry is709full text and citations for every entry is
709[`docs/pypto-pro-dsl-limitations.md`](../../../../docs/pypto-pro-dsl-limitations.md).710[`docs/pypto-pro-dsl-limitations.md`](../../../../docs/pypto-pro-dsl-limitations.md).
710Per-operator `FRAMEWORK_FINDINGS.md` numbering collides from #22 up across711Per-operator `FRAMEWORK_FINDINGS.md` numbering collides from #22 up across
@@ -733,9 +734,9 @@ below is the superseding record.
733 [patterns/vec-scan-prefix-dependent.md](../patterns/vec-scan-prefix-dependent.md).734 [patterns/vec-scan-prefix-dependent.md](../patterns/vec-scan-prefix-dependent.md).
734- **`vf.*` is three-address only** — the assignment-form rule under #1f735- **`vf.*` is three-address only** — the assignment-form rule under #1f
735 above.736 above.
736-- **The build cache keys on `co_name`** — #1g above for the collision737+- **The build cache keys on `co_name`** — #1g above for both directions: the
737- direction; the stale-binary converse is a listed trap in738+ collision, and the stale-binary converse where an edited body under an
738- [playbooks/benchmark-scoring.md](../playbooks/benchmark-scoring.md).739+ unchanged name is served the previous binary.
739- **UB ordering hazards inside a vector function** — store-then-reload under740- **UB ordering hazards inside a vector function** — store-then-reload under
740 #1f above; cross-call scatter ordering in741 #1f above; cross-call scatter ordering in
741 [patterns/vec-scatter-owner-model.md](../patterns/vec-scatter-owner-model.md)742 [patterns/vec-scatter-owner-model.md](../patterns/vec-scatter-owner-model.md)
@@ -780,18 +781,18 @@ below is the superseding record.
780 `min`, `max`, `data`.781 `min`, `max`, `data`.
781- **A module-level Python `float("inf")` constant renders as the undeclared782- **A module-level Python `float("inf")` constant renders as the undeclared
782 C++ identifier `inff`** — bisheng fails with `use of undeclared identifier783 C++ identifier `inff`** — bisheng fails with `use of undeclared identifier
783- 'inff'` in the generated `kernel.cpp` (cummin `cummin_agg_float32`,784+ 'inff'` in the generated `kernel.cpp` (observed 2026-08-06 in a scan
784- 2026-08-06). Treat any non-finite module-level float constant consumed785+ aggregation kernel). Treat any non-finite module-level float constant consumed
785 inside a jit body as a compile risk; check the generated source.786 inside a jit body as a compile risk; check the generated source.
786- **Two caveats on hoisting `vf.update_mask`** (the lever itself is in the787- **Two caveats on hoisting `vf.update_mask`** (the lever itself is in the
787 alignment page above): the tail loop must be its **own pass** over rows —788 alignment page above): the tail loop must be its **own pass** over rows —
788 nesting it inside the main loop cost 1.65x on empty tails — and one hoisted789 nesting it inside the main loop cost 1.65x on empty tails — and one hoisted
789- variant (`rope_bcast_interleaved_float32`) **faults the device and poisons790+ variant of a broadcast-interleave body **faults the device and poisons
790 the NPU context**, failing later cases in791 the NPU context**, failing later cases in
791 `copy_between_host_and_device_opapi`; root cause unestablished. Keep a792 `copy_between_host_and_device_opapi`; root cause unestablished. Keep a
792 non-hoisted fallback in reach.793 non-hoisted fallback in reach.
793 794 
794-### The four upstream asks (cummin branch, near-verbatim)795+### The four upstream asks (near-verbatim)
795 796 
7961. Expose a register-level lane shift (vslide-style) — the substantive ask;7971. Expose a register-level lane shift (vslide-style) — the substantive ask;
797 everything else is papercuts around it.798 everything else is papercuts around it.
@@ -802,7 +803,7 @@ below is the superseding record.
8024. Move the unaligned entry points next to the aligned ones, or8034. Move the unaligned entry points next to the aligned ones, or
803 cross-reference them.804 cross-reference them.
804 805 
805-## rms_norm session findings (2026-08-06, bench/rms_norm-a5)806+## Row-reduce/normalization session findings (2026-08-06)
806 807 
807Identified by title, per the numbering-collision rule above.808Identified by title, per the numbering-collision rule above.
808 809 
@@ -814,8 +815,9 @@ Identified by title, per the numbering-collision rule above.
814 to. Bounds the earlier "`CAST_RINT` *is* half-to-even" finding to the815 to. Bounds the earlier "`CAST_RINT` *is* half-to-even" finding to the
815 tile-op `pl.cast` path. vf kernels narrow with `CAST_ROUND` (half-away);816 tile-op `pl.cast` path. vf kernels narrow with `CAST_ROUND` (half-away);
816 vs a torch-RNE golden that measured 1 ulp on a sub-percent of elements,817 vs a torch-RNE golden that measured 1 ulp on a sub-percent of elements,
817- 10x inside the bench gate. Keep the mode a one-line switch.818+ 10x inside the accuracy gate. Keep the mode a one-line switch.
818- (`docs/pypto-pro-dsl-limitations.md` entry 20 has the full probe record.)819+ (`docs/pypto-pro-dsl-limitations.md` entry **II-20** has the full probe
820+ record; the report carries two entries numbered 20, one per part.)
819- **`section_vector` launch width must come from `vector_core_num`, not821- **`section_vector` launch width must come from `vector_core_num`, not
820 `core_num`.** `get_platform_info()` on Ascend950PR_9579 reports822 `core_num`.** `get_platform_info()` on Ascend950PR_9579 reports
821 `core_num=28, vector_core_num=56`; the launch dimension of a823 `core_num=28, vector_core_num=56`; the launch dimension of a
@@ -877,7 +879,7 @@ the entry says so. The upstream-facing subset, severity-ordered, is
877 `torch.zeros(dtype=torch.uint32/uint64, device=npu)` fails inside `zero_`879 `torch.zeros(dtype=torch.uint32/uint64, device=npu)` fails inside `zero_`
878 (`ZerosLikeKernelNpuOpApi.cpp:26`, error 161002), so a uint64 **device**880 (`ZerosLikeKernelNpuOpApi.cpp:26`, error 161002), so a uint64 **device**
879 tensor cannot be constructed to begin with. Route 64-bit index work through881 tensor cannot be constructed to begin with. Route 64-bit index work through
880- two 32-bit words (see the `vf.interleave` workaround under entry 14 of the882+ two 32-bit words (see the `vf.interleave` workaround under the four-operator report's gather/scatter index-register typing entry of the
881 consolidated section).883 consolidated section).
882 884 
883- **The AIV block id is the raw `0..N-1`, and each block observes885- **The AIV block id is the raw `0..N-1`, and each block observes
@@ -940,13 +942,18 @@ the entry says so. The upstream-facing subset, severity-ordered, is
940 apart" returns every other element. Consistent with the official sample at942 apart" returns every other element. Consistent with the official sample at
941 `test_quant_lightning_indexer_vf.py:193-196`.943 `test_quant_lightning_indexer_vf.py:193-196`.
942 944 
945+- **`CastLayout` 声明四个成员,不是两个。** 已安装的 Python API 是权威:`vf.astype`
946+ 的 docstring(本 checkout 的 `pypto_pro/language/_vf_api.py:655`)列出四个位置,
947+ 而 `astype.md` 只描述两个。跨 4 倍位宽比的转换(b32↔b8、bf16↔fp4 等)要预期**指名
948+ layout**、并预期**四个位置存在**;按两成员的读法写,会取到错误的半边。
949+ 
943- **Index primitives bind the index width to the data width.** The NORM tables950- **Index primitives bind the index width to the data width.** The NORM tables
944 in `scatter.md` / `gather.md`: b16 data accepts **only** UINT16 indices;951 in `scatter.md` / `gather.md`: b16 data accepts **only** UINT16 indices;
945 INT32/UINT32/FP32 take UINT32; INT64/UINT64 take UINT32 or UINT64. The952 INT32/UINT32/FP32 take UINT32; INT64/UINT64 take UINT32 or UINT64. The
946 corollary that bites: a b16 source needs UINT16 offsets, and **there is no953 corollary that bites: a b16 source needs UINT16 offsets, and **there is no
947 `vf` path that constructs them** — `vf.muls` has no 16-bit row and954 `vf` path that constructs them** — `vf.muls` has no 16-bit row and
948 `vf.astype` has no b32→u16 narrowing row. **So a b16 indexed pipeline has to955 `vf.astype` has no b32→u16 narrowing row. **So a b16 indexed pipeline has to
949- run at 32 bits end to end.** This refines entry 14 of the consolidated956+ run at 32 bits end to end.** This refines the four-operator report's gather/scatter index-register typing entry of the consolidated
950 section ("gather/scatter type the index register from the data dtype"),957 section ("gather/scatter type the index register from the data dtype"),
951 which gives the int8/int64 routes; the b16 case has no route, only the958 which gives the int8/int64 routes; the b16 case has no route, only the
952 32-bit reroute.959 32-bit reroute.
@@ -1083,65 +1090,91 @@ Not PyPTO-Pro issues — ours. Both were reproduced on this branch.
1083 `compile`), but changing the SPEC-parsing contract is a behaviour change and1090 `compile`), but changing the SPEC-parsing contract is a behaviour change and
1084 is left for a decision rather than made here.1091 is left for a decision rather than made here.
1085 1092 
1086-## EasyASC cross-port session findings (2026-08-07)1093+## A5 attention is vector-issue bound, and small shapes have a fixed-cost floor
1087 1094 
1088-Identified by title, per the numbering-collision rule above. **Scope:** these came1095+Measured on `Ascend950PR_9579` (28 cube / 56 vector), CANN 9.2.0, npu3, with
1089-out of porting a sibling Ascend DSL's knowledge base (EasyASC) onto this one. The1096+`torch_npu.profiler` PipeUtilization over 7 shapes × 2 builds. Every ratio below
1090-port itself is inventoried in1097+is measured; the models built on them are labelled as such.
1091-[`easyasc-port-ledger.md`](easyasc-port-ledger.md); only the entries below are
1092-statements about **PyPTO-Pro**, each established by reading the installed source
1093-in this checkout. Cross-DSL assertions that were *not* verified here live on the
1094-pages that carry them, marked as assumptions.
1095 1098 
1096-### `CastLayout` has four members, not two — `TWO` and `THREE` are in the source and in no document1099+### A5 attention is vector-issue bound, not traffic bound
1097- 
1098-This KB records that "`CastLayout.ZERO` / `ONE` select even / odd lanes, not the
1099-low / high half-register" (A5 probe session, above), and the installed
1100-documentation agrees with that pair: `CastLayout.ZERO` and `CastLayout.ONE` are
1101-the only members appearing anywhere under
1102-`$PYPTO_DEVKIT_DIR/docs/pypto_pro/`.
1103- 
1104-**The installed Python API declares four.** `vf.astype`'s docstring, at
1105-`pypto_pro/language/_vf_api.py:655` in this checkout:
1106 1100 
1107```1101```
1108-layout: ``pl.CastLayout.ZERO`` (default) / ``ONE`` / ``TWO`` / ``THREE``1102+aiv_time == kernel duration in all 7 shapes (within 0.1%)
1103+aiv_vec_ratio 0.51-0.86 (prefill 0.80-0.86)
1104+aic_mac_ratio 0.08-0.18 <- the Cube MAC is 82-92% IDLE
1105+aiv_mte2_ratio 0.05-0.34, aic_mte2_ratio 0.28-0.43
1109```1106```
1110 1107 
1111-The two-member reading is not wrong, it is **incomplete, and incomplete in a way1108+The critical path is the vector core in every shape, and GM traffic never binds.
1112-that matters for width ratios above 2**. `ZERO`/`ONE` selecting even/odd lanes is1109+**Consequence for design work:** a candidate justified by "it reduces GM bytes"
1113-the 2:1 case — one selector per destination position inside a source lane. A 4:11110+is aimed at an idle resource. Two such candidates were modelled at 2.04x and
1114-narrowing has four such positions, and `TWO`/`THREE` are what addresses the other1111+1.45x and would have delivered nothing. Reach for a pipe-utilisation profile
1115-two.1112+*before* adjudicating attention-scheduling candidates on a traffic model — the
1113+adjudication inherits whatever the model measures, and DESIGN-time traffic
1114+arithmetic looks equally rigorous whether or not traffic is the constraint.
1116 1115 
1117-**How this was found, because the route generalises.** EasyASC's1116+Corollary: `pl.move(Acc->Vec)` uses fixpipe too, so relocating an intermediate
1118-`constraints/a5.md` §6.1 records that on C310 (the same die) a BF16→FP4 register1117+from GM to UB does not reduce fixpipe bytes — and fixpipe measured 0.90/0.93 on
1119-cast **requires** one of `RegLayout.ZERO/ONE/TWO/THREE` and rejects `UNKNOWN`,1118+two prefill shapes.
1120-because the underlying `vcvt` demands one of `P0..P3` — four positions for a 4:1
1121-width ratio. That is a claim about the *instruction*, so it predicted that any DSL
1122-reaching the same `vcvt` must expose four selectors. Checking this DSL's installed
1123-source confirmed the prediction.
1124 1119 
1125-**Rule.** When a `vf.astype` spans a width ratio of 4 (b32↔b8, bf16↔fp4 — and1120+### Small shapes carry a fixed cost that no kernel-side optimisation can reach
1126-PyPTO-Pro does declare `DT_FP4`, `DT_INT4`, `DT_UINT4`), expect to name a layout
1127-and expect four positions to exist. Do not conclude from `astype.md` that only two
1128-do. This is the same trap as the dtype table: **the documentation under-reports
1129-this API's enums as well as its dtypes** — a second instance of the pattern
1130-recorded in
1131-[investigation-discipline §11](investigation-discipline.md).
1132 1121 
1133-**What is *not* established.** That `TWO`/`THREE` compile, lower correctly, or1122+On the tiny decode shape, `aiv_scalar` alone is **4.08 us against a 1.22 us
1134-have the interleaved (rather than half-register) meaning that `ZERO`/`ONE` were1123+hardware limit**. Tiling parse, `make_tensor` stride construction,
1135-measured to have. Only their declaration is established. Two further EasyASC1124+regime/layout branching and loop setup cost 3-5x the entire hardware limit
1136-claims about the same cast are carried nowhere else and are unverified here: that1125+*before any arithmetic runs*.
1137-the cast mask follows the **wider** element width (so a BF16↔FP4 cast masks at 128
1138-BF16 lanes, not at the FP4 lane count), and that this silicon **preserves signed
1139-zero** into FP4 — a negative input rounding to zero emits nibble `0x8`, not `0x0`.
1140-Both are cheap to check on a first fp4 kernel and neither should be assumed before
1141-then.
1142 1126 
1143-The same docstring also enumerates eight round modes — `CAST_ROUND` (default),1127+The consequence is a hard ceiling on achievable speedup:
1144-`CAST_RINT`, `CAST_FLOOR`, `CAST_CEIL`, `CAST_TRUNC`, `CAST_RNA`, `CAST_ODD`,1128+`t_hw / aiv_scalar = 0.299` on such a case, i.e. **<= 3.34x, even with every
1145-`CAST_HYBRID` — which is worth knowing beside the measured finding that1129+vector instruction deleted** (`1 / 0.299`, and `4.08 / 1.22` independently). Shapes whose `t_hw` is around 1 us are therefore
1146-`CAST_RINT` fails to lower on 950PR toolchains (rms_norm session, above): the1130+structurally unimprovable, and a workload weighted toward them has a ceiling set
1147-failure is one mode's lowering, not a two-mode surface.1131+by launch overhead, not by kernel quality. Establish this ratio early — it
1132+decides whether a perf deficit is addressable at all, and it is one profile
1133+away.
1134+ 
1135+**How the fixed cost was distinguished from per-iteration cost** — the general
1136+method, worth reusing: tabulate ns per loop-iteration across a wide range of
1137+iteration counts. A per-iteration cost holds it roughly constant; a fixed cost
1138+makes it fall monotonically.
1139+ 
1140+| shape | loop iters/item | x wpc | `aiv_scalar` us | **ns/loop-iter** |
1141+|---|---:|---:|---:|---:|
1142+| tiny | 768 | 1 | 4.08 | **5.315** |
1143+| small | 4,608 | 1 | 5.76 | 1.250 |
1144+| medium | 4,607 | 10 | 7.16 | 0.155 |
1145+| large | 4,608 | 18 | 12.64 | 0.152 |
1146+ 
1147+Monotone across 35x ⇒ fixed. This refuted an attribution of `aiv_scalar 0.26`
1148+to per-KV-column overhead **using the same profile that produced it**, and with
1149+it a proposed optimisation aimed at the wrong term.
1150+ 
1151+### Wall clock is not device time on A5, and the sign can differ
1152+ 
1153+Eager-mode launch carries a ~4 ms host floor that device-time measurement
1154+excludes. Measured on the same 7 shapes: **wall-clock A/B was below 1.0 on four
1155+shapes while device A/B was >= 1.0 on all seven** — the two disagree in
1156+*direction*, not merely magnitude. One shape was 15.7 us device against 4.5 ms
1157+wall. Never quote a wall-clock ratio as a device-time prediction, and treat an
1158+apparent wall-clock regression on small shapes as a host artefact until device
1159+time says otherwise. A previously open "+1.0 ms prefill regression" was closed
1160+this way — it was host-side and invisible to device time.
1161+ 
1162+Calibration point for translating a wall-clock gain into a device-time one: a
1163+decode change measuring 4.2-4.7x wall clock moved device time by **1.87x**.
1164+ 
1165+### A traffic model and an instruction model disagree by 25 points of realization
1166+ 
1167+The one change with both a model and a measurement was a causal KV-tile loop
1168+bound. Scored against two models:
1169+ 
1170+| case | measured | instruction-count model | column-count model |
1171+|---|---:|---:|---:|
1172+| A | 1.081 | 1.100 → **0.983** | 1.333 → 0.811 |
1173+| B | 1.219 | 1.263 → **0.965** | 1.600 → 0.762 |
1174+| C | 1.420 | 1.459 → **0.973** | 1.778 → 0.799 |
1175+ 
1176+The column-count model was not "80% realized" — it was counting the wrong
1177+quantity. **Calibrate a model against the one change that has both a prediction
1178+and a measurement before using it to adjudicate anything**, and prefer the model
1179+whose realization factor is near 1.0. A model at 0.79 is usually mis-specified
1180+rather than pessimistic.
@@ -0,0 +1,115 @@
1+# PyPTO-Pro per-launch `block_dim` findings
2+ 
3+Scope: A5 MIX kernels with host-selected launch geometry. 本页同时收录两类证据:
4+**源码级语义**与**一次锁板 A/B 的结论**(按下方方法可复算)。两类分别标注——
5+采用某个 policy 前,源码级部分可直接引用,锁板部分需在自己的目标上复现。
6+ 
7+> **源码引用怎么核对。** 下面的 `pypto_pro/runtime/jit.py:NNNN` 指的是**已安装的
8+> PyPTO-Pro 发行版**,不在本仓(pypto-gym 不含 `pypto_pro/`)。核对方式是在自己的
9+> 安装里定位该文件,例如
10+> `python -c "import pypto_pro, pathlib; print(pathlib.Path(pypto_pro.__file__).parent)"`。
11+> 行号随版本漂移,以函数名为准而非行号;跨版本差异见第 5 条的版本表。
12+ 
13+## Confirmed runtime semantics
14+ 
15+1. `kernel[stream, block_dim, tiling_key]` called as `(...)` parses `block_dim`
16+ as a normal launch-key value. `_TileJitKernel.__getitem__` captures it in the returned
17+ launcher and calls `_launch` with that value
18+ (`pypto_pro/runtime/jit.py:1428-1447`).
19+2. The shared-library caller receives `uint32_t blockDim` and launches
20+ `kernel<<<blockDim, nullptr, stream>>>`; the same path is used for kernels
21+ carrying FFTS cross-core synchronization
22+ (`pypto_pro/runtime/jit.py:599-623`).
23+3. Compilation cache identity is static shape + datatype + tiling key, not
24+ `block_dim` (`pypto_pro/runtime/jit.py:1552-1577`). One compiled kernel can
25+ therefore be launched with a different positive core count on later calls.
26+4. `pl.get_block_num()` is the device API for the number of blocks in that
27+ launch (`pypto_pro/language/_api.py:1111-1113`). A kernel that strides work
28+ by this value adjusts ownership to the selected launch geometry.
29+5. **The caller must clamp. Do not rely on the runtime to do it.** Compute
30+ `block_dim = min(requested, cores_of_the_execution_domain, task_count)` in the
31+ wrapper, where the domain is `PlatformInfo.core_num` for MIX kernels and
32+ `vector_core_num` for AIV-only kernels.
33+ 
34+ Whether the runtime also clamps is **installation-dependent, and the current
35+ direction is that it does not**:
36+ 
37+ | Build | Behaviour |
38+ |---|---|
39+ | `v9.1.0-beta.3` lineage (e.g. `d1839f034`) | `_clamp_block_dim` silently lowers an oversized value to the core count (`runtime/jit.py:1203-1227`, called at `:1446`) |
40+ | `9.2.0-beta.2` lineage, from `4c835a12` (2026-08-07, *"delete wrong core num check"*) | `_clamp_block_dim` is gone. `_validate_block_dim` raises `ValueError` on a non-`int` or non-positive value and the launch uses the value **unchanged** |
41+ 
42+ This is not a detail to leave to the runtime. `pl.get_block_num()` returns the
43+ value actually launched, so task ownership (`range(core_id, total, get_block_num())`)
44+ and the count of MIX-barrier participants both derive from it. On a build that
45+ does not clamp, an oversized request means blocks that own no work still have
46+ to reach every barrier — or do not exist to reach them. Clamping in the caller
47+ makes the launched value knowable at the point the ownership arithmetic is
48+ written, on every build.
49+ 
50+This permits a host wrapper to compute one `block_dim` from ordinary tensor
51+shape integers and pass it to the same JIT kernel. It does not require, and
52+must not use, mutation of cached `PlatformInfo.core_num`.
53+ 
54+> **与 `constraints/wrapper-boundary.md` 的边界关系(该页是 topology-map 里唯一的
55+> `mandatory_constraints`,对 architect / coder / verifier 全类生效)。** 那条强制
56+> 条款说的是"数据的 shape/dtype 处理必须在 kernel 内,wrapper 只做参数校验、输出
57+> 分配和一次 launch"。这里允许的是**从 shape 读整数算出一个 launch 几何标量**,
58+> 不触碰任何张量数据、不改变任何张量形状——属于"一次 launch"的参数计算,
59+> 不是被禁止的数据处理。
60+>
61+> 判定边界:wrapper 里只允许出现**读 `.shape` 得到 int、做整数运算、得到 `block_dim`**
62+> 这一条链路。一旦开始 cast / slice / transpose / pad / concat 张量,或按 shape 选择
63+> 不同的数据布局,就已经越界,按 wrapper-boundary 处理。
64+ 
65+## Safety conditions when varying `block_dim` on a staged multi-stage kernel
66+ 
67+- Select one core count for the whole launch. It cannot change between hard
68+ stages because all launched AIC/AIV participants must reach the same five
69+ paired MIX-barrier boundaries.
70+- Keep each task loop in the form `range(core_id, total_tasks, get_block_num())`
71+ and prove exact one-owner coverage at every selected core count.
72+- Keep the AIV physical-id normalization and subblock barrier participation
73+ unchanged. Lowering `block_dim` changes how many physical blocks launch; it
74+ does not turn the two AIV subblocks into independent GM workers.
75+- Use a positive Python `int`, cap it by both the platform count and the largest
76+ stage task count, and keep unseen shapes on the production fallback until the
77+ policy has evidence on shapes you have not measured.
78+- Give A/B variants distinct JIT function names. The build directory is keyed
79+ by function identity, so same-name variants can otherwise reuse stale code.
80+ 
81+实验与机械审计的产物**不随本仓保留**,因此这里不列路径——指向读者打不开的文件,
82+只会诱使人重跑一次已经付过钱的测量。下面这组扫描按如下方法可自行重做:
83+锁板独占、每个点五次 profiled launch、只改 `block_dim` 一个变量、其余(shape、dtype、
84+tiling key、launch 网格)全部固定。
85+ 
86+锁板扫描(单位:微秒,同一算子的五个代表性 case,按耗时升序记为 A–E):
87+ 
88+| cores | case A | case B | case C | case D | case E | geomean time / 28 cores |
89+|---:|---:|---:|---:|---:|---:|---:|
90+| 8 | 203.637 | 291.351 | 426.549 | 861.328 | 3422.529 | 2.0041 |
91+| 12 | 148.549 | 231.659 | 347.043 | 633.982 | 2487.767 | 1.5218 |
92+| 16 | 123.933 | 206.311 | 306.427 | 509.048 | 1997.335 | 1.2812 |
93+| 20 | 103.111 | 184.970 | 276.798 | 460.163 | 1723.907 | 1.1266 |
94+| 24 | 92.724 | 174.526 | 260.211 | 417.375 | 1559.180 | 1.0350 |
95+| 28 | 92.994 | 171.138 | 254.997 | 397.086 | 1431.979 | 1.0000 |
96+ 
97+The single smallest case favored 24 cores by well under a percent, while every
98+other measured case and the geomean favored the full 28. That kernel therefore
99+retains the full-core launch and the dispatch candidate is rejected for that
100+workload. Read this as the shape of the result — one small case dissenting by
101+noise does not outweigh the geomean — not as a claim that lowering `block_dim`
102+can never help.
103+ 
104+## Framework limitations
105+ 
106+- Validation of `block_dim` is not portable across builds: the older lineage
107+ returns a non-positive or non-`int` value **unchanged** from
108+ `_clamp_block_dim` (`runtime/jit.py:1213-1214`), while `4c835a12` onward
109+ **raises** `ValueError`. A wrapper that validates positivity itself behaves
110+ the same on both.
111+- There is no built-in per-shape launch-policy object or measured auto-tuner;
112+ the user wrapper owns dispatch, fallback, and regression evidence.
113+- No build warns about under-occupancy or barrier-vs-work trade-offs, and the
114+ newer lineage does not bound an oversized value at all. Only on-board
115+ profiling can choose the count.