草稿
[WIP] docs(kb): Stage-5 verdict taxonomy and env-fault triage #3
[WIP] docs(kb): Stage-5 verdict taxonomy and env-fault triage #3
草稿
hid22900163创建于 8月17日
共 121 个文件变更+25274-765
M.gitignore+4-0文件内容审核中,请稍后刷新重试
MOAT.xml+9-0文件内容审核中,请稍后刷新重试
@@ -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/ # 模型适配与推理优化 Skills89├── model/ # 模型适配与推理优化 Skills
90└── plugins-official/ # 官方 Plugins(开发路径入口,含 Agents)90└── plugins-official/ # 官方 Plugins(开发路径入口,含 Agents)
91 ├── pypto-op-orchestrator/ # PyPTO classic 算子开发(8 Subagent + 状态机)91 ├── pypto-op-orchestrator/ # PyPTO classic 算子开发(8 Subagent + 状态机)
92- ├── pypto-pro-op-orchestrator/ # PyPTO-Pro 算子开发(5 Subagent)92+ ├── pypto-pro-op-orchestrator/ # PyPTO-Pro 算子开发(6 Subagent)
93 ├── pypto-model-tools/ # 模型适配工具集(安装时附带 8 个算子支撑 skill)93 ├── pypto-model-tools/ # 模型适配工具集(安装时附带 8 个算子支撑 skill)
94 └── pypto-kernel-validator/ # 算子产物校验(反作弊 + 精度 + 性能,单 Subagent)94 └── pypto-kernel-validator/ # 算子产物校验(反作弊 + 精度 + 性能,单 Subagent)
95```95```
@@ -0,0 +1,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-0文件内容审核中,请稍后刷新重试
Acannbot-skills/ops/pypto-pro-cann-bench-eval/references/submission-contract.md+127-0文件内容审核中,请稍后刷新重试
Acannbot-skills/ops/pypto-pro-cann-bench-eval/scripts/check_submission.py+572-0文件内容审核中,请稍后刷新重试
@@ -1,6 +1,6 @@
1---1---
2name: pypto-pro-environment-check2name: 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/kernel108等于把本 case 输入/参数代入合同 shape 表达式后的结果。rank-0 tensor 写 `[]`。tile/kernel
104shape 仍由 Stage 3 决定。每个动态 shape 符号须在至少一个输入维中单独出现,保证 P0109shape 仍由 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+ 
335def _valid_range_bounds(value: Any) -> bool:343def _valid_range_bounds(value: Any) -> bool:
336 if not isinstance(value, list):344 if not isinstance(value, list):
337 return False345 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)
Mcannbot-skills/ops/pypto-pro-op-design/SKILL.md+10-0文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-op-develop/references/vf-reduction-perf.md+7-7文件内容审核中,请稍后刷新重试
@@ -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}}
Mcannbot-skills/ops/pypto-pro-op-kb/ROUTER.md+16-0文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-op-kb/constraints/sync-stitch.md+198-0文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-op-kb/patterns/pattern-index.md+34-0文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-op-kb/playbooks/numerical-error-localisation.md+34-0文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-op-kb/references/easyasc-port-ledger.md+82-1文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-op-kb/references/investigation-discipline.md+87-0文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-op-kb/references/pypto-pro-dsl-limitations-a5.md+453-38文件内容审核中,请稍后刷新重试
Acannbot-skills/ops/pypto-pro-op-kb/references/pypto-pro-launch-block-dim.md+79-0文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-op-kb/topology-map.json+39-12文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-op-perf-tune/SKILL.md+117-0文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-op-perf-tune/references/a5-roofline-and-levers.md+96-61文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-op-perf-tune/references/csv_fields_reference.md+23-0文件内容审核中,请稍后刷新重试
Mcannbot-skills/ops/pypto-pro-op-perf-tune/references/msprof-op-guide.md+144-0文件内容审核中,请稍后刷新重试
Acannbot-skills/ops/pypto-pro-op-perf-tune/references/pl-routing-table.md+69-0文件内容审核中,请稍后刷新重试
Adocs/PYPTO_PRO_DSL_LIMITATIONS_REPORT.md+1771-0文件内容审核中,请稍后刷新重试
Adocs/arpe-hidden-cases-observed.md+404-0文件内容审核中,请稍后刷新重试
Mdocs/pypto-pro-dsl-limitations.md+350-1文件内容审核中,请稍后刷新重试
Atools/_repo_paths.py+64-0文件内容审核中,请稍后刷新重试
Atools/build_dsq_delivery.py+300-0文件内容审核中,请稍后刷新重试
Atools/build_submission.py+485-0文件内容审核中,请稍后刷新重试
Atools/cann_bench_a5/README.md+134-0文件内容审核中,请稍后刷新重试
Atools/cann_bench_a5/build_pkgs.py+190-0文件内容审核中,请稍后刷新重试
Atools/cann_bench_a5/casegen.py+135-0文件内容审核中,请稍后刷新重试
Atools/cann_bench_a5/gen_kernels.py+415-0文件内容审核中,请稍后刷新重试
Atools/cann_bench_a5/perf.py+266-0文件内容审核中,请稍后刷新重试
Atools/cann_bench_a5/test_casegen.py+130-0文件内容审核中,请稍后刷新重试
Atools/cann_bench_a5/validate.py+216-0文件内容审核中,请稍后刷新重试
Atools/cann_bench_a5/vendor/__init__.py+39-0文件内容审核中,请稍后刷新重试
Atools/dsq_classes.py+34-0文件内容审核中,请稍后刷新重试
Atools/gen_dsq_classes.py+295-0文件内容审核中,请稍后刷新重试
Atools/gen_dsq_narrow.py+301-0文件内容审核中,请稍后刷新重试
Atools/precision_oracle.py+742-0文件内容审核中,请稍后刷新重试
Atools/roofline_a5.py+521-0文件内容审核中,请稍后刷新重试
Atools/verify_codegen.py+232-0文件内容审核中,请稍后刷新重试