Closed
[WIP] docs(kb): Stage-5 verdict taxonomy and env-fault triage #497
hid22900163Add on Aug 17Closed at Aug 17
[WIP] docs(kb): Stage-5 verdict taxonomy and env-fault triage #497
Closed
Merged fromNikita17/pypto-gym_5266stage5-kb-masterintocann/pypto-gymmaster
Total: 31 files changed+4905-32
| @@ -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. | ||
| @@ -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) |
| @@ -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 | | 来源 | 路径 | 用途 | |
| @@ -13,11 +13,14 @@ for signatures and platform-specific behavior. | |||
| 13 | | Check vector authoring choices | `pypto-pro-op-develop` | [constraints/vec.md](constraints/vec.md) | | 13 | | Check vector authoring choices | `pypto-pro-op-develop` | [constraints/vec.md](constraints/vec.md) | |
| 14 | | Check synchronization | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/sync-stitch.md](constraints/sync-stitch.md) | | 14 | | Check synchronization | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/sync-stitch.md](constraints/sync-stitch.md) | |
| 15 | | Check dynamic tails | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/tail-validshape.md](constraints/tail-validshape.md) | | 15 | | Check dynamic tails | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/tail-validshape.md](constraints/tail-validshape.md) | |
| 16 | -| Select A5 constraints; use limits only after target detection | design/develop/perf skills | [constraints/arch-a5.md](constraints/arch-a5.md) | | 16 | +| Use A5-specific limits | design/develop/perf skills, after target detection | [constraints/arch-a5.md](constraints/arch-a5.md) | |
| 17 | | Decide what may run on the host | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/wrapper-boundary.md](constraints/wrapper-boundary.md) | | 17 | | Decide what may run on the host | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/wrapper-boundary.md](constraints/wrapper-boundary.md) | |
| 18 | | Measure and tune a correct kernel | `pypto-pro-op-perf-tune` | [playbooks/benchmark-scoring.md](playbooks/benchmark-scoring.md) | | 18 | | Measure and tune a correct kernel | `pypto-pro-op-perf-tune` | [playbooks/benchmark-scoring.md](playbooks/benchmark-scoring.md) | |
| 19 | | Localise a numerical error | `pypto-pro-op-develop` | [playbooks/numerical-error-localisation.md](playbooks/numerical-error-localisation.md) | | 19 | | Localise a numerical error | `pypto-pro-op-develop` | [playbooks/numerical-error-localisation.md](playbooks/numerical-error-localisation.md) | |
| 20 | | Quantize per row with a scale that is also an output | `pypto-pro-op-design` | [patterns/vec-per-token-dynamic-quant.md](patterns/vec-per-token-dynamic-quant.md) | | 20 | | Quantize per row with a scale that is also an output | `pypto-pro-op-design` | [patterns/vec-per-token-dynamic-quant.md](patterns/vec-per-token-dynamic-quant.md) | |
| 21 | +| Reduce rows whose last dimension is a handful of bytes | `pypto-pro-op-design` | [patterns/vec-narrow-row-packing.md](patterns/vec-narrow-row-packing.md) | | ||
| 22 | +| One kernel must serve a last dimension spanning orders of magnitude, or several dtypes, or several ranks | `pypto-pro-op-design` / `pypto-pro-op-develop` | [patterns/tiling-key-width-ladder.md](patterns/tiling-key-width-ladder.md) | | ||
| 23 | +| A correct `vf.*` kernel is far slower than its memory roof | `pypto-pro-op-perf-tune` | [constraints/vec.md](constraints/vec.md), then [constraints/vec-alignment-and-rotation.md](constraints/vec-alignment-and-rotation.md), then [playbooks/benchmark-scoring.md](playbooks/benchmark-scoring.md) | | ||
| 21 | | Hit a framework limit, or debug something that makes no sense | any | [references/pypto-pro-framework-findings.md](references/pypto-pro-framework-findings.md) | | 24 | | Hit a framework limit, or debug something that makes no sense | any | [references/pypto-pro-framework-findings.md](references/pypto-pro-framework-findings.md) | |
| 22 | | An API looks unsupported, or a correct-looking call returns stale/wrong data | any | [references/pypto-pro-dsl-limitations-a5.md](references/pypto-pro-dsl-limitations-a5.md) — severity-ordered, silent failures first | | 25 | | An API looks unsupported, or a correct-looking call returns stale/wrong data | any | [references/pypto-pro-dsl-limitations-a5.md](references/pypto-pro-dsl-limitations-a5.md) — severity-ordered, silent failures first | |
| 23 | | An investigation keeps failing to converge, or you are about to trust a measurement | any | [references/investigation-discipline.md](references/investigation-discipline.md) | | 26 | | An investigation keeps failing to converge, or you are about to trust a measurement | any | [references/investigation-discipline.md](references/investigation-discipline.md) | |
| @@ -25,9 +28,19 @@ for signatures and platform-specific behavior. | |||
| 25 | | Several agents are working in parallel on one shared record, or you are merging their branches | any | [references/investigation-discipline.md](references/investigation-discipline.md) §10 | | 28 | | Several agents are working in parallel on one shared record, or you are merging their branches | any | [references/investigation-discipline.md](references/investigation-discipline.md) §10 | |
| 26 | | Map a Chinese/English hardware, pipe, tiling, or layout term to its meaning | any | [references/terminology.md](references/terminology.md) | | 29 | | Map a Chinese/English hardware, pipe, tiling, or layout term to its meaning | any | [references/terminology.md](references/terminology.md) | |
| 27 | | A page carries a cross-DSL claim and you need its provenance, or you are about to re-derive something a sibling DSL already knew | any | [references/easyasc-port-ledger.md](references/easyasc-port-ledger.md) — provenance record, not a selected pattern or constraint | | 30 | | A page carries a cross-DSL claim and you need its provenance, or you are about to re-derive something a sibling DSL already knew | any | [references/easyasc-port-ledger.md](references/easyasc-port-ledger.md) — provenance record, not a selected pattern or constraint | |
| 31 | +| Recognise a failure someone has already hit | `pypto-pro-op-develop` / `pypto-pro-op-perf-tune` | [references/pitfall-records.md](references/pitfall-records.md) | | ||
| 32 | +| Judge whether an ops-per-register lever can pay on a narrow reduction, or are about to generalise a perf measurement across dtypes | `pypto-pro-op-perf-tune` | [references/rms-norm-a5-narrow-d-roofline.md](references/rms-norm-a5-narrow-d-roofline.md) | | ||
| 33 | +| Judging a Stage-5 tuning result, or a whole-set failure that might be the card rather than the kernel | `pypto-pro-op-perf-tune` | [references/stage5-verdicts.md](references/stage5-verdicts.md) | | ||
| 28 | 34 | ||
| 29 | -Load [constraints/arch-a5.md](constraints/arch-a5.md) when runtime/build selects A5 or when | 35 | +[references/pitfall-records.md](references/pitfall-records.md) is a symptom |
| 30 | -the workflow default A5 applies; do not use its numerical limits until the exact device and source are confirmed. | 36 | +index, not a rule page: it maps an observed error code, hang or wrong result to |
| 37 | +the cause that was actually found. Read it when something fails, not when | ||
| 38 | +designing. Each entry records the runtime it was observed on; confirm the | ||
| 39 | +behaviour still reproduces on the detected target before treating an entry as | ||
| 40 | +current. | ||
| 41 | + | ||
| 42 | +Do not load [constraints/arch-a5.md](constraints/arch-a5.md) until the runtime or build | ||
| 43 | +configuration confirms an A5 target. | ||
| 31 | 44 | ||
| 32 | ## Routing by topology | 45 | ## Routing by topology |
| 33 | 46 | ||
| @@ -39,7 +52,7 @@ For the selected topology and the properties that actually hold: | |||
| 39 | 52 | ||
| 40 | 1. Collect every matching topology constraint. | 53 | 1. Collect every matching topology constraint. |
| 41 | 2. Collect every matching property constraint. | 54 | 2. Collect every matching property constraint. |
| 42 | -3. Add the target-gated constraint selected by the explicit target or workflow default. | 55 | +3. Add any confirmed target-gated constraint. |
| 43 | 4. Add every `mandatory_constraints` entry whose `applies_to` roles participate. | 56 | 4. Add every `mandatory_constraints` entry whose `applies_to` roles participate. |
| 44 | 5. Deduplicate these into `required_constraints`; do not truncate them. | 57 | 5. Deduplicate these into `required_constraints`; do not truncate them. |
| 45 | 6. Evaluate every matching pattern and retain it only when its preconditions hold and it | 58 | 6. Evaluate every matching pattern and retain it only when its preconditions hold and it |
| @@ -57,6 +57,44 @@ INDEXES = ("patterns/pattern-index.md", "examples/kernel-index.md") | |||
| 57 | 57 | ||
| 58 | _MD_LINK = re.compile(r"\[[^\]]*\]\(([^)#]+?)(?:#[^)]*)?\)") | 58 | _MD_LINK = re.compile(r"\[[^\]]*\]\(([^)#]+?)(?:#[^)]*)?\)") |
| 59 | 59 | ||
| 60 | +#: A code span. Bounded to a single line on purpose: an unbalanced backtick would | ||
| 61 | +#: otherwise blank the document from that point to the next backtick anywhere | ||
| 62 | +#: later, silently un-checking every link in between. | ||
| 63 | +_CODE_SPAN = re.compile(r"(`+)[^\n]*?\1") | ||
| 64 | + | ||
| 65 | +#: An opening or closing fence line: ``` or ~~~, optionally with an info string. | ||
| 66 | +_FENCE = re.compile(r"^\s{0,3}(`{3,}|~{3,})") | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def _without_code(text: str) -> str: | ||
| 70 | + """Blank out fenced blocks and code spans before looking for links. | ||
| 71 | + | ||
| 72 | + A markdown link is prose. Code is not, and the two share punctuation: a pl | ||
| 73 | + kernel launch reads ``kern[None, num_cores](q, k, w, out)``, which is | ||
| 74 | + ``[...](...)`` to the naked eye of a link matcher. Nothing a page can do to | ||
| 75 | + itself fixes this -- the matcher's ``[^)#]+?`` spans newlines, so splitting | ||
| 76 | + the arguments across lines does not help, and backticking or fencing did not | ||
| 77 | + help either because nothing here used to look at fences. So the fix belongs | ||
| 78 | + to the matcher: strip code first, then match links in what is left. | ||
| 79 | + """ | ||
| 80 | + out: list[str] = [] | ||
| 81 | + fence: str | None = None | ||
| 82 | + for line in text.splitlines(): | ||
| 83 | + match = _FENCE.match(line) | ||
| 84 | + if fence is None: | ||
| 85 | + if match: | ||
| 86 | + fence = match.group(1) | ||
| 87 | + out.append("") | ||
| 88 | + continue | ||
| 89 | + out.append(line) | ||
| 90 | + else: | ||
| 91 | + # A fence closes only on the same character and at least the same | ||
| 92 | + # length, so a ```` ```` ````-opened block is not closed by ``` inside it. | ||
| 93 | + if match and match.group(1)[0] == fence[0] and len(match.group(1)) >= len(fence): | ||
| 94 | + fence = None | ||
| 95 | + out.append("") | ||
| 96 | + return _CODE_SPAN.sub(" ", "\n".join(out)) | ||
| 97 | + | ||
| 60 | #: Transient labels that must never appear in a retained filename. | 98 | #: Transient labels that must never appear in a retained filename. |
| 61 | _BAD_NAME_TOKENS = ( | 99 | _BAD_NAME_TOKENS = ( |
| 62 | "run_2", | 100 | "run_2", |
| @@ -139,7 +177,7 @@ def _absolute_path_errors(paths: Iterable[Path]) -> list[str]: | |||
| 139 | 177 | ||
| 140 | def _links_from(path: Path) -> list[tuple[str, Path]]: | 178 | def _links_from(path: Path) -> list[tuple[str, Path]]: |
| 141 | out: list[tuple[str, Path]] = [] | 179 | out: list[tuple[str, Path]] = [] |
| 142 | - for target in _MD_LINK.findall(_text(path)): | 180 | + for target in _MD_LINK.findall(_without_code(_text(path))): |
| 143 | target = target.strip() | 181 | target = target.strip() |
| 144 | if not target or target.startswith(("http://", "https://", "mailto:")): | 182 | if not target or target.startswith(("http://", "https://", "mailto:")): |
| 145 | continue | 183 | continue |
| @@ -268,3 +268,30 @@ gamma vector rather than through the obvious data input. | |||
| 268 | 268 | ||
| 269 | Use `$PYPTO_DEVKIT_DIR/docs/pypto_pro/api/` as the primary source for supported | 269 | Use `$PYPTO_DEVKIT_DIR/docs/pypto_pro/api/` as the primary source for supported |
| 270 | dtype pairs and API semantics in the current SDK. | 270 | dtype pairs and API semantics in the current SDK. |
| 271 | + | ||
| 272 | +--- | ||
| 273 | + | ||
| 274 | +## BF16 narrowing at register level is bit-exact with the tile cast | ||
| 275 | + | ||
| 276 | +The note above says the register-level cast is `vf.astype(...)` and the tile-level | ||
| 277 | +one is `pl.cast(out, src, mode=...)`, and warns that both are platform-gated. For | ||
| 278 | +the **FP32 → BF16** direction on A5 / DAV_3510 the gate has been measured, and the | ||
| 279 | +answer is favourable enough to change how a BF16 output should be published: | ||
| 280 | + | ||
| 281 | +* the two produce **identical bytes**, verified on inputs that are exact BF16 ties | ||
| 282 | + (low 16 mantissa bits `== 0x8000`) as well as random values; | ||
| 283 | +* the `round_mode` kwarg does not reach the instruction — the hardware always | ||
| 284 | + rounds nearest-even, which is what `CAST_RINT` asks for anyway; | ||
| 285 | +* `CAST_RINT` and `CAST_HYBRID` do not compile for this pair at all. | ||
| 286 | + | ||
| 287 | +So a chain that computes in FP32 and ends in a single tile-level narrowing cast can | ||
| 288 | +instead publish BF16 straight from the register file, deleting a whole UB→UB pass | ||
| 289 | +(and its `auto_mutex` barrier) **without changing a single output byte**. Measured | ||
| 290 | +on `rms_norm`: publish traffic per element falls from 10 B (4 B FP32 store + 4 B | ||
| 291 | +cast read + 2 B cast write) to 2 B. | ||
| 292 | + | ||
| 293 | +The reverse direction is **not** symmetric — BF16 → FP32 at register level reaches | ||
| 294 | +only the even elements — so keep the widening at tile level. The lane mechanics of | ||
| 295 | +both directions, and why the "BF16 is the top 16 bits of FP32" bit-trick does not | ||
| 296 | +port to this DSL, are recorded in | ||
| 297 | +[vec.md](vec.md#bf16-at-register-level-what-vfastype-can-and-cannot-do). | ||
| @@ -56,3 +56,85 @@ one K alignment or one fractal shape for all dtypes. | |||
| 56 | 56 | ||
| 57 | The installed `$PYPTO_DEVKIT_DIR/docs/pypto_pro/api/` pages and official | 57 | The installed `$PYPTO_DEVKIT_DIR/docs/pypto_pro/api/` pages and official |
| 58 | examples are the primary source for the current version. | 58 | examples are the primary source for the current version. |
| 59 | + | ||
| 60 | +--- | ||
| 61 | + | ||
| 62 | +## Launch geometry on a5 / DAV_3510 — measured, run H (rms_norm, 2026-08-12) | ||
| 63 | + | ||
| 64 | +Instrument: `cold_probe.py`-derived paired sweep (`probe/sweep.py`), **cold** L2 (192 MB flush | ||
| 65 | +inside the measured window), Level1 NPU profiler, all arms of a shape in ONE process so the arms | ||
| 66 | +share a compiled binary and differ only in launch geometry. Card 0 of a5-238 (shared box). | ||
| 67 | +🔴 Estimator note: on a shared box, contention is **one-sided** (it can only add time), so `min` | ||
| 68 | +over reps is the unbiased estimator of uncontended kernel time — but `min` is *not* robust to | ||
| 69 | +spuriously-fast profiler samples. Report `min`, 2nd-smallest and median together; where they | ||
| 70 | +disagree, the robust pair wins. This changed two verdicts in run H (a "−11.0 %" became +0.8 %, | ||
| 71 | +a "−66.8 %" became −36 %). | ||
| 72 | + | ||
| 73 | +### Shrinking blockDim for small inputs — DOES NOT APPLY to a `min(coreNum, n_tiles)` grid | ||
| 74 | + | ||
| 75 | +A widely-quoted rule (`blockDim = elems < SMALL_GRID_ELEMS ? min(coreNum,8) : coreNum`, with | ||
| 76 | +15000/30000 per dtype) is a repair for kernels that launch `coreNum` blocks **unconditionally**. | ||
| 77 | +A planner that already emits `blocks = max(1, min(coreNum, n_tiles))` **has the fix in a stronger | ||
| 78 | +form**, and applying the threshold on top is a no-op below `n_tiles = 8` and a large regression | ||
| 79 | +above it. Measured on `[11,13,17,67]` fp16 (162 877 elements, 304 tiles): grid 56 → 8 cost | ||
| 80 | +**4.7364 → 19.5766 µs = +4.13×**, because `ceil(304/56)=6` waves become `ceil(304/8)=38`. | ||
| 81 | +Break-even, derived from that measurement rather than assumed: capping an `N`-tile launch to 8 | ||
| 82 | +costs `(ceil(N/8)−1)·T_tile` and saves `(N−8)·d`; both scale as `N/8`, so the break-even sits at | ||
| 83 | +`T_tile ≈ 0.32 µs` **almost independently of N**. Check that number before porting the rule. | ||
| 84 | + | ||
| 85 | +### Wave alignment is NOT the objective; tile size is | ||
| 86 | + | ||
| 87 | +Tiles are handed to blocks strided (`for t in pl.range(ci, nt, nc)`), so wall-clock is | ||
| 88 | +`ceil(n_tiles/blocks) · T_tile`. It is tempting to minimise wave count. Measured, that is wrong: | ||
| 89 | +`[31,129,2049]` fp32's best rung has **7 → 18 waves** and is still 9 % faster, and | ||
| 90 | +`[3,7,11,4096]` fp32's one-wave rungs are 17–22 % **slower** than a three-wave rung. Twice more, | ||
| 91 | +a launch that leaves cores idle beat one that filled them: 38-of-56 blocks beat 56 by 30 %, and | ||
| 92 | +28-of-56 beat 56 by 41 %. **Filling every core is not the objective.** | ||
| 93 | + | ||
| 94 | +### There is no closed-form optimal `Rows` — but `Rows` derived from `S` alone is a real defect | ||
| 95 | + | ||
| 96 | +Swept every legal `Rows` rung on all 18 Mode-0 public shapes. A rule "pick the rung whose | ||
| 97 | +`Rows·MaxN` is nearest T" was evaluated offline against the measured table for | ||
| 98 | +T ∈ {7k…12k}: **every T regresses at least one case by ≥ 6.5 %**, up to +32 %. Same rung | ||
| 99 | +(`MaxN=1024`), same S band, opposite optima by dtype: fp32 wants `Rows=5`, fp16 wants `Rows=16` | ||
| 100 | +and is +32 % worse at 5. **Do not ship a global `Rows` rule.** | ||
| 101 | + | ||
| 102 | +What *is* real: a `_pick_rows` that computes `bal = S // (coreNum · MIN_TILES_PER_CORE)` is a | ||
| 103 | +function of **S alone and ignores MaxN**, so at the narrowest rung it starves the tile. At | ||
| 104 | +`MaxN = 128` it picked `Rows = 8` (a 1 KB tile) where the UB ceiling was 64. Growing `Rows` to | ||
| 105 | +the largest rung that still leaves `≥ coreNum/2` tiles measured **−12 % to −42 %, mean −27 % | ||
| 106 | +(fp16) / −21 % (bf16), zero regressions**, over `S` from 56 to 2431 — a 43× range, both dtypes. | ||
| 107 | +🔴 The same rule applied to **other** rungs regresses `MaxN=384` by **+40.8 %** and | ||
| 108 | +`MaxN=4096` by **+22.1 %**. Gate it to the rung it was measured on. | ||
| 109 | + | ||
| 110 | +### Regrouping rows into tiles is bit-neutral | ||
| 111 | + | ||
| 112 | +Changing `Rows` changes only how rows are grouped; each row's reduction is independent of the | ||
| 113 | +grouping. Verified byte-for-byte: **30 configurations, 5 shapes, 96 386 842 bytes compared, | ||
| 114 | +0 differing bytes**. A `Rows` change that alters even one output word means something else moved. | ||
| 115 | + | ||
| 116 | +### The narrow-rung `Rows` floor — where growing helps and where it overshoots (run H, extended) | ||
| 117 | + | ||
| 118 | +Same instrument as above. The `bal = S // (coreNum * MIN_TILES_PER_CORE)` defect (Rows chosen from | ||
| 119 | +S alone, MaxN ignored) starves the tile at EVERY narrow rung, not just the narrowest. Measured at | ||
| 120 | +`MaxN` 192 and 256, both dtype classes, `S in {56,127,254,896}`: the planner's pick is beaten by | ||
| 121 | +**-4.4 % to -48.8 %**, and `Rows = 8` is the best arm in 9 of those 12 points. | ||
| 122 | + | ||
| 123 | +🔴 But the FIX does not generalise the way the defect does. Growing `Rows` to the largest rung that | ||
| 124 | +still leaves >= coreNum/2 tiles is right at `MaxN = 128` (measured best-or-within-5 % over S from 56 | ||
| 125 | +to 14336) and **wrong at `MaxN >= 192` once S is large**: | ||
| 126 | + | ||
| 127 | +| MaxN | dt | S | grow-to-cap vs planner | | ||
| 128 | +|---|---|---|---| | ||
| 129 | +| 192 | fp32 | 7168 | **+14.6 %** | | ||
| 130 | +| 384 | fp16 | 4037 | **+17.6 %** | | ||
| 131 | +| 384 | fp32 | 4037 | **+38.5 %** | | ||
| 132 | + | ||
| 133 | +That last row is public case `[11,367,373]`, and +38.5 % here reproduces a +40.8 % measured from an | ||
| 134 | +independent sweep — the boundary is real. | ||
| 135 | + | ||
| 136 | +**The portable lesson: at rungs above the narrowest, use a FLOOR (`Rows >= 8`), not a target.** | ||
| 137 | +A floor is provably inert for `S >= 8 * MIN_TILES_PER_CORE * coreNum` (= 1792 here), so it cannot | ||
| 138 | +fire in the regime where growth overshoots, while still capturing the whole starved corner. Measured | ||
| 139 | ++0.0 % at all 12 large-S points and -4.4 %…-48.8 % at small S. Growth guards must be gated to the | ||
| 140 | +single rung they were measured on. | ||
| @@ -127,6 +127,15 @@ pure overhead — and on a short body they dominate. | |||
| 127 | **Rule.** Build one `vf.create_mask(pattern=pl.MaskPattern.ALL, ...)` outside the loop and | 127 | **Rule.** Build one `vf.create_mask(pattern=pl.MaskPattern.ALL, ...)` outside the loop and |
| 128 | use it for every register. | 128 | use it for every register. |
| 129 | 129 | ||
| 130 | +**Independently confirmed, and not only here.** The same lever is recorded in | ||
| 131 | +[`docs/pypto-pro-dsl-limitations.md`](../../../../docs/pypto-pro-dsl-limitations.md) #18 from a | ||
| 132 | +different campaign and a different operator family: hoisting the mask out of the per-register | ||
| 133 | +loop recovered **550.75 → 398.06 µs** (the DMA floor) on a 67M index fill, and on the reference | ||
| 134 | +generator's exp kernels moved mean SOL **0.300 → 0.961 across 20/20 cases**. Treat the two as | ||
| 135 | +corroborating measurements of one effect rather than as separate findings — and read the two | ||
| 136 | +caveats recorded with #18 (the tail loop must be its own pass; one hoisted variant faults the | ||
| 137 | +device) before applying it, since neither is visible from the numbers on this page. | ||
| 138 | + | ||
| 130 | **Whether the tail path can then be dropped depends on what the inactive lanes' output is | 139 | **Whether the tail path can then be dropped depends on what the inactive lanes' output is |
| 131 | used for, and getting this wrong corrupts results silently.** | 140 | used for, and getting this wrong corrupts results silently.** |
| 132 | 141 | ||
| @@ -160,6 +169,21 @@ one module so neither could be served the other's binary: | |||
| 160 | | 8 | 1538x1537 fp32, dim 0 | 8.36 us | 3.50 us | 2.4x | | 169 | | 8 | 1538x1537 fp32, dim 0 | 8.36 us | 3.50 us | 2.4x | |
| 161 | | 5 | 2039x65520 fp32 | 655.86 us | 649.88 us | 1.01x | | 170 | | 5 | 2039x65520 fp32 | 655.86 us | 649.88 us | 1.01x | |
| 162 | 171 | ||
| 172 | +The same lever on `rms_norm`, a two-pass reduce-and-broadcast body, on a second Ascend950PR | ||
| 173 | +host — interleaved A/B/A, run-to-run spread 0.02–0.11 %: | ||
| 174 | + | ||
| 175 | +| case | shape, dtype | per-register mask | hoisted | ratio | | ||
| 176 | +|---|---|---|---|---| | ||
| 177 | +| 4 | 16x256x4096 f16 | 158.83 us | 30.77 us | **5.16x** | | ||
| 178 | +| 18 | 2x511x8192 bf16 | 80.83 us | 17.02 us | 4.75x | | ||
| 179 | +| 8 | 16x511x2049 fp32 | 162.91 us | 96.63 us | 1.68x | | ||
| 180 | +| 16 | 11x13x17x67 f16 | 5.34 us | 3.50 us | 1.53x | | ||
| 181 | + | ||
| 182 | +Both tables are the same curve. The fp32 row lands at 1.68x for the reason case 5 lands at | ||
| 183 | +1.01x — it is the memory-bound shape in its suite, and the vector-side win has nowhere to go. | ||
| 184 | +On the two cache-resident cases the dynamic mask accounted for **81 %** and **79 %** of total | ||
| 185 | +kernel time. | ||
| 186 | + | ||
| 163 | **The gain scales with how far the kernel is from the DRAM roof, which is why it is easy to | 187 | **The gain scales with how far the kernel is from the DRAM roof, which is why it is easy to |
| 164 | dismiss.** Case 5 moves 801 MB and is bandwidth-bound at 1.23 TB/s, so the mask costs it 1%; | 188 | dismiss.** Case 5 moves 801 MB and is bandwidth-bound at 1.23 TB/s, so the mask costs it 1%; |
| 165 | every case that fits cache pays the full 2.4–6.5x. A kernel tuned only on its largest case | 189 | every case that fits cache pays the full 2.4–6.5x. A kernel tuned only on its largest case |
| @@ -216,6 +240,11 @@ row pre-filled with a sentinel, then read the sentinel back. If it was overwritt | |||
| 216 | `vf.store_align` rounds up too — order the writes so the spill lands on not-yet-written | 240 | `vf.store_align` rounds up too — order the writes so the spill lands on not-yet-written |
| 217 | data, or store the boundary through `vf.scatter`. | 241 | data, or store the boundary through `vf.scatter`. |
| 218 | 242 | ||
| 243 | +**Below one register's width the lever stops paying, and that boundary has been hit twice.** | ||
| 244 | +At 8 or 16 columns the hoist measured +5 % with six cases 3–4 % *slower*; applying the identical | ||
| 245 | +hoist to a D=2 packed path measured **-1.0 %** and was rolled back as inside noise. The | ||
| 246 | +full-register loop does not execute there, so the hoist buys only bookkeeping. | ||
| 247 | + | ||
| 219 | --- | 248 | --- |
| 220 | 249 | ||
| 221 | ## The one that is already fixed here, kept for its diagnostic | 250 | ## The one that is already fixed here, kept for its diagnostic |
| @@ -316,3 +345,73 @@ was allocated next to it. | |||
| 316 | half *is* measured here). To verify: place a sentinel immediately after a scratch | 345 | half *is* measured here). To verify: place a sentinel immediately after a scratch |
| 317 | tile sized to the active lane count, issue a masked distribution store into it, | 346 | tile sized to the active lane count, issue a masked distribution store into it, |
| 318 | and read the sentinel back. | 347 | and read the sentinel back. |
| 348 | + | ||
| 349 | +## `D` not being a multiple of 64 costs nothing — register COUNT is what costs | ||
| 350 | + | ||
| 351 | +**Claim under test.** On `rms_norm`/A5, every public fp16 case with `D` a multiple of 64 beat | ||
| 352 | +the CANN reference (ratio 0.91–0.92) and every fp16 case with `D` not a multiple of 64 lost to | ||
| 353 | +it (1.08–1.48). A 7/7 split, and the near-controlled pair `[32,128,768]` vs `[33,127,769]` — | ||
| 354 | +one extra element of `D`, row count controlled to 2.3 % — showed **+21 %**. The natural reading | ||
| 355 | +is a ragged-column-tail or 32-byte-burst-alignment defect. | ||
| 356 | + | ||
| 357 | +**It is not.** Measured on the pinned `kernel_eval` harness (`--perf-metric-strategy | ||
| 358 | +kernel_details`), Ascend950PR card 4, fp16, `S = 4096` held fixed while `D` walks. Same-shape | ||
| 359 | +repeats inside the run drifted **0.00 %, 0.00 %, −1.88 %**, so the instrument resolves ~2 %. | ||
| 360 | + | ||
| 361 | +The decisive triple shares the `MaxN = 1024` rung, 16 registers per row and one UB footprint — | ||
| 362 | +only alignment differs: | ||
| 363 | + | ||
| 364 | +| D | 32B-aligned | `D mod 64` | `D == MaxN` | µs | | ||
| 365 | +|---:|:--:|---:|:--:|---:| | ||
| 366 | +| 1008 | ✓ | **48** | ✗ | 10.50 | | ||
| 367 | +| 1023 | ✗ | 63 | ✗ | 10.47 | | ||
| 368 | +| 1024 | ✓ | 0 | ✓ | 10.44 | | ||
| 369 | + | ||
| 370 | +**0.6 % apart.** `D = 1023` — the width of the public case that loses 11 % — costs what | ||
| 371 | +`D = 1024` costs. The same holds one rung down: `D = 80` (`mod 64 = 16`, 32B-aligned) costs | ||
| 372 | +3.07 µs, exactly what `D = 128` (`mod 64 = 0`) costs, while `65/67/127` cost 3.22/3.19/3.14 — | ||
| 373 | +a residual of ≤ 3.7 % that **shrinks with `D` and is gone by `D ≈ 1000`**, the opposite of the | ||
| 374 | +direction the deficit needs. | ||
| 375 | + | ||
| 376 | +**So the modulus question is ill-posed: there is no modulus.** 64 is dead, and 128 and 256 die | ||
| 377 | +with it. What predicts cost is `ceil(D/64)` — the register count — a *ceiling*, not a residue | ||
| 378 | +class. Every `D` in `(64k, 64k+64]` costs the same, which is exactly why aligned and misaligned | ||
| 379 | +`D` are indistinguishable once register count is controlled. Fitting the three points that | ||
| 380 | +share `MaxN = 1024` and `Rows = 16` (13, 15, 16 registers → 9.04, 10.13, 10.47 µs) gives | ||
| 381 | +**2.75 µs fixed + 0.486 µs per register**, reproducing all three to ±1 %. | ||
| 382 | + | ||
| 383 | +**Why the public split looked so convincing — the confound.** In that suite the aligned fp16 | ||
| 384 | +cases sit at `D = 768, 4096, 4096` and the misaligned ones at `D = 67, 769, 1021, 1023`. There | ||
| 385 | +is **no aligned fp16 case anywhere in the `D ∈ [769, 2047]` band**, so "aligned vs misaligned" | ||
| 386 | +is perfectly confounded with "`D` at 768/4096 vs `D` near 1024". Probing `D = 960, 1008, 1024` | ||
| 387 | +— aligned and *in band* — breaks the confound: they are just as slow as 1023. Measured against | ||
| 388 | +the fused reference (`torch_npu.npu_rms_norm`) on one clock, our ratio is 1.19 at `D = 768` and | ||
| 389 | +1.40–1.42 at `D = 960/1008/1023/1024` alike. The ratio degrades with `D`-position on the rung | ||
| 390 | +ladder, not with alignment. | ||
| 391 | + | ||
| 392 | +**Two hypotheses this also kills**, since the same points control them: | ||
| 393 | + | ||
| 394 | +* *Row tiling / ragged `S`.* With `D = 768` fixed, the ragged row counts of the slow cases cost | ||
| 395 | + **less** per row than the round one: 1.8611 (S=4191) and 1.8645 (S=4221) against 1.8945 | ||
| 396 | + µs/1000 rows (S=4096). The remaining variation with `S` is `_pick_rows` landing on Rows 21 or | ||
| 397 | + 8 instead of 16 — a documented smooth function of `S`, not of its factorisation. | ||
| 398 | +* *Burst contiguity collapse* (`D == MaxN` ⟹ `dst_gap == 0` ⟹ the whole `[Rows, D]` block moves | ||
| 399 | + as one burst instead of `Rows` short ones). `D = 1024` has it, `D = 1008` and `1023` do not, | ||
| 400 | + and all three cost the same. Worth 0 here. | ||
| 401 | + | ||
| 402 | +**What the `768 → 769` +21 % actually is.** It reproduces (+16.9 % at controlled `S = 4096`) and | ||
| 403 | +then decomposes entirely into two already-known quantisations: 12 → 13 registers (+8.3 % of | ||
| 404 | +vector work) and a `MaxN` rung jump 768 → 1024 (a 33 % wider tile for one extra element, worth | ||
| 405 | +~10 % by the fit above). `D = 1040` clinches it — one register *more* than 1024, on the 2048 | ||
| 406 | +rung — at **10.20 µs, below** `D = 1024`'s 10.44. Only rung/`Rows` selection can do that; | ||
| 407 | +alignment cannot. | ||
| 408 | + | ||
| 409 | +**Rule.** Do not spend a run making `D` "aligned" for a `vf` row kernel of this shape. Size the | ||
| 410 | +tile to `align64(D)` because `load_align` moves a whole register and will otherwise fault | ||
| 411 | +`507035` (first rule on this page) — that is a **correctness** constraint. It is not a | ||
| 412 | +performance one. If a benchmark's slow cases all have ragged `D`, check first whether ragged | ||
| 413 | +`D` is confounded with `D` magnitude or with register count in that suite; in this one it was. | ||
| 414 | + | ||
| 415 | +**Diagnostic that settles it in one eval run:** probe three `D` values sharing a rung and a | ||
| 416 | +register count, one aligned-and-equal-to-rung, one aligned-but-below-rung, one misaligned. If | ||
| 417 | +they land together, alignment is not your mechanism. | ||
| @@ -55,6 +55,180 @@ vf.store_align(output_tile + offset, result, predicate) | |||
| 55 | `vf.load_align(input_tile, offset, predicate)` is not a supported mask | 55 | `vf.load_align(input_tile, offset, predicate)` is not a supported mask |
| 56 | placement in the retained guidance. | 56 | placement in the retained guidance. |
| 57 | 57 | ||
| 58 | +## Performance: the mask is the first thing to look at | ||
| 59 | + | ||
| 60 | +A `vf.*` register loop that recomputes its mask per register is the largest | ||
| 61 | +single performance defect this knowledge base has a measurement for. It is worth | ||
| 62 | +checking before any other vector lever, because it can be several times | ||
| 63 | +everything else put together. | ||
| 64 | + | ||
| 65 | +**Why it costs so much.** `vf.update_mask` lowers to `plt_b32(scalar, | ||
| 66 | +POST_UPDATE)` — a **special-purpose-register write**, not an ordinary vector | ||
| 67 | +issue slot. Inside a hot loop it serialises against the vector pipe. There is no | ||
| 68 | +cheap per-register mask to ask for instead. | ||
| 69 | + | ||
| 70 | +**The fix is structural, not a tuning knob.** Every register but the last is | ||
| 71 | +*fully* valid, so it can run on one hoisted constant mask; only the ragged last | ||
| 72 | +register needs a computed mask, and that mask depends on the row width alone, so | ||
| 73 | +it is computed once per call. Peel the last register out of the loop: | ||
| 74 | + | ||
| 75 | +```python | ||
| 76 | +preg = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=pl.DT_FP32) | ||
| 77 | +n_full = (n_cols + LANES - 1) // LANES - 1 # whole registers | ||
| 78 | +toff = n_full * LANES # offset of the ragged one | ||
| 79 | +mtail = vf.update_mask(n_cols - toff, dtype=pl.DT_FP32) # once per call | ||
| 80 | +for r in pl.range(0, n_full): | ||
| 81 | + ... # on preg | ||
| 82 | +... # peeled tail, on mtail | ||
| 83 | +``` | ||
| 84 | + | ||
| 85 | +This is **bit-identical by construction**, not an approximation: | ||
| 86 | +`min(LANES, n_cols - r*LANES) == LANES` for exactly the registers that now run | ||
| 87 | +on `preg`, and the peeled register keeps the mask value it had. Confirm it in | ||
| 88 | +the generated code — the inner loops must contain **no `plt_b32`**. | ||
| 89 | + | ||
| 90 | +**One guard the snippet above needs.** `n_full = (n_cols + LANES - 1) // LANES - 1` | ||
| 91 | +is `-1` when `n_cols == 0`, which makes `toff` negative and turns the peeled tail | ||
| 92 | +into a whole-register access **below the tile base** — and `mtail` is | ||
| 93 | +`update_mask(0 - (-LANES)) = update_mask(LANES)`, i.e. the ALL mask, so the store | ||
| 94 | +writes a full register out of bounds. That is a **507035 device fault**, which is | ||
| 95 | +not a compile error and survives every device-free gate. The per-register form it | ||
| 96 | +replaces degraded harmlessly (`n_regs = 0`, empty loop), so this is a hazard the | ||
| 97 | +rewrite *introduces*. | ||
| 98 | + | ||
| 99 | +Clamp it. `n_full = pl.max((n_cols + LANES - 1) // LANES - 1, 0)` works inside a | ||
| 100 | +`@pl.vector_function` (device-verified) and costs **one scalar op per call**, not | ||
| 101 | +per register — measured free, inside a ±1.5 % noise floor, on the two cases that | ||
| 102 | +reach a 1-lane block. Whether `n_cols == 0` is reachable is a property of the | ||
| 103 | +*caller*; on the operator this was measured on it was not, but a later change to | ||
| 104 | +the planner or the column-block count re-arms it silently. | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +**The measurements live on one page, and it is not this one.** The table for this lever — both suites, the curve they sit on, the memory-bound control that reads 1.68x, and the width below which the hoist stops paying — is | ||
| 108 | +[`vec-alignment-and-rotation.md`](vec-alignment-and-rotation.md). Quote it from there. | ||
| 109 | +What belongs here is the authoring rule above: never recompute a mask per register. | ||
| 110 | + | ||
| 111 | +### 🏆 Officially scored: the hoist is worth 1.77-2.99x in the COLUMN-BLOCK loop | ||
| 112 | + | ||
| 113 | +Everything else on this page is box-measured. This entry is the first **grader-scored** confirmation, | ||
| 114 | +from an official cann-bench hidden-set run (rms_norm, 80 cases, 2026-08-10). | ||
| 115 | + | ||
| 116 | +The kernel splits a row across column blocks when `D` exceeds one tile (`Mode 2 / COLBLK`), and its | ||
| 117 | +inner helpers recomputed `vf.update_mask` **per register** inside that per-block loop. At `D = 16384` | ||
| 118 | +the computed mask is identically the all-lanes constant, so every one of those writes is a no-op | ||
| 119 | +`plt_b32` -- 512 of them per row. Hoisting them out, and nothing else in that lever: | ||
| 120 | + | ||
| 121 | +| hidden case | before | after | speedup | | ||
| 122 | +|---|---|---|---| | ||
| 123 | +| 55 | 660.71 us | **221.10 us** | **2.988x** | | ||
| 124 | +| 56 | 1309.69 | **465.78** | **2.812x** | | ||
| 125 | +| 97 | 118.17 | **43.68** | **2.705x** | | ||
| 126 | +| 51 | 88.23 | **35.99** | **2.452x** | | ||
| 127 | +| 54 | 316.05 | 178.85 | 1.767x | | ||
| 128 | + | ||
| 129 | +**+0.9212 benchmark points from five cases out of eighty**, and the whole submission moved | ||
| 130 | +84.3476 -> 84.9747. The five were named **in advance** from the operator's tiling modes, so this is | ||
| 131 | +attribution, not a post-hoc story. | ||
| 132 | + | ||
| 133 | +**Two things to take from it.** | ||
| 134 | + | ||
| 135 | +1. **A column-blocked / multi-tile-per-row loop is the highest-value place to look for this defect**, | ||
| 136 | + higher than the single-tile row loop the rest of this page describes. The per-block loop body runs | ||
| 137 | + `ceil(D/MaxN)` times per row, so a per-register mask there is multiplied by the block count on top | ||
| 138 | + of the register count. | ||
| 139 | +2. **The magnitude survives to the official grader.** A 2.4-6.5x box measurement of this lever is not | ||
| 140 | + a box artifact; here the graded speedups (1.77-2.99x) were *larger* than the box's own estimate of | ||
| 141 | + the same cohort (1.65-2.03x). When this lever is available, it is worth more than any tiling | ||
| 142 | + knob measured in this campaign. | ||
| 143 | + | ||
| 144 | +🔴 **The same run also shows what did NOT survive.** A tile-count/`Rows` planner change measured | ||
| 145 | +2.27x on its target case and was a **net negative** once scored (see | ||
| 146 | +`../playbooks/benchmark-scoring.md`), and a "drop the tiling struct, pass scalars" change large | ||
| 147 | +enough to be visible on paper produced a public delta whose per-case pattern did not match its own | ||
| 148 | +mechanism. **The mask hoist is the lever with an official number behind it; treat the others as | ||
| 149 | +unproven until they have one.** | ||
| 150 | + | ||
| 151 | +### The second lever, and why it must be gated | ||
| 152 | + | ||
| 153 | +Replacing the per-register horizontal `vf.reduce_sum` with a lane-wise | ||
| 154 | +accumulate and one horizontal reduction per row is the textbook next step. | ||
| 155 | + | ||
| 156 | +🔴 **This is two separable changes, and doing only the first is half the lever.** | ||
| 157 | +(a) *lane-wise accumulation* — accumulate into a register and reduce once per row | ||
| 158 | +instead of reducing per register; and (b) *fusion* — spell that accumulation as the | ||
| 159 | +fused `acc = vf.mul_add_dst(r0, r0, preg)` rather than `s = vf.mul(x, x, preg)` | ||
| 160 | +followed by `acc = vf.add(acc, s, preg)`, which is one instruction per register | ||
| 161 | +instead of two. A kernel that does (a) with `vf.add` has taken the structural half | ||
| 162 | +and left the instruction-count half on the table. Both halves are gated by the same | ||
| 163 | +condition below. | ||
| 164 | + | ||
| 165 | +With a **single** accumulator chain the fused form **measured slower** (+0.7 and | ||
| 166 | ++1.4 percent): the accumulator is a loop-carried dependency and the | ||
| 167 | +multiply-accumulate serialises. It only pays with **four independent accumulator chains** unrolled | ||
| 168 | +by four, which measured 1.256x and 1.305x on the two large cases in | ||
| 169 | +[`vec-alignment-and-rotation.md`](vec-alignment-and-rotation.md). | ||
| 170 | + | ||
| 171 | +But four accumulator inits and three merges per row are pure overhead on a row | ||
| 172 | +that never fills a quad. Applied ungated it **cost 3.0 percent** on the `D = 67` | ||
| 173 | +case (one whole register per row, so no quad is ever entered). It ships behind a | ||
| 174 | +**compile-time width test**: | ||
| 175 | + | ||
| 176 | +```python | ||
| 177 | +if MaxN >= UNROLL_MAXN: # MaxN is a tilingkey constant; this folds | ||
| 178 | + rows_unrolled_vf(...) | ||
| 179 | +else: | ||
| 180 | + rows_plain_vf(...) | ||
| 181 | +``` | ||
| 182 | + | ||
| 183 | +The general rule: an unrolled or multi-accumulator reduction is only correct as | ||
| 184 | +a *performance* choice above a width threshold, and the threshold belongs in a | ||
| 185 | +compile-time constant so each specialisation gets one body. A runtime branch | ||
| 186 | +would pay for itself on every row. See | ||
| 187 | +[../patterns/tiling-key-width-ladder.md](../patterns/tiling-key-width-ladder.md) | ||
| 188 | +for the mechanism, and note that `vf.add(vf.add(a, b), c)` is a parse error — | ||
| 189 | +accumulator merges need explicit assignments. | ||
| 190 | + | ||
| 191 | +**The gate was re-tested from the other side, and it held.** The obvious | ||
| 192 | +objection to the width gate is that it blames the *four chains* for the narrow-row | ||
| 193 | +loss, when the single-accumulator form might pay there on its own — it removes a | ||
| 194 | +horizontal `vf.reduce_sum` from every register, and four inits are not involved. | ||
| 195 | +So it was measured directly: single full-width accumulator, one reduce per row, | ||
| 196 | +**no** unrolling, on the narrow rungs only. | ||
| 197 | + | ||
| 198 | +It is **slower**. Ratios 0.986 / 0.969 / 0.992 on rows of `D = 373 / 67 / 128` | ||
| 199 | +(control drift +1.9 / +0.1 / −1.0 %, A/B/A in one process). It cut the narrow path | ||
| 200 | +from **9 to 7 vector ops per register** and still lost. | ||
| 201 | + | ||
| 202 | +Two things to carry forward. First, this is direct evidence for the *stated | ||
| 203 | +mechanism* rather than for the gate's boundary: the accumulator is a loop-carried | ||
| 204 | +dependency, and with one chain there is nothing to interleave against it, so the | ||
| 205 | +saved horizontal reduce buys less than the serialisation costs. Four chains are | ||
| 206 | +not an optimisation *on top of* the fused accumulate — they are what makes it | ||
| 207 | +viable at all. Second, and more generally: **op count is not the objective | ||
| 208 | +function on this vector pipe.** A rewrite that provably issues fewer instructions | ||
| 209 | +per register can be slower, so a lever counted in ops still has to be timed. | ||
| 210 | + | ||
| 211 | + | ||
| 212 | +## Missing primitives to plan around | ||
| 213 | + | ||
| 214 | +- **`Vf` has no `rsqrt` and no `recip`.** `pl.rsqrt` and `pl.recip` exist but | ||
| 215 | + are tile level and leave the vector-function domain, so a normalisation | ||
| 216 | + written in `vf.*` pays `sqrt` **plus** `div` on every row where one | ||
| 217 | + instruction would do. Budget for it; do not design a chain that assumes a | ||
| 218 | + reciprocal-square-root exists at register level. (Measured on the same box, | ||
| 219 | + fp32 over 2^-24 … 2^24: `1/sqrt(v)` is also the *more accurate* of the two, | ||
| 220 | + matching the CPU bit for bit, while the NPU `rsqrt` primitive is about 1.39x | ||
| 221 | + looser in the worst case — so the missing primitive costs speed, not | ||
| 222 | + precision.) | ||
| 223 | +- **There is no `vf.cast`.** Widening at register level is `Vf.astype`, whose | ||
| 224 | + documented dtype table covers FP32 to and from FP16 and INT32 only — **BF16 | ||
| 225 | + is undocumented**. Prefer `pl.cast` at tile level for a BF16 chain. | ||
| 226 | +- **There is no unroll control.** `pl.range` takes start/stop/step, so unrolling | ||
| 227 | + is hand-written source duplication plus a remainder loop. | ||
| 228 | + | ||
| 229 | +Confirm each of these against the installed API documentation for the target | ||
| 230 | +version before designing around it. | ||
| 231 | + | ||
| 58 | ## Evidence | 232 | ## Evidence |
| 59 | 233 | ||
| 60 | - Tile-operation implementation and golden: | 234 | - Tile-operation implementation and golden: |
| @@ -67,3 +241,207 @@ placement in the retained guidance. | |||
| 67 | 241 | ||
| 68 | The installed `$PYPTO_DEVKIT_DIR/docs/pypto_pro/api/` documentation remains the | 242 | The installed `$PYPTO_DEVKIT_DIR/docs/pypto_pro/api/` documentation remains the |
| 69 | primary source for signatures and target-version behavior. | 243 | primary source for signatures and target-version behavior. |
| 244 | + | ||
| 245 | +--- | ||
| 246 | + | ||
| 247 | +## BF16 at register level: what `Vf.astype` can and cannot do | ||
| 248 | + | ||
| 249 | +Measured on A5 / DAV_3510 (CANN 9.1.0-beta.3) with `rms_norm`, by direct probe on | ||
| 250 | +the device. This section resolves the "**BF16 is undocumented**" caveat recorded | ||
| 251 | +above for `Vf.astype`: BF16 *is* supported, but asymmetrically, and the asymmetry | ||
| 252 | +decides whether a whole class of lever is expressible. | ||
| 253 | + | ||
| 254 | +**Narrowing FP32 → BF16 works, and is bit-identical to the tile cast.** | ||
| 255 | + | ||
| 256 | +```python | ||
| 257 | +be = vf.astype(e, preg, dtype=pl.DT_BF16, layout=pl.CastLayout.ZERO) # -> EVEN lanes | ||
| 258 | +bo = vf.astype(o, preg, dtype=pl.DT_BF16, layout=pl.CastLayout.ONE) # -> ODD lanes | ||
| 259 | +both = vf.or_(be, bo, pn) # both casts are MODE_ZEROING, so OR merges them | ||
| 260 | +``` | ||
| 261 | + | ||
| 262 | +Each call converts one 64-lane FP32 register into half of a 128-lane BF16 register. | ||
| 263 | +To publish 128 *contiguous* outputs, de-interleave the two FP32 sources first — | ||
| 264 | +`e, o = vf.de_interleave(o0, o1)` splits the `[o0|o1]` stream into even/odd, which | ||
| 265 | +is the exact inverse of the ZERO/ONE lane placement. A single register (a ragged | ||
| 266 | +tail) goes through the same sequence as `vf.de_interleave(o, o)`: the low 64 lanes | ||
| 267 | +then hold `o[0..63]` in order, and the store mask keeps the rest unwritten. | ||
| 268 | + | ||
| 269 | +**The `round_mode` kwarg is IGNORED for FP32 → BF16.** `CAST_RINT` and | ||
| 270 | +`CAST_HYBRID` do not even compile — | ||
| 271 | + | ||
| 272 | +``` | ||
| 273 | +The 4th argument of this vcvt (f322bf16) can only be: | ||
| 274 | +ROUND_R, ROUND_A, ROUND_F, ROUND_C, ROUND_Z | ||
| 275 | +``` | ||
| 276 | + | ||
| 277 | +— and the six modes that *do* compile (`CAST_ROUND`, `CAST_RNA`, `CAST_ODD`, | ||
| 278 | +`CAST_FLOOR`, `CAST_CEIL`, `CAST_TRUNC`) all return **the same bytes**, including on | ||
| 279 | +64 inputs that are exact BF16 ties (low 16 mantissa bits `== 0x8000`, 30 of which | ||
| 280 | +move under truncation). `FLOOR` and `CEIL` cannot both agree with nearest-even on a | ||
| 281 | +genuine tie, so the mode is not reaching the instruction: the hardware always | ||
| 282 | +rounds nearest-even. That happens to equal `pl.cast(..., mode=CAST_RINT)`, so | ||
| 283 | +replacing a tile-level narrowing cast with the register form is **bit-exact**, not a | ||
| 284 | +precision trade. Pass a mode anyway to state the intent; do not rely on it. | ||
| 285 | + | ||
| 286 | +**Widening BF16 → FP32 is HALF BROKEN, and this is the load-bearing fact.** | ||
| 287 | + | ||
| 288 | +| `vf.astype(bf16_reg, preg, dtype=pl.DT_FP32, layout=…)` | result | | ||
| 289 | +|---|---| | ||
| 290 | +| `CastLayout.ZERO` (`PART_EVEN`) | source elements 0, 2, 4, … — correct, **stride 2** | | ||
| 291 | +| `CastLayout.ONE` (`PART_ODD`) | **all zeros** — 0/64 lanes non-zero | | ||
| 292 | +| `CastLayout.TWO` / `THREE` | do not compile (`static_assert`: only `PartEven`/`PartOdd`) | | ||
| 293 | + | ||
| 294 | +Only the **even** elements of a BF16 register can be widened at register level. The | ||
| 295 | +odd elements are unreachable: no aligned load starts one BF16 element in, and | ||
| 296 | +`unpack`/`shift_left` recover the right bits but strand them in an integer register. | ||
| 297 | + | ||
| 298 | +### Consequence: there is no register bitcast, so bit-trick widening is not portable | ||
| 299 | + | ||
| 300 | +`grep -rniE "bitcast|reinterpret|as_type|raw_view|view_as"` over | ||
| 301 | +`pypto_pro/language/` finds nothing. Registers carry a dtype and `Vf.astype` is a | ||
| 302 | +*value* conversion; **tiles** can be aliased at a UB address, **registers cannot**. | ||
| 303 | + | ||
| 304 | +This kills the widely-quoted trick "BF16 is the top 16 bits of FP32, so widening is | ||
| 305 | +`interleave(zero, x)`, one instruction, bit-exact". The identity is true, but it | ||
| 306 | +delivers its result as bits in a 16-bit-typed register and there is no way to | ||
| 307 | +consume those bits as FP32 without a store+reload through UB — which is exactly the | ||
| 308 | +traffic `pl.cast` already performs in one tile operation, so it cannot win. Note in | ||
| 309 | +particular that *having* `vf.interleave` does not imply the trick is expressible: | ||
| 310 | +`vf.interleave` preserves its source's type. | ||
| 311 | + | ||
| 312 | +**Rule of thumb.** For a BF16 chain, **narrow** in the register file (free, bit-exact, | ||
| 313 | +removes a whole tile-level pass and its `auto_mutex` barrier) and **widen** at tile | ||
| 314 | +level with `pl.cast`. The asymmetry is a hardware/ISA property, not a pypto gap. | ||
| 315 | + | ||
| 316 | +### Publishing BF16 from registers: 5 ops per 128 outputs is the floor | ||
| 317 | + | ||
| 318 | +The `de_interleave` + 2×`astype` + `or_` + store sequence above is not merely *a* | ||
| 319 | +way to publish BF16 — it is the cheapest one this DSL offers. Two candidate | ||
| 320 | +shortcuts were measured on A5 / DAV_3510 and both are unavailable: | ||
| 321 | + | ||
| 322 | +* `vf.store_align(..., dist=pl.StoreDist.PACK)` does **not** compact the 64 valid | ||
| 323 | + even lanes of an `astype(..., layout=ZERO)` result into 64 contiguous BF16. With | ||
| 324 | + marker values and a pre-zeroed destination it writes 60 non-zero lanes in neither | ||
| 325 | + the contiguous nor the even-lane arrangement. | ||
| 326 | +* `dist=pl.StoreDist.NORM` for an FP32 source register into a BF16 tile does not | ||
| 327 | + compile. There is no converting store. | ||
| 328 | + | ||
| 329 | +So `de_interleave` and `or_` cannot be removed, and a register-level BF16 publish | ||
| 330 | +costs 5 register ops per 128 outputs. Budget accordingly before assuming a | ||
| 331 | +publish-side rewrite will pay: on `rms_norm` this publish traded +1.5 vector ops per | ||
| 332 | +register against one tile-level `pl.cast` pass and measured **2.8 % slower** on the | ||
| 333 | +BF16 cohort, on the pinned harness, in a control-bracketed chain. | ||
| 334 | + | ||
| 335 | +### Measuring anything with `pl.jit` variants: use a canary | ||
| 336 | + | ||
| 337 | +Two `pl.jit` kernels that share a decorated **name** and an identical **body source | ||
| 338 | +text** can silently resolve to the same compiled binary, even when they close over | ||
| 339 | +different constants or call different `@pl.vector_function`s. The factory idiom | ||
| 340 | +`def make_k(p): @pl.jit def k(...): ...; return k` decorates every variant as `k`, | ||
| 341 | +and `k.__name__ = ...` afterwards is too late — the name is captured at decoration. | ||
| 342 | + | ||
| 343 | +This does not raise. It returns clean, self-consistent, plausible data from the | ||
| 344 | +wrong kernel. Give every variant its own `def`, **and** include a canary variant | ||
| 345 | +that differs in something that must visibly change (store at a different offset). | ||
| 346 | +If the canary's output does not move, the compiles are not distinct — discard the | ||
| 347 | +run rather than reporting it. | ||
| 348 | + | ||
| 349 | +--- | ||
| 350 | + | ||
| 351 | +<!-- ADDITIVE INSERTION — Run F, rms_norm Stage 5, A5 card 4, 2026-08-11. | ||
| 352 | + Confirmed by measurement (compiled and ran on hardware) unless the line says otherwise. --> | ||
| 353 | + | ||
| 354 | +## `vf.pair_reduce_sum` is the ONLY sub-register reduction, and it is radix-2 by construction | ||
| 355 | + | ||
| 356 | +The `vf` surface on this SDK is 86 ops. Its reductions are exactly: | ||
| 357 | + | ||
| 358 | +| op | granularity | | ||
| 359 | +|---|---| | ||
| 360 | +| `vf.reduce_sum` / `vf.reduce_max` / `vf.reduce_min` | whole register → lane 0 | | ||
| 361 | +| `vf.pair_reduce_sum` | adjacent pairs, `dst_i = src_2i + src_2i+1` (`vcpadd`) | | ||
| 362 | + | ||
| 363 | +**There is no variable-width segmented reduction op.** Any in-register segmented reduce must be built | ||
| 364 | +by iterating `pair_reduce_sum`, which restricts the segment width to a power of two — and since a | ||
| 365 | +register is 64 lanes, that is exactly "the segment width divides the register". The two conditions | ||
| 366 | +coincide, so a radix-2 tree is fully general over its natural domain `{1, 2, 4, 8, 16, 32}` and serves | ||
| 367 | +nothing outside it. This is a hard ISA limit, not a frontend gap. `vf.interleave(v, v)` is the exact | ||
| 368 | +inverse and has the same domain and depth. Worked example and measured payoff: | ||
| 369 | +[patterns/vec-narrow-row-packing.md](../patterns/vec-narrow-row-packing.md). | ||
| 370 | + | ||
| 371 | +Padding a non-power-of-two width up to the next power of two is **not** a cheap escape: a Vec tile row | ||
| 372 | +must be a multiple of 32 bytes (so the padded width is ≥ 8 in fp32), and if the padding is done | ||
| 373 | +tile-side the packing factor becomes the tile *row* count, which a `Rows`-style `TilingKeyField` caps | ||
| 374 | +at 64 — collapsing the packing back into the short-burst regime it existed to escape. The remaining | ||
| 375 | +route is `vf.gather`-repack in registers; it is expressible but needs runtime segment-phase tracking | ||
| 376 | +across tiles when `D ∤ MaxN`, and has not been measured. | ||
| 377 | + | ||
| 378 | +## `vf.gatherb` and `vf.select_r` are DEPRECATED, and fail at different stages | ||
| 379 | + | ||
| 380 | +* `vf.gatherb(...)` — *"no longer accepted by the parser"*. Use | ||
| 381 | + `vf.gather(src, idx, mask, data_copy_mode=pl.DataCopyMode.DATA_BLOCK_LOAD)` for the former | ||
| 382 | + datablock-granularity gather. | ||
| 383 | +* `vf.select_r(...)` — *"not implemented … has no backend implementation"*. Use `vf.select` with | ||
| 384 | + swapped arguments, or `vf.gather`. | ||
| 385 | + | ||
| 386 | +Both are still importable and still appear in `dir(Vf)`, so `hasattr`-style feature detection reports | ||
| 387 | +that they exist and then fails later. Read the docstring, not the attribute list. | ||
| 388 | + | ||
| 389 | +## `vf.arange`'s per-lane step is fixed at ±1 | ||
| 390 | + | ||
| 391 | +`vf.arange(start, index_order=...)` gives `start + i` (`INCREASE_ORDER`, default) or `start − i` | ||
| 392 | +(`DECREASE_ORDER`) and nothing else — the step is a hardware property of `vci`. A strided index vector | ||
| 393 | +needs a following `vf.muls`. Relevant whenever you are building gather/scatter indices. | ||
| 394 | + | ||
| 395 | +## `LoadDist.BRC_B32` needs 32-byte alignment, which caps the "replicate a short vector" idiom at 2 | ||
| 396 | + | ||
| 397 | +The idiom "one 32-byte-aligned single-element tile per element, then `vf.interleave`" replicates a | ||
| 398 | +2-element vector across a register and **cannot be written for 4 elements**, which would want tiles 16 | ||
| 399 | +bytes apart. The general replacement, for any power-of-two period `P` including `P = 1`: | ||
| 400 | +`vf.arange` → `vf.and_(P-1)` → `vf.gather(tile, idx, mask)`, giving `dst_i = src[i mod P]` in four | ||
| 401 | +register ops from an ordinary `[1, N]` tile. `vf.arange`, `vf.and_` on `DT_INT32` registers and | ||
| 402 | +`vf.gather` all work inside a `@pl.vector_function` with an FP32-granularity predicate mask (b32 | ||
| 403 | +granularity is shared). | ||
| 404 | + | ||
| 405 | +## `pl.load` places at the tile ORIGIN — the `[i, j]` argument is a SOURCE offset | ||
| 406 | + | ||
| 407 | +`pl.load(dst_tile, src_tensor, [i, j])` reads `src_tensor[i, j]` and writes at the destination tile's | ||
| 408 | +base address. There is **no destination offset**. So you cannot assemble a pattern inside one tile by | ||
| 409 | +issuing several loads at different column offsets: each destination offset needs its own tile group, | ||
| 410 | +with its own address and mutex id. This is the second reason the replication problem above is not | ||
| 411 | +solvable tile-side. | ||
| 412 | + | ||
| 413 | +## Compile-time tilingkey arithmetic inside `@pl.vector_function` (measured, pypto-master-20260730) | ||
| 414 | + | ||
| 415 | +A tilingkey constant is an ordinary Python `int` in the body of a | ||
| 416 | +`@pl.vector_function`, and Python control flow over it is resolved at parse time | ||
| 417 | +and leaves no runtime branch. All of these compile and fold: | ||
| 418 | + | ||
| 419 | +```python | ||
| 420 | +NR = MaxN // LANES # noqa: F821 -- a Python int | ||
| 421 | +toff = (NR - 1) * LANES # a Python int | ||
| 422 | +if MaxN > LANES: ... # folded away | ||
| 423 | +if NR >= 3: ... # folded away | ||
| 424 | +mk = mtail if NR == j + 1 else preg # folded away | ||
| 425 | +``` | ||
| 426 | + | ||
| 427 | +This was previously documented only for a dedicated depth field (`PackLog` in | ||
| 428 | +`rms_packn_vf`). It holds for `MaxN` too, which means a rung can carry a | ||
| 429 | +compile-time **register count**, not just a compile-time width — see | ||
| 430 | +`pypto-pro-op-kb/patterns/vec-compile-time-register-count.md`. | ||
| 431 | + | ||
| 432 | +Two more, same build: | ||
| 433 | + | ||
| 434 | +* **`vf.load_align` hoists out of a `pl.range` loop and the loaded register is | ||
| 435 | + reusable in every iteration.** Precedent previously existed only for | ||
| 436 | + `vf.gather`. A per-column operand (gamma) can therefore be loaded once per call | ||
| 437 | + instead of once per register per row. | ||
| 438 | +* **Up to 8 loaded registers stay live across an intervening | ||
| 439 | + `reduce_sum` / `full` / `div` / `sqrt` / `div` chain** and can be reused | ||
| 440 | + afterwards instead of re-loaded — no spill, no compile failure, measured faster. | ||
| 441 | + | ||
| 442 | +### Non-lever, measured | ||
| 443 | + | ||
| 444 | +Row-level software pipelining inside a vector function (two independent rows in | ||
| 445 | +flight, separate accumulators and separate `sqrt`/`div` chains) is worth | ||
| 446 | +**0.0–0.4 %** on `rms_norm` at every rung from 64 to 256, i.e. nothing. The | ||
| 447 | +backend already overlaps consecutive `pl.range` iterations. | ||
| @@ -12,10 +12,20 @@ The validation column controls how a pattern may be used: | |||
| 12 | until the target SDK's official docs/examples provide a matching runnable | 12 | until the target SDK's official docs/examples provide a matching runnable |
| 13 | reference. | 13 | reference. |
| 14 | 14 | ||
| 15 | +A page may additionally carry a `Pro: not legal` banner under its title. The | ||
| 16 | +PyPTO-Pro flow mandates a single `@pl.jit` kernel (`stage4-check` #5 fails a | ||
| 17 | +multi-kernel design), so such a page describes a shape that is legal knowledge | ||
| 18 | +and an illegal Pro design. The machine-readable list is `topology-map.json`'s | ||
| 19 | +`target_gated`. | ||
| 20 | + | ||
| 15 | | Pattern | Use when | Validation | | 21 | | Pattern | Use when | Validation | |
| 16 | |---|---|---| | 22 | |---|---|---| |
| 17 | | [cube-only.md](cube-only.md) | the kernel is a pure 2-D contraction | validated skeleton for a single K block; conceptual only for K-loop accumulation | | 23 | | [cube-only.md](cube-only.md) | the kernel is a pure 2-D contraction | validated skeleton for a single K block; conceptual only for K-loop accumulation | |
| 18 | | [vec-row-reduce-broadcast.md](vec-row-reduce-broadcast.md) | each row reduces to a scalar and broadcasts it back | validated skeleton | | 24 | | [vec-row-reduce-broadcast.md](vec-row-reduce-broadcast.md) | each row reduces to a scalar and broadcasts it back | validated skeleton | |
| 25 | +| [vec-narrow-row-packing.md](vec-narrow-row-packing.md) | the reduced dimension is so narrow that one row per tile row wastes most of every register, and the natural tile is not even expressible | validated skeleton | | ||
| 26 | +| [vec-compile-time-register-count.md](vec-compile-time-register-count.md) | a rung ladder picks the tile width as the smallest rung >= D, and you want the per-register loop unrolled at compile time so loop-invariant loads hoist and pass-1 registers survive into pass 2 | validated skeleton, bit-exact on 27 shapes and measured cold on Ascend950PR_9579 | | ||
| 27 | +| [tiling-key-width-ladder.md](tiling-key-width-ladder.md) | the reduced or contracted dimension spans orders of magnitude across the cases, so no one compile-time tile serves them all | validated skeleton for the mechanism; conceptual for the rung policy | | ||
| 28 | +| [vec-compute-exposed-narrow-dtype.md](vec-compute-exposed-narrow-dtype.md) | a narrow io dtype (fp16/bf16) is widened to fp32, computed on, and narrowed back, and you are about to assume the halved byte count makes it bandwidth-bound | conceptual only; decision rules measured cold on Ascend950PR, no retained runnable skeleton | | ||
| 19 | | [buffer-reuse-lifetime.md](buffer-reuse-lifetime.md) | tile groups rotate or persist across iterations | validated skeleton for the indexed rotating groups; conceptual for other loop-carried state | | 29 | | [buffer-reuse-lifetime.md](buffer-reuse-lifetime.md) | tile groups rotate or persist across iterations | validated skeleton for the indexed rotating groups; conceptual for other loop-carried state | |
| 20 | | [batched-2d-contraction.md](batched-2d-contraction.md) | host reshaping can reduce a batched contraction to 2-D | conceptual only | | 30 | | [batched-2d-contraction.md](batched-2d-contraction.md) | host reshaping can reduce a batched contraction to 2-D | conceptual only | |
| 21 | | [quant-matmul-scaled-mm.md](quant-matmul-scaled-mm.md) | a quantized matmul uses explicit scale/round/clamp semantics | validated skeleton for the indexed int8 path | | 31 | | [quant-matmul-scaled-mm.md](quant-matmul-scaled-mm.md) | a quantized matmul uses explicit scale/round/clamp semantics | validated skeleton for the indexed int8 path | |
| @@ -26,3 +36,26 @@ The validation column controls how a pattern may be used: | |||
| 26 | | [vec-ub-strip-gather.md](vec-ub-strip-gather.md) | an index tensor selects, per element, along one axis — `torch.gather`, `GatherElements`, `take_along_dim`, the read half of `scatter` | validated skeleton, 12/12 dtype pairs bit-exact on Ascend950PR_9579 — **the sweep covered `C <= L` only**; the hoisted `c` term is wrong for `C > L` (see the load-bearing premise on that page) | | 36 | | [vec-ub-strip-gather.md](vec-ub-strip-gather.md) | an index tensor selects, per element, along one axis — `torch.gather`, `GatherElements`, `take_along_dim`, the read half of `scatter` | validated skeleton, 12/12 dtype pairs bit-exact on Ascend950PR_9579 — **the sweep covered `C <= L` only**; the hoisted `c` term is wrong for `C > L` (see the load-bearing premise on that page) | |
| 27 | | [vec-tensorlist-fixed-arity.md](vec-tensorlist-fixed-arity.md) | an input is declared `is_list: true`, so the number of tensors is a runtime value the DSL cannot express — the `torch._foreach_*` family | validated skeleton for the padded fixed-arity ladder and the phase rotation, measured to 385 declared parameters on Ascend950PR_9579 | | 37 | | [vec-tensorlist-fixed-arity.md](vec-tensorlist-fixed-arity.md) | an input is declared `is_list: true`, so the number of tensors is a runtime value the DSL cannot express — the `torch._foreach_*` family | validated skeleton for the padded fixed-arity ladder and the phase rotation, measured to 385 declared parameters on Ascend950PR_9579 | |
| 28 | | [vec-scatter-owner-model.md](vec-scatter-owner-model.md) | an index tensor decides where an output element is written | validated skeleton for the inner-tile layout; conceptual for the owner-batch and rank-1 layouts | | 38 | | [vec-scatter-owner-model.md](vec-scatter-owner-model.md) | an index tensor decides where an output element is written | validated skeleton for the inner-tile layout; conceptual for the owner-batch and rank-1 layouts | |
| 39 | + | ||
| 40 | +## Where each pattern is written down in code | ||
| 41 | + | ||
| 42 | +Retained artifacts are linked from the page itself. This table covers only the pages listed below; | ||
| 43 | +every other pattern page states where it was built in its own text. A row marked **retained** names | ||
| 44 | +an artifact kept in this repository, and the measurement behind it is this KB's own. Every other row | ||
| 45 | +is a coordinate in the **PyPTO devkit test tree**, rooted at `python/tests/ut/block/frontend/a5/` | ||
| 46 | +unless the row names another root: read those against the installed version, and do not treat them as | ||
| 47 | +validation this KB has performed. They are listed here so a page marked `conceptual only` still tells | ||
| 48 | +you where the real thing lives. | ||
| 49 | + | ||
| 50 | +| Pattern | Coordinates | | ||
| 51 | +|---|---| | ||
| 52 | +| cube-only | `matmul/test_matmul_api_basic.py:92-125` (single tile), `:128-167` (K-loop) | | ||
| 53 | +| vec-row-reduce-broadcast | `tile_vector/test_softmax.py:59-113` | | ||
| 54 | +| vec-narrow-row-packing | **retained** on branch `stage5-kb-pr`: `custom/rms_norm/test_rms_norm.py`, the PACK path at the `(512, 8)` geometry. There is no devkit sample for this packing | | ||
| 55 | +| vec-compile-time-register-count | **retained** on branch `stage5-kb-pr`: `custom/rms_norm/test_rms_norm.py`, the `rms_rows_flat_vf` path and the extended rung ladder | | ||
| 56 | +| tiling-key-width-ladder | **retained** on branch `stage5-kb-pr`: `custom/rms_norm/test_rms_norm.py`, the 11-rung MaxN ladder with its coupled Rows field, Wide fold and 3-valued Mode under one `@pl.jit`. The ladder has no devkit sample; the supporting mechanisms do, under the devkit's separate `pro_ops/` root: `pro_ops/fa/test_fa_tilingkey_attn_mask.py:127-130,410` (tilingkey, single-bit switch), `pro_ops/element_wise/test_eltwise_dynamic_rank.py:84-99` (`pl.Ptr` + in-kernel `make_tensor`), `pro_ops/fa/test_fa_perf_tkv_preload_dn_vf_bufid_dynrank.py:497-562` (`datatype=` template) | | ||
| 57 | +| buffer-reuse-lifetime | `fa/test_fa_bsnd_dn.py:463-491` (carries), `matmul/test_matmul_api_basic.py:137-167` (double buffering vs carry) | | ||
| 58 | +| batched-2d-contraction | `docs/test_doc_quickstart.py:93-136` | | ||
| 59 | +| quant-matmul-scaled-mm | `docs/test_doc_quant_cast_scatter.py:39-103`; FP8 matmul in `lightning_indexer/test_quant_lightning_indexer_vf.py` | | ||
| 60 | +| vec-per-token-dynamic-quant | no retained artifact; the page composes the row statistic and the quantized write from primitives | | ||
| 61 | +| online-softmax-tail | `tile_vector/test_softmax.py:100-111` (base case); fused streaming in `fa/test_fa_bsnd_dn.py` | | ||
| @@ -0,0 +1,402 @@ | |||
| 1 | +# Width ladder under a single `@pl.jit` | ||
| 2 | + | ||
| 3 | +**Topology:** any — this is a specialisation structure rather than a dataflow. | ||
| 4 | +The worked instance is `row-reduction`. | ||
| 5 | +**Status:** validated skeleton for the mechanism, conceptual for the rung | ||
| 6 | +policy. An 11-rung `MaxN` ladder with a coupled `Rows` field, a `Wide` dtype | ||
| 7 | +fold and a 3-valued `Mode`, all under one `@pl.jit`, passed 12 of 12 correctness | ||
| 8 | +cases on Ascend950PR across `D` in 2 … 16384, ranks 2–5 and three dtypes, with | ||
| 9 | +the host performing no tensor operation. | ||
| 10 | +**Evidence:** `custom/rms_norm/test_rms_norm.py` (on branch `stage5-kb-pr`) — one `@pl.jit`, the | ||
| 11 | +`RmsKey` class carrying `MaxN`/`Rows`/`Wide`/`Mode` in 11 of the 64 available | ||
| 12 | +key bits, and the host planner that picks a key, in the same file. | ||
| 13 | + | ||
| 14 | +## Applies when | ||
| 15 | + | ||
| 16 | +The operator's normalised or contracted dimension spans orders of magnitude | ||
| 17 | +across the graded cases, so no single compile-time tile width is defensible. The | ||
| 18 | +worked instance is a row reduction whose last dimension `D` runs **2 … 8192** | ||
| 19 | +over 20 cases, with rank 2 … 5 and three dtypes on top. | ||
| 20 | + | ||
| 21 | +This is a *specialisation* structure, not a dataflow. It composes with whatever | ||
| 22 | +dataflow the topology dictates, and it is what makes a narrow-`D` special case | ||
| 23 | +such as [vec-narrow-row-packing.md](vec-narrow-row-packing.md) shippable at all: | ||
| 24 | +the packing needs its own tile geometry, and a single fixed tile cannot supply | ||
| 25 | +both that and the wide rungs. | ||
| 26 | + | ||
| 27 | +## The problem, stated as a contradiction | ||
| 28 | + | ||
| 29 | +Two rules point in opposite directions and both are hard. | ||
| 30 | + | ||
| 31 | +- **A fixed compile-time tile cannot serve both ends.** The vector-function | ||
| 32 | + study samples this dataflow is modelled on declare `MAX_N` as a module-level | ||
| 33 | + constant with an `assert cols <= MAX_N` beside it. That is correct for one | ||
| 34 | + width and wrong for a ladder. Sizing it for `D = 8192` wastes the whole | ||
| 35 | + register file at `D = 2`; sizing it for `D = 2` cannot express `D = 8192` at | ||
| 36 | + all. A run that ships the constant anyway has not made a trade-off, it has | ||
| 37 | + chosen which half of its cases to lose. | ||
| 38 | +- **"Emit one kernel per width" is not available.** The flow's anti-cheat rule | ||
| 39 | + is exactly one `@pl.jit` in the delivered file, so a kernel factory is out. | ||
| 40 | + Independently of the rule, a factory is also a known trap: pypto keys its | ||
| 41 | + compiled-kernel cache by the function's `co_name`, so factory kernels sharing | ||
| 42 | + a `def` name silently reuse each other's binary — see | ||
| 43 | + [../references/pitfall-records.md](../references/pitfall-records.md). | ||
| 44 | + | ||
| 45 | +## The resolution | ||
| 46 | + | ||
| 47 | +`pypto_pro.runtime.tilingkey.TilingKeyField` turns a tile dimension into a | ||
| 48 | +compile-time constant selected at launch. The parser folds each field reference | ||
| 49 | +into the IR as a literal, so each concrete key compiles to its own specialised | ||
| 50 | +kernel — from one `def`, one decorator, one launch site. | ||
| 51 | + | ||
| 52 | +```python | ||
| 53 | +from pypto_pro.runtime.tilingkey import TilingKeyField | ||
| 54 | + | ||
| 55 | +class RmsKey: | ||
| 56 | + MaxN = TilingKeyField(bits=4, values=[64, 128, 256, 512, 768, 1024, | ||
| 57 | + 2048, 2112, 4096, 4160, 8192]) | ||
| 58 | + Rows = TilingKeyField(bits=4, values=[1, 2, 3, 4, 5, 6, 8, 11, 12, 16, | ||
| 59 | + 21, 24, 32, 48, 64]) | ||
| 60 | + Wide = TilingKeyField(bits=1, values=[0, 1]) # 1 <=> io dtype is 4 bytes | ||
| 61 | + Mode = TilingKeyField(bits=2, values=[0, 1, 2]) # structural variant | ||
| 62 | + | ||
| 63 | +@pl.jit(auto_mutex=True, tiling_key=RmsKey, compile_timeout=300) | ||
| 64 | +def kernel(x: pl.Ptr[pl.DT_UINT8], ..., tiling: OpTiling): | ||
| 65 | + w_t = pl.TileType(shape=[Rows, MaxN], dtype=pl.DT_FP32, ...) # folded | ||
| 66 | + ... | ||
| 67 | + | ||
| 68 | +kernel[None, blocks, {"MaxN": maxn, "Rows": rows, "Wide": w, "Mode": m}](...) | ||
| 69 | +``` | ||
| 70 | + | ||
| 71 | +The properties that make this work as a *width* ladder rather than only as a | ||
| 72 | +flag set, all read off the installed `runtime/tilingkey.py`: | ||
| 73 | + | ||
| 74 | +- **The field's bits store the *index* into `values`, not the value.** The | ||
| 75 | + packed 64-bit key places each field value's position in `values` at the | ||
| 76 | + field's offset — the same convention as AscendC template tiling keys. So | ||
| 77 | + `values` may be an arbitrary **sparse** list of ints, and tile widths are a | ||
| 78 | + documented use of it. A 4-bit field carries any 16 widths you like, including | ||
| 79 | + 8192. | ||
| 80 | +- `len(values) <= 2**bits`, values must be **unique plain ints** (`bool` is | ||
| 81 | + rejected), and the **total across all fields is <= 64 bits**. The example | ||
| 82 | + above spends `4 + 4 + 1 + 2 = 11`. | ||
| 83 | +- An optional `is_valid(self, key)` predicate on the class rejects illegal | ||
| 84 | + combinations at launch, and is what the binary-delivery path enumerates | ||
| 85 | + against. | ||
| 86 | +- **Compiles are lazy per launched combination**, cached in-process by the | ||
| 87 | + packed key. Only the keys a run actually launches are ever built. | ||
| 88 | + | ||
| 89 | +### Three dtypes are a different mechanism | ||
| 90 | + | ||
| 91 | +Do not try to put the dtype in the tilingkey. It is a separate template: | ||
| 92 | + | ||
| 93 | +```python | ||
| 94 | +@pl.jit(auto_mutex=True, tiling_key=RmsKey, | ||
| 95 | + datatype={"x": "io_dtype", "gamma": "io_dtype", "y": "io_dtype"}) | ||
| 96 | +def kernel(x: pl.Ptr[pl.DT_UINT8], gamma: pl.Ptr[pl.DT_UINT8], | ||
| 97 | + y: pl.Ptr[pl.DT_UINT8], tiling: OpTiling): | ||
| 98 | + xt = pl.make_tensor(x, [S, D], [D, 1], dtype=io_dtype) # io_dtype is the template name | ||
| 99 | + | ||
| 100 | +kernel[stream, blocks, tk_dict, dt_dict](x, gamma, y, tiling) | ||
| 101 | +``` | ||
| 102 | + | ||
| 103 | +The named datatype (`io_dtype` here) becomes usable inside the body for | ||
| 104 | +`pl.TileType(dtype=...)` and `pl.make_tensor(dtype=...)`, the parameters are | ||
| 105 | +declared as `pl.Ptr[pl.DT_UINT8]`, and the concrete map is passed as the | ||
| 106 | +**fourth** bracket argument — `[stream, block_dim, tiling_key, datatype]`. | ||
| 107 | +Omitting it while passing a tilingkey is a common shape of error, because the | ||
| 108 | +three-element form is the one every tilingkey example shows. | ||
| 109 | + | ||
| 110 | +## Choosing the rungs | ||
| 111 | + | ||
| 112 | +The rung set is a design decision with two hard constraints and one judgement | ||
| 113 | +call. | ||
| 114 | + | ||
| 115 | +**Hard: every rung is a multiple of 64** — the fp32 vector alignment granule. | ||
| 116 | +Row base addressing inside the vector function is `base = m * MaxN`, so a rung | ||
| 117 | +that is not a 64-multiple breaks register alignment for every row after the | ||
| 118 | +first. (Off-by-a-few widths are also a known device-fault mode; see | ||
| 119 | +[../references/pitfall-records.md](../references/pitfall-records.md).) | ||
| 120 | + | ||
| 121 | +**Hard: the ladder must be finite and sparse.** One key per distinct `D` defeats | ||
| 122 | +the point — the enumerable combination count is the cartesian product of the | ||
| 123 | +value lists. | ||
| 124 | + | ||
| 125 | +**Choosing `Rows` within a rung: minimise WAVES, not tiles.** For a short-`S`, | ||
| 126 | +narrow-`D` shape the per-tile prologue dominates — on one measured case ≥93 % of | ||
| 127 | +the runtime — so the instinct is "fewer tiles is better". That instinct is wrong | ||
| 128 | +at the end, and measurably so. Sweeping `Rows` at fixed `D = 67`, `S = 2431`, | ||
| 129 | +`_BLOCKS = 56`: | ||
| 130 | + | ||
| 131 | +| `Rows` | tiles | waves = `ceil(tiles/_BLOCKS)` | ratio vs `Rows = 8` | | ||
| 132 | +|---|---|---|---| | ||
| 133 | +| 8 | 304 | 6 | 1.00 | | ||
| 134 | +| 16 | 152 | 3 | 1.49 | | ||
| 135 | +| 24 | 102 | 2 | 1.75 | | ||
| 136 | +| 32 | 76 | 2 | 1.70 | | ||
| 137 | +| **48** | **51** | **1** | **2.24** | | ||
| 138 | +| 64 | 38 | 1 | 2.12 | | ||
| 139 | + | ||
| 140 | +`Rows = 64` has the fewest tiles and is **worse** than 48: 38 tiles leaves 18 of | ||
| 141 | +56 cores idle, and the run is still one wave. Equally, 24 beats 32 at equal waves. | ||
| 142 | +The quantity that predicts the curve is `ceil(ceil(S/Rows)/_BLOCKS)` — pick the | ||
| 143 | +**smallest rung that reaches the minimum wave count**, so the last wave is as full | ||
| 144 | +as possible. | ||
| 145 | + | ||
| 146 | +🔴 **HARNESS OUTCOME, added after the fact: the sweep above is sound, and generalising it into | ||
| 147 | +the planner LOST points.** The rule derived from this table changed the plan for public cases | ||
| 148 | +{1, 14, 16, 17}. Scored on the harness against a three-replicate control mean it was worth | ||
| 149 | +**+0.131 on case 16 and −0.89 on the rest** — a net negative that turned a resolved +1.03 arm into | ||
| 150 | +an unresolved +0.07 one. The tuning bench had rated three of those four cases *faster*, two of them | ||
| 151 | +by 30–34 % in the wrong direction (see `../playbooks/benchmark-scoring.md` § "An ACCEPT from your | ||
| 152 | +tuning bench is not an acceptance"). | ||
| 153 | + | ||
| 154 | +**So: trust the wave-count model for the shape it was measured on, and re-measure ON THE HARNESS | ||
| 155 | +before letting it change any other case's plan.** A planner rule keyed on `(units, maxn, cap)` | ||
| 156 | +reaches shapes you did not sweep, and this one did. | ||
| 157 | + | ||
| 158 | +The corollary for the planner: a tiles-per-core load-balance *floor* is only | ||
| 159 | +meaningful while a tile is big enough to amortise its own prologue. Gate it on | ||
| 160 | +tile occupancy (elements per tile) rather than applying it at every width, and | ||
| 161 | +key the rule on `(units, maxn, cap)` — shape and tile geometry — never on a case | ||
| 162 | +id. Cases whose `Rows` is already UB-cap-bound are unaffected by construction. | ||
| 163 | + | ||
| 164 | + | ||
| 165 | +**Judgement: put a rung just above a cluster of real widths, not at the next | ||
| 166 | +power of two.** The shipped ladder is 11 rungs and two of them are deliberate | ||
| 167 | +non-powers-of-two: | ||
| 168 | + | ||
| 169 | +| rung | = | catches `D` | would otherwise land on | | ||
| 170 | +|---|---|---|---| | ||
| 171 | +| 2112 | 33 * 64 | 2049 | 4096 | | ||
| 172 | +| 4160 | 65 * 64 | 4097, 4099 | 8192 | | ||
| 173 | + | ||
| 174 | +The cost of rounding a 2049-wide row up to a 4096-wide tile is not the padding — | ||
| 175 | +`set_validshape` crops the DMA — it is the **UB budget**, which is what caps the | ||
| 176 | +tile's row count. Measured from the shipped per-rung ceiling table (UB 253952 B, | ||
| 177 | +one core): | ||
| 178 | + | ||
| 179 | +| rung | rows at 4-byte io | rung | rows at 2-byte io | | ||
| 180 | +|---|---|---|---| | ||
| 181 | +| 2112 | 11 | 4160 | 4 | | ||
| 182 | +| 4096 | 6 | 8192 | 1 | | ||
| 183 | + | ||
| 184 | +So the near-fit rung is worth roughly 2x the tile rows on the fp32 case and 4x | ||
| 185 | +on the narrow-dtype case. Fewer rows per tile means more tiles, shorter DMA | ||
| 186 | +bursts and a worse load balance. | ||
| 187 | + | ||
| 188 | +> **Counter-evidence from the same kernel.** The one direct measurement of | ||
| 189 | +> removing a rung found **no difference**: forcing the `D = 2049` fp32 case onto | ||
| 190 | +> the 4096 rung instead of 2112 measured 96.08 us against a 96.11 us control, | ||
| 191 | +> because that case exits *memory-bound* and its byte count does not change. The | ||
| 192 | +> row-count argument above is arithmetic on the UB budget, not a measured | ||
| 193 | +> speedup, and on a memory-bound case it buys nothing. Add near-fit rungs for | ||
| 194 | +> compute-bound widths; do not assume they pay everywhere. | ||
| 195 | + | ||
| 196 | +The `Rows` field is chosen on the host per launch as `min(UB ceiling for this | ||
| 197 | +rung, load-balance floor)` snapped down to a value in the list — so the ladder | ||
| 198 | +is two coupled fields, not one. | ||
| 199 | + | ||
| 200 | +## Structural variants ride in the same key | ||
| 201 | + | ||
| 202 | +A field whose values name *modes* rather than sizes lets one kernel carry | ||
| 203 | +genuinely different bodies. The worked instance ships three: | ||
| 204 | + | ||
| 205 | +| `Mode` | body | selected when | | ||
| 206 | +|---|---|---| | ||
| 207 | +| 0 | one row per tile row | the general case | | ||
| 208 | +| 1 | narrow-row packing | `D == 2` | | ||
| 209 | +| 2 | column-block two-pass | `D >` the widest rung | | ||
| 210 | + | ||
| 211 | +`if Mode == 1:` in the kernel body folds at parse time, so each key emits only | ||
| 212 | +its own branch and the others are removed by constant propagation. The same | ||
| 213 | +technique selects between two `@pl.vector_function` bodies on a compile-time | ||
| 214 | +width test (`if MaxN >= 768: fast_body(...) else: plain_body(...)`) — a | ||
| 215 | +`vector_function` is **inlined into the one kernel**, so this is still a single | ||
| 216 | +`@pl.jit`. Confirm it in the generated code rather than assuming it: on the | ||
| 217 | +retained kernel the narrow keys were read back and do emit the un-unrolled | ||
| 218 | +instruction sequence while the wide keys emit the unrolled one. | ||
| 219 | + | ||
| 220 | +A DSL limitation to plan around: there is **no way to specialise a | ||
| 221 | +`vector_function` per key**. Tilingkey constants are visible inside a | ||
| 222 | +`vector_function` body and do fold there, but function-level selection has to be | ||
| 223 | +written at the call site in the kernel body, once per call site. | ||
| 224 | + | ||
| 225 | +## The host does zero tensor operations | ||
| 226 | + | ||
| 227 | +This is the part that clears | ||
| 228 | +[../constraints/wrapper-boundary.md](../constraints/wrapper-boundary.md) | ||
| 229 | +outright rather than by written justification, and it falls out of the same | ||
| 230 | +mechanism: | ||
| 231 | + | ||
| 232 | +- **rank** 2 … N is absorbed by `pl.Ptr[pl.DT_UINT8]` parameters plus a tiling | ||
| 233 | + struct carrying `S`, `D` and any other runtime scalars; the `[S, D]` view is | ||
| 234 | + built in the kernel by `pl.make_tensor(x, [S, D], [D, 1], dtype=io_dtype)`; | ||
| 235 | +- **dtype** is absorbed by the `datatype=` template; | ||
| 236 | +- **width** is absorbed by the tilingkey. | ||
| 237 | + | ||
| 238 | +What is left on the host is Python integer arithmetic, one output allocation, | ||
| 239 | +and one launch. Not a `reshape`, not a `.contiguous()`, not a `.to()`. Because | ||
| 240 | +the benchmark times the whole callable, "the host reshapes it into the canonical | ||
| 241 | +form the kernel wants" is a scored cost, and the justification route | ||
| 242 | +(`constraints/wrapper-boundary.md`'s "one legitimate exception") is strictly | ||
| 243 | +worse than not needing it. | ||
| 244 | + | ||
| 245 | +## Compile cost is real, and it is outside the timed window | ||
| 246 | + | ||
| 247 | +A ladder multiplies compile instances, so price it before adopting. | ||
| 248 | + | ||
| 249 | +Measured device-free on an `Ascend950PR` host for the 12 instances the host | ||
| 250 | +planner can emit: **0.6–0.9 s each, mean 0.7 s**, artifacts real (the emitted | ||
| 251 | +`kernel.cpp` was inspected per key). There is **no on-disk compiled-kernel | ||
| 252 | +cache** — every process recompiles from source — which is convenient while | ||
| 253 | +tuning (a source edit can never be measured against a stale binary) but means | ||
| 254 | +every run pays it. | ||
| 255 | + | ||
| 256 | +It does not land in the measured window: the harness runs `warmup=3, repeat=5` | ||
| 257 | +and the profiler schedule is `schedule(wait=0, warmup=warmup, active=repeat)`, | ||
| 258 | +so warm-up steps are outside the recording window and each `(tilingkey, dtype)` | ||
| 259 | +combination's first-touch compile happens in its own case's warm-up. The | ||
| 260 | +accuracy evaluation also runs first and pre-warms. Set `compile_timeout` | ||
| 261 | +explicitly on the decorator rather than relying on the default. | ||
| 262 | + | ||
| 263 | +Verify these two facts against the installed harness before relying on them — | ||
| 264 | +they are the harness's configuration, not a property of the DSL. | ||
| 265 | + | ||
| 266 | +## Failure signatures | ||
| 267 | + | ||
| 268 | +- **`name 'A_W0' is not defined`** from `make_tile_group(addrs=[...])`. The | ||
| 269 | + parser resolves `addrs=` from the enclosing scope plus the tilingkey | ||
| 270 | + constants; a kernel-local `A_W0 = 0` is an IR value, not a Python int. Write | ||
| 271 | + the address arithmetic inline from the tilingkey constants, and mirror it in a | ||
| 272 | + module-level function if you want a budget assertion. | ||
| 273 | +- **`assert` inside a kernel body fails to parse** (`F00005`), so the UB budget | ||
| 274 | + check must live at module scope. Assert there over every `(field, ...)` | ||
| 275 | + combination the planner can emit — that is the check that catches a rung whose | ||
| 276 | + `Rows` cap was computed wrong. | ||
| 277 | +- **A tilingkey field used as a tile dimension parses but the tile is illegal.** | ||
| 278 | + Tile-row byte alignment is enforced at bisheng compile time, not at parse | ||
| 279 | + time. A parse-level probe over the ladder is **not** evidence that every rung | ||
| 280 | + compiles. | ||
| 281 | +- **`to_kernel_def()` does not parse the kernel body.** It builds the | ||
| 282 | + `KernelDef` only, so a per-rung "does it parse" probe built on it will report | ||
| 283 | + success with an unsupported statement sitting in the body. Use | ||
| 284 | + `parse_target_program(target=...)` for each `SectionKind`, or compile. | ||
| 285 | +- **Delivery-gate import failure with a `@dataclass` tiling struct.** A file | ||
| 286 | + loaded by `spec_from_file_location` + `exec_module` without being registered | ||
| 287 | + in `sys.modules` dies inside `dataclasses` if the module uses | ||
| 288 | + `from __future__ import annotations`. Use real annotations; the tiling parser | ||
| 289 | + accepts type objects as well as strings. At least one official sample carries | ||
| 290 | + both, so this is inherited by anyone copying it. | ||
| 291 | +- **Wrong results at every width but the first**, if the ladder was implemented | ||
| 292 | + as a kernel factory instead. See the `co_name` cache entry in | ||
| 293 | + [../references/pitfall-records.md](../references/pitfall-records.md). | ||
| 294 | + | ||
| 295 | +## Runnable reference | ||
| 296 | + | ||
| 297 | +**The retained runnable.** `custom/rms_norm/test_rms_norm.py` is one | ||
| 298 | +`@pl.jit` carrying the whole structure described above: the 11-rung `MaxN` | ||
| 299 | +ladder, the coupled `Rows` field, the `Wide` dtype fold, the 3-valued `Mode` | ||
| 300 | +with its three bodies, the three-dtype `datatype=` template, and the host | ||
| 301 | +planner that maps a case to a key without touching a tensor. Read the `RmsKey` | ||
| 302 | +class for the field layout and the `Mode` branches for how a structural variant | ||
| 303 | +folds away. | ||
| 304 | + | ||
| 305 | +**How much of this is precedented.** The installed `tiling_key` tutorial page | ||
| 306 | +does document a tile-size field — `BlockM = TilingKeyField(bits=8, values=[64, | ||
| 307 | +128])` — so a width in a tilingkey is a documented use, not an invention. What | ||
| 308 | +has no sample behind it is the rest: the retained examples use a tilingkey only | ||
| 309 | +as a **single-bit branch switch**, and none of them drives the tile *type* from | ||
| 310 | +a multi-rung ladder, couples it to a second row-count field, or carries a | ||
| 311 | +structural mode in the same key. Those three were probed against the installed | ||
| 312 | +runtime before being designed on. | ||
| 313 | + | ||
| 314 | +The two supporting mechanisms are precedented individually, in the devkit's | ||
| 315 | +`pro_ops/` tree (external to this KB; read them against the installed version, | ||
| 316 | +and do not treat them as validation this KB has performed): | ||
| 317 | + | ||
| 318 | +| mechanism | coordinates | | ||
| 319 | +|---|---| | ||
| 320 | +| tilingkey field, single-bit switch | `pro_ops/fa/test_fa_tilingkey_attn_mask.py:127-130,410` | | ||
| 321 | +| `pl.Ptr` + in-kernel `pl.make_tensor` absorbing rank | `pro_ops/element_wise/test_eltwise_dynamic_rank.py:84-99` | | ||
| 322 | +| `datatype=` template over three dtypes | `pro_ops/fa/test_fa_perf_tkv_preload_dn_vf_bufid_dynrank.py:497-562` | | ||
| 323 | + | ||
| 324 | +## Do not use when | ||
| 325 | + | ||
| 326 | +- The case set has one width, or a handful whose tile can be a single | ||
| 327 | + compile-time constant without waste. The ladder's cost is compile instances | ||
| 328 | + and a second coupled field; do not pay it for nothing. | ||
| 329 | +- The varying dimension is a *runtime* value that the tile does not need to be | ||
| 330 | + sized on. Runtime scalars belong in the tiling struct, and the dynamic valid | ||
| 331 | + window handles the tail. A tilingkey field is for something a tile *type* | ||
| 332 | + depends on. | ||
| 333 | +- The width is genuinely unbounded. The ladder needs a widest rung plus a | ||
| 334 | + structural fallback mode for anything past it, not an open-ended value list. | ||
| 335 | + | ||
| 336 | +## Validation status | ||
| 337 | + | ||
| 338 | +**Validated skeleton for the mechanism; conceptual for the rung policy.** | ||
| 339 | + | ||
| 340 | +Validated: an 11-rung `MaxN` ladder with a coupled `Rows` field, a `Wide` fold | ||
| 341 | +and a 3-valued `Mode`, under one `@pl.jit` with a three-dtype `datatype=` | ||
| 342 | +template, was delivered as `custom/rms_norm/test_rms_norm.py` and passed | ||
| 343 | +12 of 12 correctness cases on hardware on `Ascend950PR` (`soc_version` | ||
| 344 | +`DAV_3510`) across `D` in {2, 67, 128, 373, 768, 769, 1021, 1023, 1024, 2048, | ||
| 345 | +2049, 4096, 4097, 4099, 8192, 16384}, ranks 2–5 and dtypes fp16/fp32/bf16, with | ||
| 346 | +the host performing no tensor operation. | ||
| 347 | + | ||
| 348 | +Not validated: that this rung set is optimal, or that near-fit rungs pay. The | ||
| 349 | +one rung-removal experiment measured no difference on a memory-bound case, and | ||
| 350 | +the row-count argument for near-fit rungs is arithmetic on the UB budget rather | ||
| 351 | +than a measured speedup. | ||
| 352 | + | ||
| 353 | +See "Runnable reference" above for exactly which parts of this have a sample | ||
| 354 | +behind them and which do not. | ||
| 355 | + | ||
| 356 | +## See also | ||
| 357 | + | ||
| 358 | +- [vec-narrow-row-packing.md](vec-narrow-row-packing.md) — the `Mode` variant | ||
| 359 | + that most needs its own geometry. | ||
| 360 | +- [../constraints/tiling.md](../constraints/tiling.md) — tile legality, which a | ||
| 361 | + ladder must satisfy at every rung, not just the one you tested. | ||
| 362 | +- [../constraints/wrapper-boundary.md](../constraints/wrapper-boundary.md) — why | ||
| 363 | + absorbing rank and dtype into the kernel is worth the mechanism. | ||
| 364 | +- [../constraints/tail-validshape.md](../constraints/tail-validshape.md) — the | ||
| 365 | + runtime valid window that handles the width between two rungs. | ||
| 366 | + | ||
| 367 | +--- | ||
| 368 | + | ||
| 369 | +<!-- ADDITIVE INSERTION — Run F, rms_norm Stage 5, A5 card 4, 2026-08-11. | ||
| 370 | + Confirmed by measurement: compiled and ran correctly at six distinct values of the field. --> | ||
| 371 | + | ||
| 372 | +## Tilingkey constants are Python `int`s at trace time — including inside `@pl.vector_function` | ||
| 373 | + | ||
| 374 | +A `TilingKeyField` value reaches the traced body as a real Python `int`, not an IR value, in the | ||
| 375 | +`@pl.jit` kernel body **and** in `@pl.vector_function` bodies. Equality (`if Mode == 3`) and | ||
| 376 | +truthiness (`if Wide`) were already in use; this run additionally confirms **inequality**, **shifts** | ||
| 377 | +and **float arithmetic** on the constant: | ||
| 378 | + | ||
| 379 | +```python | ||
| 380 | +if PackLog >= 1: ps = vf.pair_reduce_sum(ps, preg) # resolved at compile time, unrolls | ||
| 381 | +if PackLog >= 2: ps = vf.pair_reduce_sum(ps, preg) | ||
| 382 | +ms = vf.muls(ps, 1.0 / (1 << PackLog), preg) # arithmetic on the constant, also fine | ||
| 383 | +dmask = vf.full((1 << PackLog) - 1, preg, dtype=pl.DT_INT32) | ||
| 384 | +``` | ||
| 385 | + | ||
| 386 | +This is what lets **one code generator emit a whole family of fully unrolled, branch-free variants | ||
| 387 | +indexed by a tilingkey field**, instead of hand-writing one vector function per width — a ladder of | ||
| 388 | +`if <field> >= n:` lines *is* the unrolled loop, and it keeps the "build the general path, not another | ||
| 389 | +hardcoded width" rule satisfiable without a combinatorial explosion of source. | ||
| 390 | + | ||
| 391 | +🔴 **Prefer the `if` ladder to `for _ in range(<field>)`.** They are equivalent while the constant is | ||
| 392 | +an `int`, but they fail differently if a future SDK makes it an IR value: the `if` degrades to a | ||
| 393 | +runtime branch (slower, still correct), while `range()` raises `TypeError` at trace time. Choose the | ||
| 394 | +form that degrades. | ||
| 395 | + | ||
| 396 | +## Widening a tilingkey field, and adding one, did not perturb codegen for existing instances | ||
| 397 | + | ||
| 398 | +`Mode` was widened `bits=2 → bits=3` and a new `PackLog = TilingKeyField(bits=3, values=[0..5])` added | ||
| 399 | +to a kernel already carrying `MaxN`/`Rows`/`Wide`. All 20 public cases stayed **byte-identical** over | ||
| 400 | +565 632 358 bytes against the pre-change control, so neither the widening nor the new field changed | ||
| 401 | +the compiled behaviour of any pre-existing tilingkey instance. Useful when the alternative is | ||
| 402 | +encoding a new axis into an existing field's value list. | ||
| @@ -0,0 +1,123 @@ | |||
| 1 | +# Compile-time register count on a one-register rung ladder | ||
| 2 | + | ||
| 3 | +## Applies to | ||
| 4 | + | ||
| 5 | +PyPTO-Pro `@pl.vector_function` row kernels whose tile width is selected from a | ||
| 6 | +tilingkey rung ladder by "smallest rung >= D" — reductions along the last axis | ||
| 7 | +(rms_norm, layer_norm, softmax, any `y = f(reduce(row)) * row` shape). | ||
| 8 | + | ||
| 9 | +## Retained implementation | ||
| 10 | + | ||
| 11 | +`custom/rms_norm/test_rms_norm.py` (on branch `stage5-kb-pr`) -- the `rms_norm` stage-5 artifact carries this | ||
| 12 | +pattern as `rms_rows_flat_vf`, selected by `MaxN <= FLAT_MAXN` in the Mode-0 ROW branch, | ||
| 13 | +over a rung ladder extended to 64/128/192/256/320/384/448/512 so that every narrow rung is | ||
| 14 | +one register wider than its predecessor. The import-time invariant in "The trap" below ships | ||
| 15 | +with it. | ||
| 16 | + | ||
| 17 | +## The pattern | ||
| 18 | + | ||
| 19 | +A ladder that assigns `MaxN = min{r in rungs : r >= D}` gives each rung the | ||
| 20 | +half-open band `(prev_rung, MaxN]`. If **`MaxN - prev_rung == LANES`**, then | ||
| 21 | + | ||
| 22 | + ceil(D / LANES) == MaxN // LANES for every D the rung serves | ||
| 23 | + | ||
| 24 | +so the number of vector registers a row occupies is a **compile-time constant**, | ||
| 25 | +available inside the vector function as an ordinary Python `int`. | ||
| 26 | + | ||
| 27 | +That unlocks three removals that a runtime `pl.range` over registers cannot have: | ||
| 28 | + | ||
| 29 | +1. **Hoist the loop-invariant operand load out of the ROW loop.** A per-column | ||
| 30 | + operand (gamma, scale, bias) does not depend on the row, but inside a runtime | ||
| 31 | + register loop its `vf.load_align` offset is a loop variable, so it is re-issued | ||
| 32 | + once per register per row. Unrolled, the offsets are constants and the loads | ||
| 33 | + hoist. −1 op per register per row. | ||
| 34 | +2. **Reuse the pass-1 register in pass 2 instead of re-loading it.** A two-pass row | ||
| 35 | + kernel (accumulate, then apply) loads each x register twice. Unrolled, the | ||
| 36 | + pass-1 value is still live. −1 op per register per row. *Obligation:* pass 2's | ||
| 37 | + store to `base + j*LANES` must not alias another live register's load offset — | ||
| 38 | + true when each register is stored at the offset it was loaded from. | ||
| 39 | +3. **Drop the accumulator seed and its identity add.** `acc = vf.full(0.0)` then | ||
| 40 | + `acc = vf.add(acc, p_j)` per register becomes `acc = p_0` then `acc = vf.add(acc, | ||
| 41 | + p_j)` for `j >= 1`. −2 ops per row, and at `NR == 1` both were pure identity. | ||
| 42 | + | ||
| 43 | +Cost model for a two-pass row reduction with a `c`-op per-row scalar chain: | ||
| 44 | + | ||
| 45 | + runtime loop: (2 + c_pass1 + 2 + c_pass2) * k + c + 2 -> 9k + 5 (rms_norm) | ||
| 46 | + unrolled: 7k + 4 | ||
| 47 | + | ||
| 48 | +## Measured | ||
| 49 | + | ||
| 50 | +`rms_norm` on Ascend A5 / DAV_3510, card 4, `cold_probe.py` (fresh process per | ||
| 51 | +point, 192 MB L2 flush inside the measured window, flush kernel filtered by name), | ||
| 52 | +S = 65536, fp16, 3 warm-up + 5 measured: | ||
| 53 | + | ||
| 54 | +| registers `k` | rung | before µs | after µs | speedup | | ||
| 55 | +|---:|---:|---:|---:|---:| | ||
| 56 | +| 1 | 64 | 22.792 | 19.422 | **1.174×** | | ||
| 57 | +| 2 | 128 | 29.507 | 25.789 | **1.144×** | | ||
| 58 | +| 3 | 192 | 36.503 | 33.136 | **1.102×** | | ||
| 59 | +| 4 | 256 | 44.587 | 38.693 | **1.152×** | | ||
| 60 | +| 5 | 320 | 49.978 | 47.513 | 1.052× | | ||
| 61 | +| 6 | 384 | 58.686 | 57.508 | 1.020× | | ||
| 62 | +| 7 | 448 | 67.827 | 65.675 | 1.033× | | ||
| 63 | +| 8 | 512 | 75.396 | 72.428 | 1.041× | | ||
| 64 | + | ||
| 65 | +The pay-off tracks **bandwidth headroom, not op count**: the op removal is a flat | ||
| 66 | +−21…−22 % at every `k`, but converts at 10–17 % where achieved bandwidth is | ||
| 67 | +736–1505 GB/s (`k <= 4`) and only 2–4 % where it is 1715–1784 GB/s (`k >= 6`). | ||
| 68 | +**Profile the roofline before spending a rung on this.** | ||
| 69 | + | ||
| 70 | +### 🔴 It is dtype-dependent, and the table above is the fp16 case | ||
| 71 | + | ||
| 72 | +The same G2 artifact, same instrument, S = 65536, cold: | ||
| 73 | + | ||
| 74 | +| dtype | D = 64 | D = 128 | D = 256 | D = 512 | | ||
| 75 | +|---|---:|---:|---:|---:| | ||
| 76 | +| fp16 (narrow, casts) | 1.174× | 1.144× | 1.152× | 1.041× | | ||
| 77 | +| bf16 (narrow, casts) | — | 1.139× | 1.133× | — | | ||
| 78 | +| **fp32 (wide, no casts)** | **1.084×** | **1.018×** | **1.018×** | **1.003×** | | ||
| 79 | + | ||
| 80 | +At D = 128 the fp16 and fp32 kernels take *the same* wall time (29.51 vs 29.53 µs) | ||
| 81 | +while fp32 moves **twice the bytes** — fp32 is at ~2300 GB/s, its ceiling, and the | ||
| 82 | +narrow path is at ~1300 GB/s with the difference going into its two full-tile | ||
| 83 | +`pl.cast`es and its four UB tiles. **That slack is what the op removal converts.** | ||
| 84 | +So this is a **narrow-dtype (Wide == 0) lever**: expect 13–15 % on fp16/bf16 rows | ||
| 85 | +at D <= 256 and ~1 % on fp32 above D = 64. Measuring it on one dtype and | ||
| 86 | +generalising overstates its reach — that mistake was made and caught in run G. | ||
| 87 | + | ||
| 88 | +## Correctness | ||
| 89 | + | ||
| 90 | +The three removals **reorder nothing**, so the transform is bit-exact, not merely | ||
| 91 | +within tolerance. Verified by reinterpreting both outputs as integers and counting | ||
| 92 | +differing words: **0 differing words on 27 shapes** spanning every touched rung at | ||
| 93 | +its exact fit and at an interior width, fp16 / fp32 / bf16, a 50 %-NaN input and a | ||
| 94 | +±inf input. The accumulator-seed elision is exact because a sum of squares is never | ||
| 95 | +`-0.0`, so `+0.0 + p == p` bit for bit. | ||
| 96 | + | ||
| 97 | +## The trap | ||
| 98 | + | ||
| 99 | +**Adding a rung to make the ladder one-register-spaced is a correctness change, not | ||
| 100 | +a tuning change.** A flat rung whose predecessor is further than `LANES` away makes | ||
| 101 | +`MaxN // LANES` *larger* than `ceil(D/64)` for the narrow end of its band: the | ||
| 102 | +kernel reads a register past the row and reduces garbage. That is a **silent wrong | ||
| 103 | +answer**, not a 507035 fault, and it survives every device-free gate. Assert it at | ||
| 104 | +import next to the UB-budget assertion: | ||
| 105 | + | ||
| 106 | +```python | ||
| 107 | +for i, r in enumerate(_MAXN_RUNGS): | ||
| 108 | + if r <= FLAT_MAXN: | ||
| 109 | + prev = _MAXN_RUNGS[i - 1] if i else 0 | ||
| 110 | + assert r - prev == LANES and r % LANES == 0 | ||
| 111 | +``` | ||
| 112 | + | ||
| 113 | +Also check the tilingkey field width first: `TilingKeyField(bits=n)` holds `2**n` | ||
| 114 | +rungs, and a one-register ladder up to 512 needs 8 of them. | ||
| 115 | + | ||
| 116 | +## Non-lever, measured | ||
| 117 | + | ||
| 118 | +**Row-level software pipelining inside the vector function is worth nothing here.** | ||
| 119 | +Two independent rows in flight — separate accumulators, separate `sqrt`/`div` | ||
| 120 | +chains, interleaved by construction — measured within ±0.4 % of one row in flight | ||
| 121 | +at every rung from 64 to 256, on both a `FLAT_MAXN = 128` and a `FLAT_MAXN = 256` | ||
| 122 | +build. The backend already overlaps consecutive `pl.range` iterations. Do not | ||
| 123 | +spend a variant on it. | ||
| @@ -0,0 +1,94 @@ | |||
| 1 | +# Compute-exposed narrow-dtype elementwise-with-reduction | ||
| 2 | + | ||
| 3 | +## Rule | ||
| 4 | + | ||
| 5 | +For a vector op that widens a narrow io dtype (fp16/bf16) to fp32, computes, and narrows | ||
| 6 | +back, the fp16/bf16 path does **the same vector work as the fp32 path over the same number of | ||
| 7 | +fp32 lanes while moving half the GM bytes**. Do not model it as bandwidth-bound because its | ||
| 8 | +byte count is smaller. Decide by measuring how much of the tile is DMA, because at small `D` | ||
| 9 | +the narrow path is **compute-exposed**: it has too little DMA left to hide its vector work | ||
| 10 | +behind, while the fp32 path hides the identical work under a DMA that is twice as long. | ||
| 11 | + | ||
| 12 | +Two corollaries that invert the obvious optimisation: | ||
| 13 | + | ||
| 14 | +1. **Relieving the narrow path's UB budget can make it slower.** Holding fp32 and io-dtype | ||
| 15 | + tiles simultaneously costs more UB per element than fp32 alone (12 B/elem vs 8 B/elem for | ||
| 16 | + a 2-deep pair of each), which looks like a reason `Rows` must shrink. Measured, the | ||
| 17 | + time-vs-`Rows` curve is **U-shaped**, and the top of the rung is already past the minimum — | ||
| 18 | + so the extra rows a bigger budget would buy are on the wrong side of the optimum. | ||
| 19 | +2. **Moving a cast out of a tile-level `pl.cast` and into the vector function makes it | ||
| 20 | + slower**, even though it removes a pass over UB. The tile-level cast is a wide, | ||
| 21 | + well-pipelined `vcvt` loop that overlaps; the vector-function form lands in the critical | ||
| 22 | + path. For a compute-exposed kernel that is the wrong direction. | ||
| 23 | + | ||
| 24 | +## Checks | ||
| 25 | + | ||
| 26 | +1. Measure the pure `load → store` floor for the narrow dtype and for fp32 at identical | ||
| 27 | + geometry. If the narrow floor is **not** half the fp32 floor, DMA at that size is not | ||
| 28 | + byte-limited and the narrow path has already lost part of its nominal advantage. | ||
| 29 | +2. Decompose the tile into `DMA` / `+casts` / `+vector function` with three separately named | ||
| 30 | + kernels over identical GM traffic. Give each a distinct name **and** a distinct body, and | ||
| 31 | + assert their outputs differ — two `@pl.jit` kernels sharing a decorated name and identical | ||
| 32 | + body text can silently resolve to one binary. | ||
| 33 | +3. Read off `dma %`. Above ~85 % the kernel is DMA-bound and op-count work will not convert. | ||
| 34 | + Below ~70 % it is compute-exposed and op count is the live lever. | ||
| 35 | +4. Sweep `Rows` at fixed rung as a **paired, one-variable** comparison before assuming a UB or | ||
| 36 | + burst-length story. Sweep, never infer a threshold rule. | ||
| 37 | + | ||
| 38 | +## Measured instance (rms_norm, Ascend950/A5, 2026-08-12) | ||
| 39 | + | ||
| 40 | +Cold, card 4, paired same-shape ratios, `cold_probe.py`-derived instrument: | ||
| 41 | + | ||
| 42 | +| D | narrow dma | wide dma | ratio | casts | exposed math | narrow dma % | wide dma % | | ||
| 43 | +|---|---|---|---|---|---|---|---| | ||
| 44 | +| 64 | 5.768 | 8.437 | **0.68** | 2.247 (20.2 %) | 3.099 | 51.9 % | 87.4 % | | ||
| 45 | +| 128 | 8.411 | 14.246 | **0.59** | 1.536 (10.4 %) | 4.855 | 56.8 % | 87.4 % | | ||
| 46 | +| 256 | 14.416 | 28.478 | 0.51 | 1.252 (5.8 %) | 5.892 | 66.9 % | 93.5 % | | ||
| 47 | +| 512 | 14.397 | 28.084 | 0.51 | 1.075 (5.1 %) | 5.410 | 68.9 % | 91.8 % | | ||
| 48 | + | ||
| 49 | +fp16 achieved 759 → 1840 GB/s as `D` goes 64 → 512 and never reaches the fp32 wall | ||
| 50 | +(2094–2264 GB/s from `D = 192` up). A path pinned at a bandwidth ceiling does not get faster | ||
| 51 | +per byte as the row lengthens; a path paying a fixed per-row cost does. | ||
| 52 | + | ||
| 53 | +## What closes the obvious fix — and what does NOT | ||
| 54 | + | ||
| 55 | +🔴 **Correction, 2026-08-13.** An earlier version of this page stated that a widening `astype` | ||
| 56 | +"reaches only even lanes (`CastLayout.ONE` returns all zeros)" and concluded there was **no** | ||
| 57 | +in-vector-function mechanism to consume a narrow tile as fp32. **That conclusion was wrong, and the | ||
| 58 | +cause was our own probe.** | ||
| 59 | + | ||
| 60 | +`vf.astype` takes a mask of the **source** width. Our probe passed a destination-width (fp32/b32) | ||
| 61 | +mask to a b16→fp32 widening cast, and under `layout=ONE` such a mask selects nothing and returns | ||
| 62 | +zeros — silently. `CastLayout.ZERO` and `ONE` select the **even and odd lanes**; a full narrow | ||
| 63 | +register is recovered by running both and interleaving. See | ||
| 64 | +[references/pypto-pro-dsl-limitations-a5.md](../references/pypto-pro-dsl-limitations-a5.md) §21.1 | ||
| 65 | +for the b16/b32 × ZERO/ONE probe matrix, the official call sites, and the rule statement. | ||
| 66 | + | ||
| 67 | +**Method lesson.** We swept the `layout` enum but held mask width fixed, so we sampled only the | ||
| 68 | +failing column of a 2x2 and read a broken cell as a property of the enum. When an operation has two | ||
| 69 | +type-carrying operands and one enum, sweep the **cross product**, or check a negative result against | ||
| 70 | +a positive control. | ||
| 71 | + | ||
| 72 | +**What still holds, and still closes the fix in practice:** | ||
| 73 | + | ||
| 74 | +- there is **no register bitcast**, so the bits of a 16-bit-typed register cannot be reinterpreted; | ||
| 75 | +- `vf.rsqrt` does not exist; | ||
| 76 | +- `vf.pair_reduce_sum` rejects bf16; | ||
| 77 | +- `vf` operations cannot nest; | ||
| 78 | +- and, decisively for this pattern, the narrowing side **does** have a mechanism | ||
| 79 | + (`de_interleave`/`astype`/`or_`) and it measured **2.8 % slower** — see corollary 2 above. | ||
| 80 | + | ||
| 81 | +So the *route* is open and the *payoff* is not demonstrated: a correct in-VF widening costs two | ||
| 82 | +casts plus an interleave, and the one directly comparable measurement we have points the wrong way. | ||
| 83 | +Treat "fold the cast into the vector function" as **measured-negative**, not as impossible. | ||
| 84 | + | ||
| 85 | +## Evidence | ||
| 86 | + | ||
| 87 | +- instrument: `cold_probe.py` (calibrated to the grader's `T_base` to a median +6 %) and its | ||
| 88 | + derivatives `mech_probe.py` / `ablate_probe.py`; every figure above is a paired same-shape | ||
| 89 | + ratio on one card, never an absolute GB/s ported to grader scale. | ||
| 90 | +- see also [tiling-key-width-ladder.md](tiling-key-width-ladder.md), | ||
| 91 | + [buffer-reuse-lifetime.md](buffer-reuse-lifetime.md), | ||
| 92 | + [vec-compile-time-register-count.md](vec-compile-time-register-count.md) | ||
| 93 | + | ||
| 94 | +--- | ||
| @@ -0,0 +1,572 @@ | |||
| 1 | +# Narrow-row packing for a sub-knee last dimension | ||
| 2 | + | ||
| 3 | +**Topology:** `row-reduction` — the narrow-`D` packing of the dataflow in | ||
| 4 | +[vec-row-reduce-broadcast.md](vec-row-reduce-broadcast.md). | ||
| 5 | +**Status:** validated skeleton on Ascend950PR (`soc_version` `DAV_3510`, | ||
| 6 | +`vector_core_num` 56). The re-view, the gamma replication and the tail all live | ||
| 7 | +inside one `@pl.jit` kernel as a compile-time mode; that kernel passed 12 of 12 | ||
| 8 | +correctness cases on hardware, including the non-finite case, and measures | ||
| 9 | +7.17 us on `[1000003, 2]` bfloat16 against a 438.71 us control anchor. | ||
| 10 | +**Evidence:** `custom/rms_norm/test_rms_norm.py` (on branch `stage5-kb-pr`) — the `Mode == 1` PACK | ||
| 11 | +path at the shipped `(MaxN, Rows) = (512, 8)` geometry, with the measurement | ||
| 12 | +conditions in `custom/rms_norm/{RUN_REPORT.md,TUNING_STATE.md}`. | ||
| 13 | + | ||
| 14 | +## Applies when | ||
| 15 | + | ||
| 16 | +A row reduction whose last dimension `D` is small enough that one row's bytes, | ||
| 17 | +`D * itemsize`, sit far below the 128-byte strided-load knee, while the row | ||
| 18 | +count `M` is large. The measured case is `[1000003, 2]` bfloat16 — a 4-byte | ||
| 19 | +row, one thirty-second of the knee. | ||
| 20 | + | ||
| 21 | +The topology is unchanged: this is still the row-reduce-broadcast dataflow in | ||
| 22 | +[vec-row-reduce-broadcast.md](vec-row-reduce-broadcast.md). Only the packing | ||
| 23 | +changes, and it changes because the register, not the reduction, is what the | ||
| 24 | +shape is wasting. | ||
| 25 | + | ||
| 26 | +## What the row-per-register tiling costs | ||
| 27 | + | ||
| 28 | +A `[TILE_ROWS, MAX_N]` tile whose `MAX_N` is the register width holds `D` useful | ||
| 29 | +elements in each row. At `D = 2` on a 64-lane fp32 register that is 2 of 64 | ||
| 30 | +lanes — 3.1 percent lane occupancy, so a `[128, 64]` tile carries 256 useful | ||
| 31 | +elements of 8192 — and it issues one reduction per row, so `[1000003, 2]` costs | ||
| 32 | +about 1e6 reductions. Neither number improves with more tile rows: the waste is | ||
| 33 | +per register, not per tile. | ||
| 34 | + | ||
| 35 | +The DMA side costs at least as much as the register side. One source row is a | ||
| 36 | +4-byte burst; a packed tile is one long contiguous burst covering thousands of | ||
| 37 | +rows. Both effects point the same way, and the sweep below separates them. | ||
| 38 | + | ||
| 39 | +## The flat wide-row view is the only expressible form | ||
| 40 | + | ||
| 41 | +This is the constraint that turns the packing from a trick into the only legal | ||
| 42 | +option, so it comes before the dataflow rather than after it. | ||
| 43 | + | ||
| 44 | +**A Vec tile's row must be a multiple of 32 bytes.** The obvious "compact" | ||
| 45 | +alternative — declare the tile at the natural row pitch, `[M/K, D]` — is | ||
| 46 | +therefore *not expressible at all* for a narrow `D`: a `[2048, 2]` bfloat16 tile | ||
| 47 | +is 4 bytes per row and the tile type is rejected. There is no version of this | ||
| 48 | +pattern in which one tile row holds one source row. | ||
| 49 | + | ||
| 50 | +What is left is to give the tile a wide row and let it hold many source rows. | ||
| 51 | +That is the entire idea: re-view the contiguous `[M, D]` buffer at a row pitch | ||
| 52 | +of `MaxN` elements, where `MaxN` is chosen for burst size rather than for the | ||
| 53 | +operator's semantics, and let `MaxN / D` complete source rows share each tile | ||
| 54 | +row. | ||
| 55 | + | ||
| 56 | +Two mechanical notes travel with it: | ||
| 57 | + | ||
| 58 | +- the rejection is enforced at bisheng compile time, not at parse time, and the | ||
| 59 | + diagnostic names **Rows** while it is in fact testing **Cols** — see | ||
| 60 | + [../references/pitfall-records.md](../references/pitfall-records.md); | ||
| 61 | +- `MaxN` must additionally be a multiple of 64, the fp32 vector alignment | ||
| 62 | + granule, so that `base = m * MaxN` keeps every row register-aligned. | ||
| 63 | + | ||
| 64 | +## Dataflow | ||
| 65 | + | ||
| 66 | +1. **In the kernel**, re-view the contiguous `[M, D]` buffer as `[NE/MaxN, MaxN]` | ||
| 67 | + with `pl.make_tensor(x, [NP, MaxN], [MaxN, 1], dtype=io_dtype)`, where | ||
| 68 | + `NE = M * D`. This is a pure reinterpretation: zero copy, zero allocation and | ||
| 69 | + zero host-side work. | ||
| 70 | +2. **In the kernel**, replicate gamma to the register width from the `D` scalars | ||
| 71 | + in GM. This is `O(register)` work, not `O(M)`. | ||
| 72 | +3. Load a flat chunk one register wide. It now covers `64 // D` whole rows with | ||
| 73 | + no padding. | ||
| 74 | +4. Square in place. | ||
| 75 | +5. Reduce adjacent lanes with `vf.pair_reduce_sum` — hardware `vcpadd`, | ||
| 76 | + `dst[i] = src[2i] + src[2i+1]`. At `D = 2` one instruction produces | ||
| 77 | + `64 // D = 32` row sums and replaces 32 separate `vf.reduce_sum` calls. | ||
| 78 | +6. Scale by `1/D`, add epsilon, `sqrt` — all on the packed sums, so this | ||
| 79 | + arithmetic is also `64 // D` rows at a time. | ||
| 80 | +7. `vf.interleave(rms, rms)` duplicates each row's scalar back across its `D` | ||
| 81 | + lanes, which is the broadcast half of the pattern done without a mask. | ||
| 82 | +8. Divide, multiply by the repeated gamma, store flat. | ||
| 83 | + | ||
| 84 | +The tail is a partial register of *elements*, not of rows, so it is masked on | ||
| 85 | +element count. The measured shape has an odd `M` (1000003) specifically so the | ||
| 86 | +tail is exercised. | ||
| 87 | + | ||
| 88 | +> **Steps 1 and 2 are in the kernel, and that is not a placement preference.** | ||
| 89 | +> [../constraints/wrapper-boundary.md](../constraints/wrapper-boundary.md) is in | ||
| 90 | +> force for every class, so a host-side `reshape`/`repeat`/`cat` of gamma is | ||
| 91 | +> measured device work whatever its asymptotic size. The validated implementation | ||
| 92 | +> builds the re-view and replicates gamma inside the kernel, and its wrapper | ||
| 93 | +> performs no tensor operation at all. | ||
| 94 | + | ||
| 95 | +## Tile placement | ||
| 96 | + | ||
| 97 | +The knobs are the re-view pitch `MaxN` and the tile row count `Rows`. Together | ||
| 98 | +they set the burst: one `[Rows, MaxN]` tile is one contiguous DMA of | ||
| 99 | +`Rows * MaxN * itemsize` bytes covering `Rows * MaxN / D` complete source rows. | ||
| 100 | + | ||
| @@ -23,6 +23,27 @@ attachment on the drain out of the accumulator, and neither form is per-token: | |||
| 23 | Per-token therefore has to be composed by hand. Treat that as the expected | 23 | Per-token therefore has to be composed by hand. Treat that as the expected |
| 24 | shape of the work, not as a sign of a wrong approach. | 24 | shape of the work, not as a sign of a wrong approach. |
| 25 | 25 | ||
| 26 | +### Correction (2026-08-13): `pl.quant` / `pl.dequant` *are* demonstrated | ||
| 27 | + | ||
| 28 | +The paragraph above says their scale-tile conventions are undemonstrated. There | ||
| 29 | +is a call site, in the docs test tree rather than the example tests: | ||
| 30 | +`python/tests/ut/block/frontend/a5/docs/test_doc_quant_cast_scatter.py:39-58` | ||
| 31 | +(`pl.quant`, SYM), `:79-103` (`pl.dequant`), `:124-138` (`pl.cast` FP16→FP32). | ||
| 32 | + | ||
| 33 | +The conventions it fixes: | ||
| 34 | + | ||
| 35 | +- `pl.quant(out, src, scale, mode=pl.QuantMode.SYM)` — symmetric FP32 → INT8, | ||
| 36 | + computing `clamp(round(x · scale))`. | ||
| 37 | +- `pl.dequant(out, src, scale, offset)` — recovers `(src − offset) · scale`. | ||
| 38 | +- `scale` / `offset` are **per-row `[rows, 1]` FP32 tiles**, which is the | ||
| 39 | + convention the section above reports as unknown. | ||
| 40 | +- Both run inside `with pl.section_vector():` on `MemorySpace.Vec` tiles. | ||
| 41 | + | ||
| 42 | +That makes the per-row granularity reachable directly, so the hand composition | ||
| 43 | +below is the right shape for *per-token* but is not the only quantization route. | ||
| 44 | +The block-scaled `mx` carrier remains genuinely absent: `pl.quant_mx`, | ||
| 45 | +`pl.scaled_mm` and `DT_FP8E8M0` have no call site on this surface. | ||
| 46 | + | ||
| 26 | ## Dataflow | 47 | ## Dataflow |
| 27 | 48 | ||
| 28 | Per row block, with the row's values in a resident wide-precision buffer `V`: | 49 | Per row block, with the row's values in a resident wide-precision buffer `V`: |
| @@ -76,6 +76,12 @@ dimension is small enough — `[2048, 2]` bf16 is 4 bytes of Cols — cannot be | |||
| 76 | declared at all, which removes "re-view a packed buffer at a D-element row pitch" | 76 | declared at all, which removes "re-view a packed buffer at a D-element row pitch" |
| 77 | from the toolbox for a very short axis. | 77 | from the toolbox for a very short axis. |
| 78 | 78 | ||
| 79 | +It removes the *compact* re-view, at a `D`-element pitch. It does **not** remove | ||
| 80 | +the *wide*-pitch re-view, which satisfies this same rule — see "When the reduced | ||
| 81 | +axis is very short" below. The rule is scoped to the declared pitch, not to where | ||
| 82 | +the re-view is written: a host-side compact `D`-pitch view fails it exactly as a | ||
| 83 | +kernel-side one does, and a wide-pitch view passes either way. | ||
| 84 | + | ||
| 79 | ## Where the time goes | 85 | ## Where the time goes |
| 80 | 86 | ||
| 81 | Measured on `Ascend950PR_9579` for `rms_norm`, which is this pattern with the | 87 | Measured on `Ascend950PR_9579` for `rms_norm`, which is this pattern with the |
| @@ -99,11 +105,55 @@ Measured on `Ascend950PR_9579` for `rms_norm`, which is this pattern with the | |||
| 99 | Below about 32 bytes per row this pattern degrades badly and the fix is not | 105 | Below about 32 bytes per row this pattern degrades badly and the fix is not |
| 100 | inside it. A `[TR, W]` tile with `valid_shape [TR, D]` issues TR DMA bursts of | 106 | inside it. A `[TR, W]` tile with `valid_shape [TR, D]` issues TR DMA bursts of |
| 101 | `D * itemsize` bytes, and the strided-load knee is 128 bytes per row; at D=2 bf16 | 107 | `D * itemsize` bytes, and the strided-load knee is 128 bytes per row; at D=2 bf16 |
| 102 | -a *pure copy* measured 117 GB/s, and the reduce-and-broadcast chain on top runs | 108 | +that is 4 bytes, one thirty-second of the knee. A *pure copy* there measured |
| 103 | -every vector op over 2-element rows. Packing several rows per tile row makes the | 109 | +117 GB/s, and the reduce-and-broadcast chain on top runs every vector op over |
| 104 | -load contiguous but destroys the per-row reduction, and the compact re-view that | 110 | +2-element rows. On `rms_norm` this case measured **412.50 us against a 36.25 us |
| 105 | -would restore it is blocked by the Cols alignment rule above. Record the cost | 111 | +budget — 1.5 score points** (`custom/rms_norm/DESIGN.md` §8, Ascend950PR_9579). |
| 106 | -rather than assuming a tiling escape exists. | 112 | + |
| 113 | +Packing several rows per tile row makes the load contiguous but destroys the | ||
| 114 | +per-row reduction, and the *compact* re-view that would restore it — a tile whose | ||
| 115 | +row is one source row, at a `D`-element pitch — is blocked by the Cols alignment | ||
| 116 | +rule above. **Inside the tile-operation surface that is the end of the road, and | ||
| 117 | +the alignment rule is not negotiable.** | ||
| 118 | + | ||
| 119 | +The escape is outside that surface. A segmented vector reduction recovers per-row | ||
| 120 | +sums from inside a packed register and takes no tile shape at all, so the Cols | ||
| 121 | +rule never binds it. `vf.pair_reduce_sum` is the hardware `vcpadd` | ||
| 122 | +(`dst[i] = src[2i] + src[2i+1]`): a stride-2 reduction over adjacent lanes. | ||
| 123 | +Re-viewing `[1000003, 2]` at a *wide* pitch — `MaxN = 512`, giving `[3907, 512]` — | ||
| 124 | +every tile that is then declared satisfies the same rule: | ||
| 125 | + | ||
| 126 | +| declared tile | dtype | bytes per row | `% 32` | | ||
| 127 | +|---|---|---|---| | ||
| 128 | +| `[8, 512]` | bf16 | 1024 | 0 | | ||
| 129 | +| `[8, 512]` | fp32 | 2048 | 0 | | ||
| 130 | +| `[1, 8]` | fp32 | 32 | 0 | | ||
| 131 | +| `[2048, 2]` | bf16 | 4 | **never declared** | | ||
| 132 | + | ||
| 133 | +No `[TR, 1]` reduction tile exists on this path. Two conditions the Cols rule does | ||
| 134 | +not state also bind: **`MaxN % 64 == 0`** — the fp32 register granule for | ||
| 135 | +`load_align`/`store_align`, strictly stronger than the multiple of 8 that | ||
| 136 | +`Cols * 4 % 32` permits, and violating it faults **507035** — and `MaxN % D == 0`. | ||
| 137 | + | ||
| 138 | +Measured, with conditions, on separate hosts and not to be divided into each | ||
| 139 | +other: | ||
| 140 | + | ||
| 141 | +| figure | value | conditions | | ||
| 142 | +|---|---|---| | ||
| 143 | +| tile-op form, scored run | 412.50 us | Ascend950PR_9579, `custom/rms_norm/DESIGN.md` §8 | | ||
| 144 | +| control anchor, this campaign | 438.71 us | Ascend950PR, scored-report anchor | | ||
| 145 | +| packing, first correct build | 7.72 us | Ascend950PR, profiler device time | | ||
| 146 | +| packing, after instruction tuning | 7.17 us | same | | ||
| 147 | +| paired fp32 A/B | 96.22 -> 12.27 us (7.84x) | one host, interleaved. Probe-1's baseline disagrees with the benchmark's for the same shape by 2.43x, unexplained — **no score may be derived from this ratio** | | ||
| 148 | + | ||
| 149 | +The precondition is `64 % D == 0` **and** a segmented primitive matching `D`. | ||
| 150 | +`vf.pair_reduce_sum` pairs adjacent lanes and nothing else, so **`D = 2` is the | ||
| 151 | +only measured instance**; where the precondition fails — `D = 4, 8, …`, with no | ||
| 152 | +matching primitive — record the cost rather than assuming a tiling escape exists. | ||
| 153 | + | ||
| 154 | +**At `D = 2`, the precondition holds and the escape is built: go to | ||
| 155 | +[vec-narrow-row-packing.md](vec-narrow-row-packing.md), which carries the | ||
| 156 | +skeleton.** | ||
| 107 | 157 | ||
| 108 | **Measured escapes now exist for the vf form** (rms_norm, Ascend950PR_9579, | 158 | **Measured escapes now exist for the vf form** (rms_norm, Ascend950PR_9579, |
| 109 | 2026-08-06, 20/20 public + 19/19 hidden-guess): keep the reduction in | 159 | 2026-08-06, 20/20 public + 19/19 hidden-guess): keep the reduction in |
| @@ -140,3 +190,11 @@ close one. The "very short axis" section's degradation is measured; its | |||
| 140 | register-shuffle escapes above are also measured (on branch `bench/rms_norm-a5`, | 190 | register-shuffle escapes above are also measured (on branch `bench/rms_norm-a5`, |
| 141 | `custom/rms_norm/{DESIGN.md,test_rms_norm.py}`, verifier-rerun 2026-08-06) — | 191 | `custom/rms_norm/{DESIGN.md,test_rms_norm.py}`, verifier-rerun 2026-08-06) — |
| 142 | port the family structure, not the numbers. | 192 | port the family structure, not the numbers. |
| 193 | + | ||
| 194 | +That section is additionally **solved at `D = 2`** by | ||
| 195 | +[vec-narrow-row-packing.md](vec-narrow-row-packing.md) — 12 of 12 correctness | ||
| 196 | +cases on hardware including the non-finite case, 7.17 us on `[1000003, 2]` | ||
| 197 | +bfloat16 — and remains a measured limitation at every other narrow `D`, where no | ||
| 198 | +segmented primitive matches the row width. That timing and the 9.7 us recorded | ||
| 199 | +above were taken on different hosts with different instruments, so they rank | ||
| 200 | +nothing against each other; both are reported as measured. | ||