Draft
[WIP] docs(kb): Stage-5 verdict taxonomy and env-fault triage #3
hid22900163Add on Aug 17
[WIP] docs(kb): Stage-5 verdict taxonomy and env-fault triage #3
Draft
Total: 121 files changed+25274-765
| @@ -92,3 +92,7 @@ package-lock.json | |||
| 92 | .DS_Store | 92 | .DS_Store |
| 93 | Thumbs.db | 93 | Thumbs.db |
| 94 | msprof_output/ | 94 | msprof_output/ |
| 95 | + | ||
| 96 | +# nested working trees — never part of this repo | ||
| 97 | +worktrees/ | ||
| 98 | +.codex/ | ||
| @@ -6,6 +6,12 @@ | |||
| 6 | <policy name="projectPolicy" desc=""> | 6 | <policy name="projectPolicy" desc=""> |
| 7 | <policyitem type="license" name="CANN-2.0" path=".*" filefilter="defaultFilter" desc="Dynamically linked by module X"/> | 7 | <policyitem type="license" name="CANN-2.0" path=".*" filefilter="defaultFilter" desc="Dynamically linked by module X"/> |
| 8 | </policy> | 8 | </policy> |
| 9 | + <policy name="samplePolicy" desc="Exempt reference samples from code-quality rules that conflict with PyPTO framework constraints"> | ||
| 10 | + <policyitem type="duplicate_code" name="*" path="cannbot-skills/ops/pypto-pro-op-kb/examples/samples/.*" rule="may" group="sampleGroup" filefilter="sampleCodeFilter" desc="Samples are self-contained reference kernels that intentionally repeat standard tiling patterns"/> | ||
| 11 | + <policyitem type="too_many_arguments" name="*" path="cannbot-skills/ops/pypto-pro-op-kb/examples/samples/.*" rule="may" group="sampleGroup" filefilter="sampleCodeFilter" desc="PyPTO kernel ABI requires each tensor operand as an independently typed parameter"/> | ||
| 12 | + <policyitem type="too_long_function" name="*" path="cannbot-skills/ops/pypto-pro-op-kb/examples/samples/.*" rule="may" group="sampleGroup" filefilter="sampleCodeFilter" desc="PyPTO requires the complete tile-memory plan in one compiled kernel body"/> | ||
| 13 | + <policyitem type="too_deep_function" name="*" path="cannbot-skills/ops/pypto-pro-op-kb/examples/samples/.*" rule="may" group="sampleGroup" filefilter="sampleCodeFilter" desc="NPU test functions require device-gate + skip + assert nesting"/> | ||
| 14 | + </policy> | ||
| 9 | </policylist> | 15 | </policylist> |
| 10 | <filefilterlist> | 16 | <filefilterlist> |
| 11 | <filefilter name="defaultFilter" desc="files not to check"> | 17 | <filefilter name="defaultFilter" desc="files not to check"> |
| @@ -15,6 +21,9 @@ | |||
| 15 | name="framework/tests/st/distributed/ops/test_case/.*.csv" | 21 | name="framework/tests/st/distributed/ops/test_case/.*.csv" |
| 16 | desc="ST distributed ops test case cvs files, no license header required"/> | 22 | desc="ST distributed ops test case cvs files, no license header required"/> |
| 17 | </filefilter> | 23 | </filefilter> |
| 24 | + <filefilter name="sampleCodeFilter" desc="Reference sample files: self-contained kernel patterns where duplication and length are inherent to the PyPTO programming model"> | ||
| 25 | + <filteritem type="filepath" name="cannbot-skills/ops/pypto-pro-op-kb/examples/samples/.*" desc="PyPTO reference implementations — each file is a self-contained kernel pattern that intentionally repeats the standard tiling handoff sequence"/> | ||
| 26 | + </filefilter> | ||
| 18 | </filefilterlist> | 27 | </filefilterlist> |
| 19 | <licensematcherlist> | 28 | <licensematcherlist> |
| 20 | <licensematcher name="cann License - 2026" desc="If the scanning result is InvalidLicense, you can define matching rules here. Note that quotation marks must be escaped."> | 29 | <licensematcher name="cann License - 2026" desc="If the scanning result is InvalidLicense, you can define matching rules here. Note that quotation marks must be escaped."> |
| @@ -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 | ||
| @@ -48,7 +48,7 @@ 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 | ||
| @@ -89,7 +89,7 @@ cannbot-skills/ | |||
| 89 | ├── model/ # 模型适配与推理优化 Skills | 89 | ├── 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,314 @@ | |||
| 1 | +--- | ||
| 2 | +name: pypto-pl-cube-bound | ||
| 3 | +description: 把任意 pl tile-DSL matmul 类 kernel 调到 CUBE-BOUND(aic_mac_ratio > 0.80),适用于任意 M/N/K、任意操作数 dtype、任意核数。提供由实测片上容量推导的 sizing 流程(tile 形状、K 分块与多缓冲份数)、pipe 代价模型、生产者/消费者缓冲纪律、瓶颈到杠杆的路由表,以及防止错误结论的测量规则。当 matmul 或 conv-as-GEMM kernel 必须是计算瓶颈、profiling 显示 mte2/fixpipe/scalar 占优、或某个「cube-bound」结论需要验证时加载。触发词:cube-bound、算子性能调优、Gate B、计算瓶颈、mte2 瓶颈、tiling 选择、多缓冲、bf16/fp16/int8 性能优化。 | ||
| 4 | +--- | ||
| 5 | + | ||
| 6 | +# Driving a `pl` matmul kernel to CUBE-BOUND on a5 | ||
| 7 | + | ||
| 8 | +**本技能做什么**:把 matmul 类 kernel 推到 cube 计算瓶颈。§2 是 sizing 推导流程(`scripts/sizing.py` | ||
| 9 | +可直接算出配置),§3–§6 是 pipe 代价模型、缓冲纪律与瓶颈路由表,§7 隔离硬件常量。判定口径只有一个: | ||
| 10 | +`aic_mac_ratio` > 0.80。正文为英文,术语与 API 名保持原文。 | ||
| 11 | + | ||
| 12 | +> **Note on referenced material.** Sample citations below — and the reproducer paths in | ||
| 13 | +> `references/sizing-examples.md` — resolve into the governed knowledge base at `pypto-pro-op-kb/`. | ||
| 14 | +> Where that tree retains a matching implementation the citation names it; where it does not, the | ||
| 15 | +> citation names the constraint or record page that carries the surviving rule. The cross-cutting | ||
| 16 | +> trap index is `pypto-pro-op-kb/references/pitfall-records.md`. | ||
| 17 | + | ||
| 18 | +**Scope.** Any matmul-shaped kernel on a5 — plain GEMM, fused-epilogue GEMM, and conv-as-GEMM | ||
| 19 | +(conv lowers to a GEMM; see the conv twins). Any M/N/K, any operand dtype, any core count. | ||
| 20 | +Hardware constants are isolated in §7, so only that section changes on new silicon. | ||
| 21 | + | ||
| 22 | +**Companion tool:** `scripts/sizing.py` implements §2 — run it to get a config for your | ||
| 23 | +shape. `references/sizing-examples.md` holds worked outputs. All figures are measured on a real Ascend950 | ||
| 24 | +(2026-07-21). The measurement harness those figures came from is **not retained in this KB**; the one | ||
| 25 | +kernel that is retained is `pypto-pro-op-kb/examples/samples/bf16_matmul_operand_reuse/bf16_matmul_operand_reuse_impl.py`, | ||
| 26 | +an operand-residency study with an embedded correctness test — it demonstrates the reuse topology, not | ||
| 27 | +the numbers below. | ||
| 28 | + | ||
| 29 | +--- | ||
| 30 | + | ||
| 31 | +## 0. The verdict rule — read before measuring anything | ||
| 32 | + | ||
| 33 | +**CUBE-BOUND ⇔ `aic_mac_ratio` > 0.80.** Being the *top* sub-ratio is necessary but **not** | ||
| 34 | +sufficient — a kernel can lead on mac at 0.50 and still leave the cube half idle. Always report the | ||
| 35 | +number. Compare all five: `aic_mac_ratio`, `aic_scalar_ratio`, `aic_mte1_ratio`, `aic_mte2_ratio`, | ||
| 36 | +`aic_fixpipe_ratio`. | ||
| 37 | + | ||
| 38 | +- **`cube_utilization(%)` is NOT the verdict and is actively misleading.** Measured configs read | ||
| 39 | + **88–92%** while solidly **mte2-bound** (`mte2=0.98` vs `mac=0.21`). Never cite it as evidence. | ||
| 40 | +- **Never omit `aic_scalar_ratio`.** It reached **0.235, above mac's 0.129** at T=128/K=32. A filter | ||
| 41 | + covering only mac/mte1/mte2/fixpipe will mis-name the bottleneck. | ||
| 42 | +- **Report `mac_ratio` AND throughput** (`MMAC/µs = M·N·K / aicore_time`). They answer different | ||
| 43 | + questions and can move in opposite directions: bf16 vs fp32 at identical shape gives mac 0.181 vs | ||
| 44 | + 0.689 (bf16 far worse) but 23.1 vs 8.5 MMAC/µs (bf16 **2.7× faster**). Optimising `mac_ratio` | ||
| 45 | + alone can make a kernel slower. | ||
| 46 | +- **A kernel that fails Gate A has no Gate B.** Assert correctness, then profile. | ||
| 47 | +- **`aicore_time` is the AIC (cube unit) busy time**, not wall-clock (`Duration(us)` is larger and | ||
| 48 | + includes launch/dispatch). `aiv_time` is the vector engine. Every `aic_*_ratio` is normalised by | ||
| 49 | + `aicore_time`, so **ratios are comparable across shapes; absolute times are not.** | ||
| 50 | + | ||
| 51 | +--- | ||
| 52 | + | ||
| 53 | +## 1. The cost model | ||
| 54 | + | ||
| 55 | +Per output tile `[T,T]`, contraction depth `K`, operand bytes `bi`, output bytes `bo`, fp32 | ||
| 56 | +accumulator: | ||
| 57 | + | ||
| 58 | +| pipe | work per output tile | scales as | | ||
| 59 | +|---|---|---| | ||
| 60 | +| MAC | `T·T·K` | `T²K` | | ||
| 61 | +| MTE2 (GM→L1) | `(T·K + K·T)·bi` | `2·bi·KT` | | ||
| 62 | +| MTE1 (L1→L0) | same bytes, on-chip | `2·bi·KT` | | ||
| 63 | +| FIXPIPE (L0C→GM) | `T·T·bo` | `bo·T²` | | ||
| 64 | + | ||
| 65 | +``` | ||
| 66 | +MAC / fixpipe ∝ K / bo → raise K, or narrow the OUTPUT dtype, to beat FIXPIPE | ||
| 67 | +MAC / mte2 ∝ T / bi → raise T, or narrow the OPERAND dtype, to beat MTE2 (K cancels!) | ||
| 68 | +``` | ||
| 69 | + | ||
| 70 | +**The K-cancellation is the load-bearing insight:** raising K does nothing for mte2, because | ||
| 71 | +operand traffic grows with K exactly as fast as MAC work does. Confirmed across a 16-point sweep — | ||
| 72 | +at T=16, mte2 stayed 0.92→0.98 as K went 32→256, while fixpipe fell 0.571→0.333. | ||
| 73 | + | ||
| 74 | +**Corollary that decides most tuning:** to flip a verdict you must change a **ratio**, not remove | ||
| 75 | +time. Removing a pipe's *time* (e.g. K-accumulation removing fixpipe work) shrinks `aicore_time` | ||
| 76 | +and lifts mac **and** its competitor proportionally — the ratio is unchanged. | ||
| 77 | + | ||
| 78 | +--- | ||
| 79 | + | ||
| 80 | +## 2. THE SIZING PROCEDURE — derive tiling and buffers for your shape | ||
| 81 | + | ||
| 82 | +> **The inversion that matters:** buffer counts are **requirements, not leftovers**. Size `T` and | ||
| 83 | +> `K_blk` so the *required* multi-buffering fits — do not maximise `T`/`K` and then accept whatever | ||
| 84 | +> buffering is left over. Getting this backwards capped an earlier attempt at mac 0.58; applying it | ||
| 85 | +> correctly reached **0.870**. | ||
| 86 | + | ||
| 87 | +**Required multi-buffering** — each removes a specific stall (§4): | ||
| 88 | + | ||
| 89 | +| buffer | min | why | | ||
| 90 | +|---|---|---| | ||
| 91 | +| `acc` (L0C) | **2** (4 better) | else FIXPIPE drain blocks the next MAC | | ||
| 92 | +| `b_l0b` (L0B) | **2** | else MAC blocks the MTE1 refill | | ||
| 93 | +| `a_l0a` (L0A) | **2** | else row i+1's A move **races** row i's matmuls → *wrong results* | | ||
| 94 | +| `b_l1` (L1) | 2–4 | else MTE1 blocks the next GM load | | ||
| 95 | +| `a_l1` (L1) | 2 | only useful once there are ≥2 row-blocks/core | | ||
| 96 | + | ||
| 97 | +**Three constraints** (`bi` = operand bytes, `CORES` = core count, caps from §7): | ||
| 98 | + | ||
| 99 | +``` | ||
| 100 | +(1) T ≤ sqrt( L0C / (4 · acc_buf) ) # fp32 accumulator | ||
| 101 | +(2) K_blk ≤ L0A / (T · bi · a_l0a_buf) # L0B gives the same bound | ||
| 102 | +(3) M ≥ rows_target · T · CORES # rows_target >= 2, ideally 4 | ||
| 103 | +``` | ||
| 104 | +Round `T` and `K_blk` down to powers of two, ≥ the 16-element fractal. | ||
| 105 | + | ||
| 106 | +**Worked derivation — bf16 on a5** (`L0C`=256 KB, `L0A`=64 KB, 32 cores): | ||
| 107 | +- (1) with `acc_buf=4`: `T ≤ sqrt(262144/16) = 128` ⇒ **T = 128** | ||
| 108 | +- (2) `K_blk ≤ 65536/(128·2·2) = 128` ⇒ **K_blk = 128** | ||
| 109 | +- (3) with `rows_target=4`: `M ≥ 4·128·32 = 16384` ⇒ **4 row-blocks/core** | ||
| 110 | + | ||
| 111 | +That is **exactly the measured optimum** (mac 0.870, 179.9 MMAC/µs) — derived, not tuned. | ||
| 112 | + | ||
| 113 | +**Same procedure, other dtypes** (via `scripts/sizing.py`): | ||
| 114 | + | ||
| 115 | +| operands | `bi` | T | `K_blk` | note | | ||
| 116 | +|---|---|---|---|---| | ||
| 117 | +| bf16 / fp16 | 2 | 128 | **128** | the validated point | | ||
| 118 | +| fp32 | 4 | 128 | **64** | wider operands ⇒ shallower K | | ||
| 119 | +| int8 | 1 | 128 | **256** | narrower operands ⇒ deeper K | | ||
| 120 | + | ||
| 121 | +⇒ **`K_blk` is inversely proportional to operand width. Never carry a K over from another dtype.** | ||
| 122 | + | ||
| 123 | +Note (1) also explains why large T backfires: at T=256 the accumulator tile *is* 256 KB, so only | ||
| 124 | +**one** `acc` buffer fits — no MAC↔FIXPIPE overlap. Measured T=256 peaked at mac 0.485. | ||
| 125 | + | ||
| 126 | +--- | ||
| 127 | + | ||
| 128 | +## 3. Kernel skeleton (shape-independent) | ||
| 129 | + | ||
| 130 | +```python | ||
| 131 | +@pl.jit(auto_mutex=True) | ||
| 132 | +def gemm(a, b, out): # A[M,K] @ B[K,N] -> out[M,N] | ||
| 133 | + nc, cid = pl.get_block_num(), pl.get_block_idx() | ||
| 134 | + with pl.section_cube(): | ||
| 135 | + a_l1 = pl.make_tile_group(type=TT([T, KB], DT_IN, Mat, NZ), addrs=A_L1, mutex_ids=[...]) | ||
| 136 | + a_l0a = pl.make_tile_group(type=TT([T, KB], DT_IN, Left, NZ), addrs=0x0, mutex_ids=[..,..]) | ||
| 137 | + b_l1 = pl.make_tile_group(type=TT([KB, T], DT_IN, Mat, NZ), addrs=B_L1, mutex_ids=[...]) | ||
| 138 | + b_l0b = pl.make_tile_group(type=TT([KB, T], DT_IN, Right, ZN), addrs=0x0, mutex_ids=[..,..]) | ||
| 139 | + acc = pl.make_tile_group(type=TT([T, T], DT_FP32, Acc, NZ, fractal=1024), addrs=0x0, mutex_ids=[...]) | ||
| 140 | + nt_n, n_rows = b.shape[1] // T, a.shape[0] // T | ||
| 141 | + for i in pl.range(cid, n_rows, nc): # each core owns whole ROW-BLOCKS | ||
| 142 | + ca = a_l1.next(); pl.load_tile(ca, a, [i, 0]) # ONE GM load of A per row-block | ||
| 143 | + al = a_l0a.next(); pl.move(al, ca) # HOISTED: A is read-only below | ||
| 144 | + for j in pl.range(0, nt_n): | ||
| 145 | + cb = b_l1.next(); pl.load_tile(cb, b, [0, j]) # only B streams from GM | ||
| 146 | + br = b_l0b.next(); pl.move(br, cb) | ||
| 147 | + ac = acc.next() | ||
| 148 | + pl.matmul(ac, al, br) | ||
| 149 | + pl.store_tile(out, ac, [i, j]) | ||
| 150 | +``` | ||
| 151 | + | ||
| 152 | +Three structural rules, all shape-independent: | ||
| 153 | +1. **`.next()` for streaming operands; `.current()` only to re-read a resident one.** `.current()` | ||
| 154 | + does NOT advance the rotation (§9). | ||
| 155 | +2. **Row-block decomposition with the reused operand resident** — this is what buys operand reuse. | ||
| 156 | +3. **Hoist the resident operand's L1→L0 move out of the inner loop** (measured mte1 −41%). | ||
| 157 | + | ||
| 158 | +--- | ||
| 159 | + | ||
| 160 | +## 4. Pipeline discipline — who blocks whom | ||
| 161 | + | ||
| 162 | +``` | ||
| 163 | +MTE2 MTE1 MAC FIXPIPE | ||
| 164 | +GM ---> L1 ------> L0A/L0B ---------> L0C ---------------> GM | ||
| 165 | + ^ b_l1 ^ b_l0b ^ acc | ||
| 166 | +``` | ||
| 167 | +Each stage's **output** buffer must be multi-buffered **and** accessed with `.next()`: | ||
| 168 | + | ||
| 169 | +- `b_l1` ×1 ⇒ MTE1 blocks MTE2 · `b_l0b` ×1 ⇒ **MAC blocks MTE1** · `acc` ×1 ⇒ **FIXPIPE blocks MAC** | ||
| 170 | +- `a_l0a` ×1 ⇒ once the outer loop pipelines, row i+1's move **races** row i's matmuls — a | ||
| 171 | + **correctness** failure (measured `rel=1.045`), not merely a stall. | ||
| 172 | + | ||
| 173 | +**A buffer needs multi-buffering only if it is WRITTEN every iteration.** A reused operand needs | ||
| 174 | +residency; a second buffer there steals capacity that a streaming operand needs. | ||
| 175 | + | ||
| 176 | +**Standing rule: prefer the `K_blk` that lets EVERY stage rotate over the K that maximises | ||
| 177 | +per-matmul MAC work.** Pipeline occupancy beats arithmetic density — measured, K=128 fully rotating | ||
| 178 | +(mac 0.870) beats K=256 with single-buffered L0A/L0B (mac 0.716). | ||
| 179 | + | ||
| 180 | +--- | ||
| 181 | + | ||
| 182 | +## 5. Bottleneck → lever routing | ||
| 183 | + | ||
| 184 | +Profile with `AiCMetrics.PipeUtilization` → `kernel_details.csv` (harness | ||
| 185 | +`python/tests/ut/block/frontend/a5/profilling/test_profiling.py:50-125`), take the top AIC | ||
| 186 | +sub-ratio, then: | ||
| 187 | + | ||
| 188 | +| top pipe | meaning | lever | | ||
| 189 | +|---|---|---| | ||
| 190 | +| `mte2` | GM operand traffic | raise `T`; **operand reuse** (the only lever that changes mac:mte2); narrower operand dtype | | ||
| 191 | +| `fixpipe` | accumulator drain | raise `K_blk`; **narrower output dtype** (bf16 out halved it); K-accumulation (§6) | | ||
| 192 | +| `mte1` | L1→L0 movement | hoist the resident operand's move; check NZ/ZN layouts aren't forcing a transpose branch | | ||
| 193 | +| `scalar` | loop / instruction overhead | fewer, larger iterations — but this fights rows-per-core, so it is a trade | | ||
| 194 | +| `mac` **> 0.80** | done | ✅ | | ||
| 195 | +| `mac` top but **< 0.80** | no single pipe dominates | you are schedule-limited: fix buffering (§4) before touching traffic | | ||
| 196 | + | ||
| 197 | +**Before optimising a pipe, confirm it is on the critical path:** cut it and check `aicore_time` | ||
| 198 | +actually falls. A ratio measures **occupancy, not causality** — a 2D core grid cut mte2 by 40% and | ||
| 199 | +made the kernel *slower*, because mte2 was already overlapped (§6). | ||
| 200 | + | ||
| 201 | +--- | ||
| 202 | + | ||
| 203 | +## 6. When the standard recipe does not apply | ||
| 204 | + | ||
| 205 | +| situation | symptom | what to do | | ||
| 206 | +|---|---|---| | ||
| 207 | +| **M < 2·T·CORES** | `a_l1` rotation dead; A load is a serial prologue | lower `T`, use fewer cores, or accept lower mac — cube-bound may be unreachable | | ||
| 208 | +| **N/T small** (few columns) | A-reuse amortises over few tiles | if `M/T ≫ N/T`, **swap roles**: make B resident, stream A | | ||
| 209 | +| **K_total > K_blk** | K does not fit on-chip | K-loop, `Partial` until the last `Final`. ⚠️ this did **not** compose with a *rotating* `acc` (fault **507014**) — use `conv_half_large`/C5's non-rotating-acc discipline | | ||
| 210 | +| **M or N not divisible by T** | tail tiles | `valid_shape` / `set_validshape` | | ||
| 211 | +| **tiny shapes** (Gate-A sizes) | latency-bound; nothing can be cube-bound | measure Gate A at the small shape, Gate B at a scaled one | | ||
| 212 | +| **fused epilogue** | vector work after the matmul | prefer the fixpipe path (`relu_pre_mode`, `pre_quant_scalar`) — `aiv=0`, no L0C→UB handoff | | ||
| 213 | + | ||
| 214 | +**Does NOT work:** K-accumulation cannot flip a verdict — it removes *fixpipe time*, shrinking | ||
| 215 | +`aicore_time` and lifting mac **and** mte2 proportionally. Use it to reclaim wall-clock, never to | ||
| 216 | +change the bound. | ||
| 217 | + | ||
| 218 | +--- | ||
| 219 | + | ||
| 220 | +## 7. Hardware constants (a5, MEASURED — the only section to re-derive on new silicon) | ||
| 221 | + | ||
| 222 | +| resource | value | evidence | | ||
| 223 | +|---|---|---| | ||
| 224 | +| **L0A / L0B** | **64 KB each** | T=256,K=256 (128 KB tile) → fault **507015** | | ||
| 225 | +| **L0C (Acc)** | **≥ 256 KB** | T=256 fp32 acc (256 KB, ×1) allocated **and golden-checked** — docs said 128 KB | | ||
| 226 | +| **L1** | ≥ 256 KB | 8K template uses 256 KB; 384 KB configs also ran | | ||
| 227 | +| UB | ~256 KB | earlier probe (253 KB ok, 259 KB faults) | | ||
| 228 | +| MAC rate | fp16/**bf16 = 4096**/cycle/core ("Default"); **fp32 = 2048** (0.5×); int8 8192; int4 16384 | re-derive per runtime from the platform files named by the evidence gate in `../pypto-pro-op-perf-tune/references/a5-roofline-and-levers.md` §Evidence gate | | ||
| 229 | +| peak check | 206.7 TMAC/s while MAC busy ⇒ ≈1.58 GHz at 4096×32 | measured on the final kernel | | ||
| 230 | +| GM-facing BW | MTE2 & FIXPIPE plateau at **3.4–4.3 TB/s**; MTE1 (on-chip) 7.5–11.4 TB/s | measured 2026-07-21; the per-pipe write-up is not part of this tree — re-measure before relying on it | | ||
| 231 | + | ||
| 232 | +**Binding tile constraint:** `T · K_blk · bi · buffers ≤ 64 KB` (L0A/L0B); with the mandatory ×2 | ||
| 233 | +that is `T · K_blk · bi ≤ 32768`. | ||
| 234 | + | ||
| 235 | +**Dtype caution:** fp32 runs the cube at half MAC rate, so a kernel is MAC-heavy *by construction* | ||
| 236 | +and "cube-bound in fp32" is a much weaker claim than it looks. **Always re-verify at the dtype you | ||
| 237 | +deploy.** Same kernel and tiling: fp32 → mac 0.689; bf16 → mac 0.181 (yet 2.7× faster). | ||
| 238 | + | ||
| 239 | +--- | ||
| 240 | + | ||
| 241 | +## 8. Worked example — the full measured ladder (bf16, T=128, 32 cores) | ||
| 242 | + | ||
| 243 | +⚠️ **Rows are different problem sizes, so `aicore_time` is NOT comparable across them.** Normalise | ||
| 244 | +to MMAC/µs. (Row 0 does 1/16 the MACs of the last rows, hence its small `aicore_time`.) | ||
| 245 | + | ||
| 246 | +| # | lever | M×N×K | mac | mte2 | fix | MMAC/µs | | ||
| 247 | +|---|---|---|---|---|---|---| | ||
| 248 | +| 0 | naive tiled | 1024×1024×64 | 0.181 | 0.389 | 0.417 | 23.1 | | ||
| 249 | +| 1 | T=128, K=256 (sweep best) | 1024×1024×256 | 0.320 | 0.520 | 0.231 | 57.1 | | ||
| 250 | +| 2 | + A-reuse | 4096×1024×256 | 0.499 | 0.443 | 0.340 | 91.5 | | ||
| 251 | +| 3 | + hoist A→L0A move | 4096×1024×256 | 0.489 | 0.451 | 0.343 | 91.5 | | ||
| 252 | +| 4 | + bf16 output | 4096×1024×256 | 0.568 | 0.517 | 0.238 | 104.9 | | ||
| 253 | +| 5 | + **`.next()`** rotation | 4096×1024×256 | 0.618 | 0.472 | 0.282 | 115.8 | | ||
| 254 | +| 6 | + 2 row-blocks/core | 8192×1024×256 | 0.669 | 0.551 | 0.291 | 126.7 | | ||
| 255 | +| 7 | + **K=128** (all stages rotate), 4 rows/core | 16384×1024×128 | 0.849 | 0.787 | 0.756 | 162.8 | | ||
| 256 | +| 8 | + `acc`×4 | 16384×1024×128 | **0.870** | 0.816 | 0.829 | **179.9** | | ||
| 257 | + | ||
| 258 | +**End to end: mac ×4.8, throughput ×7.8.** That decomposes into ×4.8 more cube-busy time and ×1.6 | ||
| 259 | +higher MACs-per-busy-µs (escaping fractal underfill at tiny K, plus better operand staging). | ||
| 260 | + | ||
| 261 | +--- | ||
| 262 | + | ||
| 263 | +## 9. Traps that produced WRONG conclusions here | ||
| 264 | + | ||
| 265 | +- **`.current()` does not advance a tile group — `.next()` does.** Declaring `mutex_ids=[a,b]` and | ||
| 266 | + then calling `.current()` gives ZERO rotation: single-buffered while paying the capacity. This | ||
| 267 | + silently invalidated three conclusions ("0.80 is unreachable", "mte2 is bandwidth-bound", | ||
| 268 | + "K=128 is worse than K=256"). **Diagnostic: if adding a buffer moves performance <2%, suspect | ||
| 269 | + inert rotation before blaming the pipe.** | ||
| 270 | +- **Before declaring a hardware ceiling, verify the optimisation is ACTIVE.** A lever that "should" | ||
| 271 | + work and measures ~0 is more often un-plumbed than ineffective. | ||
| 272 | +- **A high sub-ratio ≠ that pipe is the bottleneck.** The 2D core grid cut mte2 by 40% and lost 6% | ||
| 273 | + throughput — mte2 was already overlapped with MAC. | ||
| 274 | +- **Utilisation is a RATIO** — it rises when a pipe does more work *or* when the kernel gets faster. | ||
| 275 | + Fixpipe 29.1% → 82.9% was ~half "2× the bytes" and ~half "0.70× the time", at **constant** | ||
| 276 | + 3.4 TB/s. Check achieved bandwidth before calling it a regression. | ||
| 277 | +- **Never compare `aicore_time` across shapes.** Normalise to MMAC/µs. | ||
| 278 | + | ||
| 279 | +--- | ||
| 280 | + | ||
| 281 | +## 10. Operational pitfalls | ||
| 282 | + | ||
| 283 | +- **Copy the proven tiled template verbatim** (`a5/matmul/test_matmul_8K_example.py`). Hand-rolling | ||
| 284 | + it with `@pl.jit()` + `make_tile` + manual sync **device-faulted 507015**; the verbatim | ||
| 285 | + `auto_mutex` + `make_tile_group` copy ran bit-exact. | ||
| 286 | +- **Shared box: diagnose contention before debugging your kernel.** Triage order: `MARK:` prints | ||
| 287 | + per phase (a stall before "device ok" means device acquisition, not your kernel) → run the repo's | ||
| 288 | + own `test_matmul_api_basic.py::test_t01` (if that hangs too, it isn't you) → `fuser -v | ||
| 289 | + /dev/davinci*` then `ps -o pid,lstart,user,cmd -p <pid>`. **`npu-smi info` reports `OK` even when | ||
| 290 | + saturated — that is health, not availability.** When contended, stop issuing work; never reset the | ||
| 291 | + device or kill other users' processes. | ||
| 292 | +- **Never pipe a remote run through `tail`** — it buffers until exit, making a hang and a slow | ||
| 293 | + compile indistinguishable. Stream to a log and tail that instead. | ||
| 294 | +- **Check budgets before emitting a config** (§2/§7) — a generator that filters on them avoids | ||
| 295 | + burning box runs on configs that cannot fit. | ||
| 296 | + | ||
| 297 | +--- | ||
| 298 | + | ||
| 299 | +## 11. Reference data | ||
| 300 | + | ||
| 301 | +**Inverse skill:** to deliberately drive MTE2/FIXPIPE/MTE1 to its limit (roofline / | ||
| 302 | +microbenchmark), see `pypto-pl-pipe-roofline` — same cost model, opposite goal. | ||
| 303 | + | ||
| 304 | + | ||
| 305 | +- `scripts/sizing.py` — implements §2; `references/sizing-examples.md` for worked outputs. | ||
| 306 | +- `pypto-pro-op-kb/examples/samples/bf16_matmul_operand_reuse/bf16_matmul_operand_reuse_impl.py` — the | ||
| 307 | + one retained artifact of the operand-residency work: a bf16 matmul that reuses each A tile across the | ||
| 308 | + output-column loop, with an embedded NPU correctness test. The sweep harness, the per-shape testcase | ||
| 309 | + registry, the per-pipe bandwidth analysis and the negative results (2-D grid, L0B buffering A/B) that | ||
| 310 | + produced §§4–6 are **not retained in this KB**; §§4–6 are the surviving record of them, and any figure | ||
| 311 | + quoted from them must be re-measured before it is relied on. | ||
| 312 | +- `pypto-pro-op-kb/constraints/precision.md` — the dtype and cast rules the fp32-versus-bf16 comparison | ||
| 313 | + in §4 turns on. It carries the rules, not the profiler output; no raw CSV is retained. | ||
| 314 | +- `pypto-pro-op-kb/references/pitfall-records.md` — the same traps in cross-cutting form. | ||
| @@ -0,0 +1,61 @@ | |||
| 1 | +# Worked outputs of `scripts/sizing.py` | ||
| 2 | + | ||
| 3 | +Raw output of the §2 sizing procedure, kept so a reader can check the derivation against a known | ||
| 4 | +answer before trusting it on a new shape. Regenerate with `python3 scripts/sizing.py`. | ||
| 5 | + | ||
| 6 | +## Validation — does the procedure reproduce the measured optimum? | ||
| 7 | + | ||
| 8 | +Measured best on Ascend950, 32 cores: `M=16384 N=1024 K=128` bf16, actual `T=128 K=128 4rows, | ||
| 9 | +mac 0.870`. | ||
| 10 | + | ||
| 11 | +``` | ||
| 12 | +### MEASURED BEST: M=16384 N=1024 K=128 bf16, 32 cores (actual: T=128 K=128 4rows, mac 0.870) | ||
| 13 | + -> T=128 K_blk=128 rows/core=4.00 cols=8 fits=True | ||
| 14 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 15 | + on-chip: L0A 64KB/64KB L0B 64KB/64KB L0C 256KB/256KB L1 192KB/256KB | ||
| 16 | +``` | ||
| 17 | + | ||
| 18 | +The derived config is the measured optimum — derived, not tuned. | ||
| 19 | + | ||
| 20 | +## Generalisation — other shapes and dtypes | ||
| 21 | + | ||
| 22 | +``` | ||
| 23 | +### fp32 operands, square | ||
| 24 | + -> T=128 K_blk=64 rows/core=4.00 cols=32 fits=True | ||
| 25 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 26 | + on-chip: L0A 64KB/64KB L0B 64KB/64KB L0C 256KB/256KB L1 192KB/256KB | ||
| 27 | + ! K_total=1024 > K_blk=64: needs a K-loop with Partial/Final accumulation. CAUTION: that did NOT compose with a rotating (.next()) acc here (fault 507014); use conv_half_large's non-rotating-acc discipline. | ||
| 28 | + | ||
| 29 | +### int8 operands | ||
| 30 | + -> T=128 K_blk=256 rows/core=4.00 cols=32 fits=True | ||
| 31 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 32 | + on-chip: L0A 64KB/64KB L0B 64KB/64KB L0C 256KB/256KB L1 192KB/256KB | ||
| 33 | + ! K_total=1024 > K_blk=256: needs a K-loop with Partial/Final accumulation. CAUTION: that did NOT compose with a rotating (.next()) acc here (fault 507014); use conv_half_large's non-rotating-acc discipline. | ||
| 34 | + | ||
| 35 | +### tall-skinny (N small) | ||
| 36 | + -> T=128 K_blk=128 rows/core=16.00 cols=2 fits=True | ||
| 37 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 38 | + on-chip: L0A 64KB/64KB L0B 64KB/64KB L0C 256KB/256KB L1 192KB/256KB | ||
| 39 | + ! N/T=2 is small: A-reuse amortises over few columns. If M/T >> N/T, swap roles (make B resident, stream A). | ||
| 40 | + ! K_total=256 > K_blk=128: needs a K-loop with Partial/Final accumulation. CAUTION: that did NOT compose with a rotating (.next()) acc here (fault 507014); use conv_half_large's non-rotating-acc discipline. | ||
| 41 | + | ||
| 42 | +### short-fat (M small) | ||
| 43 | + -> T=128 K_blk=128 rows/core=0.12 cols=128 fits=True | ||
| 44 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 45 | + on-chip: L0A 64KB/64KB L0B 64KB/64KB L0C 256KB/256KB L1 192KB/256KB | ||
| 46 | + ! M too small for >=2 row-blocks/core: a_l1 rotation is DEAD and the A load is a serial prologue. Reduce T, use fewer cores, or expect lower mac. | ||
| 47 | + ! K_total=256 > K_blk=128: needs a K-loop with Partial/Final accumulation. CAUTION: that did NOT compose with a rotating (.next()) acc here (fault 507014); use conv_half_large's non-rotating-acc discipline. | ||
| 48 | + | ||
| 49 | +### deep K (needs K-loop) | ||
| 50 | + -> T=128 K_blk=128 rows/core=2.00 cols=64 fits=True | ||
| 51 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 52 | + on-chip: L0A 64KB/64KB L0B 64KB/64KB L0C 256KB/256KB L1 192KB/256KB | ||
| 53 | + ! K_total=4096 > K_blk=128: needs a K-loop with Partial/Final accumulation. CAUTION: that did NOT compose with a rotating (.next()) acc here (fault 507014); use conv_half_large's non-rotating-acc discipline. | ||
| 54 | + | ||
| 55 | +### tiny (Gate-A shape) | ||
| 56 | + -> T=64 K_blk=64 rows/core=0.03 cols=1 fits=True | ||
| 57 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 58 | + on-chip: L0A 16KB/64KB L0B 16KB/64KB L0C 64KB/256KB L1 48KB/256KB | ||
| 59 | + ! M too small for >=2 row-blocks/core: a_l1 rotation is DEAD and the A load is a serial prologue. Reduce T, use fewer cores, or expect lower mac. | ||
| 60 | + ! N/T=1 is small: A-reuse amortises over few columns. If M/T >> N/T, swap roles (make B resident, stream A). | ||
| 61 | +``` | ||
| @@ -0,0 +1,66 @@ | |||
| 1 | +"""Derive tiling + buffer counts for ANY matmul from the measured on-chip caps.""" | ||
| 2 | +import math | ||
| 3 | +L0A = L0B = 64*1024 | ||
| 4 | +L0C = 256*1024 # measured lower bound | ||
| 5 | +L1 = 256*1024 # conservative | ||
| 6 | +FRACTAL = 16 # tile dims should be multiples of the fractal | ||
| 7 | + | ||
| 8 | +def size(M, N, Ktot, bi, bo, cores, acc_buf=4, l0a_buf=2, l0b_buf=2, | ||
| 9 | + b_l1_buf=4, a_l1_buf=2, rows_target=4): | ||
| 10 | + """bi/bo = operand/output bytes. Returns a config dict.""" | ||
| 11 | + notes = [] | ||
| 12 | + # 1) T from the L0C constraint: T^2 * 4 (fp32 acc) * acc_buf <= L0C | ||
| 13 | + T = 1 << int(math.log2(math.sqrt(L0C / (4 * acc_buf)))) | ||
| 14 | + T = min(T, 1 << int(math.log2(max(M, FRACTAL))), 1 << int(math.log2(max(N, FRACTAL)))) | ||
| 15 | + # 2) K_blk from the L0A constraint with the REQUIRED double buffering | ||
| 16 | + Kb = int(L0A / (T * bi * l0a_buf)) | ||
| 17 | + Kb = 1 << int(math.log2(max(Kb, FRACTAL))) | ||
| 18 | + Kb = min(Kb, 1 << int(math.log2(max(Ktot, FRACTAL)))) | ||
| 19 | + # 3) core mapping | ||
| 20 | + n_rows, n_cols = M // T, N // T | ||
| 21 | + rows_per_core = n_rows / cores | ||
| 22 | + if rows_per_core < 2: | ||
| 23 | + notes.append("M too small for >=2 row-blocks/core: a_l1 rotation is DEAD and the A load " | ||
| 24 | + "is a serial prologue. Reduce T, use fewer cores, or expect lower mac.") | ||
| 25 | + if n_cols < 4: | ||
| 26 | + notes.append("N/T=%d is small: A-reuse amortises over few columns. If M/T >> N/T, " | ||
| 27 | + "swap roles (make B resident, stream A)." % n_cols) | ||
| 28 | + if Ktot > Kb: | ||
| 29 | + notes.append("K_total=%d > K_blk=%d: needs a K-loop with Partial/Final accumulation. " | ||
| 30 | + "CAUTION: that did NOT compose with a rotating (.next()) acc here (fault " | ||
| 31 | + "507014); use conv_half_large's non-rotating-acc discipline." % (Ktot, Kb)) | ||
| 32 | + if M % T or N % T: | ||
| 33 | + notes.append("M or N not divisible by T=%d: needs valid_shape / tail handling." % T) | ||
| 34 | + # capacity check | ||
| 35 | + used = dict(L0A=T*Kb*bi*l0a_buf, L0B=Kb*T*bi*l0b_buf, L0C=T*T*4*acc_buf, | ||
| 36 | + L1=T*Kb*bi*a_l1_buf + Kb*T*bi*b_l1_buf) | ||
| 37 | + ok = used["L0A"] <= L0A and used["L0B"] <= L0B and used["L0C"] <= L0C and used["L1"] <= L1 | ||
| 38 | + return dict(T=T, Kblk=Kb, rows_per_core=rows_per_core, n_cols=n_cols, used=used, ok=ok, | ||
| 39 | + bufs=dict(a_l1=a_l1_buf, a_l0a=l0a_buf, b_l1=b_l1_buf, b_l0b=l0b_buf, acc=acc_buf), | ||
| 40 | + notes=notes) | ||
| 41 | + | ||
| 42 | +def show(title, **kw): | ||
| 43 | + c = size(**kw) | ||
| 44 | + print("\n### %s" % title) | ||
| 45 | + print(" -> T=%d K_blk=%d rows/core=%.2f cols=%d fits=%s" % ( | ||
| 46 | + c["T"], c["Kblk"], c["rows_per_core"], c["n_cols"], c["ok"])) | ||
| 47 | + print(" buffers: " + ", ".join("%s x%d" % (k, v) for k, v in c["bufs"].items())) | ||
| 48 | + print(" on-chip: L0A %dKB/%dKB L0B %dKB/%dKB L0C %dKB/%dKB L1 %dKB/%dKB" % ( | ||
| 49 | + c["used"]["L0A"]//1024, L0A//1024, c["used"]["L0B"]//1024, L0B//1024, | ||
| 50 | + c["used"]["L0C"]//1024, L0C//1024, c["used"]["L1"]//1024, L1//1024)) | ||
| 51 | + for n in c["notes"]: print(" ! " + n) | ||
| 52 | + | ||
| 53 | +print("=" * 78) | ||
| 54 | +print("VALIDATION — does the procedure reproduce the measured optimum?") | ||
| 55 | +print("=" * 78) | ||
| 56 | +show("MEASURED BEST: M=16384 N=1024 K=128 bf16, 32 cores (actual: T=128 K=128 4rows, mac 0.870)", | ||
| 57 | + M=16384, N=1024, Ktot=128, bi=2, bo=2, cores=32) | ||
| 58 | +print("\n" + "=" * 78) | ||
| 59 | +print("GENERALISATION — other shapes and dtypes") | ||
| 60 | +print("=" * 78) | ||
| 61 | +show("fp32 operands, square", M=16384, N=4096, Ktot=1024, bi=4, bo=4, cores=32) | ||
| 62 | +show("int8 operands", M=16384, N=4096, Ktot=1024, bi=1, bo=1, cores=32) | ||
| 63 | +show("tall-skinny (N small)", M=65536, N=256, Ktot=256, bi=2, bo=2, cores=32) | ||
| 64 | +show("short-fat (M small)", M=512, N=16384, Ktot=256, bi=2, bo=2, cores=32) | ||
| 65 | +show("deep K (needs K-loop)", M=8192, N=8192, Ktot=4096, bi=2, bo=2, cores=32) | ||
| 66 | +show("tiny (Gate-A shape)", M=64, N=64, Ktot=64, bi=2, bo=4, cores=32) | ||
| @@ -0,0 +1,169 @@ | |||
| 1 | +--- | ||
| 2 | +name: pypto-pl-pipe-roofline | ||
| 3 | +description: 写一个刻意只卡在某一条 pipe(MTE2、FIXPIPE、MTE1 或 MAC)上的 pl tile-DSL matmul,用来刻画该 pipe 在 a5 NPU 上的硬件上限,即 roofline / microbenchmark 探针。给出选择各瓶颈的旋钮(tile T、深度 K、dtype)、占满全部核的 shape 规则,以及 utilisation-bound 与 bandwidth-bound 的关键区分。它是 pypto-pl-cube-bound 的逆操作(后者把 MAC 顶到最高)。需要测某条 pipe 的天花板、构造饱和 microbenchmark、或验证 roofline 模型时加载。触发词:roofline、带宽测试、pipe 打满、MTE2 瓶颈、FixPipe 瓶颈、硬件极限、饱和测试、microbenchmark。 | ||
| 4 | +--- | ||
| 5 | + | ||
| 6 | +# Driving one pipe to its hardware limit on a5 | ||
| 7 | + | ||
| 8 | +**本技能做什么**:把负载全部压到指定的一条 pipe 上,测出它的实际上限。§0 区分 bandwidth-bound 与 | ||
| 9 | +utilisation-bound,§1–§2 是选瓶颈的旋钮与占核规则,§§3–6 是实测表。正文为英文,术语与 API 名保持原文。 | ||
| 10 | + | ||
| 11 | +> **Note on referenced material.** Sample citations below resolve into the governed knowledge base | ||
| 12 | +> at `pypto-pro-op-kb/`. No saturation reproducer is retained there, so those citations name | ||
| 13 | +> `pypto-pro-op-kb/constraints/arch-a5.md`, whose platform gate states how to re-derive the | ||
| 14 | +> platform constants a saturation probe needs from the installed runtime. The companion skill is | ||
| 15 | +> `pypto-pl-cube-bound`. | ||
| 16 | + | ||
| 17 | +To measure what a pipe can do — or to prove a kernel is limited by the pipe you think — build a | ||
| 18 | +matmul that is bottlenecked on **exactly that pipe**. This is the inverse of `pypto-pl-cube-bound`: | ||
| 19 | +there you push everything off the cube; here you push everything ONTO one target pipe. | ||
| 20 | + | ||
| 21 | +All figures measured on Ascend950, 32 cores. The saturation reproducers and their raw data are **not | ||
| 22 | +retained in this KB** — the tables in §§3–6 are the surviving record. Before relying on any of them, | ||
| 23 | +re-derive the platform ceilings for the runtime in front of you by the evidence gate in | ||
| 24 | +`pypto-pro-op-kb/constraints/arch-a5.md`, which names the installed platform files to read them | ||
| 25 | +from. | ||
| 26 | + | ||
| 27 | +--- | ||
| 28 | + | ||
| 29 | +## 0. Two meanings of "reach the hardware limit" — and which one to target | ||
| 30 | + | ||
| 31 | +| bound | definition | how to confirm | | ||
| 32 | +|---|---|---| | ||
| 33 | +| **Bandwidth-bound** | the pipe hits its physical GB/s (or TMAC/s) ceiling | compute `bytes / (util · engine_time)` and compare to §4 | | ||
| 34 | +| **Utilisation-bound** | the pipe's occupancy (`*_ratio`) → 1.0 | it is the top sub-ratio and near 1.0 | | ||
| 35 | + | ||
| 36 | +**For the data-movement pipes MTE1/2/3 (and FIXPIPE), the PRIMARY goal is BANDWIDTH-bound — hit the | ||
| 37 | +GB/s ceiling. Utilisation is a secondary check** (confirming the pipe you targeted is the one | ||
| 38 | +dominating). A mover at 97% util but 28% of its bandwidth is NOT at its hardware limit. Only MAC is | ||
| 39 | +naturally reported as a utilisation/fraction-of-peak; the movers are reported in GB/s. | ||
| 40 | + | ||
| 41 | +**They diverge (measured).** MTE2 at T=16 runs **97% utilised but only 1.33 TB/s** (~28% of its | ||
| 42 | +~4.7 TB/s ceiling) — util-saturated, NOT bandwidth-saturated, because tiny 8 KB transfers cannot | ||
| 43 | +fill the bus. Grow T to 64 and util *falls* to 84% while bandwidth *rises* to 3.1 TB/s; T=128 | ||
| 44 | +no-reuse hits the full 4.7 TB/s. So chasing util would have *stopped at the wrong place*. **Always | ||
| 45 | +report the achieved GB/s as the verdict for a mover, with the top sub-ratio as the confirmation.** | ||
| 46 | + | ||
| 47 | +--- | ||
| 48 | + | ||
| 49 | +## 1. The knob that selects each bottleneck | ||
| 50 | + | ||
| 51 | +Whole-problem arithmetic intensity, **flattened tiling with no operand reuse** (reuse moves you | ||
| 52 | +toward MAC-bound, so for a pipe probe you deliberately drop it), operand bytes `bi`, output bytes | ||
| 53 | +`bo`: | ||
| 54 | + | ||
| 55 | +``` | ||
| 56 | +MAC / mte2_bytes = T / (2·bi) ← shrink T (or widen operands) ⇒ MTE2-bound | ||
| 57 | +MAC / fix_bytes = K / bo ← shrink K (or widen output) ⇒ FIXPIPE-bound | ||
| 58 | +MAC / mte1_bytes = T / (2·bi) ← same bytes as mte2 but on-chip; rarely the binding pipe | ||
| 59 | +``` | ||
| 60 | + | ||
| 61 | +**M and N do not change the ratio** — they set total work and core occupancy only. So: | ||
| 62 | + | ||
| 63 | +| target pipe | primary knob | secondary knob | proven config (M=N=1024) | | ||
| 64 | +|---|---|---|---| | ||
| 65 | +| **MTE2** (GM→L1 read) | **small T** (16–64) | wider operand dtype | T=16 → util 0.97; T=64 → 3.1 TB/s | | ||
| 66 | +| **FIXPIPE** (L0C→GM write) | **small K** (16–32) | **fp32 output** (bo=4) | T=128,K=32 → util 0.91, 4.5 TB/s | | ||
| 67 | +| **MAC** (reference) | large T, large K, reuse, multi-buffer | narrow dtype | see `pypto-pl-cube-bound` (mac 0.87) | | ||
| 68 | +| **scalar** | very small tiles ⇒ many loop iterations | — | rises as T,K shrink (loop overhead) | | ||
| 69 | + | ||
| 70 | +--- | ||
| 71 | + | ||
| 72 | +## 2. Shape rules — so you measure the pipe, not an artefact | ||
| 73 | + | ||
| 74 | +1. **Full core occupancy:** `M/T ≥ CORES` (ideally `≥ 2·CORES`). With too few tiles, cores idle and | ||
| 75 | + you measure an occupancy wall, not the pipe. E.g. T=128, 32 cores ⇒ `M ≥ 4096`. | ||
| 76 | +2. **Enough iterations to amortise launch:** each core should run many tiles; keep N·(M/T) large. | ||
| 77 | +3. **Keep the *non-target* pipes cheap** so the target clearly dominates — for a FIXPIPE probe use | ||
| 78 | + small K (also starves MAC and MTE2); for an MTE2 probe use small T (also shrinks the FIXPIPE | ||
| 79 | + drain and MAC). | ||
| 80 | +4. **Gate A first.** A wrong kernel's utilisation is meaningless. | ||
| 81 | + | ||
| 82 | +--- | ||
| 83 | + | ||
| 84 | +## 3. To hit the BANDWIDTH ceiling (not just util) — transfer granularity matters | ||
| 85 | + | ||
| 86 | +A pipe reaches its GB/s ceiling only when its transfers are **large and contiguous**. The tension: | ||
| 87 | + | ||
| 88 | +- **MTE2-bound needs small T**, but small T ⇒ small (T·K·bi) loads ⇒ sub-peak bandwidth. Measured | ||
| 89 | + MTE2 bandwidth vs T (K=128, no reuse): **T=16 → 1.33 TB/s @ 97% util; T=32 → 2.03; T=64 → 3.10 @ | ||
| 90 | + 84% util**. Util falls while bandwidth climbs. To approach the MTE2 ceiling (~4.7 TB/s), use the | ||
| 91 | + **largest T still mte2-dominant** (T=64 here) and accept util < 1.0; T=128 no-reuse hits the full | ||
| 92 | + 4.7 TB/s but is barely mte2-bound. | ||
| 93 | +- **FIXPIPE has no tension**: at T=128 the drain is already a 64 KB tile, so shrinking K makes | ||
| 94 | + fixpipe dominant *and* bus-efficient — measured **~4.1–4.5 TB/s at ~90% util** (K=16/32/64). This | ||
| 95 | + is why fixpipe saturates trivially and mte2 does not. | ||
| 96 | + | ||
| 97 | +**Rule of thumb:** to characterise a pipe's *bandwidth*, maximise transfer size subject to staying | ||
| 98 | +bound on that pipe; to characterise its *occupancy limit*, minimise arithmetic intensity. | ||
| 99 | + | ||
| 100 | +--- | ||
| 101 | + | ||
| 102 | +## 4. a5 pipe ceilings (measured 2026-07-22 — the roofline) | ||
| 103 | + | ||
| 104 | +| pipe | path / engine | **ceiling (GB/s or TMAC/s)** | reached by | | ||
| 105 | +|---|---|---|---| | ||
| 106 | +| MTE1 (L1→L0) | on-chip, cube | **7.5–11.4 TB/s** | matmul A-reuse (never binding) | | ||
| 107 | +| MTE2 (GM→L1) | load, cube | **~4.7 TB/s** (large T); ~1.3 at T=16 | `sat_mac_ref` vs `sat_mte2_t16` | | ||
| 108 | +| MTE2 (GM→UB) | load, vector | **~2.2 TB/s** | vector datacopy | | ||
| 109 | +| MTE3 (UB→GM) | store, vector | **~2.35 TB/s** | vector datacopy | | ||
| 110 | +| FIXPIPE (L0C→GM) | store, cube | **~4.5 TB/s** | `sat_fix_k32` | | ||
| 111 | +| MAC (cube) | compute | **~207 TMAC/s** (bf16) | cube-bound kernel | | ||
| 112 | + | ||
| 113 | +**The cube and vector engines have different GM bandwidth** — the cube's GM paths (~4.5–4.7 TB/s) | ||
| 114 | +run ~2× the vector's (~2.2–2.35 TB/s). Root cause (investigated; the write-up is not part of this tree): | ||
| 115 | +NOT the HBM bus (shared, ≥4.7) and NOT bidirectional sharing (isolated load-only 2.14, store-only | ||
| 116 | +2.29 TB/s) — it is the **per-engine DMA port width** (AIC↔L1 ~2× wider than AIV↔UB). And | ||
| 117 | +`block_dim` clamps to `core_num` (=32 here, `jit.py:1059`), so more vector cores is not an option. | ||
| 118 | +**To approach the HBM ceiling, overlap cube+vector** — their GM ports are separate and sum. Use | ||
| 119 | +aic_* ratios for cube kernels, aiv_* for vector. | ||
| 120 | + | ||
| 121 | +**Dtype (bf16 vs fp8) — the bus is BYTE-limited, not element-limited.** Measured vector datacopy: | ||
| 122 | +bf16 and fp8 reach the **same GB/s** (~2.2 load / ~2.35 store) at equal tile-KB. So fp8 moves **2× | ||
| 123 | +the elements/sec** at the same bandwidth — its data-movement win is fewer *bytes* for a given | ||
| 124 | +problem (halving operand width halves MTE time), NOT a faster bus. fp8 = `DT_FP8E4M3FN`; isolate | ||
| 125 | +movement with `load → pl.move → store` (fp8 *arithmetic* like `pl.add` does not compile). | ||
| 126 | + | ||
| 127 | +MAC rate by dtype: fp16/bf16 4096/cyc·core, fp32 2048 (0.5×), int8 8192, int4 16384. | ||
| 128 | + | ||
| 129 | +## 5. Procedure | ||
| 130 | + | ||
| 131 | +1. Pick the target pipe and its knob (§1). Pick M,N,K,T,dtypes so (a) the knob drives that pipe's | ||
| 132 | + intensity low, (b) `M/T ≥ CORES` (§2), (c) for a bandwidth probe, transfers stay large (§3). | ||
| 133 | +2. Use a **flattened, no-reuse** kernel — reuse would pull toward MAC-bound. No such reproducer is | ||
| 134 | + retained here; write one from §1's knob table. | ||
| 135 | +3. Gate A, then profile (`AiCMetrics.PipeUtilization` → `kernel_details.csv`). | ||
| 136 | +4. Report the **top sub-ratio** (is it the pipe you targeted?) **and** the achieved GB/s (is it at | ||
| 137 | + the §4 ceiling?). State util-bound vs bandwidth-bound explicitly. | ||
| 138 | +5. Sweep the knob (e.g. T ∈ {16,32,64} or K ∈ {16,32,64}) to show the crossover and find the | ||
| 139 | + configuration that maximises the target metric. | ||
| 140 | + | ||
| 141 | +--- | ||
| 142 | + | ||
| 143 | +## 6. Traps (shared with `pypto-pl-cube-bound`) | ||
| 144 | + | ||
| 145 | +- **`cube_utilization(%)` lies** — it read 88–92% on kernels that were mte2-bound. Use the top AIC | ||
| 146 | + sub-ratio, never `cube_util`. | ||
| 147 | +- **Include `aic_scalar_ratio`** — at tiny tiles it dominates (loop overhead), and an MTE2 probe at | ||
| 148 | + T=16 will show scalar climbing; do not mistake it for the intended bottleneck. | ||
| 149 | +- **Never compare `aicore_time` across shapes** — normalise to a rate (GB/s, TMAC/s). | ||
| 150 | +- **Utilisation is a ratio** — it rises when a pipe does more work OR when the kernel runs shorter; | ||
| 151 | + confirm with achieved bandwidth before drawing conclusions. | ||
| 152 | +- **Shared box:** if a run fails, check it is not the env before blaming the kernel — run the repo's | ||
| 153 | + own `test_matmul_api_basic.py::test_t01`; if that also fails (e.g. `ModuleNotFoundError` during an | ||
| 154 | + editable-install rebuild), it is the box, not you. | ||
| 155 | + | ||
| 156 | +--- | ||
| 157 | + | ||
| 158 | +## 7. Reference | ||
| 159 | + | ||
| 160 | +- 🔴 **Not retained in this KB**: the parameterised `sat_mte2_*` / `sat_fix_*` / `sat_mac_ref` kernels, | ||
| 161 | + the vector-datacopy MTE2(load)/MTE3(store) bandwidth probe for bf16 and fp8, and the measured | ||
| 162 | + util-versus-bandwidth table they produced. §§3–6 above are what survives of them. Rebuilding a probe | ||
| 163 | + means writing it from §2's knob table, not recovering a file. | ||
| 164 | +- `pypto-pro-op-kb/constraints/arch-a5.md` — the platform gate and the primary source paths to read | ||
| 165 | + the ceilings from. It is a constraint-discovery page: it holds no measured ratio, bandwidth or | ||
| 166 | + duration by design, which is why a probe is needed at all. | ||
| 167 | +- `pypto-pl-cube-bound` — the inverse skill (drive MAC to the top), its cost model, and the | ||
| 168 | + bandwidth figures it retains in §7. The per-pipe bandwidth write-up those figures came from is not | ||
| 169 | + part of this tree. | ||
| @@ -0,0 +1,393 @@ | |||
| 1 | +--- | ||
| 2 | +name: pypto-pl-vector-kernel | ||
| 3 | +description: 设计、实现与优化 pl tile-DSL 的 VECTOR(section_vector)kernel——行归一化、激活函数、elementwise 算子及其混合精度变体。提供 kernel 模板、行 reduce 惯用法、成套的高代价陷阱、算子组合表、cast 模式,以及带实测 roofline 的 compute-bound / memory-bound 判定;§7b/§7c 覆盖寄存器级 `pl.vf` 与动态 shape 生产化(build cache 撞名、64 lane 宽度与 UB slot、设备 reduce 挂死、D 分块、评分)。构建或调试任何 vector/elementwise/归一化 kernel 时加载。触发词:vector kernel、section_vector、softmax、layernorm、rmsnorm、l2norm、激活函数、silu、gelu、elementwise、混合精度、bf16/fp8、向量算子开发、compute-bound、memory-bound、pl.vf、寄存器算子、动态shape、cann-bench、507034、507035、特殊值 inf/nan。 | ||
| 4 | +--- | ||
| 5 | + | ||
| 6 | +# Building vector (section_vector) kernels on a5 | ||
| 7 | + | ||
| 8 | +**本技能做什么**:给出 `section_vector` kernel 的可复制模板(§1)、行 reduce 惯用法(§2)、必须避开的 | ||
| 9 | +陷阱(§3)、算子组合表(§4)、混合精度 cast(§5–§6)与 compute/memory-bound 判定(§7),§7b/§7c 是寄存器 | ||
| 10 | +级 `pl.vf` 与动态 shape 生产化。正文为英文,术语与 API 名保持原文。 | ||
| 11 | + | ||
| 12 | +> **Note on referenced material.** Sample citations below resolve into the governed knowledge base | ||
| 13 | +> at `pypto-pro-op-kb/`. Where that tree retains a matching implementation the citation names it; | ||
| 14 | +> where it does not, the citation names the constraint or record page that carries the surviving | ||
| 15 | +> rule, and the measurement behind it was made on the environment the sentence states. The sibling | ||
| 16 | +> skills are `pypto-pl-cube-bound` and `pypto-pl-pipe-roofline`, and the cross-cutting trap index is | ||
| 17 | +> `pypto-pro-op-kb/references/pitfall-records.md`. | ||
| 18 | + | ||
| 19 | +Covers row-normalisations, activations, elementwise ops, and their mixed-precision variants. All | ||
| 20 | +numbers measured on Ascend950 (32 vector cores) 2026-07-22. Kernels + data: | ||
| 21 | +`pypto-pro-op-kb/examples/samples/vector_kernels/` and `.../norm_softmax_rms_l2/`. | ||
| 22 | + | ||
| 23 | +**Companions:** `pypto-pl-cube-bound` (matmul → MAC-bound), `pypto-pl-pipe-roofline` (drive a pipe | ||
| 24 | +to its GB/s limit). This skill is the vector-engine counterpart. | ||
| 25 | + | ||
| 26 | +### 🔑 Scored levers for narrow / dynamic-width row reductions — read these before tuning one | ||
| 27 | + | ||
| 28 | +These four pages carry the levers that produced a **+1.17 hidden-score gain on `rms_norm`** | ||
| 29 | +(Ascend950PR, 2026-08). They are routed in `topology-map.json` under `row-reduction` and | ||
| 30 | +`mixed_precision`, but a Stage-5 optimizer arrives here first, so they are named directly: | ||
| 31 | + | ||
| 32 | +| when your kernel looks like this | read | what it bought | | ||
| 33 | +|---|---|---| | ||
| 34 | +| the reduced axis is a handful of bytes (`D` small, e.g. 2) | [`pypto-pro-op-kb/patterns/vec-narrow-row-packing.md`](../../pypto-pro-op-kb/patterns/vec-narrow-row-packing.md) | **+0.7055** — pack `D\|64` rows per register instead of one row per pass | | ||
| 35 | +| one kernel must span a wide range of `D`, dtypes or ranks | [`pypto-pro-op-kb/patterns/tiling-key-width-ladder.md`](../../pypto-pro-op-kb/patterns/tiling-key-width-ladder.md) | the rung ladder + coupled `Rows` field under one `@pl.jit` | | ||
| 36 | +| you are about to blame 32-byte alignment for a width-dependent cost | [`pypto-pro-op-kb/patterns/vec-compile-time-register-count.md`](../../pypto-pro-op-kb/patterns/vec-compile-time-register-count.md) | **+0.1008** — cost tracks `ceil(D/64)` **registers**, not `D mod 64`; the alignment story is a confound | | ||
| 37 | +| the kernel is fp16/bf16 and slower than its byte count predicts | [`pypto-pro-op-kb/patterns/vec-compute-exposed-narrow-dtype.md`](../../pypto-pro-op-kb/patterns/vec-compute-exposed-narrow-dtype.md) | the narrow path is **compute-exposed**, not bandwidth-bound | | ||
| 38 | +| you are choosing `Rows` / block count | [`pypto-pro-op-kb/constraints/tiling.md`](../../pypto-pro-op-kb/constraints/tiling.md) | **+0.2323** — `Rows` rules, and why "fill every core" is wrong (38 of 56 blocks beat 56 by 30 %) | | ||
| 39 | +| your reduction is `acc += a*b` **and** you already have four independent accumulator chains | [`pypto-pro-op-kb/constraints/vec.md`](../../pypto-pro-op-kb/constraints/vec.md) § "The second lever" + §7b below | **1.256x / 1.305x** — use the **fused** `vf.mul_add_dst`, one instruction per register instead of `vf.mul` then `vf.add`. 🔴 Lane-wise accumulation and fusion are **separable**: doing the first with `vf.add` is only half the lever | | ||
| 40 | + | ||
| 41 | +🔴 These are **measured on one operator and one SKU**. Use the trigger column to decide whether the | ||
| 42 | +shape applies to your kernel; do not port the numbers. | ||
| 43 | + | ||
| 44 | +--- | ||
| 45 | + | ||
| 46 | +## 1. The template (copy this) | ||
| 47 | + | ||
| 48 | +```python | ||
| 49 | +@pl.jit(auto_mutex=True) | ||
| 50 | +def kern(x: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP32], y: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP32]): | ||
| 51 | + TR, N = 8, 1024 | ||
| 52 | + tt = pl.TileType(shape=[TR, N], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec, valid_shape=[-1, -1]) | ||
| 53 | + rt = pl.TileType(shape=[TR, 1], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec, layout=pl.DN, valid_shape=[-1, -1]) | ||
| 54 | + ing = pl.make_tile_group(type=tt, addrs=[0x00000, 0x08000], mutex_ids=[0, 1]) # double-buffered | ||
| 55 | + outg = pl.make_tile_group(type=tt, addrs=[0x10000, 0x18000], mutex_ids=[2, 3]) | ||
| 56 | + tmpg = pl.make_tile_group(type=tt, addrs=[0x20000, 0x28000], mutex_ids=[4, 5]) | ||
| 57 | + redg = pl.make_tile_group(type=rt, addrs=[0x30000, 0x30400], mutex_ids=[6, 7]) | ||
| 58 | + with pl.section_vector(): | ||
| 59 | + rows, cols = x.shape[0], x.shape[1] | ||
| 60 | + nc, cid = pl.get_block_num(), pl.get_block_idx() | ||
| 61 | + nt = (rows + TR - 1) // TR | ||
| 62 | + for t in pl.range(cid, nt, nc): # row-tiles striped across vector cores | ||
| 63 | + ro = t * TR; vr = pl.min(TR, rows - ro) # vr = valid rows (tail tile is partial) | ||
| 64 | + xi = ing.next(); pl.set_validshape(xi, [vr, cols]); pl.load(xi, x, [ro, 0]) | ||
| 65 | + o = outg.next(); tm = tmpg.next(); rd = redg.next() | ||
| 66 | + pl.set_validshape(o, [vr, cols]); pl.set_validshape(tm, [vr, cols]); pl.set_validshape(rd, [vr, 1]) | ||
| 67 | + # ... compute ... | ||
| 68 | + pl.store(y, o, [ro, 0]) | ||
| 69 | +``` | ||
| 70 | + | ||
| 71 | +Load form: `kern[None, min(32, nt)](args)` (block_dim clamps to `core_num`≈32; see | ||
| 72 | +`pypto-pl-pipe-roofline`). Each core owns whole row-tiles → the reduction over N stays local. | ||
| 73 | + | ||
| 74 | +--- | ||
| 75 | + | ||
| 76 | +## 2. The row-reduction idiom | ||
| 77 | + | ||
| 78 | +Per-row reduce over N, then broadcast back. Reduction result is `[TR,1]` **DN layout**. | ||
| 79 | + | ||
| 80 | +| op | call | | ||
| 81 | +|---|---| | ||
| 82 | +| row max / sum | `pl.row_max(rd, xi, tm)` / `pl.row_sum(rd, xi, tm)` — `tm` is a `[TR,N]` scratch tile | | ||
| 83 | +| broadcast a `[TR,1]` per-row scalar over N | `pl.row_expand_sub / _mul / _div / _add(out, src, rd)` | | ||
| 84 | +| broadcast a `[1,N]` per-column vector over rows | `pl.col_expand_mul / _sub / _div(out, src, vec)` | | ||
| 85 | +| unary | `pl.exp, log, sqrt, rsqrt, recip, relu, abs, neg` | | ||
| 86 | +| binary (tile or scalar rhs) | `pl.add, sub, mul, div, maximum, minimum` | | ||
| 87 | + | ||
| 88 | +Worked kernels (all Gate-A validated): | ||
| 89 | +- **softmax**: `row_max → row_expand_sub → exp → row_sum → row_expand_div` | ||
| 90 | +- **l2norm**: `mul(sq)=x² → row_sum → (rsqrt on alias) → row_expand_mul` | ||
| 91 | +- **rmsnorm**: as l2norm + `mul(1/N)` and `add(eps)` on the alias before rsqrt | ||
| 92 | +- **layernorm**: `row_sum→mean → row_expand_sub(xc) → mul(xc²)→row_sum→var → rsqrt → row_expand_mul → col_expand_mul(γ) → col_expand_sub(-β)` | ||
| 93 | + | ||
| 94 | +--- | ||
| 95 | + | ||
| 96 | +## 3. THE PITFALLS — every one cost real debugging time | ||
| 97 | + | ||
| 98 | +### 3a. Computed / reused tiles MUST be `make_tile_group`, not bare `make_tile` | ||
| 99 | +`auto_mutex` tracks cross-op read-after-write hazards **only for tile groups**. A bare | ||
| 100 | +`pl.make_tile` that is *written by one op and read by a later op* (e.g. `negbeta = mul(beta,-1)` | ||
| 101 | +then `col_expand_sub(out, xc, negbeta)`) is **not** synced → the reader sees stale data → **wrong | ||
| 102 | +result, no error**. This produced a layernorm that computed `maxdiff≈5` until every gamma/beta/ | ||
| 103 | +negbeta tile was switched to `make_tile_group`. **Rule: use `make_tile_group` for any tile that | ||
| 104 | +participates in a cross-op dependency.** Bare `make_tile` is only safe for a transient reduction | ||
| 105 | +scratch or its row-major alias (§3b). | ||
| 106 | + | ||
| 107 | +### 3b. Scalar ops on a reduction need the ROW-MAJOR alias (the DN view faults) | ||
| 108 | +A reduction writes a `[TR,1]` **DN** tile (consumed by `row_expand_*`). But `rsqrt / div / add / | ||
| 109 | +mul` **fault on the DN view**. Alias the same address as a `[1,TR]` row-major tile and run the | ||
| 110 | +scalar op there: | ||
| 111 | +```python | ||
| 112 | +rd = pl.make_tile(pl.TileType(shape=[TR,1], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec, layout=pl.DN), addr=0x30000, size=512) | ||
| 113 | +rdm = pl.make_tile(pl.TileType(shape=[1,TR], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x30000, size=512) # same addr | ||
| 114 | +pl.row_sum(rd, sq, tm); pl.add(rdm, rdm, EPS); pl.rsqrt(rdm, rdm); pl.row_expand_mul(o, x, rd) | ||
| 115 | +``` | ||
| 116 | +`set_validshape(rdm, [1, vr])` before the scalar ops. (Bare `make_tile` is fine here — the alias is | ||
| 117 | +transient and the DSL threads the dependency through the shared address.) | ||
| 118 | + | ||
| 119 | +### 3c. There is NO `col_expand_add` | ||
| 120 | +`row_expand_add` exists; `col_expand_add` does **not**. For a per-column bias `β [1,N]`, precompute | ||
| 121 | +`-β` and use `col_expand_sub(out, x, negbeta)` (== `x + β`). This is why every layernorm/bias kernel | ||
| 122 | +carries a `negbeta` tile. | ||
| 123 | + | ||
| 124 | +### 3d. `make_tile` `addr` and `size` must be COMPILE-TIME LITERALS | ||
| 125 | +`pl.make_tile(tt, addr=0x8000, size=32768)` works; `size=TR*N*4` or `addr=cond?a:b` **fail to | ||
| 126 | +parse** ("Unsupported kwarg type for key: memref_size/addr"). The tracer wraps computed | ||
| 127 | +expressions. Hardcode the numbers. | ||
| 128 | + | ||
| 129 | +### 3e. Divide by a compile-time constant, not always the traced shape | ||
| 130 | +`pl.div(rdm, rdm, cols)` with `cols=x.shape[1]` (a traced runtime value) can misbehave; the proven | ||
| 131 | +kernels divide by the literal `float(N)` for mean/`1/N`. Prefer the literal when N is fixed. | ||
| 132 | + | ||
| 133 | +### 3f. UB budget ≈ 256 KB — pack tiles, expect a runtime fault if you overshoot | ||
| 134 | +Over-subscription is a **device fault (507035)**, not a compile error. Sum every live buffer | ||
| 135 | +(double-buffered groups count ×2). Keep total ≲ 224 KB for margin (253 KB allocates, 259 KB | ||
| 136 | +faults). Pack addresses contiguously; a spread-out layout wastes UB and faults. | ||
| 137 | + | ||
| 138 | +--- | ||
| 139 | + | ||
| 140 | +## 4. Activations — there are NO activation primitives; compose them | ||
| 141 | + | ||
| 142 | +`pl` has **no** `sigmoid / tanh / gelu / silu / erf`. Available unary: `exp, log, sqrt, rsqrt, | ||
| 143 | +recip, relu, abs, neg`. Compose: | ||
| 144 | + | ||
| 145 | +| activation | recipe (measured Gate-A correct) | | ||
| 146 | +|---|---| | ||
| 147 | +| **sigmoid** `1/(1+e^-x)` | `mul(t,x,-1); exp(t,t); add(t,t,1.0); recip(t,t)` | | ||
| 148 | +| **silu / swish** `x·σ(x)` | sigmoid, then `mul(o, x, t)` — maxdiff 4.8e-7 vs `F.silu` | | ||
| 149 | +| **gelu** (sigmoid approx) `x·σ(1.702x)` | `mul(t,x,-1.702); exp; add 1; recip; mul(o,x,t)` — ~2e-2 vs exact `F.gelu`, exact vs the approx | | ||
| 150 | +| **tanh** | compose from `exp` (`1 - 2/(e^{2x}+1)`) | | ||
| 151 | + | ||
| 152 | +Note `lrelu`, `prelu`, `relu`, and fused `add_relu`/`fused_mul_add`/`mul_cast` DO exist. | ||
| 153 | + | ||
| 154 | +--- | ||
| 155 | + | ||
| 156 | +## 4b. Ops with NO native primitive — compose them (activations, cumsum, RoPE, reduce) | ||
| 157 | + | ||
| 158 | +`pl` lacks several common primitives. Build them: | ||
| 159 | + | ||
| 160 | +| op | missing primitive | how (validated) | | ||
| 161 | +|---|---|---| | ||
| 162 | +| **sigmoid/silu/gelu/tanh** | no activation ops | compose from `exp/recip/mul` (§4) | | ||
| 163 | +| **reduce (sum/max)** | — (`row_sum`/`row_max` exist) | `row_sum(rd, x, tmp)` → store `[M,1]`. Load-heavy ⇒ **memory-bound** | | ||
| 164 | +| **cumsum / prefix scan** | **no scan op** | **matmul with a triangular ones matrix**: `y = x @ U`, `U = triu(ones[N,N])` ⇒ `y[i]=Σ_{j≤i}x[j]`. A *cube* kernel (`matmul` computes `al@br` directly — pass `triu`, not its transpose). L0A/L0B single-buffered (`[128,128]fp32 = 64 KB = the cap`; double faults 507015). **O(N²)** — the honest workaround; a true scan would need an additive DSL op or a gather-based Hillis-Steele. | | ||
| 165 | +| **RoPE (rotary embedding)** | **no trig op; `load` has no stride** | (1) precompute `cos/sin` per (position, freq) **on the host**, pass as `[M, D/2]` tensors. (2) the interleaved even/odd pairs: **host-split** `x[:,0::2]`, `x[:,1::2]` into 2D tensors (a `tile_dims` 3D load does NOT extract strided pairs). (3) the rotation is on-device: `ye = xe·cos − xo·sin`, `yo = xe·sin + xo·cos`; host re-interleaves. Bit-exact (0.0). | | ||
| 166 | + | ||
| 167 | +**General principle: a missing primitive is either composed from elementwise ops, expressed as a | ||
| 168 | +matmul (scan → triangular, permutation → sparse matrix), or moved to a host pre/post-step (trig | ||
| 169 | +tables, interleave layout).** The device does the arithmetic; the host does layout and table | ||
| 170 | +generation. | ||
| 171 | + | ||
| 172 | +--- | ||
| 173 | + | ||
| 174 | +## 5. Mixed precision — bf16/fp8 input, fp32 compute | ||
| 175 | + | ||
| 176 | +Norm/softmax need fp32 for numerical stability. Pattern: **load low-precision → `pl.cast` up to | ||
| 177 | +fp32 → compute in fp32 → `pl.cast` down → store**. | ||
| 178 | + | ||
| 179 | +```python | ||
| 180 | +xb = xbf16_group.next(); pl.load(xb, x, [ro, 0]) # bf16 (or fp8) load, half/quarter the bytes | ||
| 181 | +pl.cast(xf32, xb, mode=pl.RoundMode.CAST_NONE) # widen — exact, mode irrelevant | ||
| 182 | +# ... fp32 compute into of32 ... | ||
| 183 | +oo = obf16_group.next(); pl.cast(oo, of32, mode=pl.RoundMode.CAST_ROUND) # narrow — CAST_ROUND | ||
| 184 | +pl.store(y, oo, [ro, 0]) | ||
| 185 | +``` | ||
| 186 | + | ||
| 187 | +- **bf16**: full compute-capable dtype; `pl.cast` fp32↔bf16 is proven. Widen `CAST_NONE`, narrow | ||
| 188 | + `CAST_ROUND`. | ||
| 189 | +- **fp8** (`DT_FP8E4M3FN` / `E5M2` / `HF8`): **storage-only** — you **cannot** do fp8 arithmetic | ||
| 190 | + (`pl.mul` on an fp8 tile **fails to compile**). BUT **`pl.cast` fp8↔fp32 WORKS** (empirically | ||
| 191 | + verified, contradicting the static "storage-only" reading). So the same cast-bridge pattern | ||
| 192 | + builds fp8 norms: load fp8 → cast fp32 → compute → cast fp8 → store. Measured softmax_fp8 maxdiff | ||
| 193 | + 2.58e-3 (fine for e4m3). | ||
| 194 | + | ||
| 195 | +### ⚠️ Counter-intuitive result: narrower input is SLOWER for these ops | ||
| 196 | +Measured softmax, same shape (8192×1024): | ||
| 197 | + | ||
| 198 | +| input dtype | aiv_time | vec util | GM (r+w) | verdict | | ||
| 199 | +|---|---|---|---|---| | ||
| 200 | +| fp32 | **31.8 µs** | 0.957 | 2.11 TB/s | compute-bound | | ||
| 201 | +| bf16→fp32 | 63.7 µs | 0.987 | 0.53 TB/s | **more** compute-bound | | ||
| 202 | +| fp8→fp32 | 93.4 µs | 0.992 | 0.18 TB/s | **most** compute-bound | | ||
| 203 | + | ||
| 204 | +Narrowing the input **halves/quarters the memory traffic** (GM 2.11→0.18 TB/s) but these ops are | ||
| 205 | +**already compute-bound**, so the memory saving buys nothing — and the two extra cast passes make | ||
| 206 | +the kernel **slower**. **Mixed-precision input helps only if the COMPUTE runs in the narrow dtype** | ||
| 207 | +(2× vector ALU throughput); casting to fp32 forfeits that. For a compute-bound vector op, prefer | ||
| 208 | +fp32 in/out unless memory bandwidth or capacity is the real constraint elsewhere. | ||
| 209 | + | ||
| 210 | +--- | ||
| 211 | + | ||
| 212 | +## 6. Compute-bound vs memory-bound — the analysis that decides the ceiling | ||
| 213 | + | ||
| 214 | +**Count the passes over the data.** Vector ALU passes vs memory passes (1 read + 1 write = 2): | ||
| 215 | + | ||
| 216 | +| kernel | vec passes | mem passes | measured vec util | GM r+w | bound | | ||
| 217 | +|---|---|---|---|---|---| | ||
| 218 | +| softmax | 5 | 2 | 0.957 | 2.11 TB/s | **compute** | | ||
| 219 | +| layernorm | ~7 | 2 | 0.954 | 1.42 TB/s | **compute** | | ||
| 220 | +| l2norm / rmsnorm | ~4 | 2 | 0.91–0.92 | 3.7 TB/s | compute (near both) | | ||
| 221 | +| silu / gelu | 5 | 2 | 0.94 | 3.0 TB/s | **compute** | | ||
| 222 | +| **elementwise** `2x+1` | 1 | 2 | 0.53 | **4.57 TB/s** | **MEMORY** (mte2 0.91) | | ||
| 223 | +| **reduce_sum** (row→[M,1]) | 1 | ~1 (read-heavy) | 0.57 | read 2.36 TB/s | **MEMORY** (mte2 0.94) | | ||
| 224 | +| **RoPE** (interleaved) | ~5 | 2 | 0.88 | 1.04 TB/s | **compute** | | ||
| 225 | +| **cumsum** (matmul, N=128) | — (cube) | — | (cube MAC) | — | cube — no vector scan op | | ||
| 226 | + | ||
| 227 | +**Rule: vec passes > mem passes ⇒ compute-bound.** Row-reductions and activations (4–7 passes) are | ||
| 228 | +compute-bound — the vector ALU saturates (util 0.91–0.99). A pure 1-op elementwise is the | ||
| 229 | +memory-bound end (mte saturated, GM at the ceiling). There is **no fused square-sum reduce** on a5 | ||
| 230 | +(`reduce_sum/max/min` only), so l2/rms cannot drop below their pass count to become memory-bound. | ||
| 231 | + | ||
| 232 | +**How to characterise (do both):** | ||
| 233 | +1. Gate A first (a wrong kernel's utilisation is meaningless). | ||
| 234 | +2. Profile `AiCMetrics.PipeUtilization` → read `aiv_vec_ratio` (compute) and `aiv_mte2/mte3_ratio` | ||
| 235 | + (memory). Vector kernels use **`aiv_time`**, not `aicore_time`. | ||
| 236 | +3. **Verdict = the top `aiv_*` sub-ratio.** Report it AND the aggregate GM `= (read+write bytes) / | ||
| 237 | + aiv_time` in TB/s. | ||
| 238 | + | ||
| 239 | +### a5 vector-engine rooflines (measured) | ||
| 240 | +- **Vector ALU**: saturates ~0.95–0.99 for compute-bound ops. | ||
| 241 | +- **GM via vector (aiv_mte2 load / aiv_mte3 store)**: **~2.2 TB/s one-way**, ~3.3–4.6 TB/s aggregate | ||
| 242 | + (overlapped read+write). This is **~half the cube's GM path** (~4.5–4.7 TB/s) — the AIV↔UB DMA | ||
| 243 | + port is narrower than AIC↔L1. See `pypto-pl-pipe-roofline` §4; the underlying investigation write-up | ||
| 244 | + is not part of this tree. | ||
| 245 | + | ||
| 246 | +**Optimisation levers, by bound:** | ||
| 247 | +- **Compute-bound** (most norms/activations): fewer/cheaper vector ops; fuse (`fused_mul_add`, | ||
| 248 | + `add_relu`); avoid needless casts (§5). More memory bandwidth does nothing. | ||
| 249 | +- **Memory-bound** (elementwise): bigger contiguous tiles, double-buffer for load/store overlap, | ||
| 250 | + narrower dtype (fewer bytes). Reaching the GM ceiling needs large transfers (see roofline skill). | ||
| 251 | + | ||
| 252 | +--- | ||
| 253 | + | ||
| 254 | +## 7. Procedure | ||
| 255 | + | ||
| 256 | +1. Pick `TR`, `N` so the row tile fits UB (§3f); N ≤ tile width for single-pass reduction (N up to | ||
| 257 | + a few thousand fits at small TR; larger N needs a two-pass accumulate — **no proven template | ||
| 258 | + exists, it is new code**). | ||
| 259 | +2. Copy the §1 template; build the compute from §2/§4. | ||
| 260 | +3. Apply the §3 pitfalls **before first run** (groups for computed tiles, row-major alias for | ||
| 261 | + scalar-on-reduction, `-β`, literal make_tile args). | ||
| 262 | +4. Gate A vs torch. If wrong, **bisect** (drop gamma, then beta, etc.) — it localises DSL-semantics | ||
| 263 | + bugs fast (this is how the layernorm gamma/beta bug was found). | ||
| 264 | +5. Profile; report top `aiv_*` ratio + GM TB/s; classify compute vs memory bound (§6). | ||
| 265 | +6. For mixed precision, use the §5 cast-bridge and expect *more* compute-bound / slower. | ||
| 266 | + | ||
| 267 | +--- | ||
| 268 | + | ||
| 269 | +## 7b. When to use `pl.vf` (register-level) — it DEPENDS on the kernel | ||
| 270 | + | ||
| 271 | +Two vector programming models: the **tile-op block API** (`pl.row_sum`, `pl.exp` on whole tiles — | ||
| 272 | +everything above) and **register-level `pl.vf`** (`@pl.vector_function`, 64-lane `vf.load_align`/ | ||
| 273 | +`vf.reduce_sum`/`vf.exp` register loops). Both lower to the same ISA, but they differ in **how | ||
| 274 | +intermediates flow**, and that splits the outcome cleanly (measured, 8192×N fp32, a5): | ||
| 275 | + | ||
| 276 | +| kernel type | example | tile-op | vf | winner | | ||
| 277 | +|---|---|---|---|---| | ||
| 278 | +| **multi-op elementwise** | rope | 8.1 µs | **4.5 µs** | **vf 1.8×** | | ||
| 279 | +| | gelu / silu | 22.5 / 22.2 | **14.9 / 15.2** | **vf ~1.5×** | | ||
| 280 | +| trivial elementwise | `2x+1` | 14.7 | 14.8 | tie | | ||
| 281 | +| **reduction** (ILP-written) | l2norm | 17.4 | **14.9** | **vf 1.17×** | | ||
| 282 | +| | softmax | 31.4 | **25.8** | **vf 1.22×** | | ||
| 283 | +| | layernorm (2 reduce + affine) | 23.6 | 23.3 | tie (~1.02×) | | ||
| 284 | + | ||
| 285 | +**Why:** the tile-op API materialises every intermediate to UB (a k-op chain = ~k UB round-trips); | ||
| 286 | +`vf` chains ops **in registers** (only load + store touch UB). So a multi-op elementwise chain | ||
| 287 | +(silu, gelu, rope) drops from compute-bound to **memory-bound** in vf and runs ~1.5–1.8× faster. | ||
| 288 | +**Reductions also win in vf — but only if written for ILP** (this corrects an earlier "tile-op wins | ||
| 289 | +for reductions" verdict that was a bad-template artifact). The reduction recipe: | ||
| 290 | + | ||
| 291 | +1. **Constant mask, never dynamic.** Use `preg = vf.create_mask(ALL)` (or `update_mask(64)`) once — | ||
| 292 | + NOT a per-register `update_mask(min(LANES, n_cols−r·LANES))`. The dynamic per-register mask was | ||
| 293 | + ~86% of the old slowness (l2 22.4→16.2 µs). For ragged N, hoist the full mask and compute one | ||
| 294 | + `update_mask(tail)` for the last partial register only. | ||
| 295 | +2. **Vertical-accumulate:** one `vf.add`/`vf.max` per register into an accumulator, a *single* | ||
| 296 | + `vf.reduce_sum`/`reduce_max` at the very end — not a per-register horizontal reduce. | ||
| 297 | +For a sum-of-squares — any `acc += a*b` — the fused form is **one instruction per register instead | ||
| 298 | +of two**: `acc = vf.mul_add_dst(r0, r0, preg)`, not `s = vf.mul(x, x, preg)` then | ||
| 299 | +`acc = vf.add(acc, s, preg)`. 🔴 It is **not** a standalone win: with a single accumulator it | ||
| 300 | +measured *slower* (+0.7 %, +1.4 %) because the multiply-accumulate serialises. It pays only together | ||
| 301 | +with rule 3's four chains **and** behind a compile-time width test on a tilingkey constant — | ||
| 302 | +`if MaxN >= UNROLL_MAXN:` … `else:` a plain body, never a runtime branch. Ungated it **cost 3.0 % at | ||
| 303 | +`D = 67`**. Measured 1.256× / 1.305× with the gate; full table in | ||
| 304 | +`pypto-pro-op-kb/constraints/vec.md` § "The second lever, and why it must be gated". | ||
| 305 | +3. **4 independent accumulators (unroll-4)** to break the accumulation dependency chain. This is the | ||
| 306 | + ceiling — unroll-8 adds nothing. **Unroll only helps while the kernel is still compute-bound** | ||
| 307 | + (aiv_vec ≫ aiv_mte2): softmax (heavy `exp`) gains ~10% from it; l2norm slides to memory-bound at | ||
| 308 | + step 2 already, so unroll is within noise there. Combine the accumulators with *explicit* | ||
| 309 | + assignments — nested `vf.add(vf.add(...),...)` is a parser error. | ||
| 310 | + | ||
| 311 | +**Rule: `vf` wins or ties for both elementwise-heavy AND reduction-heavy kernels** — elementwise via | ||
| 312 | +register residency; single-reduction kernels (l2norm, softmax) via hand-written ILP beating the | ||
| 313 | +serial fused `row_sum` (1.17–1.22×). The reduction gain **shrinks to a tie** when fixed multi-pass | ||
| 314 | +overhead dominates: layernorm (2 reductions + gamma/beta affine, re-centers x in the apply pass) is | ||
| 315 | +even with tile-op — still a fix vs the old bad-template 0.90× loss, but not a win. Also: `float(...)` | ||
| 316 | +/ other Python builtins are unsupported inside a `@pl.vector_function` (args are parsed, not run — | ||
| 317 | +pass literals). Full data, attribution, and gotchas (factory-name collision; negate via | ||
| 318 | +`exp_sub(zero,x)` not `muls(-1)`; wide out-tile for `[M,1]` reduce; no `vf.rsqrt`): | ||
| 319 | +the comparison and unroll write-ups are not part of this tree; the kernels themselves are retained | ||
| 320 | +under `pypto-pro-op-kb/examples/samples/vf_vs_tileop/`. | ||
| 321 | + | ||
| 322 | +## 7c. Production / dynamic-shape vf kernels — the gotchas that cost hours (cann-bench rms/softmax) | ||
| 323 | + | ||
| 324 | +Building ONE op that must cover many runtime shapes (D=2…8192, even/odd, fp16/fp32/bf16, special | ||
| 325 | +values). Each of these was a multi-iteration bug; iteration is punishing (~60 s per compile, **~5 min | ||
| 326 | +per device-timeout hang**), so bisect on **tiny inputs** (only a *hang* costs time; a *success* | ||
| 327 | +returns instantly) and change **one variable per cycle**. | ||
| 328 | + | ||
| 329 | +- **Factory name-collision — the one that wasted the most time.** pypto keys its compiled-kernel | ||
| 330 | + **build cache by the function `co_name`** (`build/<module>__<coname>__a5/tk_none/`). A | ||
| 331 | + `def _make(D): @pl.jit def k(...)` factory returns kernels all named `k`, so the **second D silently | ||
| 332 | + reuses the first D's `.so`** (e.g. a 768-wide kernel on 1024-wide data → garbage, maxdiff ~3, NOT a | ||
| 333 | + crash). Symptom: "correct at the first shape, wrong at all others; reversing call order flips which | ||
| 334 | + works." **`k.__name__ = ...` does NOT fix it** (co_name is set at `def`); **`exec` breaks pypto's | ||
| 335 | + `inspect.getsource`.** Fix: **code-gen each per-shape kernel to a real `.py` file with a unique | ||
| 336 | + `def` name**, then `importlib` it. (The kernel-generator this was found in is not part of this tree.) | ||
| 337 | +- **vf tile width must be a multiple of 64 (`LANES`), not 8.** `vf.load_align`/`store_align` move a | ||
| 338 | + full 64-lane register, so the last register at `(n_regs-1)*64` **overruns any tile whose width isn't | ||
| 339 | + a 64-multiple → 507035** (device memory fault). Use `align64(D)` for the tile; per-register | ||
| 340 | + `vf.update_mask(pl.min(64, cols - r*64))` masks the ragged tail so pad lanes don't contribute. | ||
| 341 | +- **UB fit = count ALL slots.** Double-buffered in+out = **4 tile slots** (`0/tb/2tb/3tb`), vector UB | ||
| 342 | + is **256 KB (262144)**. vf single-tile gate: `4*TR*NN*4 ≤ 262144` ⇒ `align64(D) ≤ 2048` | ||
| 343 | + (D=2048 fits *exactly*; 2049 overruns → 507035). Over-count and you fault, don't hang. | ||
| 344 | +- **vf beats tile-op on FOOTPRINT here, not just speed:** the reduction lives in **registers**, so vf | ||
| 345 | + needs only in+out tiles (4 slots) vs the tile-op's 6+ (in/out/tmp + reduction) → it fits **larger D | ||
| 346 | + double-buffered** and **avoids the single-buffer-at-scale hang** (single-buffered tile-op passed at | ||
| 347 | + 16 rows, HUNG at 4096). Default to vf for dynamic-shape reductions. | ||
| 348 | +- **Special values (inf/nan) can hang the device reduction on some runtimes — confirm before you | ||
| 349 | + design around it.** On Ascend950 (2026-07-23) `row_sum`/`reduce_sum`/`rsqrt`/`exp` over a row | ||
| 350 | + containing inf/nan wedged the core with **507034** (vector-core timeout — a hang, not wrong | ||
| 351 | + output), and repeated hangs then wedged the whole device until reset. The same arithmetic | ||
| 352 | + (`vf.mul` / `vf.reduce_sum` / `vf.pair_reduce_sum` / `vf.sqrt` / `vf.div`) **does not reproduce it | ||
| 353 | + on Ascend950PR** (`soc_version=DAV_3510`, 2026-08-05) over a `[1000003, 2]` bf16 input carrying | ||
| 354 | + 200000 ±inf and a ~50 %-NaN `[11,13,17,67]` f16 input: no hang, no 507034, and the NaN mask matched | ||
| 355 | + the golden element for element. Treat the hang as **runtime- and API-surface-specific**, detect it | ||
| 356 | + on the target you actually run on, and do not assume it on a new SoC. Full record and both | ||
| 357 | + observations: `pypto-pro-op-kb/references/pitfall-records.md`. | ||
| 358 | +- **The torch-fallback gate is not available in the PyPTO-Pro / CANN-Bench path.** Where the hang | ||
| 359 | + *is* real, the older remedy was to detect finiteness on the host — | ||
| 360 | + `math.isfinite(float(x.abs().amax()))`, never `torch.isfinite(x).all()` which itself faulted the | ||
| 361 | + NPU on nan (507034) — and route special-value inputs to a primitive fallback. That guard puts a | ||
| 362 | + device-dispatched reduction inside the timed callable and makes the operator's arithmetic | ||
| 363 | + conditional on the host, which `pypto-pro-op-kb/constraints/wrapper-boundary.md` and the | ||
| 364 | + anti-cheat rules forbid. Under those rules the escalation for a reproducing hang is the kernel or | ||
| 365 | + the runtime, not a host guard. Plain IEEE semantics already reproduce the graded invariant on the | ||
| 366 | + inf case (exact NaN position) with no clamp, no `x == x` test and no saturation. | ||
| 367 | +- **D-chunked (tile the reduce axis) for D > single-tile fit:** accumulate the DN `[TR,1]` partial on | ||
| 368 | + its **row-major alias** (`TADD` "only supports row major"), first-chunk-seed or `pl.expands(acc,0)`. | ||
| 369 | + The `auto_mutex` version **compiles but HANGS** (cross-view read-after-write it can't sync); the | ||
| 370 | + working FA/`smla_softmax_l1_norm` chunked kernels use **manual `pl.system.bar_v()` barriers (drop | ||
| 371 | + `auto_mutex`)** — that rewrite is the path to full large-D vf coverage (still open). | ||
| 372 | +- **Surfacing the hidden bisheng compile error:** `_ensure_compiled` swallows it as "Failed to compile | ||
| 373 | + kernel 'k'". `_run_bisheng` does `logging.error(stderr)`, but pytest captures stdout logging — add a | ||
| 374 | + **`logging.FileHandler` to a file** to read the real error (this is how `TADD only support row major` | ||
| 375 | + and the collision were finally seen). Inspect the generated code at `build/…/tk_none/kernel.cpp`. | ||
| 376 | +- **Grading without the (intractable) `kernel_eval.cli`:** the CLI `eval` is silent + slow (>10 min | ||
| 377 | + for ONE case: fp64-on-CPU golden/native for big cases) and dies on a busy box. **Import the harness's | ||
| 378 | + real `kernel_eval.utils.compare.compare_tensors` directly** into a lightweight validator (same | ||
| 379 | + data-gen + fp64 golden + same-precision native + official thresholds/fallbacks) for the official | ||
| 380 | + per-case verdict — no wheel-build/profiling/subprocess machinery. (The box environment must be | ||
| 381 | +sourced first; that script is not part of this tree.) | ||
| 382 | + | ||
| 383 | +## 8. Reference | ||
| 384 | + | ||
| 385 | +- `pypto-pro-op-kb/examples/samples/vf_vs_tileop/` — the retained **dynamic-shape vf rms/softmax | ||
| 386 | + kernels** behind the 40/40 official result. The hybrid routers, the two validators and the status | ||
| 387 | + write-up that recorded every gotcha in §7c are **not part of this tree**; §7c is what survives of | ||
| 388 | + them. | ||
| 389 | +- `pypto-pro-op-kb/examples/samples/norm_softmax_rms_l2/` — fp32 softmax/l2norm/rmsnorm + bound analysis. | ||
| 390 | +- `pypto-pro-op-kb/examples/samples/vector_kernels/` — layernorm, silu/gelu, memory-bound elementwise, | ||
| 391 | + bf16 & fp8 mixed-precision norms. The raw measurement log is not part of this tree. | ||
| 392 | +- `pypto-pl-pipe-roofline` — the GM/pipe bandwidth ceilings and the GM↔UB root cause. | ||
| 393 | +- `pypto-pro-op-kb/references/pitfall-records.md` — the same pitfalls in cross-cutting form. | ||
Acannbot-skills/ops/pypto-pro-cann-bench-eval/SKILL.md+356-0File content is under review, please try again later
| @@ -0,0 +1,74 @@ | |||
| 1 | +# A5 目标识别与 CANN Bench 评分口径 | ||
| 2 | + | ||
| 3 | +只在[目标探测](../SKILL.md#步骤-0目标探测a5-是探测出来的不是假设)确认为 A5 之后使用本文。 | ||
| 4 | +`<cann-bench-root>` 指 CANN Bench checkout 根目录。 | ||
| 5 | + | ||
| 6 | +## A5 在各处的名字 | ||
| 7 | + | ||
| 8 | +同一块 A5 在工具链里有四套写法,混用会导致 baseline 取错平台: | ||
| 9 | + | ||
| 10 | +| 场景 | 取值 | 来源 | | ||
| 11 | +|---|---|---| | ||
| 12 | +| 设备原始名 | `Ascend910_95*` / `Ascend950*` | `src/kernel_eval/utils/device_manager.py` | | ||
| 13 | +| 编译 SOC 参数 | `ascend950` | `src/cann_bench_utils/build.sh` 的 SOC 分支 | | ||
| 14 | +| baseline 键 | `950pr` | `src/kernel_eval/utils/baseline_resolver.py` | | ||
| 15 | +| baseline 数据文件 | `tasks/metadata/950pr.json` | 同上 | | ||
| 16 | + | ||
| 17 | +对照的 A2 一路是 `Ascend910B*` → `ascend910b` → `910b2` → `tasks/metadata/910b2.json`。 | ||
| 18 | + | ||
| 19 | +**baseline 缺失不会报错**:`per_case_sol_score` 在 `t_baseline ≤ 0` 时用 | ||
| 20 | +`max(T_HW × 10, 10 µs)` 作为代理基线继续打分,只 warn 一次。所以一个"跑出来了的分数" | ||
| 21 | +不等于"用对了平台基线"——评测日志里出现 fallback baseline 警告时,分数不具备横向可比性。 | ||
| 22 | + | ||
| 23 | +## baseline 数据的两个字段 | ||
| 24 | + | ||
| 25 | +`tasks/metadata/950pr.json` 中每个 case 有两个值: | ||
| 26 | + | ||
| 27 | +- **`baseline_perf_us`** — CANN 内置实现在该 case 上的实测耗时,即 `T_baseline`。 | ||
| 28 | +- **`t_hw_us`** — 该 case 的**硬件理论下界**(roofline 锚点),即 `T_HW`,已应用 1 µs 下限。 | ||
| 29 | + | ||
| 30 | +例(level1/exp):case 1 为 `baseline_perf_us=3.75, t_hw_us=1.31`; | ||
| 31 | +case 5 为 `baseline_perf_us=388.95, t_hw_us=167.77`。 | ||
| 32 | + | ||
| 33 | +## SOL-Score:这是饱和型指标,不是加速比 | ||
| 34 | + | ||
| 35 | +单 case 得分(`src/kernel_eval/benches/cann_scoring.py::per_case_sol_score`,bench.tex Eq.3): | ||
| 36 | + | ||
| 37 | +``` | ||
| 38 | +score = (T_baseline − T_HW) / ((T_cand − T_HW) + (T_baseline − T_HW)) | ||
| 39 | +``` | ||
| 40 | + | ||
| 41 | +理解这个式子的形状,比记住它更重要: | ||
| 42 | + | ||
| 43 | +- 它衡量的是**候选逼近硬件下界 T_HW 的程度**,不是比 baseline 快几倍。 | ||
| 44 | +- `T_cand → T_HW` 时 score → 1;`T_cand = T_baseline` 时 score = 0.5。 | ||
| 45 | +- baseline 很慢(`T_baseline ≫ T_HW`)时,即使加速比很大,分数也只趋近 1,不会线性放大。 | ||
| 46 | +- **不做上界截断**:`T_cand < T_HW` 时 score > 1 是有意保留的,单算子分因此可能超过 100。 | ||
| 47 | + | ||
| 48 | +**由此可以预判调优收益**:一旦 `T_cand` 已经接近或低于 `T_baseline`,再压缩几个百分点对 | ||
| 49 | +分数的推动很小——分母和分子同向变化,曲线在这一段已经平了。看到"kernel 明显变快但分数几乎没动", | ||
| 50 | +先用上式估算该 case 的理论增量,再决定值不值得继续调;不要默认是评测框架出了问题。 | ||
| 51 | + | ||
| 52 | +反过来,`T_cand` 还远高于 `T_baseline` 的 case,才是分数弹性最大的地方。**优化排序应该按 | ||
| 53 | +每个 case 的 score 缺口,而不是按耗时绝对值**——耗时最长的 case 往往 `T_HW` 也高,弹性反而小。 | ||
| 54 | + | ||
| 55 | +## 返回 None 的三种情况 | ||
| 56 | + | ||
| 57 | +`per_case_sol_score` 返回 `None` 而非 0,评测会分别 warn: | ||
| 58 | + | ||
| 59 | +1. `T_cand` 或 `T_HW` 非法(NaN 或 ≤ 0)——通常是性能数据没采到。 | ||
| 60 | +2. 分母 ≤ 0——罕见,`T_cand < T_HW` 且 `T_baseline ≈ T_HW` 时可能出现。 | ||
| 61 | +3. `T_baseline` 缺失——走代理基线 fallback(见上)。 | ||
| 62 | + | ||
| 63 | +第 1 种在 PyPTO-Pro 路线上最常见的成因是**性能数据源没取到**,而**最常见的触发方式恰恰是 | ||
| 64 | +多加了 `--perf-metric-strategy trace_view`**:eager 模式提交(本流程 Stage 1–4 产出的都是) | ||
| 65 | +不产 tilefwk/PYPTO 事件,该口径下 `elapsed_us = 0.0`,进而触发反作弊把算子判 0。 | ||
| 66 | +先去掉该参数、用框架默认的 `kernel_details` 重跑,再查 `kernel_details.csv` 是否确实产出。 | ||
| 67 | +口径选择的完整依据见 [`../SKILL.md` 步骤 6](../SKILL.md#步骤-6性能评测metric-口径由实现类型决定)。 | ||
| 68 | + | ||
| 69 | +## 与 A5 kernel 侧约束的关系 | ||
| 70 | + | ||
| 71 | +本文只讲评分口径。A5 的硬件参数、roofline 与可用优化手段在: | ||
| 72 | + | ||
| 73 | +- [`kb/constraints/arch-a5.md`](../../../ops/pypto-pro-op-kb/constraints/arch-a5.md) | ||
| 74 | +- [`pypto-pro-op-perf-tune/references/a5-roofline-and-levers.md`](../../pypto-pro-op-perf-tune/references/a5-roofline-and-levers.md) | ||
| @@ -0,0 +1,357 @@ | |||
| 1 | +# CANN Bench scoring, the pole, and how to build a target sheet | ||
| 2 | + | ||
| 3 | +Measured on Ascend950PR (`Ascend950PR_9579`) against the cannbench.com grader during an | ||
| 4 | +`rms_norm` tuning campaign, 2026-08. | ||
| 5 | + | ||
| 6 | +This page lives with the evaluation skill rather than in `pypto-pro-op-kb/playbooks/`, because | ||
| 7 | +[benchmark-scoring.md](../../../pypto-pro-op-kb/playbooks/benchmark-scoring.md) scopes itself to kernel | ||
| 8 | +correctness and reproducible profiling and states that *"packaging, scoring formulas and | ||
| 9 | +submission contracts belong to whichever external driver consumes the kernel."* Scoring | ||
| 10 | +formulas are that driver's business, so they are documented here. | ||
| 11 | + | ||
| 12 | +Companion: [a5-target-and-scoring.md](a5-target-and-scoring.md) states the same saturating | ||
| 13 | +metric in Chinese and is the shorter orientation; this page is the operational detail. | ||
| 14 | + | ||
| 15 | +## How the score is formed | ||
| 16 | + | ||
| 17 | +Per case, the performance term is **saturating, not a speedup** | ||
| 18 | +(`kernel_eval/benches/cann_scoring.py`): | ||
| 19 | + | ||
| 20 | +``` | ||
| 21 | +score_i = (T_baseline - T_HW) / ((T_cand - T_HW) + (T_baseline - T_HW)) | ||
| 22 | +OperatorScore = [0.2*compiled + sum_i accurate_i * (0.3 + 0.5*score_i)/N] * 100 | ||
| 23 | +``` | ||
| 24 | + | ||
| 25 | +Both anchors are published per `(operator, case_id)` in | ||
| 26 | +`tasks/metadata/<hardware>.json`, so a target latency can be computed before any | ||
| 27 | +tuning: `T_cand = T_HW + (T_baseline - T_HW) * (1-s)/s` for a wanted score `s`. | ||
| 28 | + | ||
| 29 | +Because it saturates, halving an already-good latency moves the score far less | ||
| 30 | +than the first improvement did, and a case whose baseline is close to `T_HW` | ||
| 31 | +offers little regardless of effort. Rank cases by `T_baseline / T_HW` before | ||
| 32 | +choosing where to spend time; once a scored baseline exists, rank by recoverable | ||
| 33 | +points instead. Both instruments belong to one policy, stated under **Ranking | ||
| 34 | +targets under the ceiling**. | ||
| 35 | + | ||
| 36 | +### The score is unbounded above 1.0, and has a pole below it | ||
| 37 | + | ||
| 38 | +Two properties of that formula matter more than the saturation, and both have | ||
| 39 | +produced wrong headline numbers: | ||
| 40 | + | ||
| 41 | +- **It is not clamped above 1.0.** A case that beats the modelled roofline scores | ||
| 42 | + as much as the arithmetic gives it, and the aggregate sums raw. Measured: one | ||
| 43 | + operator's twenty cases included five above 1.0, and **case 2 alone contributed | ||
| 44 | + 0.204 of a 0.924 mean — ten OperatorScore points from one case.** Its headline | ||
| 45 | + went from a repeatedly quoted 98.0 to **86.3** once clamped. | ||
| 46 | +- **The denominator can go non-positive**, at `T_cand = 2*T_HW - T_baseline`, | ||
| 47 | + at which point the case scores **zero for being too fast**. So the score is not | ||
| 48 | + monotonic in speed: it rises through parity, through the roofline, keeps rising, | ||
| 49 | + then falls off a cliff. Measured: two cases at 2.79× the built-in scored zero. | ||
| 50 | + | ||
| 51 | +**Report both means: the clamped one (per-case `min(score, 1.0)`) as the figure to | ||
| 52 | +quote, and the raw one alongside, naming every case above 1.0.** The clamped mean | ||
| 53 | +refuses credit for proximity to a singularity, which is what makes a genuine | ||
| 54 | +speedup unable to read as a loss. | ||
| 55 | + | ||
| 56 | +**Do not engineer around the pole.** The only kernel-side levers are to be slower, | ||
| 57 | +or to park just above a singularity and harvest an inflated score. Both are gaming. | ||
| 58 | +Write the fastest correct kernel, report what the evaluator computes, and say which | ||
| 59 | +cases landed in the zone. | ||
| 60 | + | ||
| 61 | +**And read a dead-zone count correctly** — this was briefed backwards to four | ||
| 62 | +operators before anyone checked. Since `T_baseline > T_HW` always, the pole always | ||
| 63 | +sits **below `T_HW`**, so *reaching* it means beating the modelled roofline outright. | ||
| 64 | +Across one full task set **350 of 480 poles are negative** and unreachable at any | ||
| 65 | +speed. A high count is not a risk of speeding up; it means a pole *exists*. The | ||
| 66 | +cases that actually land there are the ones whose `T_HW` is **under-modelled**. | ||
| 67 | +Check a case's distance to `T_HW` before calling it a risk. | ||
| 68 | + | ||
| 69 | +#### Evidence: why `T_HW` is beatable | ||
| 70 | + | ||
| 71 | +The anchor's own construction permits it. `T_HW` in | ||
| 72 | +`tasks/metadata/<hardware>.json` is `x_bytes / 1.60 TB/s` with a 1 µs floor, | ||
| 73 | +counting **only the input read**, against a part whose achieved bandwidth depends | ||
| 74 | +on whether the working set fits the 128 MiB L2. It is a modelling constant, not a | ||
| 75 | +floor. | ||
| 76 | + | ||
| 77 | +Measured on one rms_norm submission (Ascend950PR, 20 cases): case 2 ran at | ||
| 78 | +9.42 µs against `T_HW` 10.49, and case 11 at 18.02 against 20.49. Both are faster | ||
| 79 | +than the published bound, which is why both score above 1 — 1.2642 and 1.4595 — | ||
| 80 | +in a function that has no clamp. Two of twenty cases were already inside the | ||
| 81 | +region where the pole, not the roofline, is the binding constraint. | ||
| 82 | + | ||
| 83 | +#### The mechanism: the case scores `None`, and the aggregate adds 0.0 | ||
| 84 | + | ||
| 85 | +`per_case_sol_score` does not return a small number when the candidate is very | ||
| 86 | +fast (`src/kernel_eval/report/scoring.py:135-140`): | ||
| 87 | + | ||
| 88 | +``` | ||
| 89 | +denom = (T_cand - T_HW) + (T_baseline - T_HW) | ||
| 90 | +if denom <= 0: | ||
| 91 | + return None | ||
| 92 | +score_i = (T_baseline - T_HW) / denom | ||
| 93 | +``` | ||
| 94 | + | ||
| 95 | +`denom <= 0` is exactly `T_cand <= 2*T_HW - T_baseline`. Name that bound: | ||
| 96 | + | ||
| 97 | +``` | ||
| 98 | +E_crit = 2*T_HW - T_baseline | ||
| 99 | +``` | ||
| 100 | + | ||
| 101 | +`None` is not "unscored". The aggregator adds `0.0` for it (`scoring.py:375`) | ||
| 102 | +while still counting the case as accurate, so the case keeps its `w_f` share and | ||
| 103 | +loses its entire `w_p` share. At `w_p = 0.5` over 20 cases each unit of `score_i` | ||
| 104 | +is `w_p * 100 / N` = **2.5 points**, and the report shows a passing case with | ||
| 105 | +`perf_score: null`. The only other signal is one `_warn_denom_nonpositive` line | ||
| 106 | +on stderr. That is the tell to grep for: a successful optimisation can otherwise | ||
| 107 | +read as a catastrophic one. | ||
| 108 | + | ||
| 109 | +A case has a pole at all only when `E_crit > 0`, i.e. when `T_baseline / T_HW < 2` | ||
| 110 | +— the same ratio, and the same threshold of 2, that makes a "0.5x `T_baseline`" | ||
| 111 | +target void. Read that ratio once and it answers both questions: below 2 the case | ||
| 112 | +is both hard to improve and capable of scoring zero for improving. | ||
| 113 | + | ||
| 114 | +### Reading the anchors | ||
| 115 | + | ||
| 116 | +`<hardware>` is resolved from the device name, and only some prefixes map to a | ||
| 117 | +metadata file. A device the mapping does not recognise yields no anchors and no | ||
| 118 | +performance points — diagnose that before concluding the kernel is slow. | ||
| 119 | + | ||
| 120 | +**`accurate_i` gates the whole term, including the 0.3.** A failing case | ||
| 121 | +contributes *nothing*, not 0.3. Writing the sum as `sum(0.3 + 0.5*score_i)` over | ||
| 122 | +all cases silently credits every failure with the base term — that mistake | ||
| 123 | +inflated a measured MlaProlog result from **57.95 to 62.46** before it was | ||
| 124 | +caught. One accurate case is worth `(0.3 + 0.5*score_i)/N`, which at a typical | ||
| 125 | +`score_i ≈ 0.2` is ~2 points out of 100: usually more than any plausible tuning | ||
| 126 | +of a case that already passes. | ||
| 127 | + | ||
| 128 | +That ratio is also how to decide whether an accuracy fix is worth its cost. A | ||
| 129 | +fix that converts one case but slows every case is frequently **net negative** — | ||
| 130 | +see [numerical-error-localisation.md](numerical-error-localisation.md) §3 for | ||
| 131 | +the worked arithmetic. | ||
| 132 | + | ||
| 133 | +**A target below `T_HW` is not a hard target, it is an impossible one.** `T_HW` | ||
| 134 | +is the published hardware lower bound, so any goal expressed as a fraction of | ||
| 135 | +`T_baseline` is unreachable whenever `T_baseline / T_HW` is below the reciprocal | ||
| 136 | +of that fraction — a "0.5x baseline" goal is void for every case whose ratio is | ||
| 137 | +under 2. Check the ratio distribution in `tasks/metadata/<hardware>.json` before | ||
| 138 | +accepting such a target: on MlaProlog 19 of 20 cases sit between 1.13 and 1.6, | ||
| 139 | +so 0.5x `T_baseline` lies beneath the roofline for all of them. Raise it as a | ||
| 140 | +specification problem rather than spending device time on it. | ||
| 141 | + | ||
| 142 | +## Ranking targets under the ceiling | ||
| 143 | + | ||
| 144 | +**Rank optimisation targets by the points they can still recover. Never by a | ||
| 145 | +marginal rate.** One rule, two instruments for it: | ||
| 146 | + | ||
| 147 | +| when | key | needs | | ||
| 148 | +|---|---|---| | ||
| 149 | +| **before any run** | `T_baseline / T_HW` | only `tasks/metadata/<hardware>.json` | | ||
| 150 | +| **after a scored baseline** | `R_i = (w_p * 100 / N) * (1 - score_i)`, from the **clamped** score | one baseline report | | ||
| 151 | + | ||
| 152 | +For a 20-case operator at `w_p = 0.5`, `R_i = 2.5 * (1 - score_i)`: the points | ||
| 153 | +still on the table for that case if it reached the modelled roofline. A case | ||
| 154 | +already scoring at or above 1.0 has `R_i = 0` — computed from the raw score it | ||
| 155 | +goes negative, which carries the same instruction: there is nothing there to | ||
| 156 | +recover. | ||
| 157 | + | ||
| 158 | +The two instruments agree, which is what makes the pre-run one usable. On the | ||
| 159 | +rms_norm suite below, case 15's ratio is `25.00 / 2.50` = **10.000**, the highest | ||
| 160 | +in the suite, and its `R_i` is **2.377**, also the highest. The ratio picks the | ||
| 161 | +target before a single kernel is written; `R_i` confirms it once a report exists. | ||
| 162 | + | ||
| 163 | +**Three quantities that must not be used as the key.** | ||
| 164 | + | ||
| 165 | +- **A marginal rate** such as `d pts at -10%`. It prices a small step around the | ||
| 166 | + current point and therefore assumes every case has a comparable achievable | ||
| 167 | + speedup. That assumption is what fails, and it fails hardest on exactly the | ||
| 168 | + case worth the most. | ||
| 169 | +- **`numel`.** `argmax(numel)` would have selected case 9 (33.5 M elements) as the | ||
| 170 | + bfloat16 representative and ranked case 15 — 2.0 M elements, the smallest in its | ||
| 171 | + family — next to last. | ||
| 172 | +- **`A_i`, the pole-proximity number.** `A_i = (w_p * 100 / N) * T_cand * | ||
| 173 | + (T_baseline - T_HW) / denom²` is the points moved by a 1× relative change in | ||
| 174 | + `T_cand`, so a 1 % timing wobble moves about `A_i / 100` points. It is a **risk | ||
| 175 | + guard**: above `A_i > 3` the case sits in the pole neighbourhood, its measured | ||
| 176 | + deltas are inside the noise, and it must not be pushed past `E_crit`. It is not | ||
| 177 | + a target selector, and it points the opposite way — case 15 has the **lowest | ||
| 178 | + `A_i` in the suite (0.117)** together with the highest `R_i`, while case 2 has | ||
| 179 | + `A_i` **9.485** and `R_i` 0. A low `A_i` does not mean "not worth optimising"; | ||
| 180 | + it means the points won there **stay won** and do not move with the noise. | ||
| 181 | + | ||
| 182 | +**The measured refutation of the marginal rate.** At entry, case 15 sat at | ||
| 183 | +438.73 µs against a 25.00 µs baseline and a 2.50 µs anchor — `score_i` 0.0490, | ||
| 184 | +`speedup` **0.057×**, seventeen times *slower* than the CANN reference. Its | ||
| 185 | +`d pts at -10%` was **+0.013**, dead last of twenty. Its `R_i` was **2.377**, | ||
| 186 | +first of twenty. The measurement settles which one was right: | ||
| 187 | + | ||
| 188 | +- A hand-built specialisation of case 15 alone moved it to **12.55 µs** | ||
| 189 | + (`score_i` 0.6912) for **+1.605 points**, while the other nineteen cases each | ||
| 190 | + moved within ±1.0 % for +0.039 between them. Case 15 was **98 % of that arm's | ||
| 191 | + entire gain** — the case the marginal column ranked last. | ||
| 192 | +- The shipped Stage-5 kernel moves the same case to **6.81 µs** (`score_i` | ||
| 193 | + 0.8392) for **+1.976 points** of the 2.377 available | ||
| 194 | + (`custom/rms_norm/_submission/eval/{control,stage5}.json`, on branch `stage5-kb-pr`). | ||
| 195 | + | ||
| 196 | +Case 15 was not near any ceiling. It was running a kernel structurally wrong for | ||
| 197 | +its shape — `[1000003, 2]`, two-element rows, on a kernel written for wide rows — | ||
| 198 | +so its achievable speedup was 35× for the probe and 64× for the shipped kernel, | ||
| 199 | +not the 10 % the marginal column assumed. | ||
| 200 | + | ||
| 201 | +**The signal that sees a structural mismatch is `speedup` against the CANN | ||
| 202 | +reference.** A case losing badly to the reference is not sitting near its | ||
| 203 | +ceiling; it is misconfigured, and its headroom is bounded by the pole rather than | ||
| 204 | +by the current kernel. | ||
| 205 | + | ||
| 206 | +| signal | reading | action | | ||
| 207 | +|---|---|---| | ||
| 208 | +| `speedup < 0.5x` | structural mismatch; headroom is large and unknown | **its own lever search, regardless of size or `numel` rank** | | ||
| 209 | +| low `score_i` **and** `E_crit` is `none` | far from the pole, can be pushed arbitrarily hard | high-value, low-risk — the best target class | | ||
| 210 | +| high `d pts at -10%` **and** near-pole | steep *and* fragile | guard it, do not chase it; noise here is worth points | | ||
| 211 | +| `score_i >= 1` | already beating the modelled roofline | `R_i` is 0; leave it | | ||
| 212 | + | ||
| 213 | +### The target sheet, ranked | ||
| 214 | + | ||
| 215 | +From the retained baseline report `custom/rms_norm/_submission/eval/control.json` (on branch `stage5-kb-pr`) | ||
| 216 | +(rms_norm, Ascend950PR, 20 cases, 20/20 accurate, OperatorScore 73.6112 raw / | ||
| 217 | +69.6075 clamped). `T_HW` and `T_baseline` are case constants published in the | ||
| 218 | +anchors, so the ratio, `E_crit` and the pole set are properties of the task and | ||
| 219 | +do not move between runs; only `T_cand` and the scores do. `max safe` is | ||
| 220 | +`T_cand / E_crit`, the speedup at which the case returns `None`. | ||
| 221 | + | ||
| 222 | +| case | `T_base/T_HW` | T_cand µs | E_crit µs | max safe | `score_i` raw | `score_i` clamped | `R_i` | d pts at -10% | | ||
| 223 | +|---|---|---|---|---|---|---|---|---| | ||
| 224 | +| 15 | 10.000 | 438.73 | none | unbounded | 0.0490 | 0.0490 | **2.377** | +0.013 | | ||
| 225 | +| 4 | 1.432 | 58.42 | 11.92 | 4.901x | 0.1948 | 0.1948 | **2.013** | +0.070 | | ||
| 226 | +| 12 | 1.469 | 62.52 | 11.80 | 5.298x | 0.2052 | 0.2052 | **1.987** | +0.072 | | ||
| 227 | +| 6 | 1.486 | 59.72 | 10.775 | 5.542x | 0.2081 | 0.2081 | **1.980** | +0.072 | | ||
| 228 | +| 18 | 1.580 | 33.50 | 4.40 | 7.614x | 0.2089 | 0.2089 | **1.978** | +0.068 | | ||
| 229 | +| 9 | 1.602 | 117.08 | 16.64 | 7.036x | 0.2511 | 0.2511 | **1.872** | +0.083 | | ||
| 230 | +| 3 | 1.626 | 29.78 | 3.92 | 7.597x | 0.2541 | 0.2541 | **1.865** | +0.083 | | ||
| 231 | +| 13 | 1.722 | 26.38 | 2.51 | 10.510x | 0.2727 | 0.2727 | **1.818** | +0.085 | | ||
| 232 | +| 8 | 1.546 | 95.24 | 19.00 | 5.013x | 0.3002 | 0.3002 | **1.749** | +0.107 | | ||
| 233 | +| 19 | 1.948 | 16.61 | 0.27 | 61.519x | 0.3035 | 0.3035 | **1.741** | +0.086 | | ||
| 234 | +| 20 | 1.433 | 61.95 | 18.95 | 3.269x | 0.3365 | 0.3365 | **1.659** | +0.142 | | ||
| 235 | +| 7 | 2.121 | 17.27 | none | unbounded | 0.3378 | 0.3378 | **1.656** | +0.090 | | ||
| 236 | +| 16 | 3.300 | 5.46 | none | unbounded | 0.3402 | 0.3402 | **1.649** | +0.075 | | ||
| 237 | +| 10 | 2.526 | 14.43 | none | unbounded | 0.3716 | 0.3716 | **1.571** | +0.089 | | ||
| 238 | +| 1 | 2.515 | 13.31 | none | unbounded | 0.3883 | 0.3883 | **1.529** | +0.092 | | ||
| 239 | +| 5 | 2.036 | 219.06 | none | unbounded | 0.3914 | 0.3914 | **1.521** | +0.107 | | ||
| 240 | +| 17 | 2.450 | 4.07 | none | unbounded | 0.6712 | 0.6712 | **0.822** | +0.144 | | ||
| 241 | +| 14 | 2.122 | 5.12 | none | unbounded | 0.7581 | 0.7581 | **0.605** | +0.191 | | ||
| 242 | +| 2 | 1.488 | 8.82 | 5.37 | 1.642x | 1.4841 | 1.0000 | **0.000** | **+0.000** / +1.274 raw | | ||
| 243 | +| 11 | 1.383 | 16.35 | 12.645 | 1.293x | 2.1174 | 1.0000 | **0.000** | **+0.000** / +4.181 raw | | ||
| 244 | + | ||
| 245 | +Read three things off it. | ||
| 246 | + | ||
| 247 | +- **The ranking and the marginal column disagree at both ends.** `R_i` puts case | ||
| 248 | + 15 first and cases 2 and 11 last; `d pts at -10%` puts case 15 last and, on the | ||
| 249 | + raw score, cases 11 and 2 first. Only the `R_i` ordering survived measurement. | ||
| 250 | +- **The clamped marginal column stops rewarding proximity to the pole.** Cases 2 | ||
| 251 | + and 11 gain +4.181 and +1.274 raw points from a further 10 %, and **0.000** | ||
| 252 | + clamped. The old coincidence of "highest value" and "highest risk" was a | ||
| 253 | + property of the unclamped derivative, not of the operator. | ||
| 254 | +- **Twelve of the twenty cases carry a pole** (2, 3, 4, 6, 8, 9, 11, 12, 13, 18, | ||
| 255 | + 19, 20) — a count, not a risk list. What matters is distance. In this suite only | ||
| 256 | + two cases are within 2× of `E_crit`: case 11 at **1.293×** and case 2 at | ||
| 257 | + **1.642×**. On the Stage-5 arm they exit at 20.65 µs (**1.633×**) and 9.56 µs | ||
| 258 | + (**1.780×**), and on the separate rms_norm submission quoted above at | ||
| 259 | + **1.425×** and **1.754×**. None of those is a crossing; all of them are close | ||
| 260 | + enough that a single measurement of either case is not an effect. | ||
| 261 | + | ||
| 262 | +## A near-pole case converts timing noise into points | ||
| 263 | + | ||
| 264 | +Between two runs of a submission with **identical bytes** — verified as the same | ||
| 265 | +six kernel symbols over the same 20 cases — case 11 moved from 18.02 to 20.55 µs | ||
| 266 | +(+14.0 percent) and its `score_i` from 1.4595 to 0.9924: **-1.168 points**, with | ||
| 267 | +no kernel change of any kind. Case 20 moved +66.8 percent and -1.119 points in | ||
| 268 | +the same pair, and the operator's performance term moved 27.497 to 24.401 | ||
| 269 | +(77.497 to 74.401 total). | ||
| 270 | + | ||
| 271 | +State the confound plainly: those two runs used different evaluator forks and | ||
| 272 | +different cards, so the +14 percent is not established as pure run-to-run noise. | ||
| 273 | +What *is* established is the conversion factor, and it is the point of the | ||
| 274 | +entry — near its pole, a case turns a 14 percent timing difference that changed | ||
| 275 | +no kernel into 1.168 points. | ||
| 276 | + | ||
| 277 | +**The floors it has to be read against.** Two arms run back-to-back in one | ||
| 278 | +session under one device lock reproduce the whole-operator score to **0.291** | ||
| 279 | +points (Ascend950PR, paired, A/B interleaved). Anything compared against a score | ||
| 280 | +*stored* from an earlier session carries the wider across-session floor: | ||
| 281 | +**range 0.908, σ 0.429** over four measurements in three sessions. One near-pole | ||
| 282 | +case moving on its own is worth several times either number, so a delta on such a | ||
| 283 | +case is not evidence until the arms are paired. | ||
| 284 | + | ||
| 285 | +## Detect pole crossings; do not engineer around them | ||
| 286 | + | ||
| 287 | +`T_HW` and `T_baseline` are case constants, so a ceiling computed once from a | ||
| 288 | +baseline report applies unchanged to every later arm. | ||
| 289 | + | ||
| 290 | +1. Compute `E_crit` and the max safe speedup for every case on the **baseline** | ||
| 291 | + report and publish them next to the target list. That is the distance measure. | ||
| 292 | +2. Recompute on each arm's report as a **detector**. Report any case with | ||
| 293 | + `T_cand <= E_crit * (1 + margin)` — 0.10 is a workable margin — and any case | ||
| 294 | + reporting a `perf_score` of `null` or `0` while its `status` is `success`. The | ||
| 295 | + second condition is a pole already crossed, and it is the one that is otherwise | ||
| 296 | + invisible. | ||
| 297 | +3. Report both means for the arm: **clamped as the headline figure**, raw | ||
| 298 | + alongside, naming every case above 1.0 and its distance to `E_crit`. | ||
| 299 | +4. Never read a single measurement of a near-pole case as an effect. On the | ||
| 300 | + operator above, cases 11 and 20 alone carry over 2 points of movement between | ||
| 301 | + runs that changed nothing. | ||
| 302 | + | ||
| 303 | +Write the fastest correct kernel and report what the evaluator computes. A case | ||
| 304 | +that has crossed the pole is not recovered by making it faster: the only | ||
| 305 | +kernel-side exits are to slow it back above `E_crit`, which is gaming, or to have | ||
| 306 | +never targeted it. | ||
| 307 | + | ||
| 308 | +**Recorded dissent, neither position measured.** One position on this team holds | ||
| 309 | +that step 2 should *fail* the arm rather than report it, on the reasoning that a | ||
| 310 | +crossed pole makes the arm's score unreadable and that a detector nobody reads is | ||
| 311 | +not a check — the arm ships, 2.5 points per crossed case are silently gone, and | ||
| 312 | +the loss is indistinguishable from a slow kernel. The instruction above is what | ||
| 313 | +this KB follows; the hard gate is available as a stricter local option and has | ||
| 314 | +never been compared against detection on real arms. | ||
| 315 | + | ||
| 316 | +### The clamp is not a constant offset | ||
| 317 | + | ||
| 318 | +Measured on one rms_norm campaign, three arms in one session on one card | ||
| 319 | +(Ascend950PR, A/B interleaved, `--perf-metric-strategy kernel_details`, warmup 3 / | ||
| 320 | +repeat 5): clamping cost the control arm **-4.0037** points, the Stage-4 arm | ||
| 321 | +**0.000**, and the Stage-5 arm **-0.5549**, because the arms differ in how many | ||
| 322 | +cases sit above 1.0 (control 2, Stage 4 none, Stage 5 one). The Stage-5-minus- | ||
| 323 | +control delta therefore **grew** under the clamp, from **+8.2307 raw** to | ||
| 324 | +**+11.6795 clamped**. | ||
| 325 | + | ||
| 326 | +A clamp correction measured on one arm may never be carried to another, and a raw | ||
| 327 | +delta and a clamped delta are different quantities. Report both, per arm, computed | ||
| 328 | +per arm. | ||
| 329 | + | ||
| 330 | +## Turn a box ratio into a predicted grader score before you submit | ||
| 331 | + | ||
| 332 | +Two rules collide: box absolutes never transfer, yet the levers you want to price were costed on | ||
| 333 | +grader data you cannot re-measure without spending a credit. The bridge is the half of the first rule | ||
| 334 | +that does hold -- **paired same-box RATIOS transfer**. Measure `r = T_after/T_before` on the box for | ||
| 335 | +a named cohort, then push `r` through the grader's own per-case `(T_cand, T_base, T_HW)` triples and | ||
| 336 | +recompute the score. Never scale a score; always recompute per case through | ||
| 337 | +`perf = (T_base - T_HW)/(T_cand + T_base - 2*T_HW)`. | ||
| 338 | + | ||
| 339 | +Validated on rms_norm 2026-08-10: a cohort predicted to move 1.65-2.03x moved **1.77-2.99x** on the | ||
| 340 | +grader, and the whole-set delta landed inside the projected band. | ||
| 341 | + | ||
| 342 | +**Two derivatives worth having, and they answer different questions:** | ||
| 343 | + | ||
| 344 | +| | formula | ranks | use for | | ||
| 345 | +|---|---|---|---| | ||
| 346 | +| `R_i` | `(50/N)(1 - perf)` | points still recoverable | **ratio** levers | | ||
| 347 | +| `M_i` | `(50/N)*perf^2/(T_base - T_HW)` | points per microsecond saved | **fixed-cost** levers | | ||
| 348 | + | ||
| 349 | +`M_i` is exactly `-d(score)/d(T_cand)`, so it is not a heuristic. They rank differently and the box's | ||
| 350 | +own `R_i` ranks differently again from the grader's -- pick the one matching the lever's shape, and | ||
| 351 | +compute it on the set you intend to be scored on. | ||
| 352 | + | ||
| 353 | +🔴 **Predict the comparison you are actually going to make.** In the run that validated this, the | ||
| 354 | +projected band was computed from an `A -> B` measurement isolating one lever, and then applied to a | ||
| 355 | +submission containing a *different* lever. The number landed inside the band anyway, which made a | ||
| 356 | +coincidence look like a confirmation. **State which two artifacts the ratio came from and check they | ||
| 357 | +are the two the submission compares**, or the agreement means nothing. | ||
| @@ -0,0 +1,127 @@ | |||
| 1 | +# 提交契约:权威来源与它没有覆盖的部分 | ||
| 2 | + | ||
| 3 | +`<cann-bench-root>` 指 CANN Bench checkout 根目录。 | ||
| 4 | + | ||
| 5 | +## 权威来源 | ||
| 6 | + | ||
| 7 | +**提交格式的规则由 CANN Bench 自己定义,本仓不保存副本:** | ||
| 8 | + | ||
| 9 | +``` | ||
| 10 | +<cann-bench-root>/src/auto_pipeline/generator/pypto_pro/converter/templates/to_cann.j2 | ||
| 11 | +``` | ||
| 12 | + | ||
| 13 | +组装提交前读这个文件。它定义 thin forwarder 的写法、参数绑定方式、多实现分发的复制规则、 | ||
| 14 | +`build.sh` 的产出要求,以及哪些改写属于越界。它随 cann-bench 演进——本技能刻意不复述它的条款, | ||
| 15 | +因为一份复制品只会在它变更时变成错误信息。 | ||
| 16 | + | ||
| 17 | +同样属于 CANN Bench 侧、需要直接读原文的: | ||
| 18 | + | ||
| 19 | +| 内容 | 路径 | | ||
| 20 | +|---|---| | ||
| 21 | +| 提交原则与禁止行为(反作弊边界) | `docs/guide/submission_rules.md` | | ||
| 22 | +| PyPTO 提交的参考实现与评测方式 | `examples/pypto_example/README.md` | | ||
| 23 | +| 每个 case 独立子进程的执行方式 | `src/kernel_eval/eval/pypto_pro_child.py` | | ||
| 24 | + | ||
| 25 | +## 本文负责的部分 | ||
| 26 | + | ||
| 27 | +下面这些规则**不在 `to_cann.j2` 里**,但违反同样会让提交归零或丢分。 | ||
| 28 | +每条都给出可观测的失败现象,便于从症状反查。 | ||
| 29 | + | ||
| 30 | +### class 子目录必须以 `c` 开头 | ||
| 31 | + | ||
| 32 | +`pypto_pro_child.py` 在导入提交后,会把 `cann_bench/` 下**名字以 `c` 开头**的子目录逐个插入 | ||
| 33 | +`sys.path`,让 class wrapper 里 `from <op>_golden import ...` 这类同级导入能解析: | ||
| 34 | + | ||
| 35 | +```python | ||
| 36 | +for name in sorted(os.listdir(pkg_dir)): | ||
| 37 | + cpath = os.path.join(pkg_dir, name) | ||
| 38 | + if os.path.isdir(cpath) and name.startswith("c"): | ||
| 39 | + sys.path.insert(0, cpath) | ||
| 40 | +``` | ||
| 41 | + | ||
| 42 | +内容派生的 family 名(例如 `axis-sensitive-f16-ax1-5b281577`)不满足这个前缀, | ||
| 43 | +不会被注入。**影响范围仅限依赖同级导入的 wrapper**——不依赖时不会立刻出错, | ||
| 44 | +所以这是一个会潜伏到某个 class 才暴露的问题。用 `c1 … cN` 命名可以完全规避。 | ||
| 45 | + | ||
| 46 | +失败现象:某个 class 的 case 报 `ModuleNotFoundError: No module named '<op>_golden'`, | ||
| 47 | +而其它 class 正常。 | ||
| 48 | + | ||
| 49 | +### 评测按关键字调用,dispatcher 按位置算签名 | ||
| 50 | + | ||
| 51 | +评测子进程的调用是 `func(**params)`,键取自**任务 golden 的签名**,不是候选实现的签名。 | ||
| 52 | +而生成的 dispatcher 通常按位置参数计算 `(ndim, dtype)` 签名: | ||
| 53 | + | ||
| 54 | +```python | ||
| 55 | +def _signature(args): | ||
| 56 | + for a in args: ... # 只看位置参数 | ||
| 57 | +``` | ||
| 58 | + | ||
| 59 | +两者相接的唯一正确方式,是 thin forwarder **把 tensor 按位置传给 dispatcher,把 attrs 按关键字传**: | ||
| 60 | + | ||
| 61 | +```python | ||
| 62 | +def <op>(input, gamma=None, epsilon=1e-6): # 无返回值标注 | ||
| 63 | + return _dispatch(input, gamma, epsilon=epsilon) | ||
| 64 | +``` | ||
| 65 | + | ||
| 66 | +两个方向都会出错: | ||
| 67 | + | ||
| 68 | +- tensor 写成关键字 → dispatcher 看到空签名 → `no <op> class for signature []`,**全部 case 归零**。 | ||
| 69 | +- attrs 写成位置 → class wrapper 的 attrs 常是 keyword-only → | ||
| 70 | + `TypeError: takes N positional arguments but M were given`。 | ||
| 71 | + | ||
| 72 | +### 入口必须在 `dir(cann_bench)` 顶层 | ||
| 73 | + | ||
| 74 | +`kernel_eval` 的 `scan_interfaces()` 只扫描 `dir(cann_bench)` 里的顶层非下划线可调用对象。 | ||
| 75 | +空的 `__init__.py`、或只在子模块里定义 forwarder,都会让评测报 `未扫描到任何cann_bench接口`。 | ||
| 76 | + | ||
| 77 | +### 入口不能带返回值标注 | ||
| 78 | + | ||
| 79 | +`cann_bench.<op>` 不能有 Python 返回值标注,也不能继承原始入口的 `__annotations__`, | ||
| 80 | +否则 Profiler 首次调用时会把公开入口误识别为 PyPTO-Pro 返回值 kernel。 | ||
| 81 | + | ||
| 82 | +验证方式是 `inspect.signature(fn).return_annotation is inspect.Signature.empty`。 | ||
| 83 | + | ||
| 84 | +### `build.sh` 必须真的产出 wheel | ||
| 85 | + | ||
| 86 | +`kernel_eval` 只在 `dist/cann_bench*.whl` 存在时认为编译成功。 | ||
| 87 | +只做语法或 import 检查的 `build.sh` 即使返回 0 也判编译失败。 | ||
| 88 | + | ||
| 89 | +### 关于 dispatcher 的两种修法 | ||
| 90 | + | ||
| 91 | +两种写法都能解决"评测按关键字调用,dispatcher 按位置算签名"这个问题,选一种,不要混用: | ||
| 92 | + | ||
| 93 | +1. **thin forwarder + 位置 dispatcher**(手写提交时的默认路径):dispatcher 保持按位置算签名, | ||
| 94 | + 由 forwarder 负责把 tensor 按位置传入、attrs 按关键字传入(上面那条)。 | ||
| 95 | + 遇到 `no <op> class for signature []` 时,改 forwarder,不要改 dispatcher。 | ||
| 96 | +2. **按 golden 参数顺序绑定的 dispatcher**(`tools/build_submission.py` 生成的路径): | ||
| 97 | + dispatcher 自己先把 `args`/`kwargs` 按 golden 声明的参数顺序(tensor 与非 tensor 参数 | ||
| 98 | + 交错也一样,用完整参数序号索引,不是只数 tensor 槽位)绑定成 dict,再从绑定结果里取 | ||
| 99 | + tensor 槽位算签名。这样 dispatcher 本身同时接受位置调用和关键字调用,不需要额外的 | ||
| 100 | + forwarder。生成器与自检见 [`tools/build_submission.py`](../../../../tools/build_submission.py)。 | ||
| 101 | + | ||
| 102 | +**两者的区别只在"谁负责翻译关键字调用"**:写法 1 是 forwarder,写法 2 是 dispatcher 自己。 | ||
| 103 | +手写提交、且已经有 forwarder 时用写法 1;用生成器组装多 class 提交时直接用写法 2, | ||
| 104 | +不必再手写一层 forwarder。 | ||
| 105 | + | ||
| 106 | +## 一次性校验 | ||
| 107 | + | ||
| 108 | +上述规则由 [`../scripts/check_submission.py`](../scripts/check_submission.py) 离线覆盖, | ||
| 109 | +不需要 NPU,也不需要本机装 `pypto`。 | ||
| 110 | + | ||
| 111 | +## 关于 KB 契约文件的现状 | ||
| 112 | + | ||
| 113 | +[`kb/CONTRACT.md`](../../../ops/pypto-pro-op-kb/CONTRACT.md) 描述了 `KB_SELECTION.json` / `KB_USAGE.json` | ||
| 114 | +由 CANN Bench 的 `auto_pipeline.kb_contract` 校验。**在当前可见的 cann-bench checkout | ||
| 115 | +(含其 claude-fixes 兄弟目录)中不存在该模块**:`src/auto_pipeline/` 下只有 | ||
| 116 | +`cli.py`、`config`、`converter`、`core.py`、`generator`、`prompt`、`state.py`, | ||
| 117 | +全仓也搜不到 `kb_contract` / `KB_SELECTION` / `KB_USAGE` 的实现引用。 | ||
| 118 | + | ||
| 119 | +**注意 `ops/pypto-pro-op-kb/check_kb_integrity.py` 的 `consumer agrees with the contract` 这一项会显示 `ok`, | ||
| 120 | +但它是空过的**:该检查在找不到 `<cann-bench>/src/auto_pipeline/kb_contract.py` 时直接返回无错误 | ||
| 121 | +(见 `check_consumer_agrees` 的 docstring 与 `_consumer_module`)。即使用 | ||
| 122 | +`CANN_BENCH_ROOT=<cann-bench-root>` 显式指向真实 checkout,结果仍是 `ok`——因为模块不存在。 | ||
| 123 | +这个绿灯不能当作"契约已被校验"的证据。 | ||
| 124 | + | ||
| 125 | +结论:这两个文件目前是**产出契约,尚无自动校验**。 | ||
| 126 | +按 `CONTRACT.md` 的要求生成它们仍然有效,但不要假设有一道机器门禁会拦住不合规的产出, | ||
| 127 | +也不要因为"校验没报错"就认为选择是合规的。 | ||
| @@ -0,0 +1,572 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +"""离线校验一个 PyPTO-Pro cann_bench 提交,无需 NPU、无需执行 kernel。 | ||
| 11 | + | ||
| 12 | +覆盖 cann-bench 转换契约要求、但目前没有工具承载的那部分本地检查: | ||
| 13 | +入口是否会被 ``scan_interfaces()`` 扫到、调用是否能按 golden 签名绑定、 | ||
| 14 | +dispatcher 是否把每个 class 的 (ndim, dtype) 签名路由到对应实现。 | ||
| 15 | + | ||
| 16 | +这些失败在评测机上表现为 ``未扫描到任何cann_bench接口``、``TypeError`` 或 | ||
| 17 | +``no <op> class for signature []``——全部 20 个 case 归零,且到上板才暴露。 | ||
| 18 | + | ||
| 19 | +用法 | ||
| 20 | +---- | ||
| 21 | + # 完整模式:从 cann-bench 任务读取 golden 签名与 cases.yaml | ||
| 22 | + python3 check_submission.py --submission build/submission --op swi_glu \ | ||
| 23 | + --bench-root /path/to/cann-bench --level level1 | ||
| 24 | + | ||
| 25 | + # 降级模式:无 cann-bench checkout,仅按 dispatcher 自带的 _CLASSES 校验路由 | ||
| 26 | + python3 check_submission.py --submission build/submission --op swi_glu | ||
| 27 | + | ||
| 28 | +退出码:存在 FAIL 时为 1,否则为 0。SKIP 不影响退出码。 | ||
| 29 | +""" | ||
| 30 | + | ||
| 31 | +from __future__ import annotations | ||
| 32 | + | ||
| 33 | +import argparse | ||
| 34 | +import ast | ||
| 35 | +import importlib | ||
| 36 | +import importlib.util | ||
| 37 | +import inspect | ||
| 38 | +import json | ||
| 39 | +import logging | ||
| 40 | +import sys | ||
| 41 | +from dataclasses import dataclass | ||
| 42 | +from pathlib import Path | ||
| 43 | +from typing import Any | ||
| 44 | + | ||
| 45 | +LOGGER = logging.getLogger(__name__) | ||
| 46 | + | ||
| 47 | +# 评测框架识别的 dtype 名到 torch dtype。键取自 cases.yaml 的 dtype 字段。 | ||
| 48 | +_TORCH_DTYPES = { | ||
| 49 | + "float16": "float16", | ||
| 50 | + "half": "float16", | ||
| 51 | + "bfloat16": "bfloat16", | ||
| 52 | + "float32": "float32", | ||
| 53 | + "float": "float32", | ||
| 54 | + "float64": "float64", | ||
| 55 | + "int8": "int8", | ||
| 56 | + "uint8": "uint8", | ||
| 57 | + "int16": "int16", | ||
| 58 | + "int32": "int32", | ||
| 59 | + "int64": "int64", | ||
| 60 | + "long": "int64", | ||
| 61 | + "bool": "bool", | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +class Report: | ||
| 66 | + """按检查项累计 PASS / FAIL / SKIP,并决定退出码。""" | ||
| 67 | + | ||
| 68 | + def __init__(self) -> None: | ||
| 69 | + self.rows: list[tuple[str, str, str]] = [] | ||
| 70 | + | ||
| 71 | + @property | ||
| 72 | + def failures(self) -> int: | ||
| 73 | + return sum(1 for status, _, _ in self.rows if status == "FAIL") | ||
| 74 | + | ||
| 75 | + def add(self, status: str, name: str, detail: str = "") -> None: | ||
| 76 | + self.rows.append((status, name, detail)) | ||
| 77 | + mark = {"PASS": "ok ", "FAIL": "FAIL", "SKIP": "skip"}[status] | ||
| 78 | + LOGGER.info(f" {mark} {name}" + (f" — {detail}" if detail else "")) | ||
| 79 | + | ||
| 80 | + def passed(self, name: str, detail: str = "") -> None: | ||
| 81 | + self.add("PASS", name, detail) | ||
| 82 | + | ||
| 83 | + def failed(self, name: str, detail: str = "") -> None: | ||
| 84 | + self.add("FAIL", name, detail) | ||
| 85 | + | ||
| 86 | + def skipped(self, name: str, detail: str = "") -> None: | ||
| 87 | + self.add("SKIP", name, detail) | ||
| 88 | + | ||
| 89 | + def summary(self) -> str: | ||
| 90 | + counts = {"PASS": 0, "FAIL": 0, "SKIP": 0} | ||
| 91 | + for status, _, _ in self.rows: | ||
| 92 | + counts[status] += 1 | ||
| 93 | + return f"{counts['PASS']} passed, {counts['FAIL']} failed, {counts['SKIP']} skipped" | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +@dataclass(frozen=True) | ||
| 97 | +class RoutingContext: | ||
| 98 | + entry: Any | ||
| 99 | + torch: Any | ||
| 100 | + classes: list[dict[str, Any]] | ||
| @@ -1,6 +1,6 @@ | |||
| 1 | --- | 1 | --- |
| 2 | name: pypto-pro-environment-check | 2 | name: pypto-pro-environment-check |
| 3 | -description: PyPTO-Pro 环境检测与反馈技能。当 PyPTO-Pro 工作流(Stage 1–4)任意阶段遇到疑似环境问题(软件/硬件)时统一加载:torch_npu / pypto_pro 导入失败、npu-smi 无响应、NPU 设备不可见或不可用、CANN 未配置、kernel 编译/运行超时疑似设备 hang 等。采用「事实验证优先、脚本诊断兜底」两步法 + 设备 hang 三段式评定,用于区分环境故障与算子故障;只执行有界检测并返回结构化证据,不安装依赖、不修改环境。触发词:环境检查、环境问题、环境验证、environment check、设备 hang、卡死、超时。 | 3 | +description: PyPTO-Pro 环境检测与反馈技能。当 PyPTO-Pro 工作流(Stage 1–5)任意阶段遇到疑似环境问题(软件/硬件)时统一加载:torch_npu / pypto_pro 导入失败、npu-smi 无响应、NPU 设备不可见或不可用、CANN 未配置、kernel 编译/运行超时疑似设备 hang 等。采用「事实验证优先、脚本诊断兜底」两步法 + 设备 hang 三段式评定,用于区分环境故障与算子故障;只执行有界检测并返回结构化证据,不安装依赖、不修改环境。触发词:环境检查、环境问题、环境验证、environment check、设备 hang、卡死、超时。 |
| 4 | --- | 4 | --- |
| 5 | 5 | ||
| 6 | # PyPTO-Pro 环境检测(pypto-pro-environment-check) | 6 | # PyPTO-Pro 环境检测(pypto-pro-environment-check) |
| @@ -0,0 +1,110 @@ | |||
| 1 | +# Copyright (c) 2024-2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | +# Compiler examples stay self-contained so each file exposes a complete kernel pattern. | ||
| 10 | + | ||
| 11 | +import logging | ||
| 12 | +import os | ||
| 13 | +import sys | ||
| 14 | +from dataclasses import dataclass | ||
| 15 | +from importlib import import_module | ||
| 16 | + | ||
| 17 | +import pypto_pro.language as pl | ||
| 18 | +import torch | ||
| 19 | + | ||
| 20 | +import_module("torch_npu") # Register torch.npu on supported installations. | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +@dataclass | ||
| 24 | +class OpTiling: | ||
| 25 | + """Compatibility tiling payload retained for existing smoke-test callers.""" | ||
| 26 | + | ||
| 27 | + valid_size: int | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +@pl.jit(auto_mutex=True) | ||
| 31 | +def matmul_example( | ||
| 32 | + a: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP16], | ||
| 33 | + b: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP16], | ||
| 34 | + out: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP16], | ||
| 35 | + tiling: OpTiling, | ||
| 36 | +): | ||
| 37 | + num_cores = pl.get_block_num() | ||
| 38 | + core_id = pl.get_block_idx() | ||
| 39 | + valid_n = 128 | ||
| 40 | + with pl.section_cube(): | ||
| 41 | + a_mat_4_buffer = pl.make_tile_group( | ||
| 42 | + type=pl.TileType( | ||
| 43 | + shape=[128, 128], dtype=pl.DT_FP16, | ||
| 44 | + target_memory=pl.MemorySpace.Mat, | ||
| 45 | + valid_shape=[valid_n, valid_n]), | ||
| 46 | + addrs=0, mutex_ids=[0, 1, 10, 11]) | ||
| 47 | + b_mat_4_buffer = pl.make_tile_group( | ||
| 48 | + type=pl.TileType(shape=[128, 128], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Mat), | ||
| 49 | + addrs=0x20000, mutex_ids=[2, 3, 12, 13]) | ||
| 50 | + a_left_db = pl.make_tile_group( | ||
| 51 | + type=pl.TileType(shape=[128, 128], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Left), | ||
| 52 | + addrs=0, mutex_ids=[4, 5]) | ||
| 53 | + b_right_db = pl.make_tile_group( | ||
| 54 | + type=pl.TileType(shape=[128, 128], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Right), | ||
| 55 | + addrs=0, mutex_ids=[6, 7]) | ||
| 56 | + acc_db = pl.make_tile_group( | ||
| 57 | + type=pl.TileType(shape=[128, 128], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Acc), | ||
| 58 | + addrs=0, mutex_ids=[8, 9]) | ||
| 59 | + | ||
| 60 | + for i in pl.range(core_id, a.shape[0] // 128, num_cores): | ||
| 61 | + a_l1_tile = a_mat_4_buffer.next() | ||
| 62 | + pl.load_tile(a_l1_tile, a, [i, 0]) | ||
| 63 | + for j in pl.range(0, b.shape[1] // 128, 1): | ||
| 64 | + b_l1_tile = b_mat_4_buffer.next() | ||
| 65 | + pl.load_tile(b_l1_tile, b, [0, j]) | ||
| 66 | + | ||
| 67 | + cur_a_left = a_left_db.next() | ||
| 68 | + pl.move(cur_a_left, a_l1_tile) | ||
| 69 | + cur_b_right = b_right_db.next() | ||
| 70 | + pl.move(cur_b_right, b_l1_tile) | ||
| 71 | + | ||
| 72 | + acc_tile = acc_db.next() | ||
| 73 | + pl.matmul(acc_tile, cur_a_left, cur_b_right) | ||
| 74 | + pl.store_tile(out, acc_tile, [i, j]) | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +def run_perf_test(num_iters: int = 20, warmup: int = 3): | ||
| 78 | + """Run the historical one-shot correctness smoke. | ||
| 79 | + | ||
| 80 | + ``num_iters`` and ``warmup`` remain accepted for callers of the original | ||
| 81 | + helper; this environment gate intentionally performs one kernel launch. | ||
| 82 | + """ | ||
| 83 | + logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout) | ||
| 84 | + device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", "0")) | ||
| 85 | + device = f"npu:{device_id}" | ||
| 86 | + torch.npu.set_device(device_id) | ||
| 87 | + torch.manual_seed(42) | ||
| 88 | + m_size = 8192 | ||
| 89 | + n_size = 8192 | ||
| 90 | + k_size = 128 | ||
| 91 | + a = torch.randn(m_size, k_size, device=device, dtype=torch.float16) | ||
| 92 | + b = torch.randn(k_size, n_size, device=device, dtype=torch.float16) | ||
| 93 | + out = torch.zeros(m_size, n_size, device=device, dtype=torch.float16) | ||
| 94 | + core_num = 32 | ||
| 95 | + tiling = OpTiling(valid_size=128) | ||
| 96 | + matmul_example[None, core_num](a, b, out, tiling) | ||
| 97 | + torch.npu.synchronize() | ||
| 98 | + golden = torch.matmul(a.float(), b.float()).half() | ||
| 99 | + max_diff = (out.float() - golden.float()).abs().max().item() | ||
| 100 | + logging.info("Max diff vs golden: %.6f", max_diff) | ||
| 101 | + torch.testing.assert_close(out, golden, rtol=1e-2, atol=1e-2) | ||
| 102 | + logging.info("Correctness PASS") | ||
| 103 | + | ||
| 104 | + | ||
| 105 | +def test_matmul_perf_asw_8k_k128_dn_move_offset(): | ||
| 106 | + run_perf_test() | ||
| 107 | + | ||
| 108 | + | ||
| 109 | +if __name__ == "__main__": | ||
| 110 | + run_perf_test() | ||
| @@ -99,6 +99,11 @@ P0/P1 必须进入首个版本;P2 可选;P3 明确暂缓。不要在本 skil | |||
| 99 | - `default_params` 只包含公开签名中已确认的标量默认参数;没有则写 `{}`; | 99 | - `default_params` 只包含公开签名中已确认的标量默认参数;没有则写 `{}`; |
| 100 | - `tolerance`、动态轴范围、shape 约束和性能目标直接记录已确认裁定; | 100 | - `tolerance`、动态轴范围、shape 约束和性能目标直接记录已确认裁定; |
| 101 | 101 | ||
| 102 | +性能目标遵循单一来源规则:只有用户明确给出且可复算的数值目标时,才把该值写入 | ||
| 103 | +`perf_target`,并在 SPEC“P0 与性能目标依据”中记录用户来源。用户未指定数值目标时, | ||
| 104 | +`perf_target` 写 `null`,并在“自动决策”中说明 Stage 5 将使用逐 P0 case 的默认目标 | ||
| 105 | +`golden_reference_ratio >= 1.0`;不得把这一系统默认值写成用户要求。 | ||
| 106 | + | ||
| 102 | 所有 P0 的映射 key 与顺序分别等于 `default_params`、`inputs`、`outputs`;具体 shape 必须 | 107 | 所有 P0 的映射 key 与顺序分别等于 `default_params`、`inputs`、`outputs`;具体 shape 必须 |
| 103 | 等于把本 case 输入/参数代入合同 shape 表达式后的结果。rank-0 tensor 写 `[]`。tile/kernel | 108 | 等于把本 case 输入/参数代入合同 shape 表达式后的结果。rank-0 tensor 写 `[]`。tile/kernel |
| 104 | shape 仍由 Stage 3 决定。每个动态 shape 符号须在至少一个输入维中单独出现,保证 P0 | 109 | shape 仍由 Stage 3 决定。每个动态 shape 符号须在至少一个输入维中单独出现,保证 P0 |
| @@ -120,4 +125,5 @@ python "$CANNBOT_CONFIG_ROOT/skills/pypto-pro-intent-understand/scripts/validate | |||
| 120 | - 所有 P0 配置均可供 golden 构造输入,且输出 shape 与机器合同公式一致; | 125 | - 所有 P0 配置均可供 golden 构造输入,且输出 shape 与机器合同公式一致; |
| 121 | - 所有机器合同输入/输出均有有依据、可解析的有限 `value_range`; | 126 | - 所有机器合同输入/输出均有有依据、可解析的有限 `value_range`; |
| 122 | - SPEC 恰有一个严格 JSON machine-contract、正文没有重复机器字段、无占位符或未披露默认值; | 127 | - SPEC 恰有一个严格 JSON machine-contract、正文没有重复机器字段、无占位符或未披露默认值; |
| 128 | +- 用户性能目标或 Stage 5 默认 Golden 1.0 目标的来源已按规则明确记录; | ||
| 123 | - `validate_spec.py` 通过。 | 129 | - `validate_spec.py` 通过。 |
| @@ -30,6 +30,7 @@ VALID = '''```json machine-contract | |||
| 30 | "tolerance": {"atol": 0.001, "rtol": 0.002}, | 30 | "tolerance": {"atol": 0.001, "rtol": 0.002}, |
| 31 | "dynamic_axes_ranges": {"N": [1, 128]}, | 31 | "dynamic_axes_ranges": {"N": [1, 128]}, |
| 32 | "shape_constraints": [], | 32 | "shape_constraints": [], |
| 33 | + "perf_target": null, | ||
| 33 | "p0_cases": [ | 34 | "p0_cases": [ |
| 34 | {"name": "small", "params": {}, "input_shapes": {"x": [8, 16]}, "output_shapes": {"y": [8, 16]}}, | 35 | {"name": "small", "params": {}, "input_shapes": {"x": [8, 16]}, "output_shapes": {"y": [8, 16]}}, |
| 35 | {"name": "large", "params": {}, "input_shapes": {"x": [32, 16]}, "output_shapes": {"y": [32, 16]}} | 36 | {"name": "large", "params": {}, "input_shapes": {"x": [32, 16]}, "output_shapes": {"y": [32, 16]}} |
| @@ -84,6 +85,19 @@ class SpecValidationTests(unittest.TestCase): | |||
| 84 | bad = VALID.replace('"schema_version": 1,', '"schema_version": 1,\n "extra": true,') | 85 | bad = VALID.replace('"schema_version": 1,', '"schema_version": 1,\n "extra": true,') |
| 85 | self.assertIn("unknown fields", validate_text(bad)[0]) | 86 | self.assertIn("unknown fields", validate_text(bad)[0]) |
| 86 | 87 | ||
| 88 | + def test_perf_target_is_null_or_positive_finite_number(self) -> None: | ||
| 89 | + self.assertEqual(validate_text(VALID), []) | ||
| 90 | + self.assertEqual(validate_text(VALID.replace('"perf_target": null', | ||
| 91 | + '"perf_target": 1.25')), []) | ||
| 92 | + for invalid in ('"未指定"', "true", "0", "-1", "{}"): | ||
| 93 | + with self.subTest(invalid=invalid): | ||
| 94 | + errors = validate_text( | ||
| 95 | + VALID.replace('"perf_target": null', f'"perf_target": {invalid}')) | ||
| 96 | + self.assertIn("perf_target", errors[0]) | ||
| 97 | + non_finite = validate_text( | ||
| 98 | + VALID.replace('"perf_target": null', '"perf_target": NaN')) | ||
| 99 | + self.assertIn("non-finite JSON number", non_finite[0]) | ||
| 100 | + | ||
| 87 | def test_rejects_unknown_dtype_and_dynamic_symbol_drift(self) -> None: | 101 | def test_rejects_unknown_dtype_and_dynamic_symbol_drift(self) -> None: |
| 88 | unknown_dtype = VALID.replace('"float32"', '"banana"') | 102 | unknown_dtype = VALID.replace('"float32"', '"banana"') |
| 89 | self.assertIn("canonical dtypes", validate_text(unknown_dtype)[0]) | 103 | self.assertIn("canonical dtypes", validate_text(unknown_dtype)[0]) |
| @@ -332,6 +332,14 @@ def _validate_tolerance(value: Any) -> None: | |||
| 332 | _number(value[key], f"tolerance.{key}", non_negative=True) | 332 | _number(value[key], f"tolerance.{key}", non_negative=True) |
| 333 | 333 | ||
| 334 | 334 | ||
| 335 | +def _validate_perf_target(value: Any) -> None: | ||
| 336 | + if value is None: | ||
| 337 | + return | ||
| 338 | + target = _number(value, "perf_target") | ||
| 339 | + if target <= 0: | ||
| 340 | + raise SpecContractError("perf_target must be null or a positive finite number") | ||
| 341 | + | ||
| 342 | + | ||
| 335 | def _valid_range_bounds(value: Any) -> bool: | 343 | def _valid_range_bounds(value: Any) -> bool: |
| 336 | if not isinstance(value, list): | 344 | if not isinstance(value, list): |
| 337 | return False | 345 | return False |
| @@ -409,6 +417,7 @@ def _validate(contract: dict[str, Any]) -> dict[str, Any]: | |||
| 409 | _validate_tensor_dtypes(dtypes, inputs, outputs) | 417 | _validate_tensor_dtypes(dtypes, inputs, outputs) |
| 410 | defaults = _default_params(contract["default_params"]) | 418 | defaults = _default_params(contract["default_params"]) |
| 411 | _validate_tolerance(contract["tolerance"]) | 419 | _validate_tolerance(contract["tolerance"]) |
| 420 | + _validate_perf_target(contract.get("perf_target")) | ||
| 412 | ranges = _dynamic_ranges(contract["dynamic_axes_ranges"]) | 421 | ranges = _dynamic_ranges(contract["dynamic_axes_ranges"]) |
| 413 | used_symbols = _shape_symbols(inputs + outputs) | 422 | used_symbols = _shape_symbols(inputs + outputs) |
| 414 | _validate_dynamic_symbols(ranges, used_symbols, inputs) | 423 | _validate_dynamic_symbols(ranges, used_symbols, inputs) |
| @@ -32,6 +32,16 @@ description: 设计 PyPTO-Pro 算子的 tile 级执行方案。当 Stage 1/2 产 | |||
| 32 | > 不要凭页面描述照写。 | 32 | > 不要凭页面描述照写。 |
| 33 | 平台专属约束必须先探测目标平台。API 文档与当前环境的官方样例仍是签名和行为的权威来源。 | 33 | 平台专属约束必须先探测目标平台。API 文档与当前环境的官方样例仍是签名和行为的权威来源。 |
| 34 | 34 | ||
| 35 | +**在划分 Phase / Section 结构之前先查 pattern selector**:可复用的 pl 数据流骨架就在 | ||
| 36 | +[`pypto-pro-op-kb/patterns/`](../../pypto-pro-op-kb/patterns/pattern-index.md),选好再设计比设计完再对照便宜。 | ||
| 37 | + | ||
| 38 | +⚠️ **Pro 流程只允许单一 `@pl.jit` kernel**,所以除 `Validation` 列之外,还须看 pattern 页标题 | ||
| 39 | +下方是否带 `Pro: not legal` banner。带该 banner 的页(当前无此类页面)所描述的多 kernel 形态属于「知识 | ||
| 40 | +成立、Pro 设计非法」——产出这样的 DESIGN.md 只会在 `stage4-check` #5 被拦下并浪费一轮迭代;只取 | ||
| 41 | +其融合单 kernel 子形态(同一个 `@pl.jit` 内多个 section)。机器可读的清单是 | ||
| 42 | +[`pypto-pro-op-kb/topology-map.json`](../../pypto-pro-op-kb/topology-map.json) 的 `target_gated`;pattern selector 本身只标注 | ||
| 43 | +validation 状态,不含合法性列,不要从中推读。 | ||
| 44 | + | ||
| 35 | ## 输入 | 45 | ## 输入 |
| 36 | 46 | ||
| 37 | | 来源 | 路径 | 用途 | | 47 | | 来源 | 路径 | 用途 | |
| @@ -0,0 +1,143 @@ | |||
| 1 | +# CV matmul direct handoff and rotating buffers | ||
| 2 | + | ||
| 3 | +Use this reference for A5 Cube matmul kernels whose accumulator is consumed by | ||
| 4 | +a Vector epilogue in the same launch. It adapts the EasyASC `DBuff + auto_sync` | ||
| 5 | +shape to PyPTO-Pro `make_tile_group + auto_mutex`; it is not a drop-in operator. | ||
| 6 | + | ||
| 7 | +## Buffer map | ||
| 8 | + | ||
| 9 | +For a two-level K loop, start from the target SDK's official dynamic-ASW roles: | ||
| 10 | + | ||
| 11 | +| role | depth | cursor operation | | ||
| 12 | +|---|---:|---| | ||
| 13 | +| A/B Mat (L1) | 4 | `.next()` once per non-empty K1 iteration | | ||
| 14 | +| A/B Left/Right (L0) | 2 | `.next()` once per non-empty K0 iteration | | ||
| 15 | +| int32 Acc (L0C) | 1 | `.current()` once per output tile | | ||
| 16 | +| direct int32 Vec tile | 1 | `.current()` once per output tile | | ||
| 17 | + | ||
| 18 | +A scalar `addrs=` value is the first TileGroup slot base. PyPTO-Pro lays later | ||
| 19 | +slots contiguously by physical tile bytes. Prove the high-water mark with the | ||
| 20 | +largest compile-time tile family; do not count only the logical tail window. | ||
| 21 | +L0A, L0B and L0C are different memories, while both Mat operands share L1. | ||
| 22 | + | ||
| 23 | +Assign every simultaneously live TileGroup a unique mutex ID. In a fused | ||
| 24 | +cross-core kernel, reserve the logical READY/FREE IDs and their AIV mirrors | ||
| 25 | +before assigning buffer IDs; on the validated A5 mapping, logical 0/1 occupy | ||
| 26 | +physical 0/1/16/17. | ||
| 27 | + | ||
| 28 | +## Direct Acc-to-Vector handoff | ||
| 29 | + | ||
| 30 | +If the final accumulator uses `pl.move(..., acc_to_vec_mode=...)` instead of an | ||
| 31 | +Acc store: | ||
| 32 | + | ||
| 33 | +- leave `phase` unspecified on `pl.matmul` and `pl.matmul_acc`; a TMOV has no | ||
| 34 | + `STPhase.Final` peer to reset the Acc unit flag; | ||
| 35 | +- pin a compact Acc to its full physical window before the first matmul and do | ||
| 36 | + not narrow it before TMOV; use `[tile_m, tile_n]` so a gated wider family is | ||
| 37 | + not silently decoded with the baseline TN; | ||
| 38 | +- use the matching hardware split only when each AIV share fits UB and final GM | ||
| 39 | + stores cannot share an unaligned 32-byte beat; otherwise select a proven | ||
| 40 | + single-AIV family; | ||
| 41 | +- retain a matching-runtime-proven M-to-FIX dependency. Older deployments may | ||
| 42 | + require the explicit `sync_src/sync_dst(M,FIX)` compatibility pair even when | ||
| 43 | + a newer auto-mutex test shows the Acc release/FIX acquire edge. | ||
| 44 | + | ||
| 45 | +For a one-slot Cube-to-Vector credit protocol, each AIV primes MTE3 FREE once, | ||
| 46 | +waits READY once per task, and returns MTE3 FREE after the conditional output | ||
| 47 | +store. Empty shares still return their credit. Cube waits both physical FREE | ||
| 48 | +credits before TMOV, sets both READY credits after TMOV, and drains one final | ||
| 49 | +FREE pair after the loop. For `T` tasks per core the balance is `T+1` FREE | ||
| 50 | +events and `T` READY events in each direction. Inspect generated CCE: the | ||
| 51 | +validated specializations contain two MTE3 FREE sites, no V FREE site and place | ||
| 52 | +the per-task FREE after TSTORE. | ||
| 53 | + | ||
| 54 | +## Wide-tile resource check | ||
| 55 | + | ||
| 56 | +Evaluate `(TM,TK1,TN)` candidates symbolically before codegen: | ||
| 57 | + | ||
| 58 | +```text | ||
| 59 | +L1 bytes = depth_l1 * (TM*TK1 + TK1*TN) * operand_bytes | ||
| 60 | +L0A bytes = depth_l0 * TM*TK0 * operand_bytes | ||
| 61 | +L0B bytes = depth_l0 * TK0*TN * operand_bytes | ||
| 62 | +L0C bytes = TM*TN*accumulator_bytes | ||
| 63 | +UB direct = hardware_share_rows*hardware_share_cols*accumulator_bytes | ||
| 64 | +``` | ||
| 65 | + | ||
| 66 | +Reducing L1 depth from four to two is valid only as a separate measured | ||
| 67 | +candidate. A larger TK/TN can consume the saved capacity; do not assume either | ||
| 68 | +choice is faster. | ||
| 69 | + | ||
| 70 | +### Gated TN512 family | ||
| 71 | + | ||
| 72 | +Prefer a new tiling-key bit over changing the baseline family globally. The | ||
| 73 | +retained A5 gate is: | ||
| 74 | + | ||
| 75 | +```text | ||
| 76 | +wide_n = M>=257 and K>=3584 and N%512==0 | ||
| 77 | + and not pertoken and baseline_p0_tiles>=56 | ||
| 78 | +tile_n = 512 if wide_n else 256 | ||
| 79 | +``` | ||
| 80 | + | ||
| 81 | +Propagate `tile_n` into every physical allocation and compact-window assertion. | ||
| 82 | +For the validated map, the worst-case byte high-water marks are L1 393216, | ||
| 83 | +L0A 16384, L0B 65536, L0C 262144 and UB 203264. Do not reuse this key for | ||
| 84 | +small/decode shapes: that exact candidate passed CCE and 9/9 correctness but | ||
| 85 | +regressed the six relevant public-like probes to `0.66096x` geometric speedup. | ||
| 86 | + | ||
| 87 | +### Beat-safe N-tail dual-AIV gate | ||
| 88 | + | ||
| 89 | +With a 2-byte output and a full 256-column share, adjacent row segments have: | ||
| 90 | + | ||
| 91 | +```text | ||
| 92 | +gap_bytes = (N - 256) * 2 | ||
| 93 | +``` | ||
| 94 | + | ||
| 95 | +Enumerate all 32 possible byte offsets when proving beat ownership. A gap of | ||
| 96 | +at least 32 B is sufficient for disjoint 32 B beats. Because aligned N already | ||
| 97 | +uses its normal family, N=273 is the first unaligned admitted width (34 B gap). | ||
| 98 | +N=271 has a 30 B gap and an explicit overlapping-beat counterexample. Retain | ||
| 99 | +SingleModeVec0 for N=271/narrower tails and decode; select DualModeSplitM only | ||
| 100 | +for family 0/1 with unaligned `N>=273`. | ||
| 101 | + | ||
| 102 | +## Mandatory promotion gates | ||
| 103 | + | ||
| 104 | +1. Compile representative dtype, tail-mode and tile-family keys. Inspect C++ | ||
| 105 | + for the expected slot addresses, cursor modulo, TLOAD/TEXTRACT/TMATMUL chain, | ||
| 106 | + one Acc TMOV, no GM workspace and no Acc phase. | ||
| 107 | +2. On the authorized device under the required lock, compare bit-exactly across | ||
| 108 | + K around both K0 and K1 boundaries, M/N tails, multiple output tiles, batch, | ||
| 109 | + optional epilogue inputs and repeated same-core reuse. | ||
| 110 | +3. Measure the exact kernel with msprof/`kernel_details.csv` or formal | ||
| 111 | + CANN-Bench `op_times.device_kernels`. Wrapper Event intervals are only a | ||
| 112 | + directional probe. | ||
| 113 | +4. Promote only tile families that improve the measured shapes; add a host | ||
| 114 | + metadata gate for resource-unsafe or occupancy-poor geometries. | ||
| 115 | + | ||
| 116 | +The quant_matmul development campaign validated the 4×L1/2×L0 rotation as | ||
| 117 | +bit-exact on A5 across K=1/63/64/65/127/128/129/257/513, tails, multi-tile reuse | ||
| 118 | +and batch. Performance remains a per-operator profiler decision. | ||
| 119 | +For the retained 128x256 geometry, three representative kernel-only medians | ||
| 120 | +improved by 1.3012x, 1.2426x and 1.6972x (geometric mean 1.4003x); wider K/N | ||
| 121 | +tiles were rejected because their ranking was not stable across shapes. | ||
| 122 | + | ||
| 123 | +The matching 20-case formal evaluation improved every case over the preceding | ||
| 124 | +single-buffer submission. Old/new candidate-time ratios ranged from 1.0944x | ||
| 125 | +to 2.0617x with geometric mean 1.5086x, while correctness remained 20/20. The | ||
| 126 | +score nevertheless stopped at 69.46: reaching 80 would require roughly another | ||
| 127 | +25% uniform time reduction, or comparable wins concentrated in the remaining | ||
| 128 | +slow cases. Treat that gap as a pipeline/startup problem, not evidence for | ||
| 129 | +promoting an unvalidated wide tile. Removing compatibility syncs, changing the | ||
| 130 | +initial credit protocol, changing K1 depth, or specializing the VF epilogue are | ||
| 131 | +separate candidates and each requires the full locked-device promotion gates. | ||
| 132 | + | ||
| 133 | +For a later gated TN512 plus beat-safe N-tail revision, do not compare formal | ||
| 134 | +scores as if two jobs shared an immutable evaluation baseline. Direct device- | ||
| 135 | +kernel comparison against the preceding submitted source gave 1.061559x over | ||
| 136 | +the ten selected main paths and 1.381942x on the N-tail case, closely matching | ||
| 137 | +held-lock A5 results of 1.071656x and 1.497716x. The current job nevertheless | ||
| 138 | +reported a lower 69.096548 score because its server-owned baseline differed. | ||
| 139 | +Use these evidence layers in order: same-device held-lock A/B, formal | ||
| 140 | +`op_times.device_kernels`, then the current run's baseline-relative score. | ||
| 141 | +Never use a known contamination-risk runner such as `multi-1` or `multi-3` as | ||
| 142 | +optimization evidence. The immutable revision passed public 20/20 and hidden | ||
| 143 | +80/80 on `multi-0`, with zero anti-cheat failures. | ||
Mcannbot-skills/ops/pypto-pro-op-develop/references/vf-reduction-perf.md+7-7File content is under review, please try again later
| @@ -0,0 +1,69 @@ | |||
| 1 | +# A5 CV matmul buffer skeleton. Fill every {{...}} from DESIGN.md and verify | ||
| 2 | +# against the target SDK's official matmul/Acc-to-Vector samples. | ||
| 3 | + | ||
| 4 | +@pl.jit(auto_mutex=True, arch="a5", tiling_key={{TILING_KEY}}) | ||
| 5 | +def {{KERNEL}}({{PARAMETERS}}): | ||
| 6 | + direct_group = pl.make_tile_group( | ||
| 7 | + type=pl.TileType( | ||
| 8 | + shape=[{{VEC_ROWS}}, {{VEC_COLS}}], | ||
| 9 | + dtype=pl.DT_INT32, | ||
| 10 | + target_memory=pl.MemorySpace.Vec, | ||
| 11 | + valid_shape=[-1, -1], | ||
| 12 | + compact=1, | ||
| 13 | + ), | ||
| 14 | + addrs={{DIRECT_ADDR}}, | ||
| 15 | + mutex_ids=[{{DIRECT_MUTEX}}], | ||
| 16 | + ) | ||
| 17 | + | ||
| 18 | + with pl.section_cube(): | ||
| 19 | + a_l1_group = pl.make_tile_group( | ||
| 20 | + type={{A_L1_TILE_TYPE}}, addrs={{A_L1_ADDR}}, | ||
| 21 | + mutex_ids=[{{A_L1_MUTEX_0}}, {{A_L1_MUTEX_1}}, | ||
| 22 | + {{A_L1_MUTEX_2}}, {{A_L1_MUTEX_3}}], | ||
| 23 | + ) | ||
| 24 | + b_l1_group = pl.make_tile_group( | ||
| 25 | + type={{B_L1_TILE_TYPE}}, addrs={{B_L1_ADDR}}, | ||
| 26 | + mutex_ids=[{{B_L1_MUTEX_0}}, {{B_L1_MUTEX_1}}, | ||
| 27 | + {{B_L1_MUTEX_2}}, {{B_L1_MUTEX_3}}], | ||
| 28 | + ) | ||
| 29 | + a_l0_group = pl.make_tile_group( | ||
| 30 | + type={{A_L0_TILE_TYPE}}, addrs={{A_L0_ADDR}}, | ||
| 31 | + mutex_ids=[{{A_L0_MUTEX_0}}, {{A_L0_MUTEX_1}}], | ||
| 32 | + ) | ||
| 33 | + b_l0_group = pl.make_tile_group( | ||
| 34 | + type={{B_L0_TILE_TYPE}}, addrs={{B_L0_ADDR}}, | ||
| 35 | + mutex_ids=[{{B_L0_MUTEX_0}}, {{B_L0_MUTEX_1}}], | ||
| 36 | + ) | ||
| 37 | + acc_group = pl.make_tile_group( | ||
| 38 | + type={{ACC_TILE_TYPE}}, addrs={{ACC_ADDR}}, | ||
| 39 | + mutex_ids=[{{ACC_MUTEX}}], | ||
| 40 | + ) | ||
| 41 | + | ||
| 42 | + for {{TASK}} in pl.range({{CORE_ID}}, {{TOTAL_TILES}}, {{CORE_COUNT}}): | ||
| 43 | + acc = acc_group.current() | ||
| 44 | + pl.set_validshape(acc, [{{PHYSICAL_TM}}, {{SELECTED_TILE_N}}]) | ||
| 45 | + for {{K1_INDEX}} in pl.range(0, {{K1_TILES}}): | ||
| 46 | + a_l1 = a_l1_group.next() | ||
| 47 | + b_l1 = b_l1_group.next() | ||
| 48 | + {{LOAD_L1_WITH_REAL_TAILS}} | ||
| 49 | + for {{K0_INDEX}} in pl.range(0, {{INNER_K0_TILES}}): | ||
| 50 | + a_l0 = a_l0_group.next() | ||
| 51 | + b_l0 = b_l0_group.next() | ||
| 52 | + {{MOVE_L1_TO_L0_WITH_REAL_TAILS}} | ||
| 53 | + {{PHASE_FREE_MATMUL_OR_MATMUL_ACC}} | ||
| 54 | + | ||
| 55 | + {{WAIT_BOTH_VECTOR_FREE_CREDITS}} | ||
| 56 | + {{M_TO_FIX_COMPATIBILITY_DEPENDENCY}} | ||
| 57 | + direct = direct_group.current() | ||
| 58 | + pl.move(direct, acc, acc_to_vec_mode={{PROVEN_SPLIT_MODE}}) | ||
| 59 | + {{SET_BOTH_VECTOR_READY_CREDITS}} | ||
| 60 | + | ||
| 61 | + {{DRAIN_BOTH_VECTOR_FREE_CREDITS}} | ||
| 62 | + | ||
| 63 | + with pl.section_vector(): | ||
| 64 | + {{PRIME_FREE_CREDIT}} | ||
| 65 | + for {{TASK}} in pl.range({{VECTOR_CORE_ID}}, {{TOTAL_TILES}}, {{CORE_COUNT}}): | ||
| 66 | + {{WAIT_READY_CREDIT}} | ||
| 67 | + direct = direct_group.current() | ||
| 68 | + {{VF_EPILOGUE_AND_VALID_STORE}} | ||
| 69 | + {{RETURN_MTE3_FREE_CREDIT_AFTER_CONDITIONAL_OUTPUT_STORE}} | ||
| @@ -0,0 +1,78 @@ | |||
| 1 | +# PyPTO-Pro FP32-chain precision fragments | ||
| 2 | +# | ||
| 3 | +# Use only after replaying the candidate dataflow against the benchmark's real | ||
| 4 | +# comparator proves that stagewise BF16 storage fails. These are composable | ||
| 5 | +# fragments, not a standalone kernel. Shapes, addresses, mutex ids, phases, | ||
| 6 | +# event ids, and API signatures still come from DESIGN.md and the installed SDK. | ||
| 7 | +# Verified source pattern: kb/references/pypto-pro-framework-findings.md §22, | ||
| 8 | +# §24, §28, §29, §33, and §36. | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +# A. Deep-K projection: partition K blocks into four independent FP32 L0C | ||
| 12 | +# accumulators, then store all four FP32 partials. The four bodies must be | ||
| 13 | +# written explicitly so every accumulator has a statically named first/last | ||
| 14 | +# phase; require n_k_blocks % 4 == 0. This first body is the copy pattern for | ||
| 15 | +# acc1/acc2/acc3 with k_block offsets +1/+2/+3. | ||
| 16 | +for q in pl.range(0, n_k_blocks // 4): | ||
| 17 | + k_block = q * 4 | ||
| 18 | + # Load/move lhs0 and rhs0 for k_block into their selected groups. | ||
| 19 | + if q == 0: | ||
| 20 | + pl.matmul(acc0, lhs0, rhs0, phase=pl.AccPhase.Partial) | ||
| 21 | + elif q == n_k_blocks // 4 - 1: | ||
| 22 | + pl.matmul_acc(acc0, acc0, lhs0, rhs0, phase=pl.AccPhase.Final) | ||
| 23 | + else: | ||
| 24 | + pl.matmul_acc(acc0, acc0, lhs0, rhs0, phase=pl.AccPhase.Partial) | ||
| 25 | + # Repeat explicitly for acc1/acc2/acc3. Do not use acc[part] or a runtime | ||
| 26 | + # part loop: PyPTO-Pro tile objects are compile-time handles, not a list | ||
| 27 | + # that can be dynamically indexed by a pl.range induction variable. | ||
| 28 | +# Recombine downstream as (p0 + p1) + (p2 + p3), not left-to-right. | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +# B. Encode a computed FP32 Cube operand as three BF16 residual terms. The | ||
| 32 | +# intermediate widen/subtract stays FP32. CAST_ROUND here is the validated | ||
| 33 | +# residual encoding mode; do not replace it with the final-output mode. | ||
| 34 | +pl.cast(term1_bf16, source_fp32, mode=pl.RoundMode.CAST_ROUND) | ||
| 35 | +pl.cast(term1_fp32, term1_bf16, mode=pl.RoundMode.CAST_NONE) | ||
| 36 | +subtract_vf(source_fp32, term1_fp32, residual_fp32) | ||
| 37 | +pl.cast(term2_bf16, residual_fp32, mode=pl.RoundMode.CAST_ROUND) | ||
| 38 | +pl.cast(term2_fp32, term2_bf16, mode=pl.RoundMode.CAST_NONE) | ||
| 39 | +subtract_vf(residual_fp32, term2_fp32, residual2_fp32) | ||
| 40 | +pl.cast(term3_bf16, residual2_fp32, mode=pl.RoundMode.CAST_ROUND) | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +# C. If one K128 three-term contraction still fails only at final BF16 | ||
| 44 | +# boundaries, keep the physical K128 Mat/Left/Right types but contract two | ||
| 45 | +# compact K64 windows into distinct FP32 accumulators. Repeat the three-term | ||
| 46 | +# chain for k_offset 0 and 64; never alias the two live L0C values. | ||
| 47 | +pl.set_validshape(mat_lhs, [valid_m, 64]) | ||
| 48 | +pl.set_validshape(mat_rhs, [64, valid_n]) | ||
| 49 | +pl.set_validshape(lhs_k0, [valid_m, 64]) | ||
| 50 | +pl.set_validshape(rhs_k0, [64, valid_n]) | ||
| 51 | +pl.move(lhs_k0, mat_lhs, offset=[0, 0]) | ||
| 52 | +pl.move(rhs_k0, mat_rhs, offset=[0, 0]) | ||
| 53 | +pl.matmul(acc_k0, lhs_k0, rhs_k0, phase=pl.AccPhase.Partial) | ||
| 54 | +# Move K0 term2, then term3 through lhs_k0 and close with Partial, Final. | ||
| 55 | +# Repeat explicitly for acc_k1/lhs_k1/rhs_k1 using offsets [0,64]/[64,0]. | ||
| 56 | +# Store acc_k0 and acc_k1 to distinct FP32 GM workspaces with STPhase.Final. | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +# D. Add FP32 K partials in VF and perform the only protocol conversion with | ||
| 60 | +# RNE. On A5 CAST_ROUND is tie-away; PyTorch BF16 output conversion is RNE. | ||
| 61 | +add_fp32_vf(k0_fp32, k1_fp32, total_fp32, valid_rows, valid_cols) | ||
| 62 | +pl.cast(output_bf16_tile, total_fp32, mode=pl.RoundMode.CAST_RINT) | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +# E. Materialize a BF16-high / FP32-low decomposition with Tile casts when a | ||
| 66 | +# cancellation-sensitive consumer needs a hard rounding boundary. Do not use | ||
| 67 | +# vf.astype(... CAST_RINT) for FP32->BF16: the CANN 9.1 backend lowers it to an | ||
| 68 | +# invalid ROUND_N vcvt mode. Repeat this pair for every partial, then combine | ||
| 69 | +# highs and lows with explicit pairwise trees in a basic VF helper. | ||
| 70 | +pl.cast(high_bf16, partial_fp32, mode=pl.RoundMode.CAST_RINT) | ||
| 71 | +pl.cast(high_fp32, high_bf16, mode=pl.RoundMode.CAST_NONE) | ||
| 72 | +subtract_vf(partial_fp32, high_fp32, low_fp32) | ||
| 73 | +# high = (high0 + high1) + (high2 + high3) | ||
| 74 | +# low = (low0 + low1) + (low2 + low3) | ||
| 75 | +# total = high + low | ||
| 76 | +# This removes only the local reduction error. It cannot reconstruct rounding | ||
| 77 | +# already accumulated inside the upstream Cube partials, so validate the | ||
| 78 | +# cancellation cases on every target CANN/hardware combination. | ||
Mcannbot-skills/ops/pypto-pro-op-kb/ROUTER.md+16-0File content is under review, please try again later
Mcannbot-skills/ops/pypto-pro-op-kb/topology-map.json+39-12File content is under review, please try again later
Acannbot-skills/ops/pypto-pro-op-perf-tune/templates/tiling-key-resource-specialization.py.tmpl+29-0File content is under review, please try again later