Closed
[WIP] feat(cannbot): add Stage-5 NPU-measure optimization loop and its measurement-confirmed KB #472
hid22900163Add on Aug 12Closed at Aug 24
[WIP] feat(cannbot): add Stage-5 NPU-measure optimization loop and its measurement-confirmed KB #472
Closed
hid22900163Add on Aug 12Closed at Aug 24
Total: 395 files changed+128185-149
A.devkit+1-0
@@ -0,0 +1 @@
1+/Users/limjiunnbin/work/pypto-pro/pypto-gym/.devkit
@@ -66,8 +66,19 @@ package-lock.json
66 66 
67# Agent local settings67# Agent local settings
68.claude/settings.local.json68.claude/settings.local.json
69+.claude/worktrees/
69.omo/70.omo/
70 71 
72+# Generated by cannbot-skills init.sh -- absolute symlinks and a CLAUDE.md with
73+# substituted absolute paths, both per-machine. Regenerate with:
74+# bash cannbot-skills/plugins-official/pypto-pro-op-orchestrator/init.sh project claude
75+.claude/agents/
76+.claude/skills/
77+.claude/references/
78+.claude/kb
79+.claude/cannbot-manifest.json
80+/CLAUDE.md
81+ 
71# PyPTO-Pro devkit cache82# PyPTO-Pro devkit cache
72.devkit/83.devkit/
73 84 
@@ -95,7 +95,7 @@ cannbot-skills/
95| 方案与开发类 | `pypto-op-plan`、`pypto-op-design`、`pypto-op-develop`、`pypto-op-construct` | 实施计划、方案设计、代码开发、工程脚手架 |95| 方案与开发类 | `pypto-op-plan`、`pypto-op-design`、`pypto-op-develop`、`pypto-op-construct` | 实施计划、方案设计、代码开发、工程脚手架 |
96| 验证与调优类 | `pypto-golden-generate`、`pypto-precision-compare`、`pypto-precision-debug`、`pypto-op-verify`、`pypto-op-review`、`pypto-op-perf-tune`、`pypto-kernel-validate` | Golden 生成、精度对比与排查、功能验证、代码检视、性能调优、产物校验(反作弊 + 精度 + 性能) |96| 验证与调优类 | `pypto-golden-generate`、`pypto-precision-compare`、`pypto-precision-debug`、`pypto-op-verify`、`pypto-op-review`、`pypto-op-perf-tune`、`pypto-kernel-validate` | Golden 生成、精度对比与排查、功能验证、代码检视、性能调优、产物校验(反作弊 + 精度 + 性能) |
97| 监控与调试类 | `pypto-op-monitor`、`pypto-general-debug` | 任务监控、通用诊断 |97| 监控与调试类 | `pypto-op-monitor`、`pypto-general-debug` | 任务监控、通用诊断 |
98-| 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 精简流程的全部八项技能 |98+| 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-eval` | PyPTO-Pro 精简流程的全部九项技能 |
99 99 
100### 模型适配(model/)100### 模型适配(model/)
101 101 
@@ -9,7 +9,7 @@
9 9 
10## 📢 项目概述10## 📢 项目概述
11 11 
12-**CANNBot Skills — PyPTO-Gym** 是面向 PyPTO 与 PyPTO-Pro Tile 算子开发、大模型适配和模型治理的 CANNBot Agent Skills 模块,提供 30 个可复用技能与 4 个开发路径插件。12+**CANNBot Skills — PyPTO-Gym** 是面向 PyPTO 与 PyPTO-Pro Tile 算子开发、大模型适配和模型治理的 CANNBot Agent Skills 模块,提供 34 个可复用技能与 4 个开发路径插件。
13 13 
14**面向用户**:基于 PyPTO 编程框架的昇腾 NPU 算子开发者、模型适配工程师。14**面向用户**:基于 PyPTO 编程框架的昇腾 NPU 算子开发者、模型适配工程师。
15 15 
@@ -48,13 +48,13 @@ opencode
48| 领域 / 路径 | 适用场景 | 入口插件 |48| 领域 / 路径 | 适用场景 | 入口插件 |
49|------------|---------|---------|49|------------|---------|---------|
50| **PyPTO 算子开发** | Stage 1–7 全流程融合算子开发与调优 | [pypto-op-orchestrator](plugins-official/pypto-op-orchestrator/AGENTS.md) |50| **PyPTO 算子开发** | Stage 1–7 全流程融合算子开发与调优 | [pypto-op-orchestrator](plugins-official/pypto-op-orchestrator/AGENTS.md) |
51-| **PyPTO-Pro 算子开发** | Stage 1–4 精简流程算子开发与调优 | [pypto-pro-op-orchestrator](plugins-official/pypto-pro-op-orchestrator/AGENTS.md) |51+| **PyPTO-Pro 算子开发** | Stage 1–5 精简流程算子开发与调优 | [pypto-pro-op-orchestrator](plugins-official/pypto-pro-op-orchestrator/AGENTS.md) |
52| **模型适配** | HF 模型上 NPU、融合算子整网集成、模型格式转换 | [pypto-model-tools](plugins-official/pypto-model-tools/AGENTS.md) |52| **模型适配** | HF 模型上 NPU、融合算子整网集成、模型格式转换 | [pypto-model-tools](plugins-official/pypto-model-tools/AGENTS.md) |
53| **算子产物校验** | KernelBench 评测把关:反作弊 + 精度 + 性能统一校验 | [pypto-kernel-validator](plugins-official/pypto-kernel-validator/AGENTS.md) |53| **算子产物校验** | KernelBench 评测把关:反作弊 + 精度 + 性能统一校验 | [pypto-kernel-validator](plugins-official/pypto-kernel-validator/AGENTS.md) |
54 54 
55### 技能清单55### 技能清单
56 56 
57-**算子开发**(ops/,共 27 个)57+**算子开发**(ops/,共 31 个)
58 58 
59| 类别 | 技能 | 说明 |59| 类别 | 技能 | 说明 |
60|------|------|------|60|------|------|------|
@@ -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 精简流程的八项专属技能 |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-eval`、`pypto-pl-vector-kernel`、`pypto-pl-cube-bound`、`pypto-pl-pipe-roofline` | PyPTO-Pro 精简流程的十二项专属技能,含 CANN Bench 提交与评测,以及 Stage 5 调优所用的三项 pl 语言技能(向量 kernel、cube-bound sizing、pipe roofline)。三项 `pypto-pl-*` 按 `ops/` 一级目录平铺,而非嵌套在 `pypto-pro-op-perf-tune/` 下——插件 `init.sh` 只扫描 `ops/` 的一级子目录并按 basename 匹配白名单,嵌套目录会被静默跳过、安装为零个技能 |
71 71 
72**模型适配**(model/,共 3 个)72**模型适配**(model/,共 3 个)
73 73 
@@ -89,7 +89,7 @@ cannbot-skills/
89├── model/ # 模型适配与推理优化 Skills89├── model/ # 模型适配与推理优化 Skills
90└── plugins-official/ # 官方 Plugins(开发路径入口,含 Agents)90└── plugins-official/ # 官方 Plugins(开发路径入口,含 Agents)
91 ├── pypto-op-orchestrator/ # PyPTO classic 算子开发(8 Subagent + 状态机)91 ├── pypto-op-orchestrator/ # PyPTO classic 算子开发(8 Subagent + 状态机)
92- ├── pypto-pro-op-orchestrator/ # PyPTO-Pro 算子开发(5 Subagent)92+ ├── pypto-pro-op-orchestrator/ # PyPTO-Pro 算子开发(6 Subagent)
93 ├── pypto-model-tools/ # 模型适配工具集(安装时附带 8 个算子支撑 skill)93 ├── pypto-model-tools/ # 模型适配工具集(安装时附带 8 个算子支撑 skill)
94 └── pypto-kernel-validator/ # 算子产物校验(反作弊 + 精度 + 性能,单 Subagent)94 └── pypto-kernel-validator/ # 算子产物校验(反作弊 + 精度 + 性能,单 Subagent)
95```95```
@@ -0,0 +1,101 @@
1+# Knowledge contract
2+ 
3+Three places in this repository state that a pipeline validates the knowledge artifacts a
4+generation run produces — [`ROUTER.md`](ROUTER.md), the plan skill and the develop skill.
5+No validator lives here, which made those claims read as false. They are not: the validator
6+lives in the repository that *drives* generation, and this file is the contract between them.
7+ 
8+- **PyPTO-Gym produces.** The planner writes `KB_SELECTION.json`; the coder writes
9+ `KB_USAGE.json`. The vocabulary they draw on is [`topology-map.json`](topology-map.json).
10+- **The driver validates.** CANN-Bench's `auto_pipeline.kb_contract` reads both files and
11+ fails the family that produced a missing or non-conforming one. It locates this KB by
12+ walking up from the PyPTO-Gym checkout to `cannbot-skills/kb`.
13+- **This file is the single source of the shared vocabulary.** It is declared in
14+ `topology-map.json` under `contract`. A consumer reads it; it does not keep its own copy.
15+ Both repositories carry a test that fails if the copies diverge.
16+ 
17+`contract_version` is **1**.
18+ 
19+---
20+ 
21+## What the driver supplies, and what happens without it
22+ 
23+`cases.yaml` is an **input from the driver**, placed beside the task materials. It is not a
24+PyPTO-Gym stage output, and it is absent when the workflow is run standalone.
25+ 
26+Any rule keyed on it must therefore degrade to *not applicable* rather than fail. A check
27+that cannot read `cases.yaml` records `n/a`; it must never report FAIL on the grounds that a
28+file the driver did not supply is missing.
29+ 
30+## Where a family's artifacts live
31+ 
32+```
33+custom/<op>/ single family
34+custom/<op>/<family>/ one directory per family when the cases split
35+```
36+ 
37+The driver decides whether the cases split. When they do not, everything is written flat
38+into `custom/<op>/` and the family's `class_id` is the literal `"."` — the validator rejects
39+an empty `class_id`, so the flat case still needs a value.
40+ 
41+`<family>` is a **content-derived name** describing the family, for example
42+`axis-sensitive-f16-ax1-5b281577`. It is derived from the family's normalized semantics, so
43+it is stable when the case list is reordered and changes when the semantics change. Earlier
44+runs used discovery-order names (`c1`, `c2`); those are still read so work already on disk is
45+found, but nothing new is named that way, and no rule may assume either form.
46+ 
47+## Where the KB is
48+ 
49+| Layout | Path |
50+|---|---|
51+| A checkout of this repository | `cannbot-skills/kb/` |
52+| An installed tree | `$CONFIG_ROOT/kb` — a symlink created by `init.sh`, where `$CONFIG_ROOT` is the tool-specific config root the installer reported |
53+ 
54+Paths inside `KB_SELECTION.json` are relative to whichever of those is in force, so one
55+selection file is valid under both layouts. Never record an absolute path.
56+ 
57+---
58+ 
59+## `KB_SELECTION.json`
60+ 
61+Written before any design exists, from the topology and the dtype/shape facts — never from
62+the operator's name.
63+ 
64+| Field | Requirement |
65+|---|---|
66+| `schema_version` | must equal `contract_version` |
67+| `op` | operator name |
68+| `class_id` | the family directory, or `"."` when flat. Must not be empty |
69+| `topology` | one of the eight `topologies` keys in `topology-map.json` |
70+| `properties` | the dtype and shape facts the selection was derived from; keys drawn from `contract.property_keys` |
71+| `primary_references` | at most `max_primary_references` (3). Each needs a repository-relative `path` that exists, a `reason`, and a content hash |
72+| `no_matching_pattern` | `true` when nothing applies. Must not be set alongside a selection |
73+ 
74+`constraints/wrapper-boundary.md` is in force for every family and does not count against the
75+bound.
76+ 
77+## `KB_USAGE.json`
78+ 
79+Written after the implementation exists. It records what the knowledge *did*, which is the
80+thing opening a document does not demonstrate.
81+ 
82+| Field | Requirement |
83+|---|---|
84+| `schema_version` | must equal `contract_version` |
85+| `op`, `class_id` | as above |
86+| `invariants` | one or more per selected reference. Each names the reference, the invariant derived from it, and the `implementation.file` plus `symbol` where it landed — both must really exist |
87+| `verification.status` | one of `contract.verification_statuses`: `verified`, `deviated`, `not_applicable` |
88+| justification | required whenever the status is `deviated` or `not_applicable` |
89+ 
90+A selected reference that produced no invariant is rejected: a reference that changed nothing
91+should not have been selected.
92+ 
93+---
94+ 
95+## Changing the contract
96+ 
97+Adding a topology, a property key, a verification status, or changing the reference bound is a
98+contract change. Edit `topology-map.json`, raise `contract_version`, and update the consumer to
99+accept the new version. The divergence tests in both repositories fail until it does, which is
100+the point — the previous arrangement had two independent copies and nothing that noticed when
101+they drifted.
@@ -0,0 +1,66 @@
1+# PyPTO-Pro knowledge base
2+ 
3+This directory contains reusable PyPTO-Pro design constraints, patterns, and
4+validated study kernels. It supplements the installed PyPTO-Pro API
5+documentation and official examples; it does not override them.
6+ 
7+Start at [ROUTER.md](ROUTER.md) and open only the reference needed for the
8+current decision.
9+ 
10+## Active resources
11+ 
12+- Platform and API constraints: [constraints/README.md](constraints/README.md)
13+- Reusable dataflows: [patterns/pattern-index.md](patterns/pattern-index.md)
14+- Selector usage contract: [examples/README.md](examples/README.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)
17+- Measurement workflow: [playbooks/benchmark-scoring.md](playbooks/benchmark-scoring.md)
18+ 
19+## Retention gate
20+ 
21+Keep a KB item only when all of these hold:
22+ 
23+1. An active router or selector links to it.
24+2. Its purpose is reusable beyond one experiment, branch, environment, date,
25+ benchmark score, or session.
26+3. Technical claims cite an official document/source path or a retained,
27+ reviewable validation artifact.
28+4. Code is selected only when its validation state is `validated`. Failed,
29+ work-in-progress, and diagnostic probes do not belong in the production
30+ selector.
31+ 
32+Use scenario and technique names for canonical files. Put measured values in
33+validation evidence, never in filenames.
34+ 
35+## How to write a reusable rule
36+ 
37+The retention gate above asks whether an item is reusable. This is how to *write*
38+one so that it is — the same principle [ROUTER.md](ROUTER.md) applies to routing:
39+**classify by the shape of the computation, never by the operator's name, because
40+an operator name tells a new operator nothing it can reuse.**
41+ 
42+Write every rule as **trigger → rule → evidence**:
43+ 
44+- **Trigger** — a structural property the reader can check against their *own*
45+ kernel with no knowledge of any other operator: tile width in lanes, pitch in
46+ bytes, pass count, whether the loop crosses lanes, whether a tile is aliased.
47+ This is what decides whether the rule applies to them.
48+- **Rule** — what to do, stated so it survives a change of SKU and of operator.
49+- **Evidence** — the measurement, with enough provenance to judge whether to
50+ trust it. Describe the subject **structurally** where you can ("a 4-op
51+ elementwise body over 128 full registers") and name the operator only as a
52+ source tag.
53+ 
54+**The failure mode is making the operator the subject of the rule** — "operator X's
55+pitch is 80 elements" instead of "a pitch that is an even multiple of 32 B
56+conflicts; check it on the tile the access actually runs on." A reader then has to
57+reconstruct the analogy before the rule means anything, and if they cannot see it,
58+the rule does not transfer at all. Three kinds of operator mention are legitimate
59+and should not be scrubbed: **the topology's defining semantics**
60+(`torch.gather` on a gather-scatter page), **API names** (`vf.scatter`), and
61+**validation provenance** (`custom/<op>/` as the retained artifact behind a
62+`validated skeleton`, which the retention gate requires).
63+ 
64+A quick self-check when writing: delete every operator name from the sentence. If
65+the rule still tells a reader when it applies and what to do, it was written
66+correctly.
@@ -0,0 +1,148 @@
1+# KB router
2+ 
3+Use the matching skill first, then open one focused KB reference. Installed API
4+documentation and official examples remain authoritative for signatures and
5+platform-specific behavior.
6+ 
7+| Task | Skill | Focused reference |
8+|---|---|---|
9+| Select a validated study implementation | `pypto-pro-material-explore` | [examples/kernel-index.md](examples/kernel-index.md) |
10+| Choose a reusable dataflow | `pypto-pro-op-design` | [patterns/pattern-index.md](patterns/pattern-index.md) |
11+| Check dtype and cast behavior | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/precision.md](constraints/precision.md) |
12+| Check tile shapes and memory placement | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/tiling.md](constraints/tiling.md), then [constraints/memory-layout.md](constraints/memory-layout.md) |
13+| Check vector authoring choices | `pypto-pro-op-develop` | [constraints/vec.md](constraints/vec.md) |
14+| Check synchronization | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/sync-stitch.md](constraints/sync-stitch.md) |
15+| Check dynamic tails | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/tail-validshape.md](constraints/tail-validshape.md) |
16+| Use A5-specific limits | any design/develop/perf skill, after target detection | [constraints/arch-a5.md](constraints/arch-a5.md) |
17+| Classify a decomposition | `pypto-pro-op-design` | [references/decomposition-primitives.md](references/decomposition-primitives.md) |
18+| Measure and tune a correct kernel | `pypto-pro-op-perf-tune` | [playbooks/benchmark-scoring.md](playbooks/benchmark-scoring.md) |
19+| Package and score a kernel on CANN Bench | `pypto-pro-cann-bench-eval` | [constraints/wrapper-boundary.md](constraints/wrapper-boundary.md) |
20+| A graded output misses the accuracy gate and you do not know which stage is at fault | `pypto-pro-op-develop` | [playbooks/numerical-error-localisation.md](playbooks/numerical-error-localisation.md) |
21+| Decide what may run on the host | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/wrapper-boundary.md](constraints/wrapper-boundary.md) |
22+| 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) |
23+| Reduce rows whose last dimension is a handful of bytes | `pypto-pro-op-design` | [patterns/vec-narrow-row-packing.md](patterns/vec-narrow-row-packing.md) |
24+| One kernel must serve a last dimension spanning orders of magnitude, or several dtypes, or several ranks | `pypto-pro-op-design` / `pypto-pro-op-develop` | [patterns/tiling-key-width-ladder.md](patterns/tiling-key-width-ladder.md) |
25+| A correct `vf.*` kernel is far slower than its memory roof | `pypto-pro-op-perf-tune` | [constraints/vec.md](constraints/vec.md), then [constraints/vec-alignment-and-rotation.md](constraints/vec-alignment-and-rotation.md), then [playbooks/benchmark-scoring.md](playbooks/benchmark-scoring.md) |
26+| Hit a framework limit, or debug something that makes no sense | any | [references/pypto-pro-framework-findings.md](references/pypto-pro-framework-findings.md) |
27+| An investigation keeps failing to converge, or you are about to trust a measurement | any | [references/investigation-discipline.md](references/investigation-discipline.md) |
28+| 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` |
29+| 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 |
30+| Recognise a failure someone has already hit | `pypto-pro-op-develop` / `pypto-pro-op-perf-tune` | [references/pitfall-records.md](references/pitfall-records.md) |
31+| Judge whether an ops-per-register lever can pay on a narrow reduction, or are about to generalise a perf measurement across dtypes | `pypto-pro-op-perf-tune` | [references/rms-norm-a5-narrow-d-roofline.md](references/rms-norm-a5-narrow-d-roofline.md) |
32+ 
33+[references/pitfall-records.md](references/pitfall-records.md) is a symptom
34+index, not a rule page: it maps an observed error code, hang or wrong result to
35+the cause that was actually found. Read it when something fails, not when
36+designing. Each entry records the runtime it was observed on; confirm the
37+behaviour still reproduces on the detected target before treating an entry as
38+current.
39+ 
40+Do not load [constraints/arch-a5.md](constraints/arch-a5.md) until the runtime
41+or build configuration confirms an A5 target.
42+ 
43+[constraints/wrapper-boundary.md](constraints/wrapper-boundary.md) is **mandatory
44+for every class**, whatever the topology: the benchmark times the wrapper, so
45+casting, slicing, transposing and every other data-shape operation belongs
46+inside the kernel. It does not count against the three-reference bound.
47+ 
48+## Routing by topology
49+ 
50+The table above answers "which document for this question". This section
51+answers "which documents for this class", and it is the one the pipeline
52+checks. Route on the **shape of the computation**, never on the operator's
53+name — an operator name tells you nothing that a new operator can reuse.
54+ 
55+[topology-map.json](topology-map.json) holds the machine-readable map. The
56+general categories are:
57+ 
58+| Topology | The computation |
59+|---|---|
60+| `elementwise` | one output element per input element, no cross-lane movement |
61+| `row-reduction` | each row reduces to a scalar that is broadcast back |
62+| `scan` | element `i` depends on elements `0..i` |
63+| `gather-scatter-indexing` | data movement driven by an index tensor |
64+| `cube-matmul` | contraction over a shared dimension on the cube unit |
65+| `quantized-matmul` | integer contraction with explicit scale/round/clamp |
66+| `multi-phase-fusion` | dependent phases in one kernel, state carried between them |
67+| `long-axis` | an axis exceeds one tile, forcing multi-tile traversal |
68+ 
69+Properties that modulate the choice within a topology: unaligned shapes, tail
70+blocks, long axes, BF16 or mixed-precision accumulation, INT32/INT64 index
71+semantics, and dynamic dimension arguments.
72+ 
73+### Retained pattern pages
74+ 
75+Every page under `patterns/` — all eighteen — with the topology node
76+[topology-map.json](topology-map.json) routes it from. A cell that names no
77+topology means the page sits in no topology node and is reached from the task
78+table above or from the index. Read
79+[patterns/pattern-index.md](patterns/pattern-index.md) first: it carries the
80+validation status that decides whether a page may be copied or only reasoned
81+from.
82+ 
83+| Page | Routed from |
84+|---|---|
85+| [patterns/vec-tensorlist-fixed-arity.md](patterns/vec-tensorlist-fixed-arity.md) | `elementwise` |
86+| [patterns/vec-row-reduce-broadcast.md](patterns/vec-row-reduce-broadcast.md) | `row-reduction` |
87+| [patterns/vec-group-reduce-broadcast.md](patterns/vec-group-reduce-broadcast.md) | `row-reduction` — modifier: the reduction is over groups within a row |
88+| [patterns/vec-narrow-row-packing.md](patterns/vec-narrow-row-packing.md) | `row-reduction` — modifier: the last dimension's bytes sit far below the 128 B/row knee |
89+| [patterns/tiling-key-width-ladder.md](patterns/tiling-key-width-ladder.md) | `row-reduction` — modifier: `dynamic_dims`, or a last dimension spanning orders of magnitude |
90+| [patterns/vec-scan-prefix-dependent.md](patterns/vec-scan-prefix-dependent.md) | `scan` |
91+| [patterns/vec-ub-strip-gather.md](patterns/vec-ub-strip-gather.md) | `gather-scatter-indexing` |
92+| [patterns/vec-scatter-owner-model.md](patterns/vec-scatter-owner-model.md) | `gather-scatter-indexing` |
93+| [patterns/cube-only.md](patterns/cube-only.md) | `cube-matmul` |
94+| [patterns/batched-2d-contraction.md](patterns/batched-2d-contraction.md) | `cube-matmul` |
95+| [patterns/quant-matmul-scaled-mm.md](patterns/quant-matmul-scaled-mm.md) | `quantized-matmul` |
96+| [patterns/fp4-mxfp-cast-pack.md](patterns/fp4-mxfp-cast-pack.md) | `quantized-matmul` |
97+| [patterns/online-softmax-tail.md](patterns/online-softmax-tail.md) | `multi-phase-fusion` |
98+| [patterns/buffer-reuse-lifetime.md](patterns/buffer-reuse-lifetime.md) | `multi-phase-fusion`, `long-axis` |
99+| [patterns/lookahead-pipeline.md](patterns/lookahead-pipeline.md) | `multi-phase-fusion` |
100+| [patterns/multi-jit-fusion.md](patterns/multi-jit-fusion.md) | `multi-phase-fusion` — gated: the PyPTO-Pro flow mandates a single `@pl.jit` kernel, so the page is legal knowledge and an illegal Pro design. Listed under `target_gated` in [topology-map.json](topology-map.json) |
101+| [patterns/vec-per-token-dynamic-quant.md](patterns/vec-per-token-dynamic-quant.md) | — reached from the task table above, when the row statistic is itself an output |
102+| [patterns/vec-paired-lane-rotation.md](patterns/vec-paired-lane-rotation.md) | — reached from [patterns/pattern-index.md](patterns/pattern-index.md) |
103+ 
104+`row-reduction` lists six references (four patterns and two constraints) and
105+`multi-phase-fusion` five, against a three-reference selection bound. That is
106+not an overflow: the bound is on what a class **selects**, not on how many pages
107+a node lists, and no check enforces a per-node cap. What it does mean is that a
108+class routed to either node must choose, and the modifier column above is how it
109+chooses. Raise it with the KB owner if a node should be split.
110+ 
111+At `row-reduction` three of the four patterns are conditional on a property of
112+the shape, so a class with none of those properties selects
113+[patterns/vec-row-reduce-broadcast.md](patterns/vec-row-reduce-broadcast.md)
114+alone. The condition on
115+[patterns/vec-narrow-row-packing.md](patterns/vec-narrow-row-packing.md)
116+is arithmetic — compute `D * itemsize` and compare it with 128 — so it is
117+decidable from `KB_SELECTION.json`'s shape properties before any design exists,
118+which is when the selection is written.
119+ 
120+**At most three primary references per class.** Reading more is how a stage
121+accumulates document access without any of it reaching the code. When no
122+pattern fits, record that outcome explicitly as `no_matching_pattern` rather
123+than selecting a loosely related page.
124+ 
125+## The selection and usage contract
126+ 
127+Knowledge selection is an artifact, not an intention. Each generated family
128+carries two files, and both are machine-validated by CANN-Bench's
129+`auto_pipeline.kb_contract` against contract version 1. What it checks, where the
130+files live, and what changing the contract requires are in [`CONTRACT.md`](CONTRACT.md).
131+ 
132+`KB_SELECTION.json`, written by the planner before any design exists: the
133+topology, the dtype and shape properties it was derived from, the selected
134+references (at most three, each with a reason and a content hash), the failure
135+signatures being guarded against, and `no_matching_pattern` when nothing fits.
136+ 
137+`KB_USAGE.json`, written by the coder and checked by the verifier, maps
138+ 
139+ selected reference -> derived invariant -> implementation location -> verification result
140+ 
141+A selected reference with no recorded invariant fails the class: a reference
142+that changed nothing should not have been selected. An invariant whose
143+implementation location does not exist, or which names a symbol absent from
144+that file, fails the class. A deliberate deviation passes only with a written
145+justification.
146+ 
147+The verifier checks the **invariants in the implementation**, not the existence
148+of the documents. Document access is not evidence that knowledge was applied.
@@ -0,0 +1,616 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+"""Knowledge-base integrity checks.
4+ 
5+Run from anywhere::
6+ 
7+ python3 cannbot-skills/kb/check_kb_integrity.py
8+ 
9+Exits non-zero and prints every violation. Deliberately dependency-free (no
10+torch, no pytest) so it runs in CI and on a laptop.
11+ 
12+What it enforces, and why each rule exists:
13+ 
14+* **Reachability** -- every retained file must be reachable from ROUTER.md or a
15+ maintained index. An unreferenced file is one no stage will ever select, and
16+ is how raw experiment output accumulates in a knowledge base.
17+* **Link resolution** -- a broken link is a reference that silently does nothing.
18+* **Filename hygiene** -- no run ids, dates, scores, or status words. A
19+ knowledge base names *what a thing is*, not which experiment produced it.
20+* **Portable paths** -- no machine-specific absolute paths, so the KB works on
21+ any checkout.
22+* **Topology map** -- every path it routes to must exist, and it must stay
23+ within the three-reference bound it declares.
24+* **Sample provenance headers** -- a retained sample must not assert a
25+ validation result that a generated copy would inherit unearned.
26+"""
27+ 
28+from __future__ import annotations
29+ 
30+import json
31+import re
32+import sys
33+from pathlib import Path
34+ 
35+KB_ROOT = Path(__file__).resolve().parent
36+REPO_ROOT = KB_ROOT.parents[1]
37+ 
38+#: Entry points a reader can actually reach. Everything else must be linked
39+#: from one of these, directly or transitively.
40+ROOTS = ("ROUTER.md", "README.md")
41+ 
42+#: Indexes are roots for the directories they curate.
43+INDEXES = ("patterns/pattern-index.md", "examples/kernel-index.md")
44+ 
45+_MD_LINK = re.compile(r"\[[^\]]*\]\(([^)#]+?)(?:#[^)]*)?\)")
46+ 
47+#: A code span. Bounded to a single line on purpose: an unbalanced backtick would
48+#: otherwise blank the document from that point to the next backtick anywhere
49+#: later, silently un-checking every link in between.
50+_CODE_SPAN = re.compile(r"(`+)[^\n]*?\1")
51+ 
52+#: An opening or closing fence line: ``` or ~~~, optionally with an info string.
53+_FENCE = re.compile(r"^\s{0,3}(`{3,}|~{3,})")
54+ 
55+ 
56+def _without_code(text: str) -> str:
57+ """Blank out fenced blocks and code spans before looking for links.
58+ 
59+ A markdown link is prose. Code is not, and the two share punctuation: a pl
60+ kernel launch reads ``kern[None, num_cores](q, k, w, out)``, which is
61+ ``[...](...)`` to the naked eye of a link matcher. Nothing a page can do to
62+ itself fixes this -- the matcher's ``[^)#]+?`` spans newlines, so splitting
63+ the arguments across lines does not help, and backticking or fencing did not
64+ help either because nothing here used to look at fences. So the fix belongs
65+ to the matcher: strip code first, then match links in what is left.
66+ """
67+ out: list[str] = []
68+ fence: str | None = None
69+ for line in text.splitlines():
70+ match = _FENCE.match(line)
71+ if fence is None:
72+ if match:
73+ fence = match.group(1)
74+ out.append("")
75+ continue
76+ out.append(line)
77+ else:
78+ # A fence closes only on the same character and at least the same
79+ # length, so a ```` ```` ````-opened block is not closed by ``` inside it.
80+ if match and match.group(1)[0] == fence[0] and len(match.group(1)) >= len(fence):
81+ fence = None
82+ out.append("")
83+ return _CODE_SPAN.sub(" ", "\n".join(out))
84+ 
85+#: Transient labels that must never appear in a retained filename.
86+_BAD_NAME_TOKENS = (
87+ "run_2", "wip", "tmp", "temp", "draft", "final", "old", "new", "backup",
88+ "todo", "fixme", "status", "report_2", "result_2", "score", "v1", "v2",
89+ "copy", "20250", "20260",
90+)
91+ 
92+#: Absolute paths that point at somebody's machine rather than a repository.
93+#: ``/tmp`` and the other shared roots belong here too: a sample that writes to a
94+#: global directory is modelling behaviour the agent rules forbid, and twelve of them
95+#: did exactly that while this pattern only looked for home directories.
96+#: ``/usr`` and ``/opt`` are deliberately absent: ``#!/usr/bin/env python3`` is portable,
97+#: and flagging it would bury the real findings in shebangs.
98+_ABS_PATH = re.compile(
99+ r"(?<![\w.])/(?:home|data|root|Users|mnt|tmp|var/tmp|dev/shm|workspace)"
100+ r"(?:/[A-Za-z0-9_][A-Za-z0-9_.-]*)?"
@@ -0,0 +1,20 @@
1+# Constraint index
2+ 
3+Use these pages as focused supplements to the installed API documentation:
4+ 
5+| Constraint | Use for |
6+|---|---|
7+| [precision.md](precision.md) | dtype, accumulation, cast, and quantization contracts |
8+| [tiling.md](tiling.md) | tile shape, layout, and memory-space legality |
9+| [memory-layout.md](memory-layout.md) | address ownership, layout conversion, and overlap |
10+| [sync-stitch.md](sync-stitch.md) | tile-group mutexes and section synchronization |
11+| [tail-validshape.md](tail-validshape.md) | dynamic dimensions and tail windows |
12+| [vec.md](vec.md) | conditional tile-op / vector-function authoring |
13+| [vec-alignment-and-rotation.md](vec-alignment-and-rotation.md) | vf lane and reduction-row alignment, buffer rotation, bare-tile sync |
14+| [vec-mask-width.md](vec-mask-width.md) | converting a mask between b8/b16/b32 element widths |
15+| [arch-a5.md](arch-a5.md) | A5-only platform discovery and evidence gate |
16+ 
17+Do not load a platform-specific page until the target architecture is
18+confirmed. If a KB statement conflicts with the installed API documentation,
19+official sample, or a correctness run, use the target environment's evidence
20+and update the derived design.
@@ -0,0 +1,53 @@
1+# A5 platform constraint discovery
2+ 
3+## Applies to
4+ 
5+Only a confirmed A5 target (`NpuArch=3510` / `dav-c310`). Do not use this page
6+for an unknown target or for A2/A3.
7+ 
8+## Platform gate
9+ 
10+1. Detect the target with
11+ [`../../ops/pypto-pro-environment-check/scripts/get_npu_arch.py`](../../ops/pypto-pro-environment-check/scripts/get_npu_arch.py)
12+ or the build configuration.
13+2. Record device model, SKU, CANN version, PyPTO version, and the resolved
14+ `pypto_pro.__file__`.
15+3. Select the platform file matching that exact installed version and SKU.
16+4. Extract only the constants needed for the current design and cite the file
17+ and key in `EXPLORE_REPORT.md` / `DESIGN.md`.
18+ 
19+Fail closed: if the architecture or matching source cannot be confirmed, do
20+not substitute remembered A5 values.
21+ 
22+## Primary source paths
23+ 
24+Resolve under the version-recorded installed PyPTO/CANN tree:
25+ 
26+- `framework/src/platform/parser/simulation_platform/platform_config/950DT_957x.ini`
27+- the matching `950DT_958x.ini`, `950PR_957x.ini`, or `950PR_958x.ini`
28+- `framework/src/platform/parser/platforminfo.ini`
29+- `python/pypto_pro/runtime/compile_config.py`
30+- `python/pypto_pro/runtime/platform.py`
31+ 
32+Use these files to obtain core counts, memory budgets, datatype/fractal
33+settings, paths, and compile target for the detected SKU. Do not duplicate
34+their numbers in this KB: doing so detaches constraints from the installed
35+version.
36+ 
37+## Design checks
38+ 
39+- Derive each live tile's byte size from shape and dtype.
40+- Sum simultaneous allocations separately for Vec, Mat, Left, Right, and Acc.
41+- Compare those sums with the detected target's corresponding limits.
42+- Read dtype-dependent contraction geometry from the matching platform file;
43+ do not assume one K-fractal for every dtype.
44+- Read launch width from runtime platform information rather than hard-coding
45+ a SKU's core count.
46+- Re-run correctness after any dtype, layout, buffering, or tile-size change.
47+ 
48+## Performance boundary
49+ 
50+Platform configuration values are roofline inputs, not measured kernel
51+performance. Use the target profiler to determine the current bottleneck. See
52+the platform-gated
53+[A5 roofline workflow](../../ops/pypto-pro-op-perf-tune/references/a5-roofline-and-levers.md).
@@ -0,0 +1,40 @@
1+# Memory layout and lifetime
2+ 
3+## Rule
4+ 
5+Treat Vec, Mat, Left, Right, and Acc as separate address spaces. Within each
6+space, allocate non-overlapping byte ranges for tiles whose lifetimes overlap.
7+ 
8+## Lifetime classes
9+ 
10+- **Rotating:** multiple slots selected with `.next()` across iterations.
11+- **Resident:** one slot kept live across an inner loop and accessed through the
12+ same handle.
13+- **Scratch:** a temporary whose lifetime ends before an overlapping address is
14+ reused.
15+ 
16+`mutex_ids` identify synchronization slots; they do not prove that two byte
17+ranges are safe to alias.
18+ 
19+## Address review
20+ 
21+For each memory space, maintain a table with:
22+ 
23+```text
24+tile | layout | start | size per slot | slots | lifetime | end
25+```
26+ 
27+Reject the design if live ranges overlap, an address violates the documented
28+alignment, or layout conversion is inferred rather than documented.
29+ 
30+## Evidence
31+ 
32+- rotating Vec groups:
33+ [softmax_impl.py](../examples/samples/softmax/softmax_impl.py)
34+- resident A operand across output columns:
35+ [bf16_matmul_operand_reuse_impl.py](../examples/samples/bf16_matmul_operand_reuse/bf16_matmul_operand_reuse_impl.py)
36+- vector→cube layout handoff:
37+ [vec_cube_abs_sqrt_matmul_impl.py](../examples/samples/vec_cube_abs_sqrt_matmul/vec_cube_abs_sqrt_matmul_impl.py)
38+ 
39+Use the installed API documentation and matching official example to confirm
40+alignment and layout semantics for the target version.
@@ -0,0 +1,270 @@
1+# Precision and cast boundaries
2+ 
3+## Rule
4+ 
5+Treat dtype, accumulation type, rounding, saturation, scaling, and tolerance as
6+part of the operator contract. Do not change one for performance without
7+updating the golden and acceptance criteria.
8+ 
9+## Checklist
10+ 
11+1. Record input, intermediate, accumulator, and output dtypes.
12+2. Confirm each cast/quant/dequant API and rounding mode in the installed
13+ documentation.
14+3. Keep numerically sensitive reductions and transcendental operations in the
15+ contract's required accumulation precision; use FP32 unless a narrower path
16+ is explicitly documented and validated. Register-level reduction primitives
17+ are typically same-type, so they cannot widen on your behalf — see
18+ "Widening a narrow-dtype reduction" below.
19+4. For quantization, make scale, rounding, clamp range, and dequantization
20+ placement explicit in both kernel and golden.
21+5. Derive tolerances from the project standard for the actual output dtype and
22+ algorithm; never copy a tolerance from an unrelated sample.
23+6. Validate boundary values, tails, and representative random inputs.
24+7. In a chain of matmuls, keep every GM intermediate **fp32** unless the golden
25+ itself rounds there, and split any computed matmul operand into bf16 residual
26+ terms — see "Chained matmuls" below.
27+8. Bound the depth of any single L0C accumulation chain — see "Deep K chains".
28+ 
29+## Widening a narrow-dtype reduction
30+ 
31+A reduction over FP16/BF16 inputs can overflow even when every input element and
32+the final mathematical result are both representable, because the *intermediate*
33+values are not. Squaring is the common case: an operand near the top of the
34+format's range squares to roughly the square of that range, far past the
35+format's maximum. The narrow type reaches `inf` mid-chain and the reduction
36+returns `inf` from finite, in-range inputs.
37+ 
38+Confirm the following against the installed docs for the target SDK, but as of
39+the current one:
40+ 
41+- The register-level reduce primitives (`vf.reduce_*`) are **same-type**: each
42+ source dtype pairs with the identical destination dtype. There is no
43+ narrow-in / wide-accumulate reduce to lean on. The widening is yours to write.
44+- The register-level cast is
45+ `vf.astype(src, preg, *, dtype=..., layout=..., round_mode=..., saturate=...)`.
46+ The tile-level cast is `pl.cast(out, src, *, mode=...)`, where the target dtype
47+ comes from `out`'s dtype. **There is no `vf.cast`.**
48+- **Both conversion APIs are platform-gated.** Their docs carry a
49+ 「产品支持情况」 section, and support is not universal across Ascend
50+ generations. Confirm availability for the *detected* target before a design
51+ depends on either one — see [arch-a5.md](arch-a5.md) for target detection.
52+ Fail closed: if the widening mechanism is unsupported on the target, the
53+ design does not silently keep the narrow chain; it finds a supported
54+ conversion path or is escalated as unsupported.
55+ 
56+### Widen before the operation that overflows, not before the reduce
57+ 
58+Placing the cast immediately ahead of the reduction is not sufficient when a
59+multiply, square, or running accumulation feeds it: that operation has already
60+produced `inf` in the narrow type, and widening `inf` yields `inf`. The order
61+that holds is **widen → compute → reduce**, with the whole chain in the wide
62+type, narrowing again only at the store so the output dtype still matches the
63+contract:
64+ 
65+```python
66+x_wide = vf.astype(x_reg, preg, dtype=pl.DT_FP32)
67+squared = vf.mul(x_wide, x_wide, preg)
68+total = vf.reduce_sum(squared, preg)
69+```
70+ 
71+Note that a widening cast changes how many elements fit in a register: the wider
72+destination holds fewer, and `layout` selects which half of the source it
73+consumes. Covering one full narrow register therefore takes more than one call.
74+Read the API's layout and element-count tables rather than assuming a 1:1
75+mapping.
76+ 
77+### A scale factor is not a substitute
78+ 
79+Pre-scaling shifts the representable window; it cannot widen it. Compare the
80+ratio between the largest and smallest intermediate the operator must represent
81+against the input format's exponent span. When the requirement is larger, no
82+scale factor exists and widening is the only correct option.
83+ 
84+Decide this at design time, in the cast-boundary chain, from the case's declared
85+value range and reduction length — not after a precision failure. The cost is
86+one extra vector op per tile plus wide-type registers along the reduction chain;
87+pay it where the range analysis says it is needed and keep the narrow type
88+everywhere else.
89+ 
90+## Chained matmuls: fp32 intermediates and residual-split operands
91+ 
92+When the golden upcasts its inputs once and carries the whole chain in fp32,
93+rounding each GM intermediate back to the narrow dtype is not a small
94+approximation — it can fail the gate outright.
95+ 
96+The mechanism matters because it is invisible in a relative-error estimate. An
97+output that is a long *signed* sum is Gaussian about zero, so each narrow
98+rounding in the chain contributes a roughly constant **absolute** error, and the
99+elements whose true value happens to land near zero then carry enormous relative
100+error. Worse, that same absolute error pushes `|output|` past the cancel-region
101+threshold, so those elements do not even qualify for the cancel region's
102+CPU comparison — they land in the normal region, which must have zero
103+exceedances. Measured on MlaProlog: ~0.1 absolute error on `query`, ~77 elements
104+per case, every case failing.
105+ 
106+Two rules follow, and they are separate:
107+ 
108+- **GM intermediates carry fp32.** This alone took one RoPE output from failing
109+ to *zero* error, because its only problem was the narrow rounding of the
110+ projection feeding it.
111+- **A computed matmul operand is split into bf16 residual terms.** The cube
112+ takes narrow operands, so an fp32 intermediate cannot be fed to it directly;
113+ split it as `t1 + t2 + t3`, each the bf16 rounding of what the previous terms
114+ could not represent, and accumulate all of them into one fp32 L0C against one
115+ resident weight tile. Measured: two terms (~16 mantissa bits) passes at M=1
116+ and fails from M=128 up; **three terms (~24 bits) passes at every shape.**
117+ 
118+Split only what needs it. A weight that arrived as bf16 is already exact, so its
119+residual terms are identically zero — a "3-term" variant that splits the *right*
120+operand is a no-op that measures identical to 2-term. Likewise a projection
121+consuming the raw narrow input needs one term; only its **output store** widens.
122+ 
123+Prefer the residual split to the cube's native fp32 mode: three bf16 passes is
124+~126 TFLOPS effective on A5 against 94.6 for fp32, and it reuses the narrow tile
125+path instead of needing fp32 L0A/L0B at half the K depth. (fp32 matmul *is*
126+supported and exact — verified — so it remains available where accuracy
127+dominates and the operand cannot be split.)
128+ 
129+## Deep K chains: one L0C accumulator is an accuracy defect
130+ 
131+`matmul_acc` over an N-block K loop sums sequentially into one fp32 accumulator.
132+The partial sums random-walk to the final magnitude, so rounding accumulates as
133+`eps · |result| · sqrt(N/2)`, while CPU BLAS reduces the same contraction
134+pairwise. For a 7168-deep contraction (N = 56) that is a ~3x gap — and on an
135+operator whose graded outputs include cancelled near-zeros it decides pass/fail.
136+ 
137+**Fix:** send block `k` to accumulator `k % 4`, so each walks `N/4` blocks whose
138+partials reach half the magnitude; emit the four partials to GM and recombine
139+them **pairwise** in the consumer — `(p0+p1) + (p2+p3)` keeps both intermediates
140+at half scale so only the final addition rounds at full scale. Four `[64, 128]`
141+fp32 accumulators cost 128 KB of a 256 KB L0C.
142+ 
143+Measured on MlaProlog's first projection: the inherited error fell 3.51e-6 →
144+1.68e-6 (2.09x), bringing the chain to parity with the CPU reference
145+(2.76e-6 vs 2.74e-6) at **unchanged runtime** — the extra GM traffic was ~19 MB
146+against 122 MB of weights. 17/20 → 19/20.
147+ 
148+Unroll the K loop by the accumulator count rather than branching on `k % 4`, so
149+the Partial/Final phase conditions stay simple (`q == 0` and `q == n_quad - 1`
150+per accumulator). That requires `n_kb % 4 == 0`; guard it on the host and raise
151+rather than silently dropping blocks.
152+ 
153+## What the benchmark gate actually measures
154+ 
155+Designing against "MERE below threshold" misreads the gate. `utils/compare.py`
156+applies it in two stages, and the second one is where most surprises live.
157+ 
158+**Stage 1.** Overall `MERE < threshold` and `MARE < 10 * threshold` passes
159+outright.
160+ 
161+**Stage 2.** Otherwise every element is sorted into one of three regions, each
162+judged separately, and **all three must pass**:
163+ 
164+| region | membership | rule |
165+|---|---|---|
166+| normal | everything else | zero errors permitted **when the same-precision reference is clean**; otherwise at most 2x the reference's error count |
167+| small-value | `\|golden\| < 2^-11` fp16, `2^-8` bf16, `2^-14` fp32 | at most `2x max(reference_errors, 1)` |
168+| cancellation | `\|output\|` near zero while `\|golden\|` sits between the small-value and cancel boundaries | same 2x rule |
169+ 
170+So a run can report `MARE` an order of magnitude over threshold and still pass,
171+because the offenders all landed in the cancellation region and the rule there
172+is relative to the reference rather than absolute. And the converse: a *single*
173+normal-region element is fatal when the reference is clean.
174+ 
175+Consequences that change design decisions:
176+ 
177+- **Find out whether your reference is clean.** The "same-precision reference"
178+ is the task golden run at input precision. When a golden promotes to fp32
179+ internally regardless of input dtype, that reference is identical to the fp64
180+ one, the reference error count is zero, and the normal region tolerates
181+ nothing. Check before assuming slack exists.
182+- **Do not delete a compensated accumulator to save vector ops without measuring
183+ the cancellation class.** Mean error barely moves while the *count* crosses the
184+ pass boundary. Reordering does not help either — cancellation is a
185+ conditioning problem, not a summation-length one.
186+- **The cheap pre-board check** is to replay the kernel's exact arithmetic on CPU
187+ against a higher-precision golden and count threshold exceedances per region,
188+ next to the same counts for the reference. That ratio is what the gate compares.
189+ `tools/precision_oracle.py` does this, including the deterministic input
190+ generation.
191+ 
192+### Integer outputs are not covered by any of that
193+ 
194+Integer outputs take an absolute-difference path: **every** element must satisfy
195+`|out - golden| <= threshold`, with no proportional fallback. The default
196+threshold for integer dtypes is `0`; an operator's `proto.yaml` may relax it via
197+`precision_thresholds` (commonly `int8: 1`). Read the code, not the operator
198+description — descriptions have been observed to state a tolerated *fraction* of
199+mismatches where the implementation tolerates none.
200+ 
201+A ±1 int8 tolerance does absorb a round-half-to-even versus round-half-away
202+difference between torch and the hardware convert, but only if nothing else has
203+already consumed the margin.
204+ 
205+### Non-finite values are compared before any error arithmetic
206+ 
207+**NaN positions must match exactly** or the case fails outright, reporting
208+`MERE=0, MARE=0` alongside a position-mismatch message. Inf on one side only is
209+saturated to the dtype maximum and comparison continues; both-inf-same-sign
210+counts as a match and is excluded from the statistics.
211+ 
212+Two traps:
213+ 
214+- **A NaN guard that lets Inf through turns Inf into NaN.** The obvious `x == x`
215+ test rejects NaN but **passes for ±Inf**, so a sum that overflows to Inf leaves
216+ an Inf residual and `total - residual = Inf - Inf = NaN` where the reference is
217+ Inf. Scale by zero first — multiplying by `0.0` maps every finite value to zero
218+ and both Inf and NaN to NaN — then compare and select.
219+- **`float -> int` conversion of a non-finite is undefined in C++** and differs
220+ between hosts and between host and device. Measure it on the evaluation host
221+ before designing the path; a wrong guess misses by up to 128 LSB on an int8
222+ output where every element must land within ±1.
223+ 
224+Special-value cases are generated **deterministically**, not randomly: a
225+`[-inf, inf]` range yields ordinary random values with the first 5% set to `-inf`
226+and the last 5% to `+inf`, and `[nan, nan]` yields random values under a 50% NaN
227+mask. They are therefore reproducible offline — but `torch.randn` never reaches
228+these paths, so they need their own sweep. Note also that such a range applies to
229+*every* input it is declared for, so a non-finite can enter through a scale or
230+gamma vector rather than through the obvious data input.
231+ 
232+## Evidence
233+ 
234+- FP32 softmax and independent golden:
235+ [softmax_impl.py](../examples/samples/softmax/softmax_impl.py) and
236+ [softmax_golden.py](../examples/samples/softmax/softmax_golden.py)
237+- explicit scale/round/clamp quantized matmul:
238+ [matmul_quant_int8_impl.py](../examples/samples/matmul_quant_int8/matmul_quant_int8_impl.py)
239+- validated BF16 contraction:
240+ [bf16_matmul_operand_reuse_impl.py](../examples/samples/bf16_matmul_operand_reuse/bf16_matmul_operand_reuse_impl.py)
241+ 
242+Use `$PYPTO_DEVKIT_DIR/docs/pypto_pro/api/` as the primary source for supported
243+dtype pairs and API semantics in the current SDK.
244+ 
245+---
246+ 
247+## BF16 narrowing at register level is bit-exact with the tile cast
248+ 
249+The note above says the register-level cast is `vf.astype(...)` and the tile-level
250+one is `pl.cast(out, src, mode=...)`, and warns that both are platform-gated. For
251+the **FP32 → BF16** direction on A5 / DAV_3510 the gate has been measured, and the
252+answer is favourable enough to change how a BF16 output should be published:
253+ 
254+* the two produce **identical bytes**, verified on inputs that are exact BF16 ties
255+ (low 16 mantissa bits `== 0x8000`) as well as random values;
256+* the `round_mode` kwarg does not reach the instruction — the hardware always
257+ rounds nearest-even, which is what `CAST_RINT` asks for anyway;
258+* `CAST_RINT` and `CAST_HYBRID` do not compile for this pair at all.
259+ 
260+So a chain that computes in FP32 and ends in a single tile-level narrowing cast can
261+instead publish BF16 straight from the register file, deleting a whole UB→UB pass
262+(and its `auto_mutex` barrier) **without changing a single output byte**. Measured
263+on `rms_norm`: publish traffic per element falls from 10 B (4 B FP32 store + 4 B
264+cast read + 2 B cast write) to 2 B.
265+ 
266+The reverse direction is **not** symmetric — BF16 → FP32 at register level reaches
267+only the even elements — so keep the widening at tile level. The lane mechanics of
268+both directions, and why the "BF16 is the top 16 bits of FP32" bit-trick does not
269+port to this DSL, are recorded in
270+[vec.md](vec.md#bf16-at-register-level-what-vfastype-can-and-cannot-do).
@@ -0,0 +1,68 @@
1+# Synchronization and section handoff
2+ 
3+## Rule
4+ 
5+Use `make_tile_group(..., auto_mutex=True)` for rotation and intra-kernel
6+buffer ownership that the target API documents as auto-managed. Do not add
7+manual synchronization to the same managed dependency without evidence.
8+ 
9+Cross-section or AIC/AIV handoff is not implied by `auto_mutex`. When the data
10+flow crosses engines or sub-blocks, copy the producer/consumer event sequence
11+from a matching official example for the installed SDK and validate it on the
12+target.
13+ 
14+## On A5: a fused cube+vector launch with per-tile handoff does not run
15+ 
16+Measured, repeatedly. A single `@pl.jit` holding a `section_cube()` and a
17+`section_vector()` with cross-core handoff on every tile compiles and then dies
18+with `aicore timeout`. One attention kernel was taken through **thirteen
19+hypotheses and nine mutation-ladder rungs** on that construct and never ran
20+once, even though every ingredient passed in isolation — the cube half
21+(including the transposed NT load and a dual-accumulator contraction) and the
22+register-level softmax were each proven separately. The reference Ascend-C
23+implementation of a sibling operator hit the identical wall on the identical
24+construct.
25+ 
26+**Decompose into single-sided launches with GM intermediates.** Each kernel is
27+cube-only or vector-only and contains *no* cross-core synchronisation at all;
28+ordering comes from the launch boundary. Two operators were rescued this way:
29+ 
30+| operator | fused | single-sided |
31+|---|---|---|
32+| attention prolog | 0/20 | 11 launches → 19/20 |
33+| attention | never ran | 3 launches → 20/20, correct on the second device run |
34+ 
35+The cost is the intermediates round-tripping through GM — up to 268 MB of score
36+matrix on the largest attention case — and that is real. It is also affordable
37+far more often than it looks, because the benchmark pays `0.3` per accurate case
38+*before* any performance term: a slow correct kernel scores, a fast one that
39+never runs does not. Try the fused form only if the split one is already correct
40+and profiling says the GM round trip dominates.
41+ 
42+The wrapper constraint that comes with it: the benchmark times the wrapper, so
43+there must be **no launch inside a host loop** — a fixed number of launches,
44+each looping internally. See
45+[wrapper-boundary.md](wrapper-boundary.md).
46+ 
47+## Review sequence
48+ 
49+1. Draw each producer→consumer dependency and the memory space carrying it.
50+2. Mark which dependencies are covered by tile-group mutexes.
51+3. For every remaining dependency, cite the official API/example that defines
52+ the required pipe and event.
53+4. Allocate event IDs without overlap across simultaneously active pipelines.
54+5. Match physical slot count to the maximum number of in-flight work items.
55+6. Validate correctness before adding preload depth or extra buffering.
56+ 
57+## Evidence
58+ 
59+- auto-managed rotating Vec groups:
60+ [softmax_impl.py](../examples/samples/softmax/softmax_impl.py)
61+- retained cube→vector handoff with embedded correctness test:
62+ [fused_matmul_add_impl.py](../examples/samples/fused_matmul_add/fused_matmul_add_impl.py)
63+- retained vector→cube handoff with embedded correctness test:
64+ [vec_cube_abs_sqrt_matmul_impl.py](../examples/samples/vec_cube_abs_sqrt_matmul/vec_cube_abs_sqrt_matmul_impl.py)
65+ 
66+These samples demonstrate their recorded environment only. The installed
67+`$PYPTO_DEVKIT_DIR/docs/pypto_pro/api/` documentation and official samples
68+remain authoritative for pipe/event signatures.
@@ -0,0 +1,34 @@
1+# Dynamic tails and valid shapes
2+ 
3+## Rule
4+ 
5+Keep a compile-time legal physical tile and set a runtime valid window for each
6+partial work item. Apply the valid window to every input, output, reduction
7+result, and workspace whose operation observes the tail.
8+ 
9+## Checklist
10+ 
11+1. Compute work-item counts with ceiling division.
12+2. Compute each remaining extent from the actual tensor dimension.
13+3. Clamp the extent to the physical tile size.
14+4. Set the valid shape before load, compute, reduction, and store as required by
15+ the installed API.
16+5. Neutralize invalid lanes for reductions when valid shape alone does not
17+ define the reduction identity.
18+6. Test dimensions smaller than one tile, exactly one tile, multiple exact
19+ tiles, and multiple tiles with a remainder.
20+ 
21+For streaming softmax, the final score chunk must exclude invalid lanes from
22+both maximum and sum. See
23+[online-softmax-tail.md](../patterns/online-softmax-tail.md), which is
24+conceptual only.
25+ 
26+## Evidence
27+ 
28+- dynamic row/column handling:
29+ [softmax_impl.py](../examples/samples/softmax/softmax_impl.py)
30+- independent mathematical reference:
31+ [softmax_golden.py](../examples/samples/softmax/softmax_golden.py)
32+ 
33+Confirm the exact `set_validshape`, load/store, padding, and reduction behavior
34+in the installed API documentation and official tail examples.
@@ -0,0 +1,119 @@
1+# Tile legality
2+ 
3+## Rule
4+ 
5+Derive every tile from the selected API's documented shape, dtype, memory-space,
6+layout, alignment, and valid-shape contract. Do not carry limits from another
7+platform or SDK version.
8+ 
9+## Checks
10+ 
11+1. Detect the target platform and record the installed PyPTO/CANN version.
12+2. For each live tile, record shape, dtype bytes, memory space, layout, address,
13+ slot count, and lifetime.
14+3. Sum simultaneous allocations separately for each memory space.
15+4. Compare each sum with the matching platform source/configuration.
16+5. Confirm offset units independently for `pl.load`, `pl.load_tile`, stores, and
17+ vector-function APIs.
18+6. For dynamic tails, keep a legal physical tile and set the runtime valid
19+ window on every operation that reads or writes it.
20+7. Re-run correctness for aligned, single-tail, multi-tail, and multi-tile
21+ cases.
22+ 
23+## Cube-specific check
24+ 
25+Obtain dtype-dependent contraction geometry and Left/Right/Acc layout
26+requirements from the installed API and official matmul examples. Do not assume
27+one K alignment or one fractal shape for all dtypes.
28+ 
29+## Evidence
30+ 
31+- [single-block matmul](../examples/samples/matmul_float_mmad/matmul_float_mmad_impl.py)
32+- [BF16 operand reuse](../examples/samples/bf16_matmul_operand_reuse/bf16_matmul_operand_reuse_impl.py)
33+- [dynamic row softmax](../examples/samples/softmax/softmax_impl.py)
34+- platform discovery: [arch-a5.md](arch-a5.md) for confirmed A5 only
35+ 
36+The installed `$PYPTO_DEVKIT_DIR/docs/pypto_pro/api/` pages and official
37+examples are the primary source for the current version.
38+ 
39+---
40+ 
41+## Launch geometry on a5 / DAV_3510 — measured, run H (rms_norm, 2026-08-12)
42+ 
43+Instrument: `cold_probe.py`-derived paired sweep (`probe/sweep.py`), **cold** L2 (192 MB flush
44+inside the measured window), Level1 NPU profiler, all arms of a shape in ONE process so the arms
45+share a compiled binary and differ only in launch geometry. Card 0 of a5-238 (shared box).
46+🔴 Estimator note: on a shared box, contention is **one-sided** (it can only add time), so `min`
47+over reps is the unbiased estimator of uncontended kernel time — but `min` is *not* robust to
48+spuriously-fast profiler samples. Report `min`, 2nd-smallest and median together; where they
49+disagree, the robust pair wins. This changed two verdicts in run H (a "−11.0 %" became +0.8 %,
50+a "−66.8 %" became −36 %).
51+ 
52+### Shrinking blockDim for small inputs — DOES NOT APPLY to a `min(coreNum, n_tiles)` grid
53+ 
54+A widely-quoted rule (`blockDim = elems < SMALL_GRID_ELEMS ? min(coreNum,8) : coreNum`, with
55+15000/30000 per dtype) is a repair for kernels that launch `coreNum` blocks **unconditionally**.
56+A planner that already emits `blocks = max(1, min(coreNum, n_tiles))` **has the fix in a stronger
57+form**, and applying the threshold on top is a no-op below `n_tiles = 8` and a large regression
58+above it. Measured on `[11,13,17,67]` fp16 (162 877 elements, 304 tiles): grid 56 → 8 cost
59+**4.7364 → 19.5766 µs = +4.13×**, because `ceil(304/56)=6` waves become `ceil(304/8)=38`.
60+Break-even, derived from that measurement rather than assumed: capping an `N`-tile launch to 8
61+costs `(ceil(N/8)−1)·T_tile` and saves `(N−8)·d`; both scale as `N/8`, so the break-even sits at
62+`T_tile ≈ 0.32 µs` **almost independently of N**. Check that number before porting the rule.
63+ 
64+### Wave alignment is NOT the objective; tile size is
65+ 
66+Tiles are handed to blocks strided (`for t in pl.range(ci, nt, nc)`), so wall-clock is
67+`ceil(n_tiles/blocks) · T_tile`. It is tempting to minimise wave count. Measured, that is wrong:
68+`[31,129,2049]` fp32's best rung has **7 → 18 waves** and is still 9 % faster, and
69+`[3,7,11,4096]` fp32's one-wave rungs are 17–22 % **slower** than a three-wave rung. Twice more,
70+a launch that leaves cores idle beat one that filled them: 38-of-56 blocks beat 56 by 30 %, and
71+28-of-56 beat 56 by 41 %. **Filling every core is not the objective.**
72+ 
73+### There is no closed-form optimal `Rows` — but `Rows` derived from `S` alone is a real defect
74+ 
75+Swept every legal `Rows` rung on all 18 Mode-0 public shapes. A rule "pick the rung whose
76+`Rows·MaxN` is nearest T" was evaluated offline against the measured table for
77+T ∈ {7k…12k}: **every T regresses at least one case by ≥ 6.5 %**, up to +32 %. Same rung
78+(`MaxN=1024`), same S band, opposite optima by dtype: fp32 wants `Rows=5`, fp16 wants `Rows=16`
79+and is +32 % worse at 5. **Do not ship a global `Rows` rule.**
80+ 
81+What *is* real: a `_pick_rows` that computes `bal = S // (coreNum · MIN_TILES_PER_CORE)` is a
82+function of **S alone and ignores MaxN**, so at the narrowest rung it starves the tile. At
83+`MaxN = 128` it picked `Rows = 8` (a 1 KB tile) where the UB ceiling was 64. Growing `Rows` to
84+the largest rung that still leaves `≥ coreNum/2` tiles measured **−12 % to −42 %, mean −27 %
85+(fp16) / −21 % (bf16), zero regressions**, over `S` from 56 to 2431 — a 43× range, both dtypes.
86+🔴 The same rule applied to **other** rungs regresses `MaxN=384` by **+40.8 %** and
87+`MaxN=4096` by **+22.1 %**. Gate it to the rung it was measured on.
88+ 
89+### Regrouping rows into tiles is bit-neutral
90+ 
91+Changing `Rows` changes only how rows are grouped; each row's reduction is independent of the
92+grouping. Verified byte-for-byte: **30 configurations, 5 shapes, 96 386 842 bytes compared,
93+0 differing bytes**. A `Rows` change that alters even one output word means something else moved.
94+ 
95+### The narrow-rung `Rows` floor — where growing helps and where it overshoots (run H, extended)
96+ 
97+Same instrument as above. The `bal = S // (coreNum * MIN_TILES_PER_CORE)` defect (Rows chosen from
98+S alone, MaxN ignored) starves the tile at EVERY narrow rung, not just the narrowest. Measured at
99+`MaxN` 192 and 256, both dtype classes, `S in {56,127,254,896}`: the planner's pick is beaten by
100+**-4.4 % to -48.8 %**, and `Rows = 8` is the best arm in 9 of those 12 points.
101+ 
102+🔴 But the FIX does not generalise the way the defect does. Growing `Rows` to the largest rung that
103+still leaves >= coreNum/2 tiles is right at `MaxN = 128` (measured best-or-within-5 % over S from 56
104+to 14336) and **wrong at `MaxN >= 192` once S is large**:
105+ 
106+| MaxN | dt | S | grow-to-cap vs planner |
107+|---|---|---|---|
108+| 192 | fp32 | 7168 | **+14.6 %** |
109+| 384 | fp16 | 4037 | **+17.6 %** |
110+| 384 | fp32 | 4037 | **+38.5 %** |
111+ 
112+That last row is public case `[11,367,373]`, and +38.5 % here reproduces a +40.8 % measured from an
113+independent sweep — the boundary is real.
114+ 
115+**The portable lesson: at rungs above the narrowest, use a FLOOR (`Rows >= 8`), not a target.**
116+A floor is provably inert for `S >= 8 * MIN_TILES_PER_CORE * coreNum` (= 1792 here), so it cannot
117+fire in the regime where growth overshoots, while still capturing the whole starved corner. Measured
118++0.0 % at all 12 large-S points and -4.4 %…-48.8 % at small S. Growth guards must be gated to the
119+single rung they were measured on.
@@ -0,0 +1,267 @@
1+# Vector tile alignment, buffer rotation, and sync — measured rules
2+ 
3+Four constraints that are cheap to satisfy and expensive to discover. Each was found by a
4+run that looked like something else: a shape-specific kernel bug, a bandwidth ceiling, an
5+arithmetic error, a device fault. All were measured on an Ascend 950-family A5 target with
6+the pypto-pro DSL; each entry names the diagnostic that identifies it.
7+ 
8+Transferred from an earlier pypto-pro working set (`.agents/kb/pitfall-records.md`,
9+2026-07-21 … 07-23) rather than re-derived. Provenance is kept because none of these are
10+in the installed API documentation, and a reader who doubts one should be able to find the
11+original run.
12+ 
13+---
14+ 
15+## `vf` tile width must be a multiple of 64 lanes, not 8
16+ 
17+**Symptom.** A `@pl.vector_function` kernel using `vf.load_align` / `vf.store_align` over
18+`n_regs = ceil(D/64)` registers faults with **`507035`** (device error type 3) at sync — for
19+any `D` whose 8-aligned width is not also a 64-multiple. `D = 2049` rounds to 2056 and
20+faults; `D = 768 / 1024 / 2048` are already 64-multiples and pass, which masks it.
21+ 
22+**Cause.** `load_align` / `store_align` move a **full 64-lane register**. The last register
23+starts at `(n_regs-1)*64` and runs off the end of a tile whose width is not a 64-multiple.
24+ 
25+**Rule.** Size the tile to `align64(D)`. Then count UB slots honestly: double-buffered in and
26+out is **four** slots, so at 256 KB of UB a single vf tile needs
27+`4 * TR * align64(D) * 4 ≤ 262144`, i.e. `align64(D) ≤ 2048` at `TR = 8`.
28+ 
29+## Reduction tiles: rows must be a multiple of 8
30+ 
31+**Symptom.** softmax at `N = 2048` with `TR = 4` fails to compile — bisheng
32+`static_assert "Rows must be 32 bytes align"` (`pto_tile.hpp:1523`).
33+ 
34+**Cause.** The `[TR, 1]` `DN` reduction tile at `TR = 4` is 16 bytes, not 32-byte aligned.
35+Eight fp32 rows is exactly 32 bytes.
36+ 
37+**Rule — the constraint binds the *declared* extent, not the working one.** Declare the
38+reduction tile `[roundup(TR, 8), 1]` and narrow it with `pl.set_validshape`. That satisfies the
39+assertion while leaving the effective `TR` free, including 1.
40+ 
41+Two operators reached this independently and it is the remedy both landed on:
42+`rms_norm` verified identical fp32 rounding at effective `TR` = 1, 2, 3, 4, 8, 16; `softmax`
43+declared `[8, 1]` and narrowed, which took every public last-axis case from a two-pass kernel
44+to single-pass. Original observation held at `TR = 16` (N=256) and `TR = 8` (N=1024).
45+ 
46+> **Corrected.** This page first said to "reduce the buffer count rather than dropping TR
47+> below 8". That advice is wrong and was propagated before it was tested: at a long
48+> normalisation axis **no buffer count rescues the tile** — 8 rows of a D=8192 fp32 row is
49+> 256 KB against 248 KB of UB, so the tile is oversized before buffering is considered.
50+> Over-declaring is the escape; reducing buffers is not.
51+ 
52+> **The assert's wording is misleading, and here is the rule in the compiler's own words.**
53+> `softmax` reported that `pto_tile.hpp:1523`'s *"Rows must be 32 bytes align"* actually
54+> constrains the **Cols** extent. `scatter` then hit the row-major form and the compiler printed
55+> the predicate itself:
56+>
57+> ```
58+> Tile<Vec, __bf16, 2048, 8, RowMajor, ...>
59+> pto_tile.hpp:1444: RowMajor + NoneBox => Cols * sizeof(T) % 32 == 0
60+> ```
61+>
62+> So the reliable statement is **`Cols * sizeof(T) % 32 == 0`** — the *contiguous* extent in
63+> bytes, whichever axis that is for the layout. For a `[TR, 1]` `DN` tile it is `TR`; for a
64+> row-major tile it is the column count. Two operators reached this from opposite layouts.
65+>
66+> It is a hard `static_assert` and it binds **every** tile of that shape, so in a mixed-dtype
67+> kernel the **narrowest** staging tile sets the floor: `scatter` charged its 2-byte staging tile
68+> against the width budget, which shrank `TB` and took working bf16 rungs from 16 columns to 8,
69+> regressing 14/20 to 8/20 before anything improved. Budget the narrow tile first.
70+ 
71+## `.current()` does not advance the rotation — `.next()` does
72+ 
73+**Symptom.** Adding a buffer changes performance by less than 2%, and multi-buffering looks
74+worthless.
75+ 
76+**Cause.** `pl.make_tile_group(..., mutex_ids=[a, b])` declares N buffers, but rotation only
77+happens through **`.next()`**. `.current()` returns the same buffer every time, so a kernel
78+declaring 2–4 buffers and calling `.current()` in its loop is **single-buffered** — paying the
79+capacity and getting none of the overlap.
80+ 
81+**Rule.** `.next()` for every *streaming* operand; `.current()` **only** to re-read an operand
82+that is deliberately resident across an inner loop after `.next()` loaded it outside.
83+ 
84+**Why it is worth checking first.** Inert rotation produced two confident, wrong conclusions
85+in one session — "MTE2 is bandwidth-bound, pipelining cannot help", and "K=128 double-buffered
86+is worse than K=256 single" (75.8 vs 108.1 MMAC/µs). With real rotation K=128 won decisively
87+at 179.9 MMAC/µs. **Diagnostic: if adding a buffer moves performance under 2%, grep the loop
88+body for `.current()` before concluding anything about the pipe.**
89+ 
90+Related correctness trap: an operand written once per outer iteration and read across the
91+whole inner loop needs a *second* buffer once the outer loop pipelines, or the next row's move
92+races the current row's reads.
93+ 
94+## `auto_mutex` does not sync a bare `make_tile` that is *computed*
95+ 
96+**Symptom.** A layernorm computes `maxdiff ≈ 5–7` — wrong, with no error raised — while its
97+normalization alone is exact.
98+ 
99+**Cause.** `auto_mutex` tracks cross-op read-after-write hazards **only for
100+`make_tile_group`**. A bare `pl.make_tile` written by one op and read by a later one is not
101+synced, and the reader sees stale data. A *loaded* bare tile happened to work; a *computed*
102+one did not, which is what makes this look like an arithmetic bug rather than a sync bug.
103+ 
104+**Rule.** Use `make_tile_group` for any tile in a cross-op dependency, even single-buffered —
105+`addrs=[A], mutex_ids=[k]`, call `.next()` once. Reserve bare `make_tile` for a transient
106+reduction scratch or its row-major alias.
107+ 
108+## `vf.update_mask` per register costs 2.4x–6.5x — hoist it
109+ 
110+**Symptom.** A `vf` kernel whose body is a handful of arithmetic ops runs several times
111+slower than its byte count implies, and profiles as vector-issue-bound rather than
112+bandwidth-bound.
113+ 
114+**Cause.** The common register-loop idiom recomputes the lane mask every iteration:
115+ 
116+```python
117+for r in pl.range(0, n_regs):
118+ valid = pl.min(LANES, n - r * LANES)
119+ m = vf.update_mask(valid, dtype=pl.DT_FP32) # scalar min + mask update, per register
120+ ...
121+```
122+ 
123+Only the *last* register of a tile ever needs a partial mask, so `n_regs - 1` of these are
124+pure overhead — and on a short body they dominate.
125+ 
126+**Rule.** Build one `vf.create_mask(pattern=pl.MaskPattern.ALL, ...)` outside the loop and
127+use it for every register. **No separate tail path is needed**: lanes past the valid length
128+compute garbage, and `pl.set_validshape` bounds the DMA so `pl.store` never transfers them.
129+ 
130+This is safe **only** when the tile width is a multiple of 64 lanes — see the first rule on
131+this page. `load_align` moves a whole register, so with a non-64-multiple width the extra
132+lanes run off the tile and fault at `507035` instead of computing harmless garbage.
133+ 
134+**Measured**, swi_glu on Ascend950PR_9579, same body, two separately `stamped()` names in
135+one module so neither could be served the other's binary:
136+ 
137+| case | shape, dtype | per-register mask | hoisted | ratio |
138+|---|---|---|---|---|
139+| 3 | 4096x8192 bf16 | 91.06 us | 14.01 us | **6.5x** |
140+| 18 | 2x1023x4096 fp32 | 19.87 us | 3.85 us | 5.2x |
141+| 15 | 512x4096 fp32 | 6.58 us | 1.50 us | 4.4x |
142+| 11 | 3x7x13x1018 fp32 | 2.52 us | 0.93 us | 2.7x |
143+| 8 | 1538x1537 fp32, dim 0 | 8.36 us | 3.50 us | 2.4x |
144+| 5 | 2039x65520 fp32 | 655.86 us | 649.88 us | 1.01x |
145+ 
146+The same lever on `rms_norm`, a two-pass reduce-and-broadcast body, on a second Ascend950PR
147+host — interleaved A/B/A, run-to-run spread 0.02–0.11 %:
148+ 
149+| case | shape, dtype | per-register mask | hoisted | ratio |
150+|---|---|---|---|---|
151+| 4 | 16x256x4096 f16 | 158.83 us | 30.77 us | **5.16x** |
152+| 18 | 2x511x8192 bf16 | 80.83 us | 17.02 us | 4.75x |
153+| 8 | 16x511x2049 fp32 | 162.91 us | 96.63 us | 1.68x |
154+| 16 | 11x13x17x67 f16 | 5.34 us | 3.50 us | 1.53x |
155+ 
156+Both tables are the same curve. The fp32 row lands at 1.68x for the reason case 5 lands at
157+1.01x — it is the memory-bound shape in its suite, and the vector-side win has nowhere to go.
158+On the two cache-resident cases the dynamic mask accounted for **81 %** and **79 %** of total
159+kernel time.
160+ 
161+**The gain scales with how far the kernel is from the DRAM roof, which is why it is easy to
162+dismiss.** Case 5 moves 801 MB and is bandwidth-bound at 1.23 TB/s, so the mask costs it 1%;
163+every case that fits cache pays the full 2.4–6.5x. A kernel tuned only on its largest case
164+will conclude the mask is free. cummin measured this lever at 28% on a scan body of ~20 ops;
165+on a 4-op elementwise body the same fix is worth an order of magnitude more, because the
166+overhead is fixed per register and the body it is amortised over is not.
167+ 
168+An explicitly masked tail register (hoisted mask for the full registers, one
169+`update_mask` for the remainder) measured within noise of the no-tail form — 3.65 vs 3.85 us
170+on case 18, 1.54 vs 1.50 on case 15 — so the tail path buys nothing and costs a branch.
171+ 
172+**Below one register's width the lever stops paying, and that boundary has been hit twice.**
173+At 8 or 16 columns the hoist measured +5 % with six cases 3–4 % *slower*; applying the identical
174+hoist to a D=2 packed path measured **-1.0 %** and was rolled back as inside noise. The
175+full-register loop does not execute there, so the hoist buys only bookkeeping.
176+ 
177+---
178+ 
179+## The one that is already fixed here, kept for its diagnostic
180+ 
181+Factory-produced kernels collide in pypto's build cache, which is keyed on `co_name`: the
182+first shape is bit-correct and every later one returns garbage (`maxdiff ~3`, not a crash),
183+and reversing the call order flips which shape "works". `k.__name__ = ...` does not help —
184+`co_name` is fixed at `def` — and `exec` breaks `inspect.getsource`. Code-generate each kernel
185+to a real file under a unique `def` name.
186+ 
187+This repo's harness handles it (`tools/cann_bench_a5/kernel_naming.py`, and
188+`FRAMEWORK_FINDINGS.md` #17 for the quieter converse, where an edited body under an unchanged
189+name is served a *stale* binary and the run comes back byte-identical). The diagnostic is worth
190+keeping: **an unchanged module-level reference kernel passing at the same shape where a
191+factory kernel fails is what exposes it.**
192+ 
193+One myth was busted in the same investigation and should not be reintroduced: `inf`/`nan` do
194+**not** hang fixed-trip `vf` reductions. That symptom was the `co_name` collision's
195+out-of-bounds access, misattributed.
196+ 
197+---
198+ 
199+## `D` not being a multiple of 64 costs nothing — register COUNT is what costs
200+ 
201+**Claim under test.** On `rms_norm`/A5, every public fp16 case with `D` a multiple of 64 beat
202+the CANN reference (ratio 0.91–0.92) and every fp16 case with `D` not a multiple of 64 lost to
203+it (1.08–1.48). A 7/7 split, and the near-controlled pair `[32,128,768]` vs `[33,127,769]` —
204+one extra element of `D`, row count controlled to 2.3 % — showed **+21 %**. The natural reading
205+is a ragged-column-tail or 32-byte-burst-alignment defect.
206+ 
207+**It is not.** Measured on the pinned `kernel_eval` harness (`--perf-metric-strategy
208+kernel_details`), Ascend950PR card 4, fp16, `S = 4096` held fixed while `D` walks. Same-shape
209+repeats inside the run drifted **0.00 %, 0.00 %, −1.88 %**, so the instrument resolves ~2 %.
210+ 
211+The decisive triple shares the `MaxN = 1024` rung, 16 registers per row and one UB footprint —
212+only alignment differs:
213+ 
214+| D | 32B-aligned | `D mod 64` | `D == MaxN` | µs |
215+|---:|:--:|---:|:--:|---:|
216+| 1008 | ✓ | **48** | ✗ | 10.50 |
217+| 1023 | ✗ | 63 | ✗ | 10.47 |
218+| 1024 | ✓ | 0 | ✓ | 10.44 |
219+ 
220+**0.6 % apart.** `D = 1023` — the width of the public case that loses 11 % — costs what
221+`D = 1024` costs. The same holds one rung down: `D = 80` (`mod 64 = 16`, 32B-aligned) costs
222+3.07 µs, exactly what `D = 128` (`mod 64 = 0`) costs, while `65/67/127` cost 3.22/3.19/3.14 —
223+a residual of ≤ 3.7 % that **shrinks with `D` and is gone by `D ≈ 1000`**, the opposite of the
224+direction the deficit needs.
225+ 
226+**So the modulus question is ill-posed: there is no modulus.** 64 is dead, and 128 and 256 die
227+with it. What predicts cost is `ceil(D/64)` — the register count — a *ceiling*, not a residue
228+class. Every `D` in `(64k, 64k+64]` costs the same, which is exactly why aligned and misaligned
229+`D` are indistinguishable once register count is controlled. Fitting the three points that
230+share `MaxN = 1024` and `Rows = 16` (13, 15, 16 registers → 9.04, 10.13, 10.47 µs) gives
231+**2.75 µs fixed + 0.486 µs per register**, reproducing all three to ±1 %.
232+ 
233+**Why the public split looked so convincing — the confound.** In that suite the aligned fp16
234+cases sit at `D = 768, 4096, 4096` and the misaligned ones at `D = 67, 769, 1021, 1023`. There
235+is **no aligned fp16 case anywhere in the `D ∈ [769, 2047]` band**, so "aligned vs misaligned"
236+is perfectly confounded with "`D` at 768/4096 vs `D` near 1024". Probing `D = 960, 1008, 1024`
237+— aligned and *in band* — breaks the confound: they are just as slow as 1023. Measured against
238+the fused reference (`torch_npu.npu_rms_norm`) on one clock, our ratio is 1.19 at `D = 768` and
239+1.40–1.42 at `D = 960/1008/1023/1024` alike. The ratio degrades with `D`-position on the rung
240+ladder, not with alignment.
241+ 
242+**Two hypotheses this also kills**, since the same points control them:
243+ 
244+* *Row tiling / ragged `S`.* With `D = 768` fixed, the ragged row counts of the slow cases cost
245+ **less** per row than the round one: 1.8611 (S=4191) and 1.8645 (S=4221) against 1.8945
246+ µs/1000 rows (S=4096). The remaining variation with `S` is `_pick_rows` landing on Rows 21 or
247+ 8 instead of 16 — a documented smooth function of `S`, not of its factorisation.
248+* *Burst contiguity collapse* (`D == MaxN` ⟹ `dst_gap == 0` ⟹ the whole `[Rows, D]` block moves
249+ as one burst instead of `Rows` short ones). `D = 1024` has it, `D = 1008` and `1023` do not,
250+ and all three cost the same. Worth 0 here.
251+ 
252+**What the `768 → 769` +21 % actually is.** It reproduces (+16.9 % at controlled `S = 4096`) and
253+then decomposes entirely into two already-known quantisations: 12 → 13 registers (+8.3 % of
254+vector work) and a `MaxN` rung jump 768 → 1024 (a 33 % wider tile for one extra element, worth
255+~10 % by the fit above). `D = 1040` clinches it — one register *more* than 1024, on the 2048
256+rung — at **10.20 µs, below** `D = 1024`'s 10.44. Only rung/`Rows` selection can do that;
257+alignment cannot.
258+ 
259+**Rule.** Do not spend a run making `D` "aligned" for a `vf` row kernel of this shape. Size the
260+tile to `align64(D)` because `load_align` moves a whole register and will otherwise fault
261+`507035` (first rule on this page) — that is a **correctness** constraint. It is not a
262+performance one. If a benchmark's slow cases all have ragged `D`, check first whether ragged
263+`D` is confounded with `D` magnitude or with register count in that suite; in this one it was.
264+ 
265+**Diagnostic that settles it in one eval run:** probe three `D` values sharing a rung and a
266+register count, one aligned-and-equal-to-rung, one aligned-but-below-rung, one misaligned. If
267+they land together, alignment is not your mechanism.
@@ -0,0 +1,117 @@
1+# Converting a mask between element widths
2+ 
3+A `MaskReg` can be converted to a different element width in **one instruction**. Two operators
4+independently concluded it could not be, and between them that cost roughly **+8 OperatorScore**
5+and several development rounds. This page exists because the capability is real but undiscoverable
6+from the place you would look for it.
7+ 
8+## Why it is missed
9+ 
10+Both operators audited the functions with `mask` in the name — `create_mask`, `update_mask`,
11+`unsqueeze`, `get_mask_spr`, `mask_gen_with_reg_tensor` — and correctly concluded that none of them
12+retypes an existing, data-dependent mask. That audit was right. The converter is filed under
13+**advanced computation**, not mask operations: `vf.interleave` and `vf.de_interleave` are *unified*
14+ops whose behaviour changes when their sources are `MaskReg`s.
15+ 
16+`mask_reg.md`'s "Mask 设置方式" table lists five construction routes and conversion is not among
17+them.
18+ 
19+## Why it works
20+ 
21+From `docs/pypto_pro/api/SIMD-API/operation/vf_computation/mask_operations/mask_reg.md:17,19`: a
22+`MaskReg` is a fixed **256-bit** object, and *width* is not a property of the register. It is the
23+**stride at which the consuming instruction reads it** — b8 reads bit *i*, b16 bit 2*i*, b32 bit
24+4*i*.
25+ 
26+A width conversion is therefore nothing but **bit re-spacing**, and `pintlv` / `pdintlv` are exactly
27+the predicate re-spacing instructions. From `_vf_api.py:1312-1313` and `:687-688`:
28+ 
29+> `dtype`: When src operands are MaskReg, specifies the interleave bit-width (selects
30+> `pintlv_b8`/`b16`/`b32`). Inferred from src0 if omitted.
31+ 
32+A corollary that matters in practice: **the `dtype=` you pass to `create_mask` when declaring a
33+destination is bookkeeping, not semantics.** The shipped sample below declares its b16 result as
34+`DT_UINT8` and is still correct.
35+ 
36+## The conversions
37+ 
38+**`dtype=` names the *finer* of the two widths.** Narrowing discards `dst1`; widening uses both.
39+ 
40+| Direction | Call | Ops |
41+|---|---|---|
42+| b32 (2×64 lanes) → b16 (128) | `m16, _ = vf.de_interleave(m32_lo, m32_hi, dtype=pl.DT_UINT16)` | 1 |
43+| b16 (2×128) → b8 (256) | `m8, _ = vf.de_interleave(m16_lo, m16_hi, dtype=pl.DT_UINT8)` | 1 |
44+| b16 (128) → b32 (2×64) | `m32_lo, m32_hi = vf.interleave(m16, m16, dtype=pl.DT_UINT16)` | 1 |
45+| b8 (256) → b16 (2×128) | `m16_lo, m16_hi = vf.interleave(m8, m8, dtype=pl.DT_UINT8)` | 1 |
46+| b32 → b8 | two `de_interleave(…, UINT16)` then one `de_interleave(…, UINT8)` | 3 |
47+ 
48+`src0 == src1` is explicitly legal (`interleave.md:53-54`); `dst0 == dst1` is not.
49+ 
50+## The shipped sample
51+ 
52+`.devkit/pro_ops/fa/test_flex_attention.py:551-553` — two 64-lane b32 masks in, one 128-lane b16
53+mask out, one instruction:
54+ 
55+```python
56+merge_bit = vf.lt(index, maskr_reg, preg_all) # b32, lanes 0..63
57+merge_unroll_bit = vf.lt(index_unroll, maskr_reg, preg_all) # b32, lanes 64..127
58+row_reg, temp_reg = vf.de_interleave(merge_bit, merge_unroll_bit, dtype=pl.DT_UINT16)
59+```
60+ 
61+Two details worth copying, both non-obvious: the destinations are pre-declared as **`DT_UINT8`**
62+(`:527-528`) rather than at the target width, and mask-level boolean combination works —
63+`vf.and_(m0, m1, preg)`, three args with a predicate third.
64+ 
65+## Evidence classes — check before building
66+ 
67+| Claim | Evidence |
68+|---|---|
69+| MaskReg is 256 raw bits; width is a read-stride | **documented** (`mask_reg.md:17,19`) |
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) |
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 |
74+| b32 ↔ b8 in three ops | **derived only** |
75+ 
76+## It working does not mean it pays
77+ 
78+`cummin` verified the widening on device, built its 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 →
80+0.480, 0.377 → 0.368, 0.322 → 0.314). Reverted.
81+ 
82+The projected gain had been **+5.8 OperatorScore across 11 of 16 cases**, carried for three rounds.
83+It was void, and it was **its own earlier fix that voided it**: a round before, `cummin` found the
84+narrow-dtype penalty was mostly a UB bank conflict on the *work tile's* pitch rather than the fp32
85+round trip, and fixing the pitch collected that value. What remained of the round trip costs less
86+than two `vf.interleave` calls plus doubled index-register traffic — the native step is 20 vector
87+ops per 128 elements against 26-plus-a-cast, and still measures 1.18–1.44× worse.
88+ 
89+**The transferable rule: an estimate inherits the lifetime of the diagnosis it came from.**
90+Re-derive a carried-forward number before spending on it, especially after fixing something in the
91+same area.
92+ 
93+## What the round-trip costs, for comparison
94+ 
95+`vf.unsqueeze` → `vf.pack` → compare-back does close the loop, and it was correctly identified by
96+both operators — the error was concluding nothing cheaper existed. It runs ≈3 ops per 64 lanes and
97+fills only the lower half of the wider register, so covering 128 lanes takes 5–6 ops plus a
98+register-level merge. `de_interleave` does it in **one**.
99+ 
100+`vf.mask_gen_with_reg_tensor` (`_vf_api.py:1885`) is a genuine, data-dependent register→mask
101+converter and is better than compare-against-zero for that route, but its source is restricted to
102+*uint16 or uint32*, so it cannot reach b8.
103+ 
104+## A documented fallback, not the primary route
105+ 
106+`load_align.md:82` gives `pl.LoadDist.US` (upsample, each bit repeated twice) and `pl.LoadDist.DS`
107+(downsample, every other bit discarded), complementary to `StoreDist.PACK`. That is a UB round-trip
108+— a store, a sync and a load — so it is slower. Its value is that it independently confirms ×2/÷2
109+mask conversion is a first-class concept in this API rather than an accidental property of
110+`pdintlv`.
111+ 
112+## The residual gap is discoverability, not capability
113+ 
114+Worth filing upstream, in decreasing value: add a **conversion row to `mask_reg.md`'s construction
115+table** (a one-line doc change that would have prevented all of this); a `vf.mask_astype(mask,
116+dtype=…)` alias over the `interleave`/`de_interleave` pair; a b8 form of
117+`mask_gen_with_reg_tensor`; and a `MaskWidth.B8` for `get_mask_spr`.
@@ -0,0 +1,437 @@
1+# Vector authoring constraints
2+ 
3+## Applies to
4+ 
5+PyPTO-Pro vector sections implemented with tile operations or
6+`@pl.vector_function` / `vf.*`.
7+ 
8+## Conditional authoring rule
9+ 
10+Select the level that is correct and supported by the installed API:
11+ 
12+- Use tile operations when they express the complete dataflow and their runtime
13+ valid-shape semantics cover the tail.
14+- Use `vf.*` when explicit lane masks, register-level control, or an instruction
15+ composition unavailable at tile level is required.
16+- When both are legal, measure both on the target before choosing for
17+ performance.
18+ 
19+No operator family, shape, or prior benchmark makes either level the universal
20+default.
21+ 
22+## Shared correctness requirements
23+ 
24+1. A row reduction writes a row scalar, conventionally a `[rows, 1]` result,
25+ which is broadcast back over the row by the matching expand operation.
26+2. Padding lanes must be excluded from reductions and stores.
27+3. Accumulation dtype follows the numerical contract; use FP32 unless a
28+ documented, validated alternative is allowed.
29+4. Input, output, reduction, and workspace tiles must fit the detected
30+ platform's vector-memory budget.
31+5. Compare/select mask dtype, layout, offset units, and supported operations are
32+ API-version-specific. Confirm them in the installed documentation.
33+ 
34+## Examples
35+ 
36+Tile-operation row softmax:
37+ 
38+```python
39+pl.row_max(row_value, input_tile, workspace)
40+pl.row_expand_sub(output_tile, input_tile, row_value)
41+pl.exp(output_tile, output_tile)
42+pl.row_sum(row_value, output_tile, workspace)
43+pl.row_expand_div(output_tile, output_tile, row_value)
44+```
45+ 
46+Vector-function load and mask placement:
47+ 
48+```python
49+register = vf.load_align(input_tile, offset)
50+accumulator = vf.add(accumulator, register, predicate)
51+result = vf.reduce_sum(accumulator, predicate)
52+vf.store_align(output_tile + offset, result, predicate)
53+```
54+ 
55+`vf.load_align(input_tile, offset, predicate)` is not a supported mask
56+placement in the retained guidance.
57+ 
58+## Performance: the mask is the first thing to look at
59+ 
60+A `vf.*` register loop that recomputes its mask per register is the largest
61+single performance defect this knowledge base has a measurement for. It is worth
62+checking before any other vector lever, because it can be several times
63+everything else put together.
64+ 
65+**Why it costs so much.** `vf.update_mask` lowers to `plt_b32(scalar,
66+POST_UPDATE)` — a **special-purpose-register write**, not an ordinary vector
67+issue slot. Inside a hot loop it serialises against the vector pipe. There is no
68+cheap per-register mask to ask for instead.
69+ 
70+**The fix is structural, not a tuning knob.** Every register but the last is
71+*fully* valid, so it can run on one hoisted constant mask; only the ragged last
72+register needs a computed mask, and that mask depends on the row width alone, so
73+it is computed once per call. Peel the last register out of the loop:
74+ 
75+```python
76+preg = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=pl.DT_FP32)
77+n_full = (n_cols + LANES - 1) // LANES - 1 # whole registers
78+toff = n_full * LANES # offset of the ragged one
79+mtail = vf.update_mask(n_cols - toff, dtype=pl.DT_FP32) # once per call
80+for r in pl.range(0, n_full):
81+ ... # on preg
82+... # peeled tail, on mtail
83+```
84+ 
85+This is **bit-identical by construction**, not an approximation:
86+`min(LANES, n_cols - r*LANES) == LANES` for exactly the registers that now run
87+on `preg`, and the peeled register keeps the mask value it had. Confirm it in
88+the generated code — the inner loops must contain **no `plt_b32`**.
89+ 
90+**One guard the snippet above needs.** `n_full = (n_cols + LANES - 1) // LANES - 1`
91+is `-1` when `n_cols == 0`, which makes `toff` negative and turns the peeled tail
92+into a whole-register access **below the tile base** — and `mtail` is
93+`update_mask(0 - (-LANES)) = update_mask(LANES)`, i.e. the ALL mask, so the store
94+writes a full register out of bounds. That is a **507035 device fault**, which is
95+not a compile error and survives every device-free gate. The per-register form it
96+replaces degraded harmlessly (`n_regs = 0`, empty loop), so this is a hazard the
97+rewrite *introduces*.
98+ 
99+Clamp it. `n_full = pl.max((n_cols + LANES - 1) // LANES - 1, 0)` works inside a
100+`@pl.vector_function` (device-verified) and costs **one scalar op per call**, not
101+per register — measured free, inside a ±1.5 % noise floor, on the two cases that
102+reach a 1-lane block. Whether `n_cols == 0` is reachable is a property of the
103+*caller*; on the operator this was measured on it was not, but a later change to
104+the planner or the column-block count re-arms it silently.
105+ 
106+ 
107+**The measurements live on one page, and it is not this one.** The table for this lever — both suites, the curve they sit on, the memory-bound control that reads 1.68x, and the width below which the hoist stops paying — is
108+[`vec-alignment-and-rotation.md`](vec-alignment-and-rotation.md). Quote it from there.
109+What belongs here is the authoring rule above: never recompute a mask per register.
110+ 
111+### 🏆 Officially scored: the hoist is worth 1.77-2.99x in the COLUMN-BLOCK loop
112+ 
113+Everything else on this page is box-measured. This entry is the first **grader-scored** confirmation,
114+from an official cann-bench hidden-set run (rms_norm, 80 cases, 2026-08-10).
115+ 
116+The kernel splits a row across column blocks when `D` exceeds one tile (`Mode 2 / COLBLK`), and its
117+inner helpers recomputed `vf.update_mask` **per register** inside that per-block loop. At `D = 16384`
118+the computed mask is identically the all-lanes constant, so every one of those writes is a no-op
119+`plt_b32` -- 512 of them per row. Hoisting them out, and nothing else in that lever:
120+ 
121+| hidden case | before | after | speedup |
122+|---|---|---|---|
123+| 55 | 660.71 us | **221.10 us** | **2.988x** |
124+| 56 | 1309.69 | **465.78** | **2.812x** |
125+| 97 | 118.17 | **43.68** | **2.705x** |
126+| 51 | 88.23 | **35.99** | **2.452x** |
127+| 54 | 316.05 | 178.85 | 1.767x |
128+ 
129+**+0.9212 benchmark points from five cases out of eighty**, and the whole submission moved
130+84.3476 -> 84.9747. The five were named **in advance** from the operator's tiling modes, so this is
131+attribution, not a post-hoc story.
132+ 
133+**Two things to take from it.**
134+ 
135+1. **A column-blocked / multi-tile-per-row loop is the highest-value place to look for this defect**,
136+ higher than the single-tile row loop the rest of this page describes. The per-block loop body runs
137+ `ceil(D/MaxN)` times per row, so a per-register mask there is multiplied by the block count on top
138+ of the register count.
139+2. **The magnitude survives to the official grader.** A 2.4-6.5x box measurement of this lever is not
140+ a box artifact; here the graded speedups (1.77-2.99x) were *larger* than the box's own estimate of
141+ the same cohort (1.65-2.03x). When this lever is available, it is worth more than any tiling
142+ knob measured in this campaign.
143+ 
144+🔴 **The same run also shows what did NOT survive.** A tile-count/`Rows` planner change measured
145+2.27x on its target case and was a **net negative** once scored (see
146+`../playbooks/benchmark-scoring.md`), and a "drop the tiling struct, pass scalars" change large
147+enough to be visible on paper produced a public delta whose per-case pattern did not match its own
148+mechanism. **The mask hoist is the lever with an official number behind it; treat the others as
149+unproven until they have one.**
150+ 
151+### The second lever, and why it must be gated
152+ 
153+Replacing the per-register horizontal `vf.reduce_sum` with a lane-wise
154+accumulate (`vf.mul_add_dst`) and one horizontal reduction per row is the
155+textbook next step. On its own it **measured slower** (+0.7 and +1.4 percent):
156+the accumulator is a loop-carried dependency and the multiply-accumulate
157+serialises. It only pays with **four independent accumulator chains** unrolled
158+by four, which measured 1.256x and 1.305x on the two large cases in
159+[`vec-alignment-and-rotation.md`](vec-alignment-and-rotation.md).
160+ 
161+But four accumulator inits and three merges per row are pure overhead on a row
162+that never fills a quad. Applied ungated it **cost 3.0 percent** on the `D = 67`
163+case (one whole register per row, so no quad is ever entered). It ships behind a
164+**compile-time width test**:
165+ 
166+```python
167+if MaxN >= UNROLL_MAXN: # MaxN is a tilingkey constant; this folds
168+ rows_unrolled_vf(...)
169+else:
170+ rows_plain_vf(...)
171+```
172+ 
173+The general rule: an unrolled or multi-accumulator reduction is only correct as
174+a *performance* choice above a width threshold, and the threshold belongs in a
175+compile-time constant so each specialisation gets one body. A runtime branch
176+would pay for itself on every row. See
177+[../patterns/tiling-key-width-ladder.md](../patterns/tiling-key-width-ladder.md)
178+for the mechanism, and note that `vf.add(vf.add(a, b), c)` is a parse error —
179+accumulator merges need explicit assignments.
180+ 
181+**The gate was re-tested from the other side, and it held.** The obvious
182+objection to the width gate is that it blames the *four chains* for the narrow-row
183+loss, when the single-accumulator form might pay there on its own — it removes a
184+horizontal `vf.reduce_sum` from every register, and four inits are not involved.
185+So it was measured directly: single full-width accumulator, one reduce per row,
186+**no** unrolling, on the narrow rungs only.
187+ 
188+It is **slower**. Ratios 0.986 / 0.969 / 0.992 on rows of `D = 373 / 67 / 128`
189+(control drift +1.9 / +0.1 / −1.0 %, A/B/A in one process). It cut the narrow path
190+from **9 to 7 vector ops per register** and still lost.
191+ 
192+Two things to carry forward. First, this is direct evidence for the *stated
193+mechanism* rather than for the gate's boundary: the accumulator is a loop-carried
194+dependency, and with one chain there is nothing to interleave against it, so the
195+saved horizontal reduce buys less than the serialisation costs. Four chains are
196+not an optimisation *on top of* the fused accumulate — they are what makes it
197+viable at all. Second, and more generally: **op count is not the objective
198+function on this vector pipe.** A rewrite that provably issues fewer instructions
199+per register can be slower, so a lever counted in ops still has to be timed.
200+ 
201+ 
202+## Missing primitives to plan around
203+ 
204+- **`Vf` has no `rsqrt` and no `recip`.** `pl.rsqrt` and `pl.recip` exist but
205+ are tile level and leave the vector-function domain, so a normalisation
206+ written in `vf.*` pays `sqrt` **plus** `div` on every row where one
207+ instruction would do. Budget for it; do not design a chain that assumes a
208+ reciprocal-square-root exists at register level. (Measured on the same box,
209+ fp32 over 2^-24 … 2^24: `1/sqrt(v)` is also the *more accurate* of the two,
210+ matching the CPU bit for bit, while the NPU `rsqrt` primitive is about 1.39x
211+ looser in the worst case — so the missing primitive costs speed, not
212+ precision.)
213+- **There is no `vf.cast`.** Widening at register level is `Vf.astype`, whose
214+ documented dtype table covers FP32 to and from FP16 and INT32 only — **BF16
215+ is undocumented**. Prefer `pl.cast` at tile level for a BF16 chain.
216+- **There is no unroll control.** `pl.range` takes start/stop/step, so unrolling
217+ is hand-written source duplication plus a remainder loop.
218+ 
219+Confirm each of these against the installed API documentation for the target
220+version before designing around it.
221+ 
222+## Evidence
223+ 
224+- Tile-operation implementation and golden:
225+ [softmax_impl.py](../examples/samples/softmax/softmax_impl.py) and
226+ [softmax_golden.py](../examples/samples/softmax/softmax_golden.py)
227+- Vector-function implementation:
228+ [vf_softmax_impl.py](../examples/samples/vf_vs_tileop/vf_softmax_impl.py)
229+- Conditional selection and source order:
230+ [vf-reduction-perf.md](../../ops/pypto-pro-op-develop/references/vf-reduction-perf.md)
231+ 
232+The installed `$PYPTO_DEVKIT_DIR/docs/pypto_pro/api/` documentation remains the
233+primary source for signatures and target-version behavior.
234+ 
235+---
236+ 
237+## BF16 at register level: what `Vf.astype` can and cannot do
238+ 
239+Measured on A5 / DAV_3510 (CANN 9.1.0-beta.3) with `rms_norm`, by direct probe on
240+the device. This section resolves the "**BF16 is undocumented**" caveat recorded
241+above for `Vf.astype`: BF16 *is* supported, but asymmetrically, and the asymmetry
242+decides whether a whole class of lever is expressible.
243+ 
244+**Narrowing FP32 → BF16 works, and is bit-identical to the tile cast.**
245+ 
246+```python
247+be = vf.astype(e, preg, dtype=pl.DT_BF16, layout=pl.CastLayout.ZERO) # -> EVEN lanes
248+bo = vf.astype(o, preg, dtype=pl.DT_BF16, layout=pl.CastLayout.ONE) # -> ODD lanes
249+both = vf.or_(be, bo, pn) # both casts are MODE_ZEROING, so OR merges them
250+```
251+ 
252+Each call converts one 64-lane FP32 register into half of a 128-lane BF16 register.
253+To publish 128 *contiguous* outputs, de-interleave the two FP32 sources first —
254+`e, o = vf.de_interleave(o0, o1)` splits the `[o0|o1]` stream into even/odd, which
255+is the exact inverse of the ZERO/ONE lane placement. A single register (a ragged
256+tail) goes through the same sequence as `vf.de_interleave(o, o)`: the low 64 lanes
257+then hold `o[0..63]` in order, and the store mask keeps the rest unwritten.
258+ 
259+**The `round_mode` kwarg is IGNORED for FP32 → BF16.** `CAST_RINT` and
260+`CAST_HYBRID` do not even compile —
261+ 
262+```
263+The 4th argument of this vcvt (f322bf16) can only be:
264+ROUND_R, ROUND_A, ROUND_F, ROUND_C, ROUND_Z
265+```
266+ 
267+— and the six modes that *do* compile (`CAST_ROUND`, `CAST_RNA`, `CAST_ODD`,
268+`CAST_FLOOR`, `CAST_CEIL`, `CAST_TRUNC`) all return **the same bytes**, including on
269+64 inputs that are exact BF16 ties (low 16 mantissa bits `== 0x8000`, 30 of which
270+move under truncation). `FLOOR` and `CEIL` cannot both agree with nearest-even on a
271+genuine tie, so the mode is not reaching the instruction: the hardware always
272+rounds nearest-even. That happens to equal `pl.cast(..., mode=CAST_RINT)`, so
273+replacing a tile-level narrowing cast with the register form is **bit-exact**, not a
274+precision trade. Pass a mode anyway to state the intent; do not rely on it.
275+ 
276+**Widening BF16 → FP32 is HALF BROKEN, and this is the load-bearing fact.**
277+ 
278+| `vf.astype(bf16_reg, preg, dtype=pl.DT_FP32, layout=…)` | result |
279+|---|---|
280+| `CastLayout.ZERO` (`PART_EVEN`) | source elements 0, 2, 4, … — correct, **stride 2** |
281+| `CastLayout.ONE` (`PART_ODD`) | **all zeros** — 0/64 lanes non-zero |
282+| `CastLayout.TWO` / `THREE` | do not compile (`static_assert`: only `PartEven`/`PartOdd`) |
283+ 
284+Only the **even** elements of a BF16 register can be widened at register level. The
285+odd elements are unreachable: no aligned load starts one BF16 element in, and
286+`unpack`/`shift_left` recover the right bits but strand them in an integer register.
287+ 
288+### Consequence: there is no register bitcast, so bit-trick widening is not portable
289+ 
290+`grep -rniE "bitcast|reinterpret|as_type|raw_view|view_as"` over
291+`pypto_pro/language/` finds nothing. Registers carry a dtype and `Vf.astype` is a
292+*value* conversion; **tiles** can be aliased at a UB address, **registers cannot**.
293+ 
294+This kills the widely-quoted trick "BF16 is the top 16 bits of FP32, so widening is
295+`interleave(zero, x)`, one instruction, bit-exact". The identity is true, but it
296+delivers its result as bits in a 16-bit-typed register and there is no way to
297+consume those bits as FP32 without a store+reload through UB — which is exactly the
298+traffic `pl.cast` already performs in one tile operation, so it cannot win. Note in
299+particular that *having* `vf.interleave` does not imply the trick is expressible:
300+`vf.interleave` preserves its source's type.
301+ 
302+**Rule of thumb.** For a BF16 chain, **narrow** in the register file (free, bit-exact,
303+removes a whole tile-level pass and its `auto_mutex` barrier) and **widen** at tile
304+level with `pl.cast`. The asymmetry is a hardware/ISA property, not a pypto gap.
305+ 
306+### Publishing BF16 from registers: 5 ops per 128 outputs is the floor
307+ 
308+The `de_interleave` + 2×`astype` + `or_` + store sequence above is not merely *a*
309+way to publish BF16 — it is the cheapest one this DSL offers. Two candidate
310+shortcuts were measured on A5 / DAV_3510 and both are unavailable:
311+ 
312+* `vf.store_align(..., dist=pl.StoreDist.PACK)` does **not** compact the 64 valid
313+ even lanes of an `astype(..., layout=ZERO)` result into 64 contiguous BF16. With
314+ marker values and a pre-zeroed destination it writes 60 non-zero lanes in neither
315+ the contiguous nor the even-lane arrangement.
316+* `dist=pl.StoreDist.NORM` for an FP32 source register into a BF16 tile does not
317+ compile. There is no converting store.
318+ 
319+So `de_interleave` and `or_` cannot be removed, and a register-level BF16 publish
320+costs 5 register ops per 128 outputs. Budget accordingly before assuming a
321+publish-side rewrite will pay: on `rms_norm` this publish traded +1.5 vector ops per
322+register against one tile-level `pl.cast` pass and measured **2.8 % slower** on the
323+BF16 cohort, on the pinned harness, in a control-bracketed chain.
324+ 
325+### Measuring anything with `pl.jit` variants: use a canary
326+ 
327+Two `pl.jit` kernels that share a decorated **name** and an identical **body source
328+text** can silently resolve to the same compiled binary, even when they close over
329+different constants or call different `@pl.vector_function`s. The factory idiom
330+`def make_k(p): @pl.jit def k(...): ...; return k` decorates every variant as `k`,
331+and `k.__name__ = ...` afterwards is too late — the name is captured at decoration.
332+ 
333+This does not raise. It returns clean, self-consistent, plausible data from the
334+wrong kernel. Give every variant its own `def`, **and** include a canary variant
335+that differs in something that must visibly change (store at a different offset).
336+If the canary's output does not move, the compiles are not distinct — discard the
337+run rather than reporting it.
338+ 
339+---
340+ 
341+<!-- ADDITIVE INSERTION — Run F, rms_norm Stage 5, A5 card 4, 2026-08-11.
342+ Confirmed by measurement (compiled and ran on hardware) unless the line says otherwise. -->
343+ 
344+## `vf.pair_reduce_sum` is the ONLY sub-register reduction, and it is radix-2 by construction
345+ 
346+The `vf` surface on this SDK is 86 ops. Its reductions are exactly:
347+ 
348+| op | granularity |
349+|---|---|
350+| `vf.reduce_sum` / `vf.reduce_max` / `vf.reduce_min` | whole register → lane 0 |
351+| `vf.pair_reduce_sum` | adjacent pairs, `dst_i = src_2i + src_2i+1` (`vcpadd`) |
352+ 
353+**There is no variable-width segmented reduction op.** Any in-register segmented reduce must be built
354+by iterating `pair_reduce_sum`, which restricts the segment width to a power of two — and since a
355+register is 64 lanes, that is exactly "the segment width divides the register". The two conditions
356+coincide, so a radix-2 tree is fully general over its natural domain `{1, 2, 4, 8, 16, 32}` and serves
357+nothing outside it. This is a hard ISA limit, not a frontend gap. `vf.interleave(v, v)` is the exact
358+inverse and has the same domain and depth. Worked example and measured payoff:
359+[patterns/vec-narrow-row-packing.md](../patterns/vec-narrow-row-packing.md).
360+ 
361+Padding a non-power-of-two width up to the next power of two is **not** a cheap escape: a Vec tile row
362+must be a multiple of 32 bytes (so the padded width is ≥ 8 in fp32), and if the padding is done
363+tile-side the packing factor becomes the tile *row* count, which a `Rows`-style `TilingKeyField` caps
364+at 64 — collapsing the packing back into the short-burst regime it existed to escape. The remaining
365+route is `vf.gather`-repack in registers; it is expressible but needs runtime segment-phase tracking
366+across tiles when `D ∤ MaxN`, and has not been measured.
367+ 
368+## `vf.gatherb` and `vf.select_r` are DEPRECATED, and fail at different stages
369+ 
370+* `vf.gatherb(...)` — *"no longer accepted by the parser"*. Use
371+ `vf.gather(src, idx, mask, data_copy_mode=pl.DataCopyMode.DATA_BLOCK_LOAD)` for the former
372+ datablock-granularity gather.
373+* `vf.select_r(...)` — *"not implemented … has no backend implementation"*. Use `vf.select` with
374+ swapped arguments, or `vf.gather`.
375+ 
376+Both are still importable and still appear in `dir(Vf)`, so `hasattr`-style feature detection reports
377+that they exist and then fails later. Read the docstring, not the attribute list.
378+ 
379+## `vf.arange`'s per-lane step is fixed at ±1
380+ 
381+`vf.arange(start, index_order=...)` gives `start + i` (`INCREASE_ORDER`, default) or `start − i`
382+(`DECREASE_ORDER`) and nothing else — the step is a hardware property of `vci`. A strided index vector
383+needs a following `vf.muls`. Relevant whenever you are building gather/scatter indices.
384+ 
385+## `LoadDist.BRC_B32` needs 32-byte alignment, which caps the "replicate a short vector" idiom at 2
386+ 
387+The idiom "one 32-byte-aligned single-element tile per element, then `vf.interleave`" replicates a
388+2-element vector across a register and **cannot be written for 4 elements**, which would want tiles 16
389+bytes apart. The general replacement, for any power-of-two period `P` including `P = 1`:
390+`vf.arange` → `vf.and_(P-1)` → `vf.gather(tile, idx, mask)`, giving `dst_i = src[i mod P]` in four
391+register ops from an ordinary `[1, N]` tile. `vf.arange`, `vf.and_` on `DT_INT32` registers and
392+`vf.gather` all work inside a `@pl.vector_function` with an FP32-granularity predicate mask (b32
393+granularity is shared).
394+ 
395+## `pl.load` places at the tile ORIGIN — the `[i, j]` argument is a SOURCE offset
396+ 
397+`pl.load(dst_tile, src_tensor, [i, j])` reads `src_tensor[i, j]` and writes at the destination tile's
398+base address. There is **no destination offset**. So you cannot assemble a pattern inside one tile by
399+issuing several loads at different column offsets: each destination offset needs its own tile group,
400+with its own address and mutex id. This is the second reason the replication problem above is not
401+solvable tile-side.
402+ 
403+## Compile-time tilingkey arithmetic inside `@pl.vector_function` (measured, pypto-master-20260730)
404+ 
405+A tilingkey constant is an ordinary Python `int` in the body of a
406+`@pl.vector_function`, and Python control flow over it is resolved at parse time
407+and leaves no runtime branch. All of these compile and fold:
408+ 
409+```python
410+NR = MaxN // LANES # noqa: F821 -- a Python int
411+toff = (NR - 1) * LANES # a Python int
412+if MaxN > LANES: ... # folded away
413+if NR >= 3: ... # folded away
414+mk = mtail if NR == j + 1 else preg # folded away
415+```
416+ 
417+This was previously documented only for a dedicated depth field (`PackLog` in
418+`rms_packn_vf`). It holds for `MaxN` too, which means a rung can carry a
419+compile-time **register count**, not just a compile-time width — see
420+`kb/patterns/vec-compile-time-register-count.md`.
421+ 
422+Two more, same build:
423+ 
424+* **`vf.load_align` hoists out of a `pl.range` loop and the loaded register is
425+ reusable in every iteration.** Precedent previously existed only for
426+ `vf.gather`. A per-column operand (gamma) can therefore be loaded once per call
427+ instead of once per register per row.
428+* **Up to 8 loaded registers stay live across an intervening
429+ `reduce_sum` / `full` / `div` / `sqrt` / `div` chain** and can be reused
430+ afterwards instead of re-loaded — no spill, no compile failure, measured faster.
431+ 
432+### Non-lever, measured
433+ 
434+Row-level software pipelining inside a vector function (two independent rows in
435+flight, separate accumulators and separate `sqrt`/`div` chains) is worth
436+**0.0–0.4 %** on `rms_norm` at every rung from 64 to 256, i.e. nothing. The
437+backend already overlaps consecutive `pl.range` iterations.
@@ -0,0 +1,115 @@
1+# Wrapper boundary: what may run on the host
2+ 
3+## The rule
4+ 
5+**The benchmark measures the wrapper.** CANN-Bench times the whole submitted
6+callable, and every host-side tensor operation is dispatched as a real device
7+kernel (`aclnnInplaceCopy_CastAiCore_Cast`, `..._TransposeAiCore_Transpose`,
8+`..._SliceAiCore_Slice`, `aclnnCat_ConcatD_ConcatD`, …) that lands in the
9+measured time exactly as if it were part of your kernel.
10+ 
11+So:
12+ 
13+> **Casting, slicing, transposing, padding, concatenating, and any other data
14+> shape or dtype processing MUST happen inside the `@pl.jit` kernel.
15+> The wrapper does argument validation, output allocation, and one kernel
16+> launch — nothing else.**
17+ 
18+This is not a performance preference. It is what the score measures.
19+ 
20+## What this costs when ignored
21+ 
22+The wrapper's share of measured device time is the lever, and it is available to
23+every operator. On the run this rule came from, the operators whose wrappers did
24+the most shaping had wrapper shares from 10% to 62% of their total device time,
25+and the ones above roughly a third of it lost more score to the wrapper than any
26+kernel change recovered.
27+ 
28+Two consequences follow, and they are the durable part:
29+ 
30+- **Kernel time and operator score can move in opposite directions.** One
31+ operator's kernel improved by roughly a third between two runs while its score
32+ fell, because its wrapper grew faster than the kernel shrank. Tuning against
33+ kernel time alone will therefore sometimes tell you the opposite of the truth.
34+ The only sound unit is wrapper plus kernel together.
35+- **Host shaping is not rare.** Across that run's generated kernels the dominant
36+ calls were `.to()`, `.contiguous()` and `.reshape()`, by a wide margin over
37+ everything else. Assume a generated wrapper has one unless the profile says
38+ otherwise.
39+ 
40+> The per-operator figures behind this are a single run on one platform at one
41+> revision. They are not reproduced here because a threshold copied out of one
42+> run is exactly what this knowledge base is not for: measure your own operator
43+> with [`pypto-pro-op-perf-tune`](../../ops/pypto-pro-op-perf-tune/SKILL.md) and
44+> read `wrapper_share` from your own profile.
45+ 
46+## The anti-pattern
47+ 
48+This is a real generated wrapper, renamed. Every marked line becomes a
49+measured device kernel:
50+ 
51+```python
52+def op_wrapper(input_tensor, dim=-1, ...):
53+ x_fp32 = input_tensor.to(torch.float32) # cast <- measured
54+ x_transposed = x_fp32.movedim(dim, -1).contiguous() # transpose+copy <- measured
55+ x_2d = x_transposed.reshape(M, D_full)
56+ y_2d = torch.empty(M, D_out, ...)
57+ op_kernel(x_2d, y_2d, ...) # the actual work
58+ y_transposed = y_2d.reshape(*non_dim_shape, D_out)
59+ y = y_transposed.movedim(-1, dim).contiguous() # transpose+copy <- measured
60+ return y.to(out_dtype) # cast <- measured
61+```
62+ 
63+Four measured device ops surround one kernel launch. The kernel was written to
64+want a canonical FP32 contiguous 2-D input, and the host was made to produce
65+it. That convenience is charged at full price.
66+ 
67+This shape recurs: the wrapper is written to hand the kernel a canonical input,
68+and every step of that convenience is a device kernel in the measured window.
69+ 
70+## What to do instead
71+ 
72+| Host does this | Move it into the kernel as |
73+|---|---|
74+| `.to(torch.float32)` on input | load the native dtype into UB, then convert on-chip — `pl.cast` at tile level or `vf.astype` at register level (there is no `vf.cast`) |
75+| `.to(out_dtype)` on output | `pl.cast` / `vf.astype` per tile before `store` |
76+| `.movedim` / `.permute` / `.transpose` | index the axis by stride/offset in the tile loop |
77+| `.contiguous()` | strided `DataCopy`, or fold the stride into the loop bounds |
78+| `.reshape` to 2-D | pass the real shape and compute the flat offset in the kernel |
79+| slicing an operand | pass base pointer plus an offset argument |
80+| `torch.cat` of operands | pass both operands and select inside the loop |
81+| padding to a tile multiple | `pl.set_validshape` for the tail |
82+| `torch.zeros` / `zeros_like` init | write every output element, or initialize in-kernel |
83+| `arange` / index construction | compute the index arithmetically in the kernel |
84+| `torch.npu.synchronize()` | delete it — the harness synchronizes; this only adds stream wait to the measured window |
85+| a `for` loop over a TensorList launching one kernel per element | pack the elements' addresses and shapes into tiling parameters and launch **once**; iterate inside the kernel |
86+ 
87+The last row is the expensive one for `foreach`-style operators. Their baseline is a
88+single fused call — eliminating per-tensor launch overhead is the entire reason those
89+operators exist — so launching per element reintroduces exactly what the baseline
90+avoids, and the gap widens with list length.
91+ 
92+The on-chip conversion APIs in the first two rows are platform-gated; confirm
93+they are supported on the detected target before relying on them, and see
94+[precision.md](precision.md) for which dtype the converted chain has to be in.
95+Moving a cast into the kernel is the rule, but an unsupported API is not a
96+migration — escalate rather than leaving the `.to()` on the host.
97+ 
98+A reshape that is a pure view of a contiguous tensor costs nothing and does not
99+appear in the profile — it is `.contiguous()`, `.to()` and the movement ops
100+that are charged. If in doubt, read the profile: anything named `aclnn*` in
101+`op_times.device_kernels` is wrapper time.
102+ 
103+## The one legitimate exception
104+ 
105+If a transformation genuinely cannot be expressed in the kernel, keep it, and
106+**record why** in `DESIGN.md` with the measured cost of the op you kept. An
107+unexplained host-side shaping op is a defect, not a trade-off.
108+ 
109+## How this is checked
110+ 
111+`KB_USAGE.json` must record the invariant, and the verifier runs a wrapper
112+audit that fails a class whose wrapper performs data shaping without a recorded
113+justification. Anti-cheat rules still apply in the other direction: the wrapper
114+must not perform the operator's *arithmetic* either, and there is still exactly
115+one `@pl.jit` kernel launched once.
@@ -0,0 +1,14 @@
1+# Validated study kernels
2+ 
3+[kernel-index.md](kernel-index.md) is the only production selector. Every row
4+has:
5+ 
6+- a general topology or technique;
7+- a canonical implementation path;
8+- `validated` state;
9+- reviewable evidence in the implementation itself or a companion golden.
10+ 
11+Do not add failed, work-in-progress, diagnostic, or benchmark-only probes to
12+the selector. Re-run the retained validation on the actual target before
13+adopting a sample in production; a historical validation does not establish
14+compatibility with a different PyPTO/CANN version or platform.
@@ -0,0 +1,48 @@
1+# Kernel selector
2+ 
3+All paths are relative to `cannbot-skills/kb/`. Performance metrics are
4+deliberately excluded: profile again for the actual platform, shape, and
5+software version.
6+ 
7+Two states, and the difference matters:
8+ 
9+- **validated** -- the retained file records a passing correctness result: what
10+ was run, on what target, and to what accuracy. Those records were taken on an
11+ Ascend 950-family A5 target. On another architecture or an unmatched SDK
12+ version, treat the row as a candidate and re-run correctness.
13+- **study** -- the file carries an embedded test but no retained record of it
14+ having passed. Read it for the shape of the implementation; it is not evidence
15+ that the implementation is correct, and it does not confer validation on
16+ anything modelled after it.
17+ 
18+A row may claim `validated` only when its file carries a scoped validation
19+record; `check_kb_integrity.py` enforces that, because the previous blanket
20+claim covered twelve files that had no record at all.
21+ 
22+| topology / technique | dtype | implementation | state | retained evidence |
23+|---|---|---|---|---|
24+| single-tile matmul | fp32 | [examples/samples/matmul_float_mmad/matmul_float_mmad_impl.py](samples/matmul_float_mmad/matmul_float_mmad_impl.py) | validated | file validation record + [golden](samples/matmul_float_mmad/matmul_float_mmad_golden.py) |
25+| transposed-left matmul | fp32 | [examples/samples/matmul_kmkn_fp32_out/matmul_tn_impl.py](samples/matmul_kmkn_fp32_out/matmul_tn_impl.py) | validated | embedded correctness tests |
26+| quantized matmul | fp32→int8 | [examples/samples/matmul_quant_int8/matmul_quant_int8_impl.py](samples/matmul_quant_int8/matmul_quant_int8_impl.py) | study | embedded correctness test |
27+| matmul operand reuse | bf16 | [examples/samples/bf16_matmul_operand_reuse/bf16_matmul_operand_reuse_impl.py](samples/bf16_matmul_operand_reuse/bf16_matmul_operand_reuse_impl.py) | study | embedded correctness test |
28+| cube→vector handoff | fp32 | [examples/samples/fused_matmul_add/fused_matmul_add_impl.py](samples/fused_matmul_add/fused_matmul_add_impl.py) | validated | embedded correctness test |
29+| matmul + bias | fp32 | [examples/samples/matmul_bias/matmul_bias_impl.py](samples/matmul_bias/matmul_bias_impl.py) | study | embedded correctness test |
30+| matmul + bias + activation | fp32 | [examples/samples/matmul_bias_relu/matmul_bias_relu_impl.py](samples/matmul_bias_relu/matmul_bias_relu_impl.py) | study | embedded correctness test |
31+| matmul + activation | fp32 | [examples/samples/matmul_relu/matmul_relu_impl.py](samples/matmul_relu/matmul_relu_impl.py) | study | embedded correctness test |
32+| matmul + row normalization | fp32 | [examples/samples/matmul_rowwise_norm/matmul_rowwise_norm_impl.py](samples/matmul_rowwise_norm/matmul_rowwise_norm_impl.py) | validated | embedded correctness test |
33+| matmul + row L2 normalization | fp32 | [examples/samples/matmul_rowwise_l2_norm/matmul_rowwise_l2_norm_impl.py](samples/matmul_rowwise_l2_norm/matmul_rowwise_l2_norm_impl.py) | study | embedded correctness test |
34+| matmul + row softmax | fp32 | [examples/samples/matmul_softmax/matmul_softmax_impl.py](samples/matmul_softmax/matmul_softmax_impl.py) | validated | embedded correctness test |
35+| cube→vector with atomic output | fp32 | [examples/samples/cube_vec_atomic_add_two_outputs/cube_vec_atomic_add_two_outputs_impl.py](samples/cube_vec_atomic_add_two_outputs/cube_vec_atomic_add_two_outputs_impl.py) | validated | embedded correctness test |
36+| vector→cube handoff | fp32 | [examples/samples/vec_cube_abs_sqrt_matmul/vec_cube_abs_sqrt_matmul_impl.py](samples/vec_cube_abs_sqrt_matmul/vec_cube_abs_sqrt_matmul_impl.py) | validated | embedded correctness test |
37+| row softmax tile ops | fp32 | [examples/samples/softmax/softmax_impl.py](samples/softmax/softmax_impl.py) | validated | file validation record + [golden](samples/softmax/softmax_golden.py) |
38+| row normalization tile ops | fp32 | [examples/samples/norm_softmax_rms_l2/norm_softmax_rms_l2_impl.py](samples/norm_softmax_rms_l2/norm_softmax_rms_l2_impl.py) | validated | embedded correctness tests |
39+| layer normalization tile ops | fp32 | [examples/samples/vector_kernels/layernorm_impl.py](samples/vector_kernels/layernorm_impl.py) | validated | embedded correctness test |
40+| activation + normalization tile ops | fp32 | [examples/samples/vector_kernels/act_layernorm_elementwise_impl.py](samples/vector_kernels/act_layernorm_elementwise_impl.py) | study | embedded correctness tests |
41+| row sum tile ops | fp32 | [examples/samples/vector_kernels/reduce_sum_impl.py](samples/vector_kernels/reduce_sum_impl.py) | validated | embedded correctness test |
42+| interleaved rotary embedding | fp32 | [examples/samples/vector_kernels/rope_interleave_impl.py](samples/vector_kernels/rope_interleave_impl.py) | validated | embedded correctness test |
43+| cumulative sum by contraction | fp32 | [examples/samples/vector_kernels/cumsum_matmul_impl.py](samples/vector_kernels/cumsum_matmul_impl.py) | validated | embedded correctness test |
44+| vector-function elementwise | fp32 | [examples/samples/vf_vs_tileop/vf_elementwise_impl.py](samples/vf_vs_tileop/vf_elementwise_impl.py) | study | embedded correctness test |
45+| vector-function L2 norm + activation | fp32 | [examples/samples/vf_vs_tileop/vf_l2norm_silu_impl.py](samples/vf_vs_tileop/vf_l2norm_silu_impl.py) | study | embedded correctness test |
46+| vector-function layer norm + rotary embedding | fp32 | [examples/samples/vf_vs_tileop/vf_layernorm_rope_impl.py](samples/vf_vs_tileop/vf_layernorm_rope_impl.py) | study | embedded correctness test |
47+| vector-function normalization and reductions | fp32 | [examples/samples/vf_vs_tileop/vf_rms_silu_gelu_reduce_impl.py](samples/vf_vs_tileop/vf_rms_silu_gelu_reduce_impl.py) | study | embedded correctness test |
48+| vector-function row softmax | fp32 | [examples/samples/vf_vs_tileop/vf_softmax_impl.py](samples/vf_vs_tileop/vf_softmax_impl.py) | study | embedded correctness test |
@@ -0,0 +1,117 @@
1+# Copyright (c) Huawei Technologies Co., Ltd. 2024-2026. All rights reserved.
2+"""BF16 matmul that reuses each A tile across the output-column loop.
3+ 
4+Validation evidence is the embedded NPU test below. The kernel is a study
5+reference for operand residency; performance must be re-measured on the target
6+device and shape.
7+"""
8+ 
9+import torch
10+import torch_npu # noqa: F401
11+ 
12+import pypto_pro.language as pl
13+ 
14+ 
15+TILE = 128
16+K = 128
17+ 
18+ 
19+@pl.jit(auto_mutex=True)
20+def bf16_matmul_operand_reuse(
21+ a: pl.Tensor[[pl.DYNAMIC, K], pl.DT_BF16],
22+ b: pl.Tensor[[K, pl.DYNAMIC], pl.DT_BF16],
23+ out: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_BF16],
24+):
25+ num_cores = pl.get_block_num()
26+ core_id = pl.get_block_idx()
27+ 
28+ with pl.section_cube():
29+ a_l1 = pl.make_tile_group(
30+ type=pl.TileType(
31+ shape=[TILE, K],
32+ dtype=pl.DT_BF16,
33+ target_memory=pl.MemorySpace.Mat,
34+ layout=pl.NZ,
35+ ),
36+ addrs=0x00000,
37+ mutex_ids=[0, 1, 10, 11],
38+ )
39+ a_l0a = pl.make_tile_group(
40+ type=pl.TileType(
41+ shape=[TILE, K],
42+ dtype=pl.DT_BF16,
43+ target_memory=pl.MemorySpace.Left,
44+ layout=pl.NZ,
45+ ),
46+ addrs=0x0,
47+ mutex_ids=[2, 5],
48+ )
49+ b_l1 = pl.make_tile_group(
50+ type=pl.TileType(
51+ shape=[K, TILE],
52+ dtype=pl.DT_BF16,
53+ target_memory=pl.MemorySpace.Mat,
54+ layout=pl.NZ,
55+ ),
56+ addrs=0x20000,
57+ mutex_ids=[3, 4, 12, 13],
58+ )
59+ b_l0b = pl.make_tile_group(
60+ type=pl.TileType(
61+ shape=[K, TILE],
62+ dtype=pl.DT_BF16,
63+ target_memory=pl.MemorySpace.Right,
64+ layout=pl.ZN,
65+ ),
66+ addrs=0x0,
67+ mutex_ids=[6, 7],
68+ )
69+ acc = pl.make_tile_group(
70+ type=pl.TileType(
71+ shape=[TILE, TILE],
72+ dtype=pl.DT_FP32,
73+ target_memory=pl.MemorySpace.Acc,
74+ layout=pl.NZ,
75+ fractal=1024,
76+ ),
77+ addrs=0x0,
78+ mutex_ids=[8, 9, 14, 15],
79+ )
80+ 
81+ column_tiles = b.shape[1] // TILE
82+ row_tiles = a.shape[0] // TILE
83+ for row_tile in pl.range(core_id, row_tiles, num_cores):
84+ a_mat = a_l1.next()
85+ pl.load_tile(a_mat, a, [row_tile, 0])
86+ a_left = a_l0a.next()
87+ pl.move(a_left, a_mat)
88+ 
89+ for column_tile in pl.range(0, column_tiles):
90+ b_mat = b_l1.next()
91+ pl.load_tile(b_mat, b, [0, column_tile])
92+ b_right = b_l0b.next()
93+ pl.move(b_right, b_mat)
94+ out_acc = acc.next()
95+ pl.matmul(out_acc, a_left, b_right)
96+ pl.store_tile(out, out_acc, [row_tile, column_tile])
97+ 
98+ 
99+def test_bf16_matmul_operand_reuse():
100+ torch.npu.set_device("npu:0")
101+ if "Ascend950" not in torch.npu.get_device_name():
102+ import pytest
103+ 
104+ pytest.skip("requires an Ascend 950-family target")
105+ 
106+ torch.manual_seed(0)
107+ rows = 128 * TILE
108+ columns = 8 * TILE
109+ a = torch.randn(rows, K, device="npu:0").to(torch.bfloat16)
110+ b = torch.randn(K, columns, device="npu:0").to(torch.bfloat16)
111+ out = torch.empty(rows, columns, device="npu:0", dtype=torch.bfloat16)
112+ 
113+ bf16_matmul_operand_reuse[None, 32](a, b, out)
114+ torch.npu.synchronize()
115+ 
116+ expected = a.float() @ b.float()
117+ torch.testing.assert_close(out.float(), expected, rtol=2e-2, atol=2e-2)
@@ -0,0 +1,88 @@
1+# SAMPLE PROVENANCE -- describes THIS reference implementation only.
2+# Do not copy this header into generated code: a generated kernel inherits
3+# no validation from the sample it was modelled on.
4+# STATUS: VALIDATED on Ascend a5 NPU (2026-07-21) — GATE A PASS, first try.
5+# out_sq maxdiff = 0.000e+00 (bit-exact)
6+# out_acc maxdiff = 0.000e+00 (bit-exact) <- the ATOMIC ADD accumulated correctly
7+# DIAG vs half0=8.316e+02, vs half1=9.793e+02 <- out_acc equals NEITHER half alone,
8+# proving the atomic genuinely SUMMED the two sub-blocks rather than one
9+# overwriting the other. 1 passed in 14.09s.
10+# Kernel P1: cube_vec_atomic_add_two_outputs — pipeline_patterns class.
11+# out_sq = (q@k)^2 (normal store, per sub-block)
12+# out_acc = (q@k)^2[0:32] + [32:64] (ATOMIC ADD from BOTH vector sub-blocks)
13+# Structure = the proven k5/k11 cube->vector handoff (handoff1, DualModeSplitM) + a second
14+# output written with pl.AtomicType.AtomicAdd. The atomic is the new capability under test:
15+# both vector sub-blocks accumulate their own 32-row slab into the SAME [0,0] region, so a
16+# correct result requires the atomic accumulate to serialize the two concurrent writes.
17+# Convention note: siblings compute q@k (not q@k.t()); easyasc golden is x@y.t() — the
18+# transpose convention is already proven separately by k4 (TN). Kept q@k to stay a pure
19+# delta on the proven template.
20+import torch, torch_npu # noqa: F401
21+import pypto_pro.language as pl
22+ 
23+ 
24+@pl.jit()
25+def mm_atomic_two_out(
26+ q: pl.Tensor[[64, 64], pl.DT_FP32],
27+ k: pl.Tensor[[64, 64], pl.DT_FP32],
28+ out_sq: pl.Tensor[[64, 64], pl.DT_FP32],
29+ out_acc: pl.Tensor[[32, 64], pl.DT_FP32],
30+):
31+ mm1_res = pl.make_tile(pl.TileType(shape=[32, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x0000, size=8192)
32+ with pl.section_cube():
33+ tile_mat = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ)
34+ q_mat = pl.make_tile(tile_mat, addr=0x0000, size=16384)
35+ k_mat = pl.make_tile(tile_mat, addr=0x4000, size=16384)
36+ q_left = pl.make_tile(pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ), addr=0x0000, size=16384)
37+ k_right = pl.make_tile(pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Right, layout=pl.ZN), addr=0x0000, size=16384)
38+ tile_c1 = pl.make_tile(pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024), addr=0x0000, size=16384)
39+ pl.load(q_mat, q, [0, 0])
40+ pl.load(k_mat, k, [0, 0])
41+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0)
42+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0)
43+ pl.move(q_left, q_mat)
44+ pl.move(k_right, k_mat)
45+ pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0)
46+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0)
47+ pl.matmul(tile_c1, q_left, k_right)
48+ pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0)
49+ pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0)
50+ pl.move(mm1_res, tile_c1, acc_to_vec_mode=pl.AccToVecMode.DualModeSplitM)
51+ pl.system.set_cross_core(pipe=pl.PipeType.FIX, event_id=0)
52+ with pl.section_vector():
53+ sub_index = pl.get_subblock_idx()
54+ off = sub_index * 32
55+ tile_o = pl.make_tile(pl.TileType(shape=[32, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x8000, size=8192)
56+ pl.system.wait_cross_core(pipe=pl.PipeType.V, event_id=0)
57+ pl.mul(tile_o, mm1_res, mm1_res) # z^2 on this sub-block's 32 rows
58+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=2)
59+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=2)
60+ pl.store(out_sq, tile_o, [off, 0]) # output 1: normal
61+ pl.store(out_acc, tile_o, [0, 0], atomic=pl.AtomicType.AtomicAdd) # output 2: atomic accumulate
62+ 
63+ 
64+def test_cube_vec_atomic_two_out_gateA():
65+ torch.npu.set_device("npu:0")
66+ if "Ascend950" not in torch.npu.get_device_name():
67+ import pytest; pytest.skip("not a5")
68+ torch.manual_seed(0)
69+ q = torch.randn(64, 64, device="npu:0", dtype=torch.float32)
70+ k = torch.randn(64, 64, device="npu:0", dtype=torch.float32)
71+ out_sq = torch.zeros(64, 64, device="npu:0", dtype=torch.float32)
72+ out_acc = torch.zeros(32, 64, device="npu:0", dtype=torch.float32) # atomic accumulates INTO this
73+ mm_atomic_two_out(q, k, out_sq, out_acc); torch.npu.synchronize()
74+ 
75+ mm = q @ k
76+ ref_sq = mm * mm
77+ ref_acc = ref_sq[0:32] + ref_sq[32:64]
78+ d_sq = (out_sq - ref_sq).abs().max().item()
79+ d_acc = (out_acc - ref_acc).abs().max().item()
80+ rel_acc = (d_acc / ref_acc.abs().max().item())
81+ print(f"GATEA cube_vec_atomic out_sq maxdiff={d_sq:.3e}")
82+ print(f"GATEA cube_vec_atomic out_acc maxdiff={d_acc:.3e} rel={rel_acc:.3e}")
83+ # Diagnostic: if the atomic silently overwrote instead of accumulating, out_acc equals
84+ # ONE of the halves rather than their sum. Print both so a failure is self-diagnosing.
85+ print(f"DIAG vs half0={(out_acc - ref_sq[0:32]).abs().max().item():.3e} "
86+ f"vs half1={(out_acc - ref_sq[32:64]).abs().max().item():.3e}")
87+ torch.testing.assert_close(out_sq, ref_sq, rtol=1e-3, atol=1e-3)
88+ torch.testing.assert_close(out_acc, ref_acc, rtol=1e-3, atol=1e-2)
@@ -0,0 +1,82 @@
1+# SAMPLE PROVENANCE -- describes THIS reference implementation only.
2+# Do not copy this header into generated code: a generated kernel inherits
3+# no validation from the sample it was modelled on.
4+# STATUS: VALIDATED on Ascend a5 NPU (2026-07-18) — FUSED cube->vector handoff template.
5+# GATE A: out = q@k + x1, fp32 64x64 -> max_abs_diff=0.000e+00 (bit-exact). PASS.
6+# (Gate B: tiny shape = latency-bound; scale + tile for cube-bound as a separate pass.)
7+# THE FUSED PATTERN (gateway to bias / rowwise-norm / attention — all need this):
8+# section_cube: load->move->matmul-> pl.move(vec, acc, acc_to_vec_mode=DualModeSplitM) [L0C->UB]
9+# -> set_cross_core(FIX, eid). MANUAL sync (NOT auto_mutex): sync_src/sync_dst
10+# with pipes MTE2->MTE1 (load->move), MTE1->M (move->matmul), M->FIX (matmul->Acc-move).
11+# section_vector: sub_index = get_subblock_idx() [2 sub-blocks of 32 rows]; wait_cross_core(V, eid);
12+# pl.add(out, mm_res, x1); store. Sync V->MTE3 (vec->store).
13+# DualModeSplitM splits the Acc M-dim across the 2 vector sub-blocks (64 -> 2x32). Use DualModeSplitN
14+# for the QK handoff in attention (split N). Cloned from repo test_matmul_add_matmul_add.py.
15+# For BIAS (matmul + [1,N] bias): same, but pl.add with a broadcast bias tile (row_expand-style).
16+# For NORM (matmul + rowwise norm): same handoff, then row_max/row_sum/... on the UB tile.
17+# Kernel 5: FUSED matmul + add (cube->vector handoff) — out = q@k + x1, fp32 64x64.
18+# Proves the L0C->UB acc_to_vec_mode handoff + manual pipe sync (gateway to bias/norm/attention).
19+# Cloned from test_matmul_add_matmul_add.py (single matmul + one add). Gate A (correctness) focus.
20+import logging
21+import torch, torch_npu # noqa: F401
22+import pypto_pro.language as pl
23+ 
24+ 
25+@pl.jit()
26+def mm_add(
27+ q: pl.Tensor[[64, 64], pl.DT_FP32],
28+ k: pl.Tensor[[64, 64], pl.DT_FP32],
29+ x1: pl.Tensor[[64, 64], pl.DT_FP32],
30+ out: pl.Tensor[[64, 64], pl.DT_FP32],
31+):
32+ tile_p_vec = pl.TileType(shape=[32, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec)
33+ mm1_res = pl.make_tile(tile_p_vec, addr=0x0000, size=8192)
34+ with pl.section_cube():
35+ tile_mat = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ)
36+ q_mat = pl.make_tile(tile_mat, addr=0x0000, size=16384)
37+ k_mat = pl.make_tile(tile_mat, addr=0x4000, size=16384)
38+ q_left = pl.make_tile(pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ), addr=0x0000, size=16384)
39+ k_right = pl.make_tile(pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Right, layout=pl.ZN), addr=0x0000, size=16384)
40+ tile_c1 = pl.make_tile(pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024), addr=0x0000, size=16384)
41+ pl.load(q_mat, q, [0, 0])
42+ pl.load(k_mat, k, [0, 0])
43+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0)
44+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0)
45+ pl.move(q_left, q_mat)
46+ pl.move(k_right, k_mat)
47+ pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0)
48+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0)
49+ pl.matmul(tile_c1, q_left, k_right)
50+ pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0)
51+ pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0)
52+ pl.move(mm1_res, tile_c1, acc_to_vec_mode=pl.AccToVecMode.DualModeSplitM) # ACC -> UB
53+ pl.system.set_cross_core(pipe=pl.PipeType.FIX, event_id=0)
54+ with pl.section_vector():
55+ sub_index = pl.get_subblock_idx()
56+ tile_x1 = pl.make_tile(pl.TileType(shape=[32, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x4000, size=8192)
57+ tile_out = pl.make_tile(pl.TileType(shape=[32, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x8000, size=8192)
58+ off = sub_index * 32
59+ pl.load(tile_x1, x1, [off, 0])
60+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=1)
61+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=1)
62+ pl.system.wait_cross_core(pipe=pl.PipeType.V, event_id=0)
63+ pl.add(tile_out, mm1_res, tile_x1)
64+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=2)
65+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=2)
66+ pl.store(out, tile_out, [off, 0])
67+ 
68+ 
69+def test_mm_add_gateA():
70+ torch.npu.set_device("npu:0")
71+ if "Ascend950" not in torch.npu.get_device_name():
72+ import pytest; pytest.skip("not a5")
73+ torch.manual_seed(0)
74+ q = torch.randn(64, 64, device="npu:0", dtype=torch.float32)
75+ k = torch.randn(64, 64, device="npu:0", dtype=torch.float32)
76+ x1 = torch.randn(64, 64, device="npu:0", dtype=torch.float32)
77+ out = torch.zeros(64, 64, device="npu:0", dtype=torch.float32)
78+ mm_add(q, k, x1, out); torch.npu.synchronize()
79+ ref = q @ k + x1
80+ d = (out - ref).abs().max().item()
81+ print(f"GATEA mm_add 64x64 maxdiff={d:.3e}")
82+ torch.testing.assert_close(out, ref, rtol=1e-3, atol=1e-3)
@@ -0,0 +1,67 @@
1+# Kernel 9: FUSED matmul + per-column bias — out = q@k + bias, bias [1,64] broadcast across rows, fp32 64x64.
2+# = kernel-5 fused handoff + per-column bias add. There is NO col_expand_add, so (layernorm-beta idiom):
3+# negbias = bias * -1; col_expand_sub(out, mm, negbias) == mm - (-bias) == mm + bias.
4+# twin_of matmul bias/sugar family.
5+import torch, torch_npu # noqa: F401
6+import pypto_pro.language as pl
7+ 
8+ 
9+@pl.jit()
10+def mm_bias(
11+ q: pl.Tensor[[64, 64], pl.DT_FP32],
12+ k: pl.Tensor[[64, 64], pl.DT_FP32],
13+ bias: pl.Tensor[[1, 64], pl.DT_FP32],
14+ out: pl.Tensor[[64, 64], pl.DT_FP32],
15+):
16+ mm1_res = pl.make_tile(pl.TileType(shape=[32, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x0000, size=8192)
17+ with pl.section_cube():
18+ tile_mat = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ)
19+ q_mat = pl.make_tile(tile_mat, addr=0x0000, size=16384)
20+ k_mat = pl.make_tile(tile_mat, addr=0x4000, size=16384)
21+ q_left = pl.make_tile(pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ), addr=0x0000, size=16384)
22+ k_right = pl.make_tile(pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Right, layout=pl.ZN), addr=0x0000, size=16384)
23+ tile_c1 = pl.make_tile(pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024), addr=0x0000, size=16384)
24+ pl.load(q_mat, q, [0, 0])
25+ pl.load(k_mat, k, [0, 0])
26+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0)
27+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0)
28+ pl.move(q_left, q_mat)
29+ pl.move(k_right, k_mat)
30+ pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0)
31+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0)
32+ pl.matmul(tile_c1, q_left, k_right)
33+ pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0)
34+ pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0)
35+ pl.move(mm1_res, tile_c1, acc_to_vec_mode=pl.AccToVecMode.DualModeSplitM)
36+ pl.system.set_cross_core(pipe=pl.PipeType.FIX, event_id=0)
37+ with pl.section_vector():
38+ sub_index = pl.get_subblock_idx()
39+ off = sub_index * 32
40+ bias_t = pl.make_tile(pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x4000, size=512)
41+ negbias = pl.make_tile(pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x4200, size=512)
42+ tile_out = pl.make_tile(pl.TileType(shape=[32, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x8000, size=8192)
43+ pl.load(bias_t, bias, [0, 0]) # [1,64] per-column, same for every row
44+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=1)
45+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=1)
46+ pl.mul(negbias, bias_t, -1.0) # negbias = -bias
47+ pl.system.wait_cross_core(pipe=pl.PipeType.V, event_id=0)
48+ pl.col_expand_sub(tile_out, mm1_res, negbias) # mm1_res - (-bias) == mm1_res + bias (col broadcast)
49+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=2)
50+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=2)
51+ pl.store(out, tile_out, [off, 0])
52+ 
53+ 
54+def test_mm_bias_gateA():
55+ torch.npu.set_device("npu:0")
56+ if "Ascend950" not in torch.npu.get_device_name():
57+ import pytest; pytest.skip("not a5")
58+ torch.manual_seed(0)
59+ q = torch.randn(64, 64, device="npu:0", dtype=torch.float32)
60+ k = torch.randn(64, 64, device="npu:0", dtype=torch.float32)
61+ bias = torch.randn(1, 64, device="npu:0", dtype=torch.float32)
62+ out = torch.zeros(64, 64, device="npu:0", dtype=torch.float32)
63+ mm_bias(q, k, bias, out); torch.npu.synchronize()
64+ ref = q @ k + bias
65+ d = (out - ref).abs().max().item()
66+ print(f"GATEA mm_bias 64x64 maxdiff={d:.3e}")
67+ torch.testing.assert_close(out, ref, rtol=1e-3, atol=1e-3)
@@ -0,0 +1,67 @@
1+# Kernel 13: FUSED matmul + bias + ReLU — out = relu(q@k + bias), the standard Linear+bias+act MLP epilogue.
2+# = k9 (col_expand_sub bias) + k11 (pl.relu) chained in one vector section. Proves multi-op vector epilogue.
3+import torch, torch_npu # noqa: F401
4+import pypto_pro.language as pl
5+ 
6+ 
7+@pl.jit()
8+def mm_bias_relu(
9+ q: pl.Tensor[[64, 64], pl.DT_FP32],
10+ k: pl.Tensor[[64, 64], pl.DT_FP32],
11+ bias: pl.Tensor[[1, 64], pl.DT_FP32],
12+ out: pl.Tensor[[64, 64], pl.DT_FP32],
13+):
14+ mm1_res = pl.make_tile(pl.TileType(shape=[32, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x0000, size=8192)
15+ with pl.section_cube():
16+ tile_mat = pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Mat, layout=pl.NZ)
17+ q_mat = pl.make_tile(tile_mat, addr=0x0000, size=16384)
18+ k_mat = pl.make_tile(tile_mat, addr=0x4000, size=16384)
19+ q_left = pl.make_tile(pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Left, layout=pl.NZ), addr=0x0000, size=16384)
20+ k_right = pl.make_tile(pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Right, layout=pl.ZN), addr=0x0000, size=16384)
21+ tile_c1 = pl.make_tile(pl.TileType(shape=[64, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc, layout=pl.NZ, fractal=1024), addr=0x0000, size=16384)
22+ pl.load(q_mat, q, [0, 0])
23+ pl.load(k_mat, k, [0, 0])
24+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0)
25+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.MTE1, event_id=0)
26+ pl.move(q_left, q_mat)
27+ pl.move(k_right, k_mat)
28+ pl.system.sync_src(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0)
29+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE1, wait_pipe=pl.PipeType.M, event_id=0)
30+ pl.matmul(tile_c1, q_left, k_right)
31+ pl.system.sync_src(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0)
32+ pl.system.sync_dst(set_pipe=pl.PipeType.M, wait_pipe=pl.PipeType.FIX, event_id=0)
33+ pl.move(mm1_res, tile_c1, acc_to_vec_mode=pl.AccToVecMode.DualModeSplitM)
34+ pl.system.set_cross_core(pipe=pl.PipeType.FIX, event_id=0)
35+ with pl.section_vector():
36+ sub_index = pl.get_subblock_idx()
37+ off = sub_index * 32
38+ bias_t = pl.make_tile(pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x4000, size=512)
39+ negbias = pl.make_tile(pl.TileType(shape=[1, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x4200, size=512)
40+ tmp = pl.make_tile(pl.TileType(shape=[32, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x6000, size=8192)
41+ tile_out = pl.make_tile(pl.TileType(shape=[32, 64], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x8000, size=8192)
42+ pl.load(bias_t, bias, [0, 0])
43+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=1)
44+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=1)
45+ pl.mul(negbias, bias_t, -1.0)
46+ pl.system.wait_cross_core(pipe=pl.PipeType.V, event_id=0)
47+ pl.col_expand_sub(tmp, mm1_res, negbias) # q@k + bias
48+ pl.relu(tile_out, tmp) # relu(q@k + bias)
49+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=2)
50+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=2)
51+ pl.store(out, tile_out, [off, 0])
52+ 
53+ 
54+def test_mm_bias_relu_gateA():
55+ torch.npu.set_device("npu:0")
56+ if "Ascend950" not in torch.npu.get_device_name():
57+ import pytest; pytest.skip("not a5")
58+ torch.manual_seed(0)
59+ q = torch.randn(64, 64, device="npu:0", dtype=torch.float32)
60+ k = torch.randn(64, 64, device="npu:0", dtype=torch.float32)
61+ bias = torch.randn(1, 64, device="npu:0", dtype=torch.float32)
62+ out = torch.zeros(64, 64, device="npu:0", dtype=torch.float32)
63+ mm_bias_relu(q, k, bias, out); torch.npu.synchronize()
64+ ref = torch.relu(q @ k + bias)
65+ d = (out - ref).abs().max().item()
66+ print(f"GATEA mm_bias_relu 64x64 maxdiff={d:.3e}")
67+ torch.testing.assert_close(out, ref, rtol=1e-3, atol=1e-3)