Draft
[WIP] feat(cannbot): reconcile the Stage-5 skill payload onto the contract-fixes branch #1
hid22900163Add on Jul 29
[WIP] feat(cannbot): reconcile the Stage-5 skill payload onto the contract-fixes branch #1
Draft
Total: 33 files changed+2603-29
| @@ -17,6 +17,13 @@ platform-specific behavior. | |||
| 17 | | Classify a decomposition | `pypto-pro-op-design` | [references/decomposition-primitives.md](references/decomposition-primitives.md) | | 17 | | Classify a decomposition | `pypto-pro-op-design` | [references/decomposition-primitives.md](references/decomposition-primitives.md) | |
| 18 | | Benchmark a correct kernel | `pypto-pro-op-perf-tune` | [playbooks/benchmark-scoring.md](playbooks/benchmark-scoring.md) | | 18 | | Benchmark a correct kernel | `pypto-pro-op-perf-tune` | [playbooks/benchmark-scoring.md](playbooks/benchmark-scoring.md) | |
| 19 | | Decide what may run on the host | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/wrapper-boundary.md](constraints/wrapper-boundary.md) | | 19 | | Decide what may run on the host | `pypto-pro-op-design` / `pypto-pro-op-develop` | [constraints/wrapper-boundary.md](constraints/wrapper-boundary.md) | |
| 20 | +| Recognise a failure someone has already hit | `pypto-pro-op-develop` / `pypto-pro-op-perf-tune` | [pitfall-records.md](pitfall-records.md) | | ||
| 21 | + | ||
| 22 | +[pitfall-records.md](pitfall-records.md) is a symptom index, not a rule page: it | ||
| 23 | +maps an observed error code, hang or wrong result to the cause that was actually | ||
| 24 | +found. Read it when something fails, not when designing. Each entry records the | ||
| 25 | +runtime it was observed on; confirm the behaviour still reproduces on the | ||
| 26 | +detected target before treating an entry as current. | ||
| 20 | 27 | ||
| 21 | Do not load [constraints/arch-a5.md](constraints/arch-a5.md) until the runtime | 28 | Do not load [constraints/arch-a5.md](constraints/arch-a5.md) until the runtime |
| 22 | or build configuration confirms an A5 target. | 29 | or build configuration confirms an A5 target. |
| @@ -51,6 +58,32 @@ Properties that modulate the choice within a topology: unaligned shapes, tail | |||
| 51 | blocks, long axes, BF16 or mixed-precision accumulation, INT32/INT64 index | 58 | blocks, long axes, BF16 or mixed-precision accumulation, INT32/INT64 index |
| 52 | semantics, and dynamic dimension arguments. | 59 | semantics, and dynamic dimension arguments. |
| 53 | 60 | ||
| 61 | +### Retained pattern pages | ||
| 62 | + | ||
| 63 | +Every page under `patterns/`, with the topology node | ||
| 64 | +[topology-map.json](topology-map.json) routes it from. Read | ||
| 65 | +[patterns/pattern-index.md](patterns/pattern-index.md) first — it carries the | ||
| 66 | +validation status that decides whether a page may be copied or only reasoned | ||
| 67 | +from. | ||
| 68 | + | ||
| 69 | +| Page | Routed from | | ||
| 70 | +|---|---| | ||
| 71 | +| [patterns/vec-row-reduce-broadcast.md](patterns/vec-row-reduce-broadcast.md) | `row-reduction` | | ||
| 72 | +| [patterns/vec-group-reduce-broadcast.md](patterns/vec-group-reduce-broadcast.md) | `row-reduction` | | ||
| 73 | +| [patterns/cube-only.md](patterns/cube-only.md) | `cube-matmul` | | ||
| 74 | +| [patterns/batched-2d-contraction.md](patterns/batched-2d-contraction.md) | `cube-matmul` | | ||
| 75 | +| [patterns/quant-matmul-scaled-mm.md](patterns/quant-matmul-scaled-mm.md) | `quantized-matmul` | | ||
| 76 | +| [patterns/fp4-mxfp-cast-pack.md](patterns/fp4-mxfp-cast-pack.md) | `quantized-matmul` | | ||
| 77 | +| [patterns/online-softmax-tail.md](patterns/online-softmax-tail.md) | `multi-phase-fusion` | | ||
| 78 | +| [patterns/buffer-reuse-lifetime.md](patterns/buffer-reuse-lifetime.md) | `multi-phase-fusion`, `long-axis` | | ||
| 79 | +| [patterns/lookahead-pipeline.md](patterns/lookahead-pipeline.md) | `multi-phase-fusion` | | ||
| 80 | +| [patterns/multi-jit-fusion.md](patterns/multi-jit-fusion.md) | `multi-phase-fusion` — 🔴 `pro_legal: false`, excluded in the PyPTO-Pro single-kernel path | | ||
| 81 | + | ||
| 82 | +`multi-phase-fusion` now offers five candidates against a three-reference | ||
| 83 | +selection bound, so a class routed there must choose; the bound is on what a | ||
| 84 | +class selects, not on how many pages a node lists, and nothing enforces a | ||
| 85 | +per-node cap. Raise it with the KB owner if the node should be split. | ||
| 86 | + | ||
| 54 | **At most three primary references per class.** Reading more is how a stage | 87 | **At most three primary references per class.** Reading more is how a stage |
| 55 | accumulates document access without any of it reaching the code. When no | 88 | accumulates document access without any of it reaching the code. When no |
| 56 | pattern fits — `scan` currently retains none — record that outcome explicitly | 89 | pattern fits — `scan` currently retains none — record that outcome explicitly |
| @@ -44,6 +44,44 @@ INDEXES = ("patterns/pattern-index.md", "examples/kernel-index.md") | |||
| 44 | 44 | ||
| 45 | _MD_LINK = re.compile(r"\[[^\]]*\]\(([^)#]+?)(?:#[^)]*)?\)") | 45 | _MD_LINK = re.compile(r"\[[^\]]*\]\(([^)#]+?)(?:#[^)]*)?\)") |
| 46 | 46 | ||
| 47 | +#: A code span. Bounded to a single line on purpose: an unbalanced backtick would | ||
| 48 | +#: otherwise blank the document from that point to the next backtick anywhere | ||
| 49 | +#: later, silently un-checking every link in between. | ||
| 50 | +_CODE_SPAN = re.compile(r"(`+)[^\n]*?\1") | ||
| 51 | + | ||
| 52 | +#: An opening or closing fence line: ``` or ~~~, optionally with an info string. | ||
| 53 | +_FENCE = re.compile(r"^\s{0,3}(`{3,}|~{3,})") | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +def _without_code(text: str) -> str: | ||
| 57 | + """Blank out fenced blocks and code spans before looking for links. | ||
| 58 | + | ||
| 59 | + A markdown link is prose. Code is not, and the two share punctuation: a pl | ||
| 60 | + kernel launch reads ``kern[None, num_cores](q, k, w, out)``, which is | ||
| 61 | + ``[...](...)`` to the naked eye of a link matcher. Nothing a page can do to | ||
| 62 | + itself fixes this -- the matcher's ``[^)#]+?`` spans newlines, so splitting | ||
| 63 | + the arguments across lines does not help, and backticking or fencing did not | ||
| 64 | + help either because nothing here used to look at fences. So the fix belongs | ||
| 65 | + to the matcher: strip code first, then match links in what is left. | ||
| 66 | + """ | ||
| 67 | + out: list[str] = [] | ||
| 68 | + fence: str | None = None | ||
| 69 | + for line in text.splitlines(): | ||
| 70 | + match = _FENCE.match(line) | ||
| 71 | + if fence is None: | ||
| 72 | + if match: | ||
| 73 | + fence = match.group(1) | ||
| 74 | + out.append("") | ||
| 75 | + continue | ||
| 76 | + out.append(line) | ||
| 77 | + else: | ||
| 78 | + # A fence closes only on the same character and at least the same | ||
| 79 | + # length, so a ```` ```` ````-opened block is not closed by ``` inside it. | ||
| 80 | + if match and match.group(1)[0] == fence[0] and len(match.group(1)) >= len(fence): | ||
| 81 | + fence = None | ||
| 82 | + out.append("") | ||
| 83 | + return _CODE_SPAN.sub(" ", "\n".join(out)) | ||
| 84 | + | ||
| 47 | #: Transient labels that must never appear in a retained filename. | 85 | #: Transient labels that must never appear in a retained filename. |
| 48 | _BAD_NAME_TOKENS = ( | 86 | _BAD_NAME_TOKENS = ( |
| 49 | "run_2", "wip", "tmp", "temp", "draft", "final", "old", "new", "backup", | 87 | "run_2", "wip", "tmp", "temp", "draft", "final", "old", "new", "backup", |
| @@ -97,7 +135,7 @@ def _kb_files() -> list[Path]: | |||
| 97 | 135 | ||
| 98 | def _links_from(path: Path) -> list[tuple[str, Path]]: | 136 | def _links_from(path: Path) -> list[tuple[str, Path]]: |
| 99 | out: list[tuple[str, Path]] = [] | 137 | out: list[tuple[str, Path]] = [] |
| 100 | - for target in _MD_LINK.findall(_text(path)): | 138 | + for target in _MD_LINK.findall(_without_code(_text(path))): |
| 101 | target = target.strip() | 139 | target = target.strip() |
| 102 | if not target or target.startswith(("http://", "https://", "mailto:")): | 140 | if not target or target.startswith(("http://", "https://", "mailto:")): |
| 103 | continue | 141 | continue |
| @@ -1,5 +1,8 @@ | |||
| 1 | # Batched contraction reduced to 2-D | 1 | # Batched contraction reduced to 2-D |
| 2 | 2 | ||
| 3 | +> **pro_legal: true** — a single `@pl.jit` kernel, so this dataflow is legal in the PyPTO-Pro | ||
| 4 | +> single-kernel path (verifier `stage4-check` #5). | ||
| 5 | + | ||
| 3 | ## Applies when | 6 | ## Applies when |
| 4 | 7 | ||
| 5 | The left operand has leading batch dimensions, the right operand is shared by | 8 | The left operand has leading batch dimensions, the right operand is shared by |
| @@ -33,9 +36,35 @@ A reshape that is a pure view of an already-contiguous tensor costs nothing and | |||
| 33 | does not appear in the profile. If you cannot show from the profile that a host | 36 | does not appear in the profile. If you cannot show from the profile that a host |
| 34 | reshape produced no device operation, it produced one. | 37 | reshape produced no device operation, it produced one. |
| 35 | 38 | ||
| 39 | +If the operator is already natively 2-D — the left operand arrives as `[T, H]` — the collapse is | ||
| 40 | +inherent to the layout and every contraction is already 2-D. There is nothing to do; do not add a | ||
| 41 | +reshape to make the pattern apply. | ||
| 42 | + | ||
| 43 | +Spread the collapsed leading axis across cores with a strided tile loop over the block index and | ||
| 44 | +block count, and declare the collapsed axis dynamic in the tensor type so one compiled kernel | ||
| 45 | +serves any batch product. | ||
| 46 | + | ||
| 36 | The kernel body then follows the ordinary 2-D contraction pattern in | 47 | The kernel body then follows the ordinary 2-D contraction pattern in |
| 37 | [cube-only.md](cube-only.md). | 48 | [cube-only.md](cube-only.md). |
| 38 | 49 | ||
| 50 | +## Failure signatures | ||
| 51 | + | ||
| 52 | +- The kernel carries `[1, 1, ...]` leading dimensions — the right operand was up-ranked to match | ||
| 53 | + the left instead of the batch axes being collapsed. It costs compile time and buys nothing. | ||
| 54 | +- The output shape restore is not the exact inverse of the collapse, so batch axes come back in | ||
| 55 | + the wrong order. | ||
| 56 | +- A reshape of a non-contiguous tensor silently materializes a copy. If you cannot show from the | ||
| 57 | + profile that a host-side reshape produced no device operation, it produced one. | ||
| 58 | +- Shape-driven control flow written inside the kernel body rather than kept to the host wrapper. | ||
| 59 | +- All of these surface at compile or on the device. There is no simulator for this surface. | ||
| 60 | + | ||
| 61 | +## Do not use when | ||
| 62 | + | ||
| 63 | +- The batch axes are genuinely non-degenerate on **both** operands — that is a real batched | ||
| 64 | + matmul, not a collapse. | ||
| 65 | +- The collapse cannot be expressed as offset arithmetic on the real shape and would require a | ||
| 66 | + materializing copy whose cost outweighs the tiling simplification. | ||
| 67 | + | ||
| 39 | ## Validation status | 68 | ## Validation status |
| 40 | 69 | ||
| 41 | **Conceptual.** No retained kernel in this KB implements the batched collapse | 70 | **Conceptual.** No retained kernel in this KB implements the batched collapse |
| @@ -1,5 +1,8 @@ | |||
| 1 | # Buffer lifetime and rotating tile groups | 1 | # Buffer lifetime and rotating tile groups |
| 2 | 2 | ||
| 3 | +> **pro_legal: true** — a single `@pl.jit` kernel, so this dataflow is legal in the PyPTO-Pro | ||
| 4 | +> single-kernel path (verifier `stage4-check` #5). | ||
| 5 | + | ||
| 3 | ## Applies when | 6 | ## Applies when |
| 4 | 7 | ||
| 5 | A tiled kernel overlaps iterations or reuses local storage for multiple roles. | 8 | A tiled kernel overlaps iterations or reuses local storage for multiple roles. |
| @@ -28,7 +31,41 @@ the same shape. Alias safety depends on live intervals. | |||
| 28 | - a running value resets or alternates between stale values; | 31 | - a running value resets or alternates between stale values; |
| 29 | - correctness changes when double buffering is enabled; | 32 | - correctness changes when double buffering is enabled; |
| 30 | - a reduction sees padding or data from a previous iteration; | 33 | - a reduction sees padding or data from a previous iteration; |
| 31 | -- local-memory usage exceeds the target budget. | 34 | +- local-memory usage exceeds the target budget. One stage over-holding workspace is the usual |
| 35 | + cause; split by head or group, or shrink the row count and the compile-time tile width. | ||
| 36 | + | ||
| 37 | +## Tile placement | ||
| 38 | + | ||
| 39 | +- Lay UB addresses out as named offsets sized by one slot — | ||
| 40 | + `SLOT_BYTES = TILE_ROWS * MAX_N * dtype_bytes` — and give each role its own window. | ||
| 41 | + Overlap two windows only when the two live ranges are provably disjoint — equal tile shapes are | ||
| 42 | + not evidence of that. | ||
| 43 | +- `.current()` is a single-buffered read or a carry; `.next()` advances a rotating ring. Using | ||
| 44 | + `.current()` everywhere serializes the loop, and rotating a carry destroys it. | ||
| 45 | +- A carry is a single-slot tile declared **outside** the loop. A rotating role needs one mutex id | ||
| 46 | + per slot, and the automatic mutex placement derives its barriers from those ids. | ||
| 47 | +- A block reduction writes a `[rows, 1]` tile and needs a scratch tile of the input shape; | ||
| 48 | + allocate the scratch once and reset its valid window per iteration rather than allocating per | ||
| 49 | + pass. | ||
| 50 | + | ||
| 51 | +## Do not use when | ||
| 52 | + | ||
| 53 | +- The kernel is one stage with one tile shape and no loop-carried state — a couple of single-slot | ||
| 54 | + groups is the whole design and there is no lifetime to manage. | ||
| 55 | +- There is no reused workspace and no double-buffering need — plain single-buffer tiles suffice. | ||
| 56 | + | ||
| 57 | +## Runnable reference | ||
| 58 | + | ||
| 59 | +- [softmax_impl.py](../examples/samples/softmax/softmax_impl.py) — retained: an explicit UB address | ||
| 60 | + map, rotating input/output/scratch groups and a `[rows, 1]` reduction group, advanced once per | ||
| 61 | + row-tile. | ||
| 62 | +- In the PyPTO devkit test tree (external to this KB): | ||
| 63 | + `python/tests/ut/block/frontend/a5/tile_vector/test_softmax.py:42-98` for the same address map and | ||
| 64 | + slot sizing; `python/tests/ut/block/frontend/a5/fa/test_fa_bsnd_dn.py:463-491` for carries | ||
| 65 | + (`running_o`, `exp_corr`, `global_sum` / `global_max`) declared single-slot outside the loop and | ||
| 66 | + rescaled in place; and | ||
| 67 | + `python/tests/ut/block/frontend/a5/matmul/test_matmul_api_basic.py:137-167` for double-buffered | ||
| 68 | + L1/L0 groups alongside a single-slot accumulator carry in a K-loop. | ||
| 32 | 69 | ||
| 33 | ## Validation status | 70 | ## Validation status |
| 34 | 71 | ||
| @@ -1,5 +1,8 @@ | |||
| 1 | # Pure cube contraction | 1 | # Pure cube contraction |
| 2 | 2 | ||
| 3 | +> **pro_legal: true** — a single `@pl.jit` kernel, so this dataflow is legal in the PyPTO-Pro | ||
| 4 | +> single-kernel path (verifier `stage4-check` #5). | ||
| 5 | + | ||
| 3 | ## Applies when | 6 | ## Applies when |
| 4 | 7 | ||
| 5 | The kernel is a 2-D contraction with no vector reduction, activation, cast, or | 8 | The kernel is a 2-D contraction with no vector reduction, activation, cast, or |
| @@ -69,8 +72,55 @@ an official example for the detected SDK version before implementing it. | |||
| 69 | design. | 72 | design. |
| 70 | - A wrong total across three or more K blocks usually means an intermediate | 73 | - A wrong total across three or more K blocks usually means an intermediate |
| 71 | block was finalized too early. | 74 | block was finalized too early. |
| 75 | +- A transposed or garbage result usually means the two operands were staged in | ||
| 76 | + the same layout. The cube unit reads its left and right operands differently, | ||
| 77 | + and a transposed contraction is expressed by transposing the operand rather | ||
| 78 | + than by changing the layout it is staged in. | ||
| 79 | +- A silent wrong-address read means element offsets and tile-index offsets were | ||
| 80 | + mixed in one kernel; see below. | ||
| 81 | +- All of these surface at compile or on the device. There is no simulator for | ||
| 82 | + this surface. | ||
| 83 | + | ||
| 84 | +## Tile placement and layout | ||
| 85 | + | ||
| 86 | +- One `pl.section_cube()` and nothing else: there is no vector operation to place. | ||
| 87 | +- Five tile groups — A and B in `MemorySpace.Mat`, A in `Left`, B in `Right`, C in `Acc`. The | ||
| 88 | + cube unit reads its two operands in different layouts: the left operand is staged `NZ`, the | ||
| 89 | + right operand `ZN`, and the `Acc` tile is declared `NZ` with `fractal=1024`. Confirm those | ||
| 90 | + values against the detected SDK before committing to them. | ||
| 91 | +- 🔴 **There is no ND→ZN load path.** A contraction of the form `x @ y.T` is expressed by | ||
| 92 | + transposing `y` on the host and passing it as the right operand — not by asking `pl.load` to | ||
| 93 | + reformat on the way in. | ||
| 94 | +- `@pl.jit(auto_mutex=True)` inserts the load → move → matmul → store synchronization for these | ||
| 95 | + five groups; adding manual synchronization on the same managed dependency needs evidence. | ||
| 96 | +- `pl.load` takes **element** offsets and `pl.load_tile` / `pl.store_tile` take **tile-index** | ||
| 97 | + offsets. Mixing the two conventions in one kernel is a silent wrong-address bug. | ||
| 98 | +- Spread M-tiles across cores with a strided `pl.range` over `pl.get_block_idx()` / | ||
| 99 | + `pl.get_block_num()`, and double-buffer the L1/L0 groups across K blocks so the next block | ||
| 100 | + loads while the current one accumulates. | ||
| 101 | + | ||
| 102 | +## Do not use when | ||
| 103 | + | ||
| 104 | +- The kernel needs any elementwise, reduction, activation, softmax, or cast — adding a vector | ||
| 105 | + section makes it a mixed cube+vector kernel, not this pattern. | ||
| 106 | +- Leading non-degenerate batch axes are genuinely required on **both** operands — that is a real | ||
| 107 | + batched matmul; see [batched-2d-contraction.md](batched-2d-contraction.md) for the case where | ||
| 108 | + only the left operand is batched. | ||
| 109 | + | ||
| 110 | +## Runnable reference | ||
| 111 | + | ||
| 112 | +- [matmul_float_mmad_impl.py](../examples/samples/matmul_float_mmad/matmul_float_mmad_impl.py) — | ||
| 113 | + retained single-tile `z = x @ y.T` FP32, bit-exact against its | ||
| 114 | + [golden](../examples/samples/matmul_float_mmad/matmul_float_mmad_golden.py). | ||
| 115 | +- In the PyPTO devkit test tree (external to this KB, read against the installed version): | ||
| 116 | + `python/tests/ut/block/frontend/a5/matmul/test_matmul_api_basic.py:92-125` (t01, single tile) and | ||
| 117 | + `:128-167` (t02, K-loop with `AccPhase.Partial` / `Final` and `pl.matmul_acc`); the NN/NT/TN/TT | ||
| 118 | + layout combinations across t01–t24; and | ||
| 119 | + `python/tests/ut/block/frontend/a5/docs/test_doc_quickstart.py:93-136` for the multicore variant | ||
| 120 | + that strides M-tiles across cores with `load_tile` / `store_tile`. | ||
| 72 | 121 | ||
| 73 | ## Validation status | 122 | ## Validation status |
| 74 | 123 | ||
| 75 | - Single K block: validated by the retained runnable reference. | 124 | - Single K block: validated by the retained runnable reference. |
| 76 | -- General K-loop: conceptual only; not a copyable validated skeleton. | 125 | +- General K-loop: conceptual only; not a copyable validated skeleton. The devkit test coordinates |
| 126 | + above are evidence to read against the installed version, not retained artifacts of this KB. | ||
| @@ -0,0 +1,63 @@ | |||
| 1 | +# fp4-mxfp-cast-pack | ||
| 2 | + | ||
| 3 | +> **pro_legal: true** — a single `@pl.jit` kernel; allowed in the Pro (single-kernel) flow. | ||
| 4 | + | ||
| 5 | +## Applies when | ||
| 6 | +You need to move a tensor through a low-precision carrier on a5: a plain per-row **quant/dequant** round-trip, a **type cast** to/from a narrow dtype, or (ideally) a **block-scaled mx** quant→matmul→dequant. On the pl tile DSL only the first two are available; the block-scaled mx path (`quant_mx` + `scaled_mm` + `E8M0`) and the packed BF16↔FP4 cast are **gaps** — flagged below. Keep this page short until those ops land. | ||
| 7 | + | ||
| 8 | +## Tensor-level dataflow | ||
| 9 | +Three lanes, by pl availability: | ||
| 10 | + | ||
| 11 | +1. **Per-row quant / dequant (available).** `pl.quant(out, src, scale, mode=pl.QuantMode.SYM)` symmetric FP32 → INT8 (`clamp(round(x·scale))`); recover with `pl.dequant(out, src, scale, offset)` (`(src − offset)·scale`). `scale`/`offset` are per-row `[rows, 1]` FP32 tiles. Simpler and coarser than mx — no shared exponent. | ||
| 12 | +2. **Type cast (available, generic).** `pl.cast(out, src, mode=pl.RoundMode.CAST_ROUND)` converts between dtypes on a `MemorySpace.Vec` tile (FP16↔FP32 is tested). `DT_FP4` exists as a pl dtype, but the **packed BF16↔FP4 cast is not demonstrated** — `(no pl op found for BF16↔FP4 cast — doc-only; confirm on the NPU or treat as additive-extension candidate; a `forbidden` decomposition per [decomposition-primitives.md](../references/decomposition-primitives.md) — redesign, do not implement it out of existing primitives)`. | ||
| 13 | +3. **Block-scaled mx (quant_mx + scaled_mm + E8M0 block 64).** `(no pl op found — additive-extension candidate; a `forbidden` decomposition per [decomposition-primitives.md](../references/decomposition-primitives.md) — redesign, do not implement it out of existing primitives)`. pl has no `quant_mx`, no `scaled_mm`, and no `DT_FP8E8M0` block scale (graph-frontend `pypto.*` only). Do not author this from existing pl primitives; it is a genuine op gap. | ||
| 14 | + | ||
| 15 | +## Tiling & pass hints (pl knobs only) | ||
| 16 | +- `pl.quant` / `pl.dequant` / `pl.cast` run in `with pl.section_vector():` on `MemorySpace.Vec` tiles; per-row scale tiles are `[rows, 1]`. Cast late, at the boundary. | ||
| 17 | +- For the low-precision **matmul** boundary that would consume mx operands, see `patterns/quant-matmul-scaled-mm.md` (Lane B is the pl-native substitute for the missing block-scaled `scaled_mm`). | ||
| 18 | +- pl has **no `RunMode.SIM`** — validate on the Tier-3 NPU. | ||
| 19 | + | ||
| 20 | +## Minimal skeleton (pl tile DSL) | ||
| 21 | + | ||
| 22 | +> `conceptual only` — per [pattern-index.md](pattern-index.md): "use the equations and decision | ||
| 23 | +> rules, but do not copy code until the target SDK's official docs/examples provide a matching | ||
| 24 | +> runnable reference." | ||
| 25 | +```python | ||
| 26 | +import pypto_pro.language as pl | ||
| 27 | + | ||
| 28 | +# per-row symmetric quant FP32 -> INT8, and dequant back (test_doc_quant_cast_scatter.py) | ||
| 29 | +with pl.section_vector(): | ||
| 30 | + pl.quant(q_tile, src_tile, scale_tile, mode=pl.QuantMode.SYM) # clamp(round(x*scale)) | ||
| 31 | + # ... consume q_tile ... | ||
| 32 | + pl.dequant(out_tile, q_tile, scale_tile, offset_tile) # (q - offset) * scale | ||
| 33 | + | ||
| 34 | +# generic type cast (FP16 -> FP32 tested) | ||
| 35 | +with pl.section_vector(): | ||
| 36 | + pl.cast(f32_tile, f16_tile, mode=pl.RoundMode.CAST_ROUND) | ||
| 37 | + | ||
| 38 | +# ── gaps (do NOT invent APIs) ──────────────────────────────────────────────── | ||
| 39 | +# packed BF16 <-> FP4 cast: doc-only, no pl test call-site | ||
| 40 | +# quant_mx / scaled_mm / DT_FP8E8M0 block scale: | ||
| 41 | +# (no pl op found — additive-extension candidate; a `forbidden` decomposition per [decomposition-primitives.md](../references/decomposition-primitives.md) — redesign, do not implement it out of existing primitives) | ||
| 42 | +``` | ||
| 43 | + | ||
| 44 | +## Failure signatures | ||
| 45 | +- Wrong quant/dequant result — `scale`/`offset` not per-row `[rows,1]`, or offset applied on the wrong side (`(q − offset)·scale`). | ||
| 46 | +- Reaching for `pl.quant_mx` / `pl.scaled_mm` / `DT_FP8E8M0` — they do not exist; block-scaled mx is an additive-op gap. | ||
| 47 | +- Assuming `pl.cast(..., DT_FP4)` round-trips — the packed BF16↔FP4 cast is untested on this surface; confirm on hardware before relying on it. | ||
| 48 | +- Surfaces at bisheng compile / NPU run (no SIM), not in a simulator. | ||
| 49 | + | ||
| 50 | +## Runnable reference | ||
| 51 | +- `python/tests/ut/block/frontend/a5/docs/test_doc_quant_cast_scatter.py:39-58` (`pl.quant` SYM), `:79-103` (`pl.dequant`), `:124-138` (`pl.cast` FP16→FP32). | ||
| 52 | +- `patterns/quant-matmul-scaled-mm.md` — the pl-native low-precision matmul that substitutes for the missing block-scaled `scaled_mm`. | ||
| 53 | +- `cannbot-skills/kb/references/decomposition-primitives.md` — the classification to apply to the `quant_mx` / `scaled_mm` / `E8M0` and packed-FP4-cast gaps: each is `forbidden` (an unsupported semantic change), so the answer is to redesign rather than to approximate one. | ||
| 54 | + | ||
| 55 | +## Do not use when | ||
| 56 | +Accuracy needs full FP16/FP32 (no low-precision budget) — stay in `pl.matmul`. You need true block-scaled mx or packed FP4 — those are the gaps above, not something to fake from `pl.quant`/`pl.cast`. | ||
| 57 | + | ||
| 58 | +## Validation status | ||
| 59 | + | ||
| 60 | +**Conceptual only.** No runnable implementation of this dataflow is retained in this KB, and the | ||
| 61 | +mx block-scale carrier (`quant_mx` / `scaled_mm` / `E8M0`) has no pl operation at all — that is the | ||
| 62 | +gap this page records, not a feature it documents. Use the equations and the decision rules; confirm | ||
| 63 | +every cast, pack and scale API against the detected SDK's official examples before writing code. | ||
| @@ -0,0 +1,91 @@ | |||
| 1 | +# lookahead-pipeline | ||
| 2 | + | ||
| 3 | +> **pro_legal: true** — a single `@pl.jit` kernel; allowed in the Pro (single-kernel) flow. | ||
| 4 | + | ||
| 5 | +## Applies when | ||
| 6 | + | ||
| 7 | +A producer stage should run ahead of a consumer that lags by one or more iterations — a double-buffer / preload so the consumer never stalls waiting for the producer (classic cube-loads-ahead-of-vector, or any cross-core producer→consumer chain over a KV / K-block loop). | ||
| 8 | + | ||
| 9 | +## Tensor-level dataflow | ||
| 10 | + | ||
| 11 | +Iteration *i* the producer emits chunk *i* while the consumer processes chunk *i−D* (D = the stage delay). Steady state overlaps producer(i) with consumer(i−D); a warmup **preload** fires the first stage D extra times before steady-state alternation, and drain flushes the last D consumer chunks. The stages alternate across pipes (Cube producer → Vector consumer → …). | ||
| 12 | + | ||
| 13 | +**Two pl expressions, from lightest to heaviest:** | ||
| 14 | + | ||
| 15 | +- **Manual double-buffer (always available):** give the producer→consumer tile a two-slot group (`addrs=[a, b], mutex_ids=[0, 1]`) and advance it with `.next()` each iteration; `@pl.jit(auto_mutex=True)` places the sync so slot *i* is produced while slot *i−1* is consumed. This is the ring buffer you write by hand (softmax / quickstart matmul use it). | ||
| 16 | +- **Declared preload pipeline:** mark each stage `@pl.pipeline.stage` and pass `pipeline=pl.pipeline.PipelineConfig(preload=N)` to `@pl.jit`; the framework rewrites the serial stage loop into a preload pipeline with a ring-buffer context and auto-inserts the cross-core sync (`test_fa_serial_dn_auto.py`). | ||
| 17 | + | ||
| 18 | +## Tiling & pass hints (pl knobs only) | ||
| 19 | + | ||
| 20 | +- `PipelineConfig` (`runtime/pipeline/config.py:15-32`): `preload` (default 2) is *"the number of times the first stage pre-fires before steady-state alternation begins. E.g. preload=2 means C1 C1 C1 C2 C1 C2 … The actual ctx ring-buffer depth is computed from the stage delays (max_delay + 1), not from preload directly."* `sync_only=True` keeps the serial loop and only auto-inserts cross-core sync around each stage — a correctness pre-check before enabling the full preload rewrite. | ||
| 21 | +- `@pl.pipeline.stage` functions must strictly alternate Cube/Vector; each takes a `tick` and the tile groups it advances with `.next()`. The consumer's delay may not be shorter than the producer's. | ||
| 22 | +- Manual path: buffer depth = number of slots in the tile group; two slots (`mutex_ids=[0,1]`) give single-lookahead, four (`[0,1,10,11]`) give deeper preload (quickstart `matmul_example`). Carry tiles that must persist across iterations stay single-slot (`.current()` / a dedicated `pl.make_tile`). | ||
| 23 | +- pl has **no `RunMode.SIM`** — validate the pipelined kernel on the Tier-3 NPU; start with `sync_only=True` to confirm correctness, then switch to `preload=N`. | ||
| 24 | + | ||
| 25 | +## Minimal skeleton (pl tile DSL) | ||
| 26 | + | ||
| 27 | +> `conceptual only` — per [pattern-index.md](pattern-index.md): "use the equations and decision | ||
| 28 | +> rules, but do not copy code until the target SDK's official docs/examples provide a matching | ||
| 29 | +> runnable reference." | ||
| 30 | + | ||
| 31 | +```python | ||
| 32 | +import pypto_pro.language as pl | ||
| 33 | + | ||
| 34 | +# ── declared preload pipeline (test_fa_serial_dn_auto.py:299-397) ──────────── | ||
| 35 | +@pl.pipeline.stage | ||
| 36 | +def compute_qk(ki, ..., left_db, right_db, acc_db, qk_vec_db): # Cube producer | ||
| 37 | + pl.matmul(acc_db.next(), left_db.next(), right_db.next()) | ||
| 38 | + pl.move(qk_vec_db.next(), acc_db.current(), acc_to_vec_mode=pl.AccToVecMode.DualModeSplitN) | ||
| 39 | + | ||
| 40 | +@pl.pipeline.stage | ||
| 41 | +def compute_p(ki, ..., qk_vec_db, p_mat_db): # Vector consumer, delay = 1 | ||
| 42 | + ... # softmax on the delayed qk_vec slot | ||
| 43 | + | ||
| 44 | +@pl.jit(auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(preload=2)) | ||
| 45 | +def fa_pipeline_kernel(q, k, v, o, ...): | ||
| 46 | + with pl.section_cube(): | ||
| 47 | + for ki in pl.range(0, skv_tiles): | ||
| 48 | + compute_qk(ki, ...) # framework preloads + inserts cross-core sync | ||
| 49 | + with pl.section_vector(): | ||
| 50 | + for ki in pl.range(0, skv_tiles): | ||
| 51 | + compute_p(ki, ...) | ||
| 52 | + | ||
| 53 | +# ── correctness pre-check: keep the serial loop, only auto-sync ────────────── | ||
| 54 | +# @pl.jit(auto_mutex=True, pipeline=pl.pipeline.PipelineConfig(sync_only=True)) | ||
| 55 | +# (test_smla_softmax_l1_norm_dense.py:259) | ||
| 56 | + | ||
| 57 | +# ── manual double-buffer (no PipelineConfig) — softmax / quickstart matmul ──── | ||
| 58 | +grp = pl.make_tile_group(type=tt, addrs=[A0, A1], mutex_ids=[0, 1]) # 2-slot ring | ||
| 59 | +for i in pl.range(0, N): | ||
| 60 | + slot = grp.next() # slot i produced while slot i-1 is consumed (auto_mutex) | ||
| 61 | + pl.load(slot, x, [i * TILE, 0]) | ||
| 62 | + ... # consume the previous slot's data downstream | ||
| 63 | +``` | ||
| 64 | + | ||
| 65 | +## Failure signatures | ||
| 66 | + | ||
| 67 | +- Consumer reads stale/uninitialized data — the producer→consumer tile is single-slot (`.current()` reused), so there is no lookahead; give it ≥2 slots and `.next()`. | ||
| 68 | +- Stages that do not strictly alternate Cube/Vector break the delay model; a consumer delay shorter than the producer's is rejected by the pipeline consistency check `(unverified — confirm on Tier 3: exact error string)`. | ||
| 69 | +- `sync_only=True` passes but `preload=N` gives wrong results — a carry tile was placed in a rotating group; carries must be single-slot and live outside the ring. | ||
| 70 | +- No parallelism gain — the loop iterations were independent to begin with; a preload pipeline only serializes them. | ||
| 71 | +- Surfaces at bisheng compile / NPU run (no SIM), not in a simulator. | ||
| 72 | + | ||
| 73 | +## Runnable reference | ||
| 74 | + | ||
| 75 | +- `python/tests/ut/block/frontend/a5/fa/test_fa_serial_dn_auto.py:299-397` — `@pl.pipeline.stage` on `compute_qk/compute_pv/compute_p/compute_gu` + `@pl.jit(pipeline=pl.pipeline.PipelineConfig(preload=2))`. | ||
| 76 | +- `python/tests/ut/block/frontend/a5/smla_softmax_l1_norm/test_smla_softmax_l1_norm_dense.py:116,226,259` — `@pl.pipeline.stage` stages + `PipelineConfig(sync_only=True)` (the correctness pre-check). | ||
| 77 | +- `python/pypto_pro/runtime/pipeline/config.py:15-32` — `PipelineConfig(preload, sync_only)` docstring (ring depth = `max_delay + 1`). | ||
| 78 | +- Manual ring buffer: `cannbot-skills/kb/examples/samples/softmax/softmax_impl.py` (2-slot in/out/tmp groups) and `python/tests/ut/block/frontend/a5/docs/test_doc_quickstart.py:105-136` (4-slot L1 buffers via `mutex_ids=[0,1,10,11]` + `.next()`). | ||
| 79 | + | ||
| 80 | +## Do not use when | ||
| 81 | + | ||
| 82 | +- Iterations are independent — a plain `pl.range` loop with single-buffer tiles is enough; a preload pipeline only serializes. | ||
| 83 | +- The producer and consumer are the same pipe with no cross-core handoff — `auto_mutex` on a two-slot group already overlaps them; `PipelineConfig` adds machinery for nothing. | ||
| 84 | + | ||
| 85 | +## Validation status | ||
| 86 | + | ||
| 87 | +**Conceptual only.** The retained | ||
| 88 | +[softmax implementation](../examples/samples/softmax/softmax_impl.py) validates rotating tile groups | ||
| 89 | +for a row-tiled topology, which is the manual half of this page; the declarative `preload` pipeline | ||
| 90 | +form has no retained runnable reference here. Validate stage decomposition, preload depth and the | ||
| 91 | +resulting synchronization against an official example for the detected SDK version. | ||
| @@ -0,0 +1,104 @@ | |||
| 1 | +# multi-jit-fusion | ||
| 2 | + | ||
| 3 | +> 🔴 **pro_legal: false — EXCLUDED in the Pro path.** The Pro flow mandates a **single `@pl.jit` | ||
| 4 | +> kernel** (verifier `stage4-check` #5). The host-composed *multiple `@pl.jit` kernels* form described | ||
| 5 | +> below is **NOT** a legal Pro design — producing a multi-kernel DESIGN only gets bounced at | ||
| 6 | +> stage4-check and wastes iterations. In the Pro path use ONLY the **fused single-kernel** form | ||
| 7 | +> (several `pl.section_cube()` / `pl.section_vector()` sections in ONE `@pl.jit`, `auto_mutex=True`); | ||
| 8 | +> at Stage 5 the router filters this pattern (`pro_legal=false`) and falls back to the cube-bound | ||
| 9 | +> levers. Read the single-kernel sub-forms here as guidance on the fuse boundary; do NOT split compute | ||
| 10 | +> across kernels. | ||
| 11 | + | ||
| 12 | +## Applies when | ||
| 13 | + | ||
| 14 | +One logical operator is built from **several pieces** — a Cube stage and a Vector stage, reusable `@pl.vector_function` / `@pl.pipeline.stage` helpers, or several `@pl.jit` kernels composed on the host. Use this to decide the fuse-vs-split boundary and to stitch the pieces without leaking Python control flow into a graph. | ||
| 15 | + | ||
| 16 | +## Tensor-level dataflow | ||
| 17 | + | ||
| 18 | +The `@pl.jit` boundary is the unit of compilation and launch: **one `@pl.jit` = one kernel = one launch**. Fusion inside pl is expressed by placing several *sections* in one kernel body: | ||
| 19 | + | ||
| 20 | +- **Multiple sections in one `@pl.jit`** (`with pl.section_cube(): …` then `with pl.section_vector(): …`) → fully fused: L1/UB tiles are shared, `auto_mutex=True` places the cross-pipe sync, no GM round-trip. This is how attention fuses QK/PV (cube) with softmax (vector) in one kernel. | ||
| 21 | +- **Plain helper called inside a `@pl.jit`** — a `@pl.vector_function` (register-level `vf.*` body) or a `@pl.pipeline.stage`, or a bare Python helper that emits tile ops — inlines into the enclosing section; no boundary, no GM handoff. This is how shared math is factored and reused. | ||
| 22 | +- **A separate `@pl.jit` kernel** → a hard boundary: its inputs/outputs live in GM, and adjacent stages in different kernels round-trip through GM and launch independently. | ||
| 23 | + | ||
| 24 | +**Fuse (one kernel, multiple sections)** when stages are adjacent, share tiles, and you want the sync placed for you. **Split (separate kernels)** when a stage is shape-specialized, reused independently, or needs a different `pipeline=` config than its neighbour. **Cross-kernel fusion does not exist** — compose separate kernels on the **host**: Python calls `kernel_a[...](...)`, then `kernel_b[...](...)`, passing torch tensors (each is a launch with a GM handoff). A shape-driven `for`/`if` over kernel launches is legal **only on the host**; inside a `@pl.jit` body use `pl.range`. | ||
| 25 | + | ||
| 26 | +A common structuring idiom is a **factory**: `make_op_kernel(constants…)` closes over compile-time shapes and `return`s the inner `@pl.jit` kernel, so the host can build a shape-specialized variant per call (`test_quant_lightning_indexer_vf.py`). | ||
| 27 | + | ||
| 28 | +## Tiling & pass hints (pl knobs only) | ||
| 29 | + | ||
| 30 | +- Fuse Cube+Vector by ordering the sections in one body; `@pl.jit(auto_mutex=True)` inserts the sync between them (`test_fa_bsnd_dn.py` — `section_cube` L491, `section_vector` L599 in one kernel). | ||
| 31 | +- Factor reusable register math into `@pl.vector_function` helpers and call them from inside `section_vector`; they inline (no launch). Factor pipeline stages into `@pl.pipeline.stage` when you also want preload (`patterns/lookahead-pipeline.md`). | ||
| 32 | +- Set tile groups / addresses per stage inside the kernel; a helper called in two kernels re-declares its own tiles each time. | ||
| 33 | +- Host composition picks the variant by shape and reshapes outputs back to user rank (`patterns/batched-2d-contraction.md`). Launch each kernel with `kernel[None, num_cores](...)` and `torch.npu.synchronize()` between dependent launches. | ||
| 34 | +- pl has **no `RunMode.SIM`** — validate each kernel and the composed chain on the NPU. | ||
| 35 | + | ||
| 36 | +## Minimal skeleton (pl tile DSL) | ||
| 37 | + | ||
| 38 | +> `conceptual only` — per [pattern-index.md](pattern-index.md): "use the equations and decision | ||
| 39 | +> rules, but do not copy code until the target SDK's official docs/examples provide a matching | ||
| 40 | +> runnable reference." | ||
| 41 | + | ||
| 42 | +```python | ||
| 43 | +import torch, pypto_pro.language as pl | ||
| 44 | +# `vf.*` is available inside a @pl.vector_function body (injected by the decorator). | ||
| 45 | + | ||
| 46 | +# 1) FUSE: one @pl.jit, two sections sharing tiles (attention — test_fa_bsnd_dn.py) | ||
| 47 | +@pl.jit(auto_mutex=True) | ||
| 48 | +def fused_kernel(q, k, v, o): | ||
| 49 | + # ... declare Mat/Left/Right/Acc + Vec tile groups ... | ||
| 50 | + with pl.section_cube(): | ||
| 51 | + for ki in pl.range(0, skv_tiles): | ||
| 52 | + pl.matmul(qk_acc, q_left.next(), k_right.next()) # QK / PV on Cube | ||
| 53 | + with pl.section_vector(): | ||
| 54 | + for ki in pl.range(0, skv_tiles): | ||
| 55 | + softmax_body(...) # softmax on Vector — sync auto | ||
| 56 | + | ||
| 57 | +# 2) FACTOR: reusable @pl.vector_function inlines into the vector section | ||
| 58 | +@pl.vector_function | ||
| 59 | +def reduce_and_cast_vf(mm_tile, scale_tile, out_tile, ...): # register-level helper | ||
| 60 | + preg = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=pl.DT_FP32) | ||
| 61 | + ... # vf.reduce_*, vf.astype, ... | ||
| 62 | + | ||
| 63 | +# 3) FACTORY: build a shape-specialized kernel, host picks the variant | ||
| 64 | +def make_op_kernel(SK, TOPK): # closes over compile-time consts | ||
| 65 | + @pl.jit(auto_mutex=True) | ||
| 66 | + def op_kernel(q, k, w, out): | ||
| 67 | + with pl.section_cube(): ... | ||
| 68 | + with pl.section_vector(): reduce_and_cast_vf(...) | ||
| 69 | + return op_kernel | ||
| 70 | + | ||
| 71 | +# 4) COMPOSE on the host: separate kernels, GM handoff, control flow in Python | ||
| 72 | +def op_npu(x, ...): | ||
| 73 | + if sk <= 64: kern = make_op_kernel(64, topk) | ||
| 74 | + else: kern = make_op_kernel(128, topk) | ||
| 75 | + kern[None, num_cores](q, k, w, out); torch.npu.synchronize() | ||
| 76 | + return out.reshape(*batch, N) | ||
| 77 | +``` | ||
| 78 | + | ||
| 79 | +## Failure signatures | ||
| 80 | + | ||
| 81 | +- Wrong result across two kernels — an intermediate that should have stayed in UB was expected to persist across a `@pl.jit` boundary; fuse the stages into one kernel (shared section) or write/read it through GM explicitly. | ||
| 82 | +- Missing cross-pipe sync between a Cube and a Vector section — `auto_mutex=True` was dropped; the vector stage reads L0C before the matmul drains. | ||
| 83 | +- Python `for`/`if` over tiles placed **inside** a `@pl.jit` body — move shape-level control flow to the host wrapper and in-graph iteration to `pl.range`. | ||
| 84 | +- Too many tiny separate kernels — GM round-trips dominate; fuse adjacent Cube+Vector stages into one kernel. | ||
| 85 | +- Surfaces at bisheng compile / NPU run (no SIM), not in a simulator. | ||
| 86 | + | ||
| 87 | +## Runnable reference | ||
| 88 | + | ||
| 89 | +- `python/tests/ut/block/frontend/a5/fa/test_fa_bsnd_dn.py` — one `@pl.jit` fusing `section_cube` (QK/PV, L491) and `section_vector` (softmax, L599); `@pl.vector_function` / stage helpers factored out. | ||
| 90 | +- `python/tests/ut/block/frontend/a5/lightning_indexer/test_quant_lightning_indexer_vf.py:343-831` — `make_quant_lightning_indexer_vf_kernel(...)` factory returning an inner `@pl.jit` (L481); Cube matmul (L593) + Vector `reduce_and_cast_sk_vf` (L68-142) fused in one kernel. | ||
| 91 | +- `cannbot-skills/kb/examples/samples/softmax/softmax_impl.py` / `matmul_float_mmad/matmul_float_mmad_impl.py` — host wrappers (`softmax_wrapper`, `matmul_float_mmad_wrapper`) launching a kernel then `torch.npu.synchronize()`; chain such wrappers to compose kernels. | ||
| 92 | + | ||
| 93 | +## Do not use when | ||
| 94 | + | ||
| 95 | +- The op is a single code path with one section and no reuse — one `@pl.jit`, no helpers. | ||
| 96 | +- Two adjacent stages that share tiles and always run together — fuse them as two sections in one kernel instead of a host GM handoff. | ||
| 97 | + | ||
| 98 | +## Validation status | ||
| 99 | + | ||
| 100 | +**Conceptual only, and `pro_legal: false` — see the banner.** The host-composed multi-kernel form is | ||
| 101 | +not a legal Pro design at all, so nothing on this page may be copied into a Pro kernel; the fused | ||
| 102 | +single-kernel sub-form is the only part that applies, and it too is conceptual here. Read it for the | ||
| 103 | +fuse-versus-split boundary and confirm section ordering and synchronization against an official | ||
| 104 | +example for the detected SDK version. | ||
| @@ -1,5 +1,8 @@ | |||
| 1 | # Streaming softmax across score chunks | 1 | # Streaming softmax across score chunks |
| 2 | 2 | ||
| 3 | +> **pro_legal: true** — a single `@pl.jit` kernel, so this dataflow is legal in the PyPTO-Pro | ||
| 4 | +> single-kernel path (verifier `stage4-check` #5). | ||
| 5 | + | ||
| 3 | ## Status | 6 | ## Status |
| 4 | 7 | ||
| 5 | Conceptual guidance only. The KB has no retained runnable PyPTO-Pro reference | 8 | Conceptual guidance only. The KB has no retained runnable PyPTO-Pro reference |
| @@ -29,12 +32,15 @@ l_new = l_old * alpha + row_sum(p) | |||
| 29 | o_new = o_old * alpha + p @ v_chunk | 32 | o_new = o_old * alpha + p @ v_chunk |
| 30 | ``` | 33 | ``` |
| 31 | 34 | ||
| 32 | -After the final chunk: | 35 | +After the final chunk, and only then: |
| 33 | 36 | ||
| 34 | ```text | 37 | ```text |
| 35 | y = o_new / l_new | 38 | y = o_new / l_new |
| 36 | ``` | 39 | ``` |
| 37 | 40 | ||
| 41 | +If the operator's output dtype is narrower than the accumulation, the cast belongs after that | ||
| 42 | +division, not before it. | ||
| 43 | + | ||
| 38 | The denominator update is indivisible: multiplying `l_old` by `alpha` without | 44 | The denominator update is indivisible: multiplying `l_old` by `alpha` without |
| 39 | adding `row_sum(p)` is incorrect. | 45 | adding `row_sum(p)` is incorrect. |
| 40 | 46 | ||
| @@ -60,6 +66,42 @@ adding `row_sum(p)` is incorrect. | |||
| 60 | - [softmax_impl.py](../examples/samples/softmax/softmax_impl.py) and its | 66 | - [softmax_impl.py](../examples/samples/softmax/softmax_impl.py) and its |
| 61 | [golden](../examples/samples/softmax/softmax_golden.py) cover only the | 67 | [golden](../examples/samples/softmax/softmax_golden.py) cover only the |
| 62 | non-streaming base case. | 68 | non-streaming base case. |
| 69 | +- A fused streaming implementation does exist in the PyPTO devkit test tree, external to this KB: | ||
| 70 | + `python/tests/ut/block/frontend/a5/fa/test_fa_bsnd_dn.py` runs QK/PV in a cube section and the | ||
| 71 | + softmax body in a vector section of one kernel (`softmax_body`, roughly `:241-335`), with the | ||
| 72 | + carries at `:463-491`. It is a coordinate to read against the installed version, not a retained | ||
| 73 | + artifact, so it does not upgrade this page's status — but it is where the streaming form is | ||
| 74 | + actually written down. | ||
| 63 | 75 | ||
| 64 | No full streaming reference is retained, so this page must remain | 76 | No full streaming reference is retained, so this page must remain |
| 65 | `conceptual only` in [pattern-index.md](pattern-index.md). | 77 | `conceptual only` in [pattern-index.md](pattern-index.md). |
| 78 | + | ||
| 79 | +## Tile placement | ||
| 80 | + | ||
| 81 | +- The two matmuls are cube work and the max/exp/sum/rescale is vector work. Put them in separate | ||
| 82 | + sections of **one** kernel so the intermediate scores never round-trip through GM, and let the | ||
| 83 | + automatic mutex placement insert the cross-pipe synchronization. | ||
| 84 | +- The chunk axis is the reduction axis: iterate it and double-buffer the per-chunk key, value and | ||
| 85 | + score tiles so the next chunk loads while the current one reduces. | ||
| 86 | +- The carries — running maximum, running denominator, unnormalized output — are single-slot tiles | ||
| 87 | + declared **outside** the chunk loop. The per-chunk tiles are rotating slots whose lifetime ends | ||
| 88 | + each iteration. | ||
| 89 | +- A row reduction writes a `[rows, 1]` tile that the broadcast operations read back directly; no | ||
| 90 | + reshape is involved. | ||
| 91 | + | ||
| 92 | +## Failure signatures | ||
| 93 | + | ||
| 94 | +- Wrong numerics on the last, partial chunk — the score tile's valid window was not clamped, so | ||
| 95 | + the max and the sum fold over padding. | ||
| 96 | +- The running state resets every chunk — the carries were allocated inside the loop on a rotating | ||
| 97 | + group instead of once outside it. | ||
| 98 | +- Overflow or NaN — the subtract-the-running-max step was dropped before `exp`. | ||
| 99 | +- Disagreement with a golden that computed a one-shot softmax: the golden must mirror the running | ||
| 100 | + renormalization, or be used only where the whole row fits one tile. | ||
| 101 | + | ||
| 102 | +## Do not use when | ||
| 103 | + | ||
| 104 | +- The whole score row fits one tile with no chunk streaming — use the single-pass chain in | ||
| 105 | + [vec-row-reduce-broadcast.md](vec-row-reduce-broadcast.md); the carries are dead weight. | ||
| 106 | +- Each tile is an independent softmax with no cross-chunk maximum — there is nothing to carry. | ||
| 107 | + | ||
| @@ -7,11 +7,59 @@ The validation column controls how a pattern may be used: | |||
| 7 | until the target SDK's official docs/examples provide a matching runnable | 7 | until the target SDK's official docs/examples provide a matching runnable |
| 8 | reference. | 8 | reference. |
| 9 | 9 | ||
| 10 | -| Pattern | Use when | Validation | | 10 | +The `pro_legal` column controls whether a pattern may be *designed to* in the |
| 11 | -|---|---|---| | 11 | +PyPTO-Pro flow at all. That flow mandates a single `@pl.jit` kernel — the |
| 12 | -| [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 | | 12 | +verifier fails a multi-kernel design at `stage4-check` #5 — so a |
| 13 | -| [vec-row-reduce-broadcast.md](vec-row-reduce-broadcast.md) | each row reduces to a scalar and broadcasts it back | validated skeleton | | 13 | +`pro_legal: false` page describes a shape that is legal knowledge and an illegal |
| 14 | -| [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 | | 14 | +Pro design. At Stage 5 the router in |
| 15 | -| [batched-2d-contraction.md](batched-2d-contraction.md) | host reshaping can reduce a batched contraction to 2-D | conceptual only | | 15 | +`../../ops/pypto-pro-op-perf-tune/references/pl-routing-table.md` filters those |
| 16 | -| [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 | | 16 | +rows and falls back to the cube-bound skill. Every page carries the same flag in |
| 17 | -| [online-softmax-tail.md](online-softmax-tail.md) | a softmax reduction streams across multiple score chunks | conceptual only | | 17 | +a banner under its title. |
| 18 | + | ||
| 19 | +| Pattern | Use when | Validation | pro_legal | | ||
| 20 | +|---|---|---|---| | ||
| 21 | +| [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 | true | | ||
| 22 | +| [vec-row-reduce-broadcast.md](vec-row-reduce-broadcast.md) | each row reduces to a scalar and broadcasts it back | validated skeleton | true | | ||
| 23 | +| [vec-group-reduce-broadcast.md](vec-group-reduce-broadcast.md) | fixed-size groups each reduce to their own scalar, and there are two statistics per group rather than one | conceptual only | true | | ||
| 24 | +| [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 | true | | ||
| 25 | +| [lookahead-pipeline.md](lookahead-pipeline.md) | a producer must run ahead of a delayed consumer | conceptual only | true | | ||
| 26 | +| [batched-2d-contraction.md](batched-2d-contraction.md) | leading batch axes can be collapsed so the contraction stays 2-D | conceptual only | true | | ||
| 27 | +| [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 | true | | ||
| 28 | +| [fp4-mxfp-cast-pack.md](fp4-mxfp-cast-pack.md) | a low-precision cast or packed quantization carrier is required | conceptual only | true | | ||
| 29 | +| [online-softmax-tail.md](online-softmax-tail.md) | a softmax reduction streams across multiple score chunks | conceptual only | true | | ||
| 30 | +| [multi-jit-fusion.md](multi-jit-fusion.md) | deciding where the fuse-versus-split boundary belongs | conceptual only | 🔴 **false** — excluded in the Pro path | | ||
| 31 | + | ||
| 32 | +## Where each pattern is written down in code | ||
| 33 | + | ||
| 34 | +Retained artifacts are linked from the page itself. The coordinates below are in the **PyPTO devkit | ||
| 35 | +test tree**, external to this KB: read them against the installed version, and do not treat them as | ||
| 36 | +validation this KB has performed. They are listed here so a page marked `conceptual only` still | ||
| 37 | +tells you where the real thing lives. | ||
| 38 | + | ||
| 39 | +| Pattern | Coordinates (`python/tests/ut/block/frontend/a5/…`) | | ||
| 40 | +|---|---| | ||
| 41 | +| cube-only | `matmul/test_matmul_api_basic.py:92-125` (single tile), `:128-167` (K-loop) | | ||
| 42 | +| vec-row-reduce-broadcast | `tile_vector/test_softmax.py:59-113` | | ||
| 43 | +| vec-group-reduce-broadcast | `vf_api/test_layernorm_tile_group_vf.py:61-114`; single-statistic sibling `vf_api/test_softmax_tile_group_vf.py:57-100` | | ||
| 44 | +| buffer-reuse-lifetime | `fa/test_fa_bsnd_dn.py:463-491` (carries), `matmul/test_matmul_api_basic.py:137-167` (double buffering vs carry) | | ||
| 45 | +| lookahead-pipeline | `fa/test_fa_serial_dn_auto.py:299-397` (pipeline stages with preload), `smla_softmax_l1_norm/test_smla_softmax_l1_norm_dense.py:259` (serial validation first) | | ||
| 46 | +| batched-2d-contraction | `docs/test_doc_quickstart.py:93-136` | | ||
| 47 | +| quant-matmul-scaled-mm | `docs/test_doc_quant_cast_scatter.py:39-103`; FP8 matmul in `lightning_indexer/test_quant_lightning_indexer_vf.py` | | ||
| 48 | +| fp4-mxfp-cast-pack | `docs/test_doc_quant_cast_scatter.py:39-138`; the mx block-scale carrier has no operation on this surface | | ||
| 49 | +| online-softmax-tail | `tile_vector/test_softmax.py:100-111` (base case); fused streaming in `fa/test_fa_bsnd_dn.py` | | ||
| 50 | +| multi-jit-fusion | `fa/test_fa_bsnd_dn.py` (two sections in one kernel); `lightning_indexer/test_quant_lightning_indexer_vf.py:343-831` (kernel factory) | | ||
| 51 | + | ||
| 52 | +## What a pattern page contains | ||
| 53 | + | ||
| 54 | +Every page follows the same contract, so a reader can skip to the part they need: | ||
| 55 | + | ||
| 56 | +``` | ||
| 57 | +# <pattern> + the pro_legal banner | ||
| 58 | +## Applies when | ||
| 59 | +## Dataflow (tensor level, not API level) | ||
| 60 | +## Tile placement (the knobs this pattern actually turns) | ||
| 61 | +## Failure signatures | ||
| 62 | +## Runnable reference (retained artifact, then external coordinates) | ||
| 63 | +## Do not use when | ||
| 64 | +## Validation status (validated skeleton vs conceptual only) | ||
| 65 | +``` | ||
| @@ -1,5 +1,8 @@ | |||
| 1 | # Matmul with explicit output quantization | 1 | # Matmul with explicit output quantization |
| 2 | 2 | ||
| 3 | +> **pro_legal: true** — a single `@pl.jit` kernel, so this dataflow is legal in the PyPTO-Pro | ||
| 4 | +> single-kernel path (verifier `stage4-check` #5). | ||
| 5 | + | ||
| 3 | ## Applies when | 6 | ## Applies when |
| 4 | 7 | ||
| 5 | A matmul writes an integer result using an explicitly defined scale, rounding | 8 | A matmul writes an integer result using an explicitly defined scale, rounding |
| @@ -34,7 +37,38 @@ similarly named quantization API without checking its documented equation. | |||
| 34 | - error grows with the reduction dimension: accumulator dtype or quantization | 37 | - error grows with the reduction dimension: accumulator dtype or quantization |
| 35 | placement differs from the golden path; | 38 | placement differs from the golden path; |
| 36 | - compilation fails at the accumulator-to-vector boundary: the selected | 39 | - compilation fails at the accumulator-to-vector boundary: the selected |
| 37 | - conversion mode is unsupported for the target. | 40 | + conversion mode is unsupported for the target; |
| 41 | +- the matmul itself mismatches: the low-precision operands are not staged in the cube unit's | ||
| 42 | + left/right layouts, or the accumulator tile is missing its fractal parameter. | ||
| 43 | + | ||
| 44 | +## Tile placement | ||
| 45 | + | ||
| 46 | +- Quantize, dequantize and cast are vector work; the contraction is cube work. Put both in one | ||
| 47 | + kernel so the automatic mutex placement handles the handoff, and cast late — at the matmul | ||
| 48 | + boundary — rather than widening early. | ||
| 49 | +- Low-precision operands still stage GM to L1 to L0 with the cube unit's left/right layouts and an | ||
| 50 | + FP32 accumulator. A scale tile is per-row `[rows, 1]`; an offset tile has the same shape. | ||
| 51 | +- Quantize takes a per-row `[rows, 1]` scale tile and a symmetric mode; dequantize takes a scale | ||
| 52 | + tile and an offset tile, and the offset is applied to the accumulator before the scale | ||
| 53 | + (`(acc − offset) · scale`). Getting that order backwards is a distinct failure mode from getting | ||
| 54 | + the rounding rule wrong. | ||
| 55 | +- 🔴 **Availability is not uniform across operand formats, and the asymmetry is specific.** On the | ||
| 56 | + PyPTO devkit test tree an FP8E4M3FN-operand `pl.matmul` with FP32 accumulation is demonstrated | ||
| 57 | + (`lightning_indexer/test_quant_lightning_indexer_vf.py`), and INT8 `pl.quant` / `pl.dequant` tile | ||
| 58 | + operations are demonstrated (`docs/test_doc_quant_cast_scatter.py`) — but an **INT8-operand | ||
| 59 | + `pl.matmul` has no block-frontend test**. Treat that combination as unproven and validate it on | ||
| 60 | + hardware before relying on it. Block-scaled ("mx") matmul, its `E8M0` scale carrier and a | ||
| 61 | + block-scaled `scaled_mm` do not exist on this surface at all; that is a recorded additive-op gap, | ||
| 62 | + not something to approximate out of the per-row quantize operation. Classify that gap with | ||
| 63 | + [decomposition-primitives.md](../references/decomposition-primitives.md): it is `forbidden`, so the | ||
| 64 | + answer is a redesign, not an approximation. | ||
| 65 | + | ||
| 66 | +## Do not use when | ||
| 67 | + | ||
| 68 | +- The golden tolerance cannot absorb the low-precision rounding — stay with FP16/BF16 operands and | ||
| 69 | + FP32 accumulation. | ||
| 70 | +- The matmul is small or latency-bound and the scale plumbing costs more than the bytes it saves. | ||
| 71 | +- You need true block-scaled mx on this surface — that is the gap above, not something to fake. | ||
| 38 | 72 | ||
| 39 | ## Validation status | 73 | ## Validation status |
| 40 | 74 | ||
| @@ -0,0 +1,90 @@ | |||
| 1 | +# vec-group-reduce-broadcast | ||
| 2 | + | ||
| 3 | +> **pro_legal: true** — a single `@pl.jit` kernel; allowed in the Pro (single-kernel) flow. | ||
| 4 | + | ||
| 5 | +## Applies when | ||
| 6 | +The normalized unit is a **fixed-size group** whose elements each reduce to their group's own scalar(s), broadcast back **only within that group** — the **LayerNorm / RMSNorm** shape. Each group (a row of `hidden_size`) independently produces mean and/or variance; groups tile independently. Distinguished from `vec-row-reduce-broadcast` by producing *two* stats (mean + var) per group. | ||
| 7 | + | ||
| 8 | +## Tensor-level dataflow | ||
| 9 | +LayerNorm over a group of size `N` (the row), per group: | ||
| 10 | +1. `mean = sum(x) / N` → `[rows, 1]`. | ||
| 11 | +2. `xc = x - mean` (broadcast the group scalar back over `N`). | ||
| 12 | +3. `var = sum(xc·xc) / N` → `[rows, 1]`. | ||
| 13 | +4. `std = sqrt(var + eps)`; `norm = xc / std` (second broadcast). | ||
| 14 | +5. `out = norm · gamma + beta` (per-column affine). | ||
| 15 | + | ||
| 16 | +RMSNorm drops the mean: `rms = sqrt(sum(x·x)/N + eps)`, `out = (x / rms) · gamma`. No cross-group dependency ⇒ groups tile in parallel and spread across vector cores. Two landing surfaces: **block tile-ops** (`pl.row_sum` → `pl.row_expand_sub` → `pl.mul` → `pl.row_sum` → `pl.sqrt`/`pl.rsqrt` → `pl.expand_*`, the softmax-shaped chain) or the **register `@pl.vector_function`** (`vf.reduce_sum` across `ceil(N/64)` registers), which is the validated reference here. | ||
| 17 | + | ||
| 18 | +## Tiling & pass hints (pl knobs only) | ||
| 19 | +- Register path (`@pl.vector_function`): each row occupies `n_regs = ceil(N / 64)` VF registers inside a `[TILE_ROWS, MAX_N]` UB tile; `MAX_N` a multiple of `LANES=64` keeps rows register-aligned. The last register is masked to its live lanes with `vf.update_mask(min(64, N - r*64))`. `gamma`/`beta` are `[1, N]`, so they too span `n_regs` registers (`vf.load_align(gamma_tile, r*LANES)`). | ||
| 20 | +- Accumulate the reductions in FP32 (`vf.full(0.0, preg, dtype=pl.DT_FP32)` + `vf.reduce_sum`) even if the source is bf16 — the reduction, not just the output, is where narrow rounding bites on long `N`. | ||
| 21 | +- Row-tile the groups across cores (`pl.range(pl.get_block_idx(), num_tiles, pl.get_block_num())`) and narrow the tail with `pl.set_validshape` (block path) / per-register masks (vf path). | ||
| 22 | +- Block path: `[rows,1]` reduction tiles use `layout=pl.DN`; each `pl.row_sum` takes a `tmp` workspace tile. `auto_mutex=True` inserts sync. pl has **no `RunMode.SIM`** — validate on the NPU. | ||
| 23 | + | ||
| 24 | +## Minimal skeleton (pl tile DSL) | ||
| 25 | + | ||
| 26 | +> `conceptual only` — per [pattern-index.md](pattern-index.md): "use the equations and decision | ||
| 27 | +> rules, but do not copy code until the target SDK's official docs/examples provide a matching | ||
| 28 | +> runnable reference." | ||
| 29 | +```python | ||
| 30 | +import pypto_pro.language as pl | ||
| 31 | +# `vf.*` register helpers are available inside a @pl.vector_function body (injected by the | ||
| 32 | +# decorator — the real tests import only `pypto_pro.language as pl`). | ||
| 33 | + | ||
| 34 | +# validated reference: register-level LayerNorm (test_layernorm_tile_group_vf.py:61-114) | ||
| 35 | +@pl.vector_function | ||
| 36 | +def layernorm_rows_vf(in_tile, out_tile, gamma_tile, beta_tile, n_rows, n_cols): | ||
| 37 | + preg = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=pl.DT_FP32) | ||
| 38 | + n_f = vf.full(n_cols, preg, dtype=pl.DT_FP32) | ||
| 39 | + for row in range(n_rows): | ||
| 40 | + base = row * MAX_N | ||
| 41 | + # pass 1: mean = sum(x) / N | ||
| 42 | + row_sum = vf.full(0.0, preg, dtype=pl.DT_FP32) | ||
| 43 | + for r in range(n_regs): | ||
| 44 | + m = vf.update_mask(pl.min(64, n_cols - r * 64), dtype=pl.DT_FP32) | ||
| 45 | + row_sum = vf.add(row_sum, vf.reduce_sum(vf.load_align(in_tile, base + r * 64), m), preg) | ||
| 46 | + mean = vf.div(vf.full(row_sum, preg), n_f, preg) # broadcast lane0 / N | ||
| 47 | + # pass 2: var = sum((x-mean)^2) / N ; std = sqrt(var + eps) | ||
| 48 | + var = vf.full(0.0, preg, dtype=pl.DT_FP32) | ||
| 49 | + for r in range(n_regs): | ||
| 50 | + m = vf.update_mask(pl.min(64, n_cols - r * 64), dtype=pl.DT_FP32) | ||
| 51 | + xc = vf.sub(vf.load_align(in_tile, base + r * 64), mean, m) | ||
| 52 | + var = vf.add(var, vf.reduce_sum(vf.mul(xc, xc, m), m), preg) | ||
| 53 | + std = vf.sqrt(vf.adds(vf.div(vf.full(var, preg), n_f, preg), EPS, preg), preg) | ||
| 54 | + # pass 3: y = (x-mean)/std * gamma + beta | ||
| 55 | + for r in range(n_regs): | ||
| 56 | + m = vf.update_mask(pl.min(64, n_cols - r * 64), dtype=pl.DT_FP32) | ||
| 57 | + xc = vf.sub(vf.load_align(in_tile, base + r * 64), mean, m) | ||
| 58 | + y = vf.add(vf.mul(vf.div(xc, std, m), vf.load_align(gamma_tile, r * 64), m), | ||
| 59 | + vf.load_align(beta_tile, r * 64), m) | ||
| 60 | + vf.store_align(out_tile + base + r * 64, y, m) | ||
| 61 | + | ||
| 62 | +# block tile-op analog (no single validated test; same chain as softmax): | ||
| 63 | +# pl.row_sum(mean, x, tmp); pl.mul(mean, mean, 1.0/N) | ||
| 64 | +# pl.row_expand_sub(xc, x, mean); pl.mul(sq, xc, xc) | ||
| 65 | +# pl.row_sum(var, sq, tmp); pl.sqrt(std, var_plus_eps) | ||
| 66 | +# pl.row_expand_div(norm, xc, std); pl.mul(out, norm, gamma); pl.add(out, out, beta) | ||
| 67 | +``` | ||
| 68 | + | ||
| 69 | +## Failure signatures | ||
| 70 | +- Wrong stats on register-unaligned `N` — the tail register mask (`vf.update_mask`) is missing, so `reduce_sum` folds padding lanes into mean/var. | ||
| 71 | +- `PRECISION_FAIL` / large `max_diff` on long `N` — bf16 accumulation of the reduction; widen the accumulator to FP32. | ||
| 72 | +- Tile over UB capacity — `MAX_N`/`TILE_ROWS` too large for the group; shrink. | ||
| 73 | +- `sqrt` of a negative (var + eps ≤ 0) — eps added on the wrong dtype or after the sqrt. | ||
| 74 | +- Surfaces at bisheng compile / NPU run (no SIM), not in a simulator. | ||
| 75 | + | ||
| 76 | +## Runnable reference | ||
| 77 | +- `python/tests/ut/block/frontend/a5/vf_api/test_layernorm_tile_group_vf.py:61-114` — VALIDATED register-level LayerNorm (`vf.reduce_sum/sub/mul/sqrt/div`, per-register masks, gamma/beta affine). | ||
| 78 | +- `python/tests/ut/block/frontend/a5/vf_api/test_softmax_tile_group_vf.py:57-100` — the single-stat sibling (max/sum) in the same VF idiom. | ||
| 79 | +- `cannbot-skills/kb/examples/samples/softmax/softmax_impl.py` + `python/tests/ut/block/frontend/a5/tile_vector/test_softmax.py:100-111` — the block tile-op `row_sum/row_expand_sub/…` chain the analog above mirrors (validated for softmax; no block-level LayerNorm test exists yet). | ||
| 80 | + | ||
| 81 | +## Do not use when | ||
| 82 | +The single reduce scalar is reused across a **whole** row with only one stat (softmax numerator) → use `vec-row-reduce-broadcast`. The reduce streams over tiled K/V → `online-softmax-tail`. The normalization scalar must be shared **across groups/rows** (a global statistic) — a different broadcast axis needing a two-pass reduction. | ||
| 83 | + | ||
| 84 | +## Validation status | ||
| 85 | + | ||
| 86 | +**Conceptual only.** The retained | ||
| 87 | +[softmax implementation](../examples/samples/softmax/softmax_impl.py) validates the single-statistic | ||
| 88 | +row-reduction sibling on the tile-operation surface; no retained implementation covers the two-statistic | ||
| 89 | +group form, and the vector-function surface below is a separate implementation choice that must be | ||
| 90 | +validated against the target SDK's current API. | ||
| @@ -1,5 +1,8 @@ | |||
| 1 | # Row reduction followed by row broadcast | 1 | # Row reduction followed by row broadcast |
| 2 | 2 | ||
| 3 | +> **pro_legal: true** — a single `@pl.jit` kernel, so this dataflow is legal in the PyPTO-Pro | ||
| 4 | +> single-kernel path (verifier `stage4-check` #5). | ||
| 5 | + | ||
| 3 | ## Applies when | 6 | ## Applies when |
| 4 | 7 | ||
| 5 | Each row independently reduces its last dimension to one scalar and then uses | 8 | Each row independently reduces its last dimension to one scalar and then uses |
| @@ -32,6 +35,43 @@ Do not use this pattern for a global reduction, a reduction shared across rows, | |||
| 32 | or a reduction streamed across multiple score chunks. The last case uses the | 35 | or a reduction streamed across multiple score chunks. The last case uses the |
| 33 | conceptual recurrence in [online-softmax-tail.md](online-softmax-tail.md). | 36 | conceptual recurrence in [online-softmax-tail.md](online-softmax-tail.md). |
| 34 | 37 | ||
| 38 | +## Tile placement and tail handling | ||
| 39 | + | ||
| 40 | +- One `[TILE_ROWS, MAX_N]` tile group for the input plus matching output and scratch groups, and a | ||
| 41 | + `[TILE_ROWS, 1]` reduction group. Every block reduction needs a scratch tile of the input shape, | ||
| 42 | + so allocate one and reuse it across passes. | ||
| 43 | +- Declare the tiles with a runtime valid window and set it before every reduce. The tail row-tile | ||
| 44 | + is partial and the reduced axis is dynamic; the row operations honour the tile's valid shape, so | ||
| 45 | + one compiled kernel serves any width up to the compile-time tile width. | ||
| 46 | +- Row-tile the rows and stride them across vector cores with `pl.get_block_idx()` / | ||
| 47 | + `pl.get_block_num()`, then double-buffer the input, output and scratch groups so the next | ||
| 48 | + row-tile loads while the current one reduces. | ||
| 49 | +- Keep the reduction accumulation in FP32 even when the source is narrower: on a long row it is | ||
| 50 | + the accumulation, not the output, where narrow rounding bites. | ||
| 51 | +- The compile-time tile width `MAX_N` must be a multiple of the 32-byte alignment, otherwise the | ||
| 52 | + row operations read across the fractal boundary. | ||
| 53 | + | ||
| 54 | +## Failure signatures | ||
| 55 | + | ||
| 56 | +- Wrong result on an unaligned width or a partial row-tile — the valid shape was not set, so the | ||
| 57 | + reduction folds over padding. | ||
| 58 | +- Overflow or NaN out of `exp` — the subtract-the-row-max step was dropped. | ||
| 59 | +- The reduction reads stale data — the `[rows, 1]` tile is reused across passes without resetting | ||
| 60 | + its valid window, or the scratch tile overlaps the input. | ||
| 61 | +- Local memory exceeded — the compile-time tile width or row count is too large; shrink it. | ||
| 62 | +- All of these surface at compile or on the device. There is no simulator for this surface. | ||
| 63 | + | ||
| 64 | +## Runnable reference | ||
| 65 | + | ||
| 66 | +- [softmax_impl.py](../examples/samples/softmax/softmax_impl.py) — retained, dynamic rows and | ||
| 67 | + columns, multicore; measured **2.98e-8** maximum absolute difference against `torch.softmax`. | ||
| 68 | +- In the PyPTO devkit test tree (external to this KB): | ||
| 69 | + `python/tests/ut/block/frontend/a5/tile_vector/test_softmax.py:59-113` for the | ||
| 70 | + `row_max` / `row_expand_sub` / `exp` / `row_sum` / `row_expand_div` chain (`:100-111`), the tail | ||
| 71 | + handled by the valid-shape setter, and the multicore launch (`:128`); and | ||
| 72 | + `python/tests/ut/block/frontend/a5/vf_api/test_softmax_tile_group_vf.py:57-100` for the | ||
| 73 | + register-level equivalent when per-lane control is required. | ||
| 74 | + | ||
| 35 | ## Validation status | 75 | ## Validation status |
| 36 | 76 | ||
| 37 | The retained [softmax implementation](../examples/samples/softmax/softmax_impl.py) | 77 | The retained [softmax implementation](../examples/samples/softmax/softmax_impl.py) |
| @@ -0,0 +1,362 @@ | |||
| 1 | +# kb/pitfall-records — dated recurring bugs | ||
| 2 | + | ||
| 3 | +One entry per recurring, concrete bug. Format: symptom → root cause → fix. Seeded from the OL lint rules and the existing experience tables (`pypto-op-knowledge/references/experience_classified/*`); grows as transfers surface real traps. Grep to a symptom; do not read linearly. | ||
| 4 | + | ||
| 5 | +Entry template: | ||
| 6 | + | ||
| 7 | +``` | ||
| 8 | +## <short symptom> (<error code / OL rule if any>) | ||
| 9 | +- symptom: <observable failure> | ||
| 10 | +- root cause: <why> | ||
| 11 | +- fix: <the correct change> | ||
| 12 | +- source: <docs / lint rule / diary date> | ||
| 13 | +``` | ||
| 14 | + | ||
| 15 | +--- | ||
| 16 | + | ||
| 17 | +## Python `range()` / list-indexing inside `@pl.jit` → F00002 "For loop must use pl.range()" | ||
| 18 | +- symptom: a kernel with a `for kt in range(N)` static-unroll (e.g. to hold N resident A K-tiles in a Python list and index `a_res[kt]`) fails to compile: `ParserSyntaxError F00002, For loop must use pl.range()` (`_control_flow_parser.py:322`). | ||
| 19 | +- root cause: pl's parser requires **every** in-kernel `for` to be `pl.range(...)`; a plain Python `range` is rejected. But `pl.range` makes the index a **traced** value, which then cannot index a trace-time Python list of tiles. | ||
| 20 | +- fix: don't try to hold-and-index N resident tiles by a traced K-index. For A-reuse across the N-loop, use the **single-K-tile** 8K-example structure (`test_matmul_8K_example.py`): load ONE A tile per row-tile `i` (outside the `pl.range(j)` loop) and reuse that single handle inside the j-loop — no kt list. K>128 needs a K-loop, which is a separate `pl.range(kt)` that re-loads per iteration (P4), not resident-and-indexed. So **A-reuse (P6) and multi-K-tile (P4) don't compose via a resident-tile list** in pl; pick the single-K-tile A-reuse for the reuse win. | ||
| 21 | +- source: diary 2026-07-18 (Wave-B kernel 2 v2 `mm_p6`). | ||
| 22 | + | ||
| 23 | +## K-loop matmul with single-buffer staged tiles → aicore timeout (507014) | ||
| 24 | +- symptom: a tiled matmul with an inner K-loop (`matmul` Partial + `matmul_acc` Final) hangs → `507014 aicore timeout` / `AI Core Error` at `torch.npu.synchronize()`. A single-tile matmul (no K-loop) with the same single-buffer tiles runs fine. | ||
| 25 | +- root cause: the K-loop reloads the staged tile group into the **same slot** each iteration; with `auto_mutex` a single-slot buffer cannot resolve the load(k+1)↔compute(k) pipe dependency and deadlocks the AI core. | ||
| 26 | +- fix: **multi-buffer the staged tiles — 2 slots + `.next()`** for `a_l1`/`b_l1`/`a_l0a`/`b_l0b` (mutex_ids `[0,1]`,`[2,3]`,…), exactly as `test_matmul_api_basic.py::t02_rec_nsq_nd_nz_kloop_if`. (The tiled variant of the retained matmul | ||
| 27 | + sample this was found on is not part of this tree.) The `Acc` group stays fixed within one K-loop (`.current()` before the loop) but may be 2-slot `.next()` across output tiles. Single-buffer is only safe for a straight-line kernel with no inner loop reusing the tile (the straight-line tiled matmul this was checked against is not part of this tree). | ||
| 28 | +- **K-accumulation phase logic (N_KT>2 works — the earlier "deadlock" was WRONG phase logic), CORRECTED 2026-07-19.** A long K-loop into ONE Acc tile is fine for arbitrary N_KT **if you use the ASW phase idiom**: the **first** mmad is `matmul(ac, al, br, phase=Partial)`; **every middle** mmad is `matmul_acc(ac, ac, al, br, phase=Partial)`; **only the very last** mmad is `matmul_acc(ac, ac, al, br, phase=Final)`. The repo's `test_matmul_perf_asw_4k_dn_move_offset.py` runs **64 mmads** this way into a single `.current()` Acc and passes. The 507014 timeout happened when `phase=Final` was used on **every** `matmul_acc` (Partial + repeated Final) — that is the wrong logic, NOT an N_KT limit. **VERIFIED 2026-07-19:** fp16 `conv_gemm_k512` with **N_KT=4** (Partial, Partial, Partial, Final) → plain matmul 256×256×512 maxdiff 1.30e-4, conv_half_large K=512 maxdiff 8.39e-5, **no deadlock**. So for K>256 you do NOT need atomic-add chaining or two kernels — one Acc + Partial-until-last handles any K. Keep the Acc fixed within the K-loop (`ac = acc.next()` once before the `kt` loop, `.current()`-style reuse inside). Staged tiles still need 2-slot `.next()` multi-buffering (single-buffer → 507014, unchanged). | ||
| 29 | +- source: diary 2026-07-18/19 (Wave-B kernels 2 & 3; Wave-C fp16 conv — those kernels are not part of this tree), `test_matmul_perf_asw_4k_dn_move_offset.py:158-203` (64-mmad single-Acc), t02 (2-block). | ||
| 30 | + | ||
| 31 | +## fp16 matmul is MTE2-bound, not cube-bound, without data reuse (Gate B) | ||
| 32 | +- symptom: a correct tiled fp16 matmul profiles `aic_mte2_ratio > aic_mac_ratio` (e.g. 0.55 > 0.427), `cube_utilization ~67%` → **data-move-bound**, fails Gate B (compute-bound), even though the same structure in **fp32 is cube-bound** (`aic_mac=0.688`, cube_util 79%). | ||
| 33 | +- root cause: fp16 has the **2× MAC rate** (16,32,16 fractal vs fp32's 0.5× 16,8,16), so it burns MACs fast and the L1→L0 / GM data-move (MTE2) becomes the ceiling. A flattened `(i,j)` tile loop reloads `A[i]` for **every** column tile `j` — no reuse. | ||
| 34 | +- fix: **P6 data reuse** — nest the loops (outer `i` over M-tiles, load `A[i]` **once**; inner `j` over N-tiles, reuse `A[i]`, load `B[j]` per j), the `test_matmul_8K_example.py` structure; and/or P2 bigger tiles / P4 more on-chip K-accum. Cuts A-reloads by `N/128×` → `aic_mte2` drops below `aic_mac`. fp32 kernels often skip this (naturally MAC-heavy); fp16/int8 kernels need it to pass Gate B. | ||
| 35 | +- source: diary 2026-07-18 (Wave-B kernel 2, `mm_kloop`); `cannbot-skills/ops/pypto-pro-op-perf-tune/references/a5-roofline-and-levers.md` (read the dtype MAC rates from the platform files its evidence gate names). | ||
| 36 | + | ||
| 37 | +--- | ||
| 38 | + | ||
| 39 | +## On-device im2col / any GM→UB→GM copy in section_vector → bisheng compiler CRASH ("UB Dead Store Elimination", stack smashing) — box-wide, verified 2026-07-19 | ||
| 40 | +- symptom: a `section_vector` kernel that does `pl.load(ub_tile, gm_in, [off])` then `pl.store(gm_out, ub_tile, [off])` (the GM→UB→GM passthrough copy — the natural on-device im2col gather) fails to compile: `RuntimeError: Failed to compile kernel`, and the bisheng stderr shows `*** stack smashing detected *** : terminated` with `Running pass 'HiIPU UB Dead Store Elimination'` in the LLVM MemorySSA/AliasAnalysis path (`llvm::MemorySSA::OptimizeUses`). It is an internal COMPILER crash (SIGABRT), not a semantic/`F*` error in the kernel. | ||
| 41 | +- root cause: a bug in the box's **bisheng compiler (CANN 9.1.0, the bisheng compiler shipped under `$ASCEND_HOME_PATH/tools/bisheng_compiler`)** "HiIPU UB Dead Store Elimination" optimization pass, triggered by the GM→UB→GM copy idiom. **NOT tile-shape / iteration-count / arithmetic dependent** — reproduced identically across THREE distinct im2col kernel structures (flat 72-iter tiny `[8,8]` tiles; 2-level nested; wide `[8,64]` 9-iter full-width stores). **DECISIVE:** the REPO'S OWN `datacopy/test_set_stride.py::set_stride_basic_kernel` (fp16, `[2,128]` tile, the documented on-device strided-gather primitive) crashes with the **byte-identical** stack-smash in the same pass on this box. So the on-device gather primitive itself is non-functional here. | ||
| 42 | +- fix / workaround: **do im2col on the HOST** (`torch.unfold` / channels-last reshape) and run the tile-aligned GEMM on device (proven `mm_f32_kloop`, GM→L1 operand load only). This is a fully valid "conv lowered to GEMM" twin and is the delivered path (the two conv twins this was delivered on are not part of this tree, , Gate A 1.14e-5). The other on-device route — assembling the multi-tap patch directly in an **L1 (Mat) tile** via `insert` into an NZ tile — is ALSO blocked, by the unresolved attention **handoff2** NZ-fractal bug (computed/assembled matmul-LEFT operand corrupts), so it is not an escape. On-device im2col needs either a fixed bisheng toolchain (for the UB path) or the NZ-L1-insert fractal spec (for the L1 path). | ||
| 43 | +- diagnostic: to see the real crash (the harness greps it away), run pytest piped to `tail -70` not `grep GATEA|passed|failed` — the `stack smashing` line and the crashing pass name only show in full output. | ||
| 44 | +- source: diary 2026-07-19 (conv Wave-C, on-device im2col attempt, 3 kernel variants + repo set_stride repro); box `pypto_pro_9688_2`, env `pypto-pro-l00276318`. | ||
| 45 | + | ||
| 46 | +## Host Python `for`-loop drives the kernel per chunk (OL45, S0) | ||
| 47 | +- symptom: only the first chunk runs; lint blocks the Write/Edit. | ||
| 48 | +- root cause: chunk iteration placed in Layer K (host wrapper) instead of the JIT graph. | ||
| 49 | +- fix: move iteration into Layer I as `pypto.loop(NT)` + `pypto.view(offsets=[nt*BT, …])`; call the JIT entry exactly once. | ||
| 50 | +- source: `pypto-op-develop/references/pypto-kernel-design-format.md` §9a. | ||
| 51 | + | ||
| 52 | +## Redundant `pypto.loop(1)` around an inner `pypto.loop(N)` (OL46) | ||
| 53 | +- symptom: lint warns; wasted layout wrapper. | ||
| 54 | +- root cause: defensive `pypto.loop(1)` added even though a real loop exists. | ||
| 55 | +- fix: `pypto.loop(1)` is only for a vector-pipe op with no other loop (OL23). Remove it otherwise. | ||
| 56 | +- source: kernel-design-format §11b. | ||
| 57 | + | ||
| 58 | +## Runtime pypto_pro ≠ the kb repo checkout (version skew) — `is_transpose` etc. — RESOLVED 2026-07-18 on `pypto-pro-l00276318` | ||
| 59 | +- status: **RESOLVED** on the a5 box env `pypto-pro-l00276318` — it was rebuilt from `_2` (an editable `pip install -e . --no-build-isolation` from the second local checkout, 2026-07-18), so `import pypto_pro`/`import pypto` now both resolve to `_2/python`. `test_fa_bsnd_dn.py::test_fa_bs_a5` (the `is_transpose` path) now PASSES on this env. History kept below because the trap recurs on **any env whose editable install points at a different checkout** — re-check whenever you move to a new box/env. | ||
| 60 | +- symptom: a kernel that parses in the kb repo fails on the box with e.g. `F00002 ... _ir_load_tile() got an unexpected keyword argument 'is_transpose'` (`test_fa_bsnd_dn.py:443`). | ||
| 61 | +- root cause: the conda env's `pypto_pro` is an **editable install pointing at a different checkout** than the repo you edit. Before the rebuild, env `pypto-pro-l00276318` resolved `import pypto_pro` to a separate harness checkout owned by another user, NOT the `_2` clone. The two diverge on advanced APIs: `_2` spells matmul transpose `load_tile(..., is_transpose=True)`; the harness lib spells it `pl.load(..., order=[...])` (via `_resolve_order`), and lacks `test_matmul_api_basic.py`; its FA tests are VF-softmax (`test_fa_with_mask.py`, `test_fa_tilingkey_attn_mask.py`). | ||
| 62 | +- fix: (1) ALWAYS check `python -c 'import pypto_pro; print(pypto_pro.__file__)'` first and author against THAT library's API + tests; (2) if it points away from the repo you edit and you own the env, rebuild it from your checkout — `pip install -e . --no-build-isolation` after backing up the old `.pth`+dist-info (fast file-copy rollback); (3) core APIs are common and validate everywhere regardless (`make_tile_group`, `section_cube/vector`, `pl.load/move/matmul/store`, `row_max/...`); only advanced APIs (transpose spelling, `load_tile`) diverged. | ||
| 63 | +- source: diary 2026-07-18 (found during the fused SDPA validation; resolved by the env rebuild the same day). | ||
| 64 | + | ||
| 65 | +## Native scan/reduction over a long axis → UB OOM (F40005) | ||
| 66 | +- symptom: `F40005: 256000 > 196608` on e.g. `pypto.cumsum` over a 4000-long axis. | ||
| 67 | +- root cause: single-op UB footprint exceeds the 192 KB UB budget. | ||
| 68 | +- fix: block the axis (length `T` fits UB), loop the few blocks, carry the accumulator across blocks; keep the vec tile small and independent of `T`. | ||
| 69 | +- source: kernel-design-format §9c. NOTE: the `196608`/`F40005` cap is the **graph-frontend/SIM** allocator — on the **pl** path it does not fire (next entry). | ||
| 70 | + | ||
| 71 | +## pl on-chip budgets: the "enforced" 192 KB/128 KB figures don't bind; oversize is a runtime device fault (verified 2026-07-18) | ||
| 72 | +- symptom: a pl kernel whose UB tiles sum to >192 KB (`196608`) runs fine; a much larger one dies not at compile but at run with `npuSynchronizeDevice ... device error type 3, error code 507035` (UB) / `507015` (L0C), no `F40005`. | ||
| 73 | +- root cause: `F40005`/`PipeConfig` (`ubSizeThreshold=196608`, `l0c=131072`) are enforced by the **graph-frontend / `RunMode.SIM`** allocator; the **pl tile DSL has no SIM** (compiles via bisheng straight to NPU), so it is bounded by the **physical** buffer and over-subscription surfaces as a **runtime NPU device fault**, not a compile-time size check. | ||
| 74 | +- fix / measured: on a5 (env `pypto-pro-l00276318`, box `_2`), growing the softmax sample's UB tiles → **259072 B (253 KB) allocates + computes bit-exact; 265216 B (259 KB) faults (507035, reproduced; also faults at 271360 B)** ⇒ usable UB ≈ **256 KB** (`262144` sits inside the [259072, 265216) bracket; above even the `253952` ini figure), NOT 192 KB. Size pl tiles to the physical buffer, not the enforced column; expect a device fault (not `F40005`) if you overshoot. | ||
| 75 | +- **method caveat 1 — golden-check the pass side:** a memory-budget probe MUST correctness-check the pass side with a golden — "did not fault" ≠ "correct". This caught the first L0C probe's "OK"s as false (`maxdiff=3.07e+01`). | ||
| 76 | +- **method caveat 2 — custom cube/matmul probes could NOT reproduce the repo's passing tests (why L0C stays unverified):** a probe kernel **byte-identical to the repo's passing `t14_rec_sq_nd_nz_single` (128³ square NN)** produced wrong numerics / `507015` device faults — tried three ways: bare-script factory, bare-script module-global, AND a pytest file under the a5 `conftest` (inline, uniquely-named) — while the repo's own `t01`/`t14` + softmax pass **reliably on the same healthy device** (checked before and after each attempt). Because the kernel is identical to a passing one, the fault is in the **test scaffolding** (input generation / golden / invocation context). **RESOLVED 2026-07-18 — the reliable cube dev methodology is now PROVEN.** A bisection test (`test_matmul_p0.py`) placed in the repo dir `python/tests/ut/block/frontend/a5/matmul/`, that (1) `from test_matmul_api_basic import _inputs, _run, _require_a5` (the repo helpers), (2) defines a **new** kernel that is a verbatim copy of `t14`, and (3) runs via `python -m pytest` — **PASSES** (both the repo's t14 and my copy, 2 passed in 261s). So a *new* cube kernel authored this way works; only the hand-rolled scaffolds (bare `python file.py`; a custom `_check`/input-gen; a wrong L1 addr `0x40000` vs the template's `0x10000`) failed. **The `arch="a5"` kwarg is NOT the fix** — a standalone probe with `@pl.jit(auto_mutex=True, arch="a5")` still garbaged (maxdiff ~50). Methodology (use for every cube/fused kernel): **author it as a pytest test file in `.../a5/<class>/`, import the repo's `_inputs`/`_run`/`_require_a5`, copy the tile-group structure verbatim from a passing template (addrs included), run under `python -m pytest`.** Do NOT hand-roll a standalone script. L0C byte cap left honest-unverified; keep `m·n·4 ≤ 128 KB`. Documentary bound: `test_matmul_8K_example.py` tiles at `[128,128]` (64 KB Acc, below the L0C budget), so production matmul tiles under the byte cap. (Probes caused transient `507015`/`507035` faults but the device auto-recovered — t01 passed after each — so no shared-box harm; still, prefer the repo's own tests over custom cube probes on shared hardware.) | ||
| 77 | +- source: diary 2026-07-18 (hardware back-fill probes); `constraints/arch-a5.md`, `vec.md`, `memory-layout.md`, `tail-validshape.md`. | ||
| 78 | + | ||
| 79 | +## Fused multi-section cube→vector→cube: (1) missing M→FIX sync before store leaks stale Acc; (2) alias distinct Acc addrs (verified 2026-07-19, attention) | ||
| 80 | +- context: full single-block attention `out=softmax(q@k)@v` fp16 64x64 = 3 sections (QK cube → softmax vector → PV cube), the k7 (QK→softmax) composition + a second matmul (handoff2). | ||
| 81 | +- symptom 1 — **stale-Acc leak**: run1 `maxdiff=31.8` (100% mismatch) and `out` ≈ raw QK scores magnitude; changes to the vector/softmax section had **zero effect on the number** (the tell: output never flowed through that section). | ||
| 82 | +- root cause 1: section-3 did `pl.matmul(pv_acc,...)` then `pl.store(out, pv_acc)` with **NO `M→FIX` sync between** — the store (FIX pipe) raced the matmul writeback (M pipe) and emitted whatever sat in L0C. AND `pv_acc` was allocated at the **same Acc addr `0x0000` as section-1's `qk_acc`**, so the leaked L0C content was exactly the stale QK scores. | ||
| 83 | +- fix 1 (both needed): (a) `pl.system.sync_src/sync_dst(set_pipe=M, wait_pipe=FIX, event_id=0)` **before** every `pl.store` that reads an Acc tile (mirror the M→FIX sync you already put before a `pl.move(...DualModeSplitM)`); (b) give each Acc tile in a multi-matmul kernel a **distinct addr** (qk_acc 0x0000, pv_acc 0x4000) so a missing/incomplete sync can never silently pass a prior matmul's result through. Also add the `MTE2→MTE1` sync between `pl.load(v_mat)` and `pl.move(v_right, v_mat)` (every load→move needs it; section 1 had it, section 3 had dropped it). Result: `maxdiff 31.8 → 4.52`. | ||
| 84 | +- **general rule: EVERY pipe transition needs an explicit `sync_src`+`sync_dst`** (MTE2→MTE1 after a load, MTE1→M before a matmul, M→FIX before a fixpipe move/store, V→MTE3 before a vector store). A dropped sync at the *end* of a section is easy to miss because the section "looks done". Diagnostic that nails it fast: in the test, `print((out - <stale_candidate>).abs().max())` — if ≈0, you're emitting the stale buffer, not computing. | ||
| 85 | +- symptom 2 — **handoff2 partial-P corruption (UNRESOLVED)**: after fix 1, `maxdiff=4.52`; disambiguation proved softmax IS applied (vs no-softmax `sc@v`=247, rejected), `out` is closest to `P@v` but not clean, and out rowsums show SOME rows ~correct O(1) and SOME ~10× inflated ⇒ **partial row corruption of P**. | ||
| 86 | +- **DECISIVE ISOLATION 2026-07-19 (P-dump probe):** added a `p_dbg` output and stored P straight from UB right after `row_expand_div` (fresh, non-in-place tile). Result: **P-in-UB vs `torch.softmax(q@k)` = 0.0 (byte-perfect)**, but **`p_dbg@v` vs kernel `out` = 3.35** ⇒ softmax/scores are PERFECT and the PV matmul reads a **corrupted P from L1**. Also rewrote the whole kernel in **fp32, 2-section, mirroring the PASSING repo test `test_matmul_add_matmul_add.py`'s exact handoff2** (`move(tile_nz,tile_out)` ND2NZ → `insert(L1,[off,0])` → cube `move(q_left, L1)` → matmul; same addresses q/k/v 0x0/0x4000/0x8000, computed-tile L1 0x10000; same cross-core event 2) — **STILL fails (maxdiff 3.35).** The only source-level difference from that passing test is the vector op (softmax vs `add`) and the P values (small, all-positive). Fresh-tile (advisor in-place hypothesis) did NOT fix it. ⇒ the bug is a **runtime NZ-layout/fractal behavior of the computed-tile→L1→matmul-LEFT path that is not visible in source** and does not reproduce from mirroring a passing test. **Ruled out:** stale-Acc (fixed), `[off,0]` offset, fp16 cast, in-place authoring, section count, addresses, softmax. **Next-session hand-off (needs DSL layout spec / maintainer):** dump the L1 P bytes (not UB) to GM to inspect the fractal directly; or find a repo test whose computed matmul-LEFT operand is a *softmax/normalized* tile; or ask whether `insert` into an NZ L1 tile requires a specific source fractal that `move(...,NZ)` from a vector-computed (DualModeSplitM-sourced) tile doesn't produce. Scratchpad: `test_attn_f32.py` (instrumented). **Timeboxed: 5 attempts, pivoted per advisor — attention is 1 of ~35 kernels and blocks only the ~6-8 attn variants, not the corpus.** | ||
| 87 | +- suspected cause 2 (SUPERSEDED by the isolation above): NOT the `[off,0]` offset. Rewrote handoff1 to `SingleModeVec0` (whole [64,64] scores → ONE sub-block), did the FULL softmax there, and inserted the whole P at `[0,0]` (no row offset, no 2-sub-block reassembly). Result was **byte-identical `maxdiff=4.5208`** ⇒ the P bytes in L1 are the same regardless of single/dual sub-block, so the `[off,0]` insert was **not** corrupting. The real suspect is the **UB→UB NZ reformat `pl.move(p_nz, p16)` (DN fp16 → NZ fp16)** or the fractal P must carry as a matmul LEFT operand: q's path (GM→L1 NZ via `pl.load` → L0A) works, but P's path (UB fp32 → cast fp16 → UB NZ move → L1 insert → L0A) may not produce the fractal the cube expects. `out` is partially right (some rows ≈ correct, `vs P@v`=4.52 is the closest hypothesis; softmax IS applied), consistent with a fractal/reformat scramble not a total-garbage bug. STATUS: isolated, gates only ~6-8 attention-family kernels; needs the DSL NZ-fractal spec (or a repo example of a UB-tile→L1→matmul-left-operand path) to resolve. The other ~25 corpus kernels compose from proven patterns and do not touch handoff2. Deferred per allocation. **Next probe when resumed:** find a repo test that feeds a *computed* (not GM-loaded) tile as a matmul left operand and copy its exact reformat sequence; or dump P from L1 to GM to inspect the fractal directly. | ||
| 88 | +- source: diary 2026-07-19; advisor-confirmed sync diagnosis. The instrumented reproducer this entry was written from is **not retained in this KB**, so the progress log above is the record. The rule it reduces to — cross-section and AIC/AIV handoff is not implied by `auto_mutex`, and its event sequence must be copied from an official example for the installed SDK — is `cannbot-skills/kb/constraints/sync-stitch.md`. | ||
| 89 | + | ||
| 90 | +## Attention handoff2 — STRONG LEAD (2026-07-21, code-reading; NOT yet hardware-tested) | ||
| 91 | + | ||
| 92 | +**The probe copied the wrong passing template.** Three data points, read ACROSS not down: | ||
| 93 | + | ||
| 94 | +| vector op | L1 recipe | result | source | | ||
| 95 | +|---|---|---|---| | ||
| 96 | +| plain `add` | NZ L1 + ROW offset `[off,0]` | **passes** | `a5/matmul/test_matmul_add_matmul_add.py` (+ `docs/test_doc_memory_movement.py:insert_matmul_kernel`, `matmul/test_single_dst.py`) | | ||
| 97 | +| **softmax** | NZ L1 + ROW offset `[off,0]` | **FAILS (3.35)** | our attention probe | | ||
| 98 | +| **softmax** | **ZN L1 + COLUMN offset + contraction-major + padded `tile_nz`** | **passes on a5** | `a5/fa/test_fa_bsnd_dn.py` (box-validated, diary 2026-07-18) | | ||
| 99 | + | ||
| 100 | +- **Provenance is RULED OUT.** `test_matmul_add_matmul_add.py` feeds a `DualModeSplitM`-sourced | ||
| 101 | + tile into a matmul LEFT operand and passes; FA feeds a `DualModeSplitN`-sourced, *softmax-computed* | ||
| 102 | + tile and passes. "DualModeSplitM as source" was never the discriminator. | ||
| 103 | +- **Layout alone is NOT the discriminator either** — NZ+row works fine for a plain `add`. | ||
| 104 | + The real statement is the **interaction**: a *softmax-computed* operand appears to need FA's | ||
| 105 | + ZN+column recipe; NZ+row only survives a plain `add`. | ||
| 106 | +- Verified in-file: `test_fa_bsnd_dn.py` declares `p_mat_type ... layout=pl.ZN`; inserts at a | ||
| 107 | + **column** offset `pl.insert(p_mat_buf1, tile_nz, [0, TS_HALF * sub_id])`; the operand `p_f16` is | ||
| 108 | + `[TKV, TS_HALF]` (contraction-major, i.e. P^T); and it carries a maintainer warning: | ||
| 109 | + *"Keep the source descriptor identical to the proven DN perf kernel. TMOV(tile_nz, p_f16) is | ||
| 110 | + sensitive to the Vec tile descriptor here."* | ||
| 111 | + | ||
| 112 | +**NEXT ACTION: port FA's insert/reformat recipe WHOLESALE to single-block attention.** FA differs | ||
| 113 | +from our probe on several axes at once (ZN layout, column offset, contraction-major operand, padded | ||
| 114 | +`tile_nz`, fp16-vs-fp32) — **do not assume which one is load-bearing.** Port it whole; if it passes, | ||
| 115 | +revert pieces one at a time to find the minimal fix. | ||
| 116 | + | ||
| 117 | +**Trap:** `a5/matmul/test_insert_left.py` / `test_insert_right.py` have comments describing FA's ZN | ||
| 118 | +recipe ("declared ZN (FA's p_mat)", "Mat(ZN) -> Left(NZ): SFractal mismatch -> TRANSPOSE") but the | ||
| 119 | +code declares `layout=pl.NZ`. Comments and code disagree — trust the code, or better, copy FA itself. | ||
| 120 | + | ||
| 121 | +**Status: code-reading only, no box run.** Evidence is repo source + previously-validated FA runs. | ||
| 122 | + | ||
| 123 | +## Box iteration harness: interactive shell-prompt matching HANGS — use `ssh host <command>` (2026-07-21) | ||
| 124 | + | ||
| 125 | +- **symptom:** an `expect` harness that spawns an interactive `ssh`, then drives it with | ||
| 126 | + `send "<cmd>\r"` / `expect -re {[#$] $}` between steps, hung indefinitely — 25 min with **zero | ||
| 127 | + bytes** of output and ~0% CPU. The connectivity probe using the same prompt pattern had worked | ||
| 128 | + minutes earlier, so the pattern is not reliably wrong, just fragile. | ||
| 129 | +- **contributing trap:** piping the harness through `| tail -N` locally makes the output file stay | ||
| 130 | + **empty until the pipeline ends**, so a hang and a slow compile look identical. Redirect to a log | ||
| 131 | + file instead (`> run.log 2>&1`) and tail *that* — then partial progress is visible. | ||
| 132 | +- **fix (now the standard):** do not drive an interactive shell. Pass the whole remote command as | ||
| 133 | + an argument — `spawn ssh -tt -p $port $user@$host $cmd` — so there is exactly ONE password prompt | ||
| 134 | + and no prompt-pattern matching at all. Handle the prompt with | ||
| 135 | + `expect { -re {[Pp]assword:} { send "$pw\r"; exp_continue } eof {} }`. Wrap the remote pytest in | ||
| 136 | + `timeout 1000 ...` so a remote hang cannot stall the harness either. Working script pattern: | ||
| 137 | + scratchpad `runk2.exp`. | ||
| 138 | +- **payoff:** the same kernel that "hung" then ran in **14 s** — the box was never slow; cube | ||
| 139 | + compiles for these small kernels are ~15-18 s, NOT the ~2 min assumed earlier in the build. | ||
| 140 | +- **credentials:** keep host/port/user/password in **env vars passed to the harness**, and keep the | ||
| 141 | + harness in the session scratchpad — never in the repo. (The repo was scrubbed of an inline box | ||
| 142 | + login on 2026-07-20; do not reintroduce one.) | ||
| 143 | + | ||
| 144 | +## Multicore-tiled AND two-section (cube+vector) in ONE kernel: not yet achieved (2026-07-21) | ||
| 145 | + | ||
| 146 | +- **goal:** a scaled cube→vector `DualModeSplitM` handoff kernel, to convert the k5/k9/k13 | ||
| 147 | + "Gate B by class arg" into a measured `aiv>0` number. | ||
| 148 | +- **symptom:** at 1024×1024×64 / TILE=128 / `kernel[None, 32]`, the two-section kernel produced | ||
| 149 | + `out` **entirely zero** — `nonzero frac = 0.0000`, `vs zeros = 4.9e-43`, maxdiff == `max|ref|` | ||
| 150 | + exactly. The `section_vector` store never landed. No hang, no device fault; it "ran" in 62 s. | ||
| 151 | +- **ruled out:** ping-pong buffering of the shared `mm_res` (2-buffer `make_tile_group` with its own | ||
| 152 | + mutex ids) changed the result **not at all** (38.96 → 39.45) ⇒ per the standing heuristic, the | ||
| 153 | + output never flowed through the vector section, so the bug is upstream of the race I fixed. | ||
| 154 | +- **hypothesis (UNVERIFIED, for the next session):** the **multicore launch `kernel[None, cores]` | ||
| 155 | + does not dispatch `section_vector`.** Evidence is circumstantial but consistent: every proven | ||
| 156 | + two-section fused sample (k5 `fused_matmul_add`, k9/k11/k13, P1) is launched as a **plain | ||
| 157 | + single-core call**; every proven multicore-tiled sample (k1, k14, `mm_fixpipe`) is **cube-only**. | ||
| 158 | + No existing sample is both. Next probes: (a) launch the two-section kernel as a plain call and | ||
| 159 | + see if the store lands; (b) check whether a vector section needs its own block/subblock mapping | ||
| 160 | + under `[None, cores]`; (c) find any repo test that is multicore-tiled AND has a vector section. | ||
| 161 | +- **also relearned (cost one device fault):** hand-rolling the tiled cube structure with | ||
| 162 | + `@pl.jit()` + `make_tile` + manual sync **device-faulted 507015**, while the verbatim | ||
| 163 | + `@pl.jit(auto_mutex=True)` + `make_tile_group` copy of the proven reproducer ran bit-exact. | ||
| 164 | + Copy the tiled template; do not re-derive it. (Same lesson as method-caveat-2.) | ||
| 165 | +- **do NOT report a utilization number for a kernel whose Gate A failed** — the harness now skips | ||
| 166 | + profiling in that case. A fast wrong kernel is not a Gate-B result. | ||
| 167 | + | ||
| 168 | +## Shared-box CONTENTION looks exactly like a broken kernel — diagnose it before debugging code (2026-07-21) | ||
| 169 | + | ||
| 170 | +- **symptom:** three consecutive runs hung with **zero output** and were killed by the remote | ||
| 171 | + `timeout`. Easy to misread as "bf16 is unsupported", "the kernel factory is broken", or "I wedged | ||
| 172 | + the device". All three were wrong. | ||
| 173 | +- **decisive diagnostic, in order (all read-only, ~1 min):** | ||
| 174 | + 1. Add `MARK:` prints around each phase. The trace stopped between `test entered` and | ||
| 175 | + `device ok` ⇒ it hangs in **`torch.npu.set_device`**, i.e. acquiring the device — before any | ||
| 176 | + kernel code runs. That alone exonerates the kernel. | ||
| 177 | + 2. Run the repo's **own** known-good test (`test_matmul_api_basic.py::test_t01`). It also timed | ||
| 178 | + out (`exit 124`) ⇒ not our code at all. | ||
| 179 | + 3. `fuser -v /dev/davinci*` → list the processes actually holding the NPU, then | ||
| 180 | + `ps -o pid,lstart,etime,user,cmd -p <pid>` on each to see **whose** they are. | ||
| 181 | +- **what it actually was:** 8 concurrent NPU jobs from OTHER users — two `pytest ut/block/language/` | ||
| 182 | + (1 h+), a full-suite `pytest .`, `./test_aclnnop`, `pytest st/block/frontend/a5/`, a datacopy test, | ||
| 183 | + a `deepseekv32_sparse_attention` model run, and an `RMSNorm` test under a different user's conda | ||
| 184 | + env. A grep for our own test filenames returned **nothing** — we had left no orphans. | ||
| 185 | +- **note `npu-smi info` says `Ascend950 OK` even while the device is saturated.** "OK" is a driver | ||
| 186 | + health flag, NOT an availability flag. Do not read it as "free". | ||
| 187 | +- **rule:** on this shared box, before debugging a hang as a code bug, check device holders. And | ||
| 188 | + when contention is found, **stop issuing NPU work** — do not reset the device and do not kill | ||
| 189 | + processes; they belong to other people. Earlier runs that same morning (~07:00-07:30) passed | ||
| 190 | + fine; the contention began ~07:38. | ||
| 191 | + | ||
| 192 | +## L0C / L0A / L0B byte caps — MEASURED 2026-07-21 (resolves the long-standing "honest-unverified" flag) | ||
| 193 | + | ||
| 194 | +The kb carried L0C as **unverified** since 2026-07-18 with a documentary bound of 128 KB | ||
| 195 | +("keep m·n·4 ≤ 128 KB"). Both caps are now pinned by direct probe on a5, bf16 operands / fp32 Acc: | ||
| 196 | + | ||
| 197 | +| probe | on-chip demand | result | | ||
| 198 | +|---|---|---| | ||
| 199 | +| T=256, K=128 | **Acc = 256 KB**, L0A/L0B = 64 KB | ✅ **allocated AND computed correctly** (rel 2.5e-3) | | ||
| 200 | +| T=256, K=256 | Acc = 256 KB, **L0A/L0B = 128 KB** | ❌ device fault **507015** | | ||
| 201 | + | ||
| 202 | +- **L0C ≥ 256 KB** — DOUBLE the documented 128 KB figure. A `[256,256]` fp32 accumulator is legal. | ||
| 203 | + This also means the Acc can be **double-buffered at T=128** (2 × 64 KB = 128 KB). | ||
| 204 | +- **L0A / L0B = 64 KB each** — the documented figure is correct, and it is the BINDING constraint: | ||
| 205 | + `T·K·(dtype bytes) ≤ 64 KB` ⇒ for bf16 **`T·K ≤ 32768`**. You may have large T *or* large K, | ||
| 206 | + never both. Measured corners: (T=128,K=256) and (T=256,K=128) both legal; (256,256) faults. | ||
| 207 | +- **Correctness caveat honoured:** the passing probe was golden-checked, not merely "did not fault" | ||
| 208 | + — the earlier L0C investigation was derailed exactly by treating no-fault as success. | ||
| 209 | +- Attribution note: the 507015 at (256,256) is an **L0A/L0B** overflow, not L0C — L0C at 256 KB was | ||
| 210 | + independently proven by the passing (256,128) case. Do not record it as "L0C < 256 KB". | ||
| 211 | + | ||
| 212 | +## Never compare `aicore_time` across different problem shapes — normalise to MMAC/µs (2026-07-21) | ||
| 213 | + | ||
| 214 | +- **symptom:** an optimisation ladder appeared self-contradictory — the *naive* bf16 kernel had the | ||
| 215 | + **lowest** `mac_ratio` (0.181) yet also the **lowest** `aicore_time` (2.90 µs), seemingly "fastest | ||
| 216 | + while least efficient". | ||
| 217 | +- **root cause:** the rows were **different problem sizes**. The naive row was M=N=1024,K=64 | ||
| 218 | + (67.1M MACs); the optimised rows were M=4096,N=1024,K=256 (1073.7M MACs) — **16× the work**. Low | ||
| 219 | + `aicore_time` just meant less work, not more speed. | ||
| 220 | +- **fix / rule:** ratios (`aic_*_ratio`, `cube_utilization`) are dimensionless and comparable across | ||
| 221 | + shapes; **absolute times are not.** Normalise: `MMAC/µs = M·N·K / aicore_time`. Under that metric | ||
| 222 | + the same ladder is monotonic — 23.1 → 57.1 → 91.5 → 104.9 → **108.2 MMAC/µs (4.7×)**. | ||
| 223 | +- **report BOTH numbers.** `mac_ratio` answers *"is the cube the bottleneck?"*; MMAC/µs answers | ||
| 224 | + *"is it actually fast?"* They can move in **opposite** directions: bf16 vs fp32 at identical shape | ||
| 225 | + gives `mac_ratio` 0.181 vs 0.689 (bf16 far worse) but 23.1 vs 8.5 MMAC/µs (bf16 **2.7× faster**). | ||
| 226 | + Optimising `mac_ratio` alone can make a kernel slower. | ||
| 227 | +- **useful decomposition:** throughput gain = (gain in `mac_ratio`, i.e. cube busy more often) | ||
| 228 | + × (gain in MACs per busy µs, i.e. bigger K amortising per-`pl.matmul` and fractal-fill overhead). | ||
| 229 | + Here 4.7× = 3.2× × 1.46×. `mac_ratio` captures only the first factor. | ||
| 230 | +- **whenever a table mixes shapes, add an explicit shape column** — the omission is what made this | ||
| 231 | + look like conflicting data. | ||
| 232 | + | ||
| 233 | +## A high AIC sub-ratio does NOT mean that pipe is the bottleneck (2026-07-21, 2D-grid negative result) | ||
| 234 | + | ||
| 235 | +- **prediction:** bf16 GEMM sat at `mac=0.580, mte2=0.524`. mte2 looked like the limiter, so a 2D | ||
| 236 | + core grid (Gi=8×Gj=4, each core holding its B tiles resident) was built to cut GM traffic ~33%. | ||
| 237 | +- **measured:** mte2 fell **40%** (0.524 → 0.313) — better than predicted — but the kernel got | ||
| 238 | + **SLOWER**: 109.0 → 102.4 MMAC/µs, aicore 9.85 → 10.49 µs, and **mac FELL 0.580 → 0.542**. | ||
| 239 | + Both kernels correct and fully covering (`rel=2.804e-03`, `nonzero=1.0`), so this is a real | ||
| 240 | + perf result, not a coverage artifact. | ||
| 241 | +- **root cause:** mte2 was **already overlapped with MAC** — it was never on the critical path. | ||
| 242 | + Removing 40% of a non-critical pipe frees nothing, and the restructure cost schedule quality: the | ||
| 243 | + 2D grid shortens the inner loop from 8 matmuls per A-load to 2, so fixed per-iteration overhead | ||
| 244 | + amortises over less work and there is less latency to hide (mte1 rose 0.173 → 0.199). | ||
| 245 | +- **rule:** a sub-ratio measures **occupancy, not causality**. Before optimising a pipe, verify it | ||
| 246 | + is on the critical path — cut it and check `aicore_time` actually falls. Corollary: two levers | ||
| 247 | + that each "should" help can conflict, because traffic reduction and pipelining depth trade off. | ||
| 248 | +- **also corrects an earlier inference in this same session:** multi-buffering buying only +0.010 | ||
| 249 | + was read as "mte2 is bandwidth-bound". Combined with this result the correct reading is the | ||
| 250 | + opposite — the kernel is **schedule/dependency-limited in a roughly MAC↔MTE2-balanced regime**. | ||
| 251 | + | ||
| 252 | +## `tile_group.current()` does NOT advance the rotation — `.next()` does. Multi-buffering is INERT without it (2026-07-21) | ||
| 253 | + | ||
| 254 | +- **the trap:** `pl.make_tile_group(..., mutex_ids=[a, b])` declares N buffers, but you only get | ||
| 255 | + rotation if you access it with **`.next()`**. `.current()` returns the SAME buffer every time. | ||
| 256 | + A kernel that declares 2–4 buffers and calls `.current()` in the loop is **single-buffered**, | ||
| 257 | + silently — it costs the extra L1/L0 capacity and delivers none of the overlap. | ||
| 258 | +- **canonical idiom** (`a5/matmul/test_matmul_8K_example.py`, the repo's perf workhorse): | ||
| 259 | + - `addrs=<scalar base>` + `mutex_ids=[...]` — N ids = N buffers laid out from the base. | ||
| 260 | + (A list of addrs also works, e.g. `lightning_indexer`, but scalar+ids is the common form.) | ||
| 261 | + - **`.next()` for every STREAMING operand** (B, L0A/L0B, Acc). | ||
| 262 | + - **`.current()` ONLY to REUSE a resident operand** — e.g. A inside the j loop after loading it | ||
| 263 | + with `.next()` in the outer loop. | ||
| 264 | +- **cost of getting this wrong here:** every "multi-buffered" kernel in this session was actually | ||
| 265 | + single-buffered. It made adding a second buffer look worthless (+0.010) and produced TWO wrong | ||
| 266 | + conclusions that had to be retracted: (1) "mte2 is bandwidth-bound, pipelining cannot help"; | ||
| 267 | + (2) "K=128 double-buffered is worse than K=256 single" (measured 75.8 vs 108.1 MMAC/µs — but the | ||
| 268 | + K=128 buffers never rotated). With real rotation **K=128 wins decisively**: mac 0.870, | ||
| 269 | + 179.9 MMAC/µs vs 108.6. | ||
| 270 | +- **diagnostic:** if adding a buffer changes performance by <2%, suspect inert rotation before | ||
| 271 | + concluding the pipe is not the bottleneck. Grep the kernel for `.current()` in a loop body. | ||
| 272 | +- **related correctness trap:** a buffer written once per OUTER iteration and read across the whole | ||
| 273 | + inner loop (the reused A operand in L0A) needs a SECOND buffer once the outer loop pipelines, | ||
| 274 | + or row i+1's move races row i's matmuls. At K=256 an L0A tile is 64 KB (the whole cap) so it | ||
| 275 | + CANNOT be doubled — that config returned `rel=1.045` (wrong) with deep buffering. **Correctness | ||
| 276 | + of the deep-pipelined form is gated on K ≤ 128.** | ||
| 277 | + | ||
| 278 | +## Utilisation is a RATIO — it rises when the kernel gets faster, not only when a pipe gets busier (2026-07-21) | ||
| 279 | + | ||
| 280 | +- **symptom / question raised:** fixpipe utilisation jumped 29.1% → 82.9% between two variants and | ||
| 281 | + looked like a regression, "but the shape is the same so the bytes should be the same". | ||
| 282 | +- **two separate corrections:** | ||
| 283 | + 1. **The shapes were NOT the same** (M 8192→16384, K 256→128), so output bytes doubled | ||
| 284 | + 16.78 → 33.55 MB. Note the two variants do **identical total MACs** (2.147e9): halving K | ||
| 285 | + halves MAC work per output tile, so 2× the tiles — and each still costs a full `T×T` drain. | ||
| 286 | + ⇒ **fixpipe bytes per unit MAC work ∝ 1/K.** | ||
| 287 | + 2. **The denominator shrank.** `aicore_time` fell 16.95 → 11.94 µs because the kernel got faster. | ||
| 288 | + Exact decomposition: bytes ×2.00, fixpipe bandwidth ×1.00 (**constant ~3.4 TB/s — the pipe | ||
| 289 | + behaved identically**), so fixpipe time ×2.01; aicore_time ×0.70; utilisation ×2.85 ⇒ | ||
| 290 | + 29.1% × 2.85 = **82.9%, matching the measurement exactly.** Roughly half the jump is purely | ||
| 291 | + the faster kernel. | ||
| 292 | +- **rule:** before reading a utilisation change as a regression, compute the pipe's **achieved | ||
| 293 | + bandwidth** (bytes ÷ pipe-time). If bandwidth is unchanged, the pipe is fine and the ratio moved | ||
| 294 | + because of byte count and/or total-time changes. Same family of error as comparing `aicore_time` | ||
| 295 | + across different shapes. | ||
| 296 | +- **glossary:** `aicore_time` = time the **AIC (cube unit)** was busy on this kernel — NOT | ||
| 297 | + wall-clock (`Duration(us)` is larger and includes launch/dispatch). `aiv_time` is the vector | ||
| 298 | + engine (0 in cube-only kernels). Every `aic_*_ratio` is normalised by `aicore_time`. | ||
| 299 | + | ||
| 300 | +## Vector kernels: bare make_tile misses auto_mutex sync for COMPUTED tiles (2026-07-22) | ||
| 301 | +- symptom: a layernorm computed `maxdiff≈5-7` (wrong, no error) while its normalization was exact | ||
| 302 | + (bisect: normalization-only = 9.5e-7, gamma-only = 1.9e-6, +beta = wrong). | ||
| 303 | +- root cause: `auto_mutex` tracks cross-op read-after-write hazards **only for `make_tile_group`**. | ||
| 304 | + A bare `pl.make_tile` that is WRITTEN by one op (`negbeta = pl.mul(beta,-1)`) and READ by a later | ||
| 305 | + op (`col_expand_sub(out, xc, negbeta)`) is NOT synced -> the reader sees stale/garbage data. | ||
| 306 | + A LOADED bare tile (gamma) happened to work; a COMPUTED bare tile (negbeta) did not. | ||
| 307 | +- fix: **use `make_tile_group` for any tile in a cross-op dependency** (even single-buffered: | ||
| 308 | + `addrs=[A], mutex_ids=[k]`, call `.next()` once). Bare `make_tile` is only safe for a transient | ||
| 309 | + reduction scratch or its row-major alias. Switching gamma/beta/negbeta to groups fixed layernorm | ||
| 310 | + (maxdiff 2.86e-6). source: diary 2026-07-22; `samples/vector_kernels/layernorm_impl.py`. | ||
| 311 | + | ||
| 312 | +## fp8 is storage-only for ARITHMETIC but pl.cast fp8<->fp32 WORKS (the mixed-precision bridge) (2026-07-22) | ||
| 313 | +- the type resolver (`_type_resolver.py:58-61`) lists fp8 (DT_FP8E4M3FN/E5M2/HF8) as storage-only, | ||
| 314 | + and **direct fp8 arithmetic fails**: `pl.mul` on an fp8 Vec tile -> "Failed to compile kernel". | ||
| 315 | +- BUT **`pl.cast(fp32_tile, fp8_tile)` and `pl.cast(fp8_tile, fp32_tile)` COMPILE AND RUN correctly** | ||
| 316 | + (empirically verified; the static analysis said no fp8 cast exists, but it works). So fp8 vector | ||
| 317 | + ops (softmax/norm) are buildable via the **cast-bridge**: load fp8 -> cast fp32 -> compute fp32 | ||
| 318 | + -> cast fp8 -> store. softmax_fp8 = maxdiff 2.58e-3 (fine for e4m3). Same pattern for bf16. | ||
| 319 | +- LESSON: empirical test beats static dtype-gate reading. The gate blocks fp8 in scalar/vector | ||
| 320 | + EXPRESSIONS, not in `pl.cast` (a data-movement op). | ||
| 321 | +- COST caveat: narrowing input (fp32->bf16->fp8) makes a COMPUTE-BOUND vector op SLOWER (softmax | ||
| 322 | + 31.8->63.7->93.4 us) -- the fp32 compute is unchanged and the casts add passes; memory (not the | ||
| 323 | + bottleneck) just goes idle. Mixed-precision input helps only if the compute runs in the narrow | ||
| 324 | + dtype. source: diary 2026-07-22; `samples/vector_kernels/mixed_precision_*`. | ||
| 325 | + | ||
| 326 | +## Vector reduction tiles: TR (rows) must be a multiple of 8 (32-byte fractal alignment) (2026-07-22) | ||
| 327 | +- symptom: softmax at N=2048 with TR=4 -> bisheng static_assert "Rows must be 32 bytes align" | ||
| 328 | + (pto_tile.hpp:1523). The [TR,1] DN reduction tile with TR=4 = 16 bytes, not 32-aligned. | ||
| 329 | +- fix: use TR a multiple of 8 (8 fp32 = 32 bytes). For large N where [8,N] doesn't fit UB with | ||
| 330 | + double-buffered groups, reduce buffer count (single-buffer the fp32 work tiles) rather than TR. | ||
| 331 | + Verified: TR=16 (N=256), TR=8 (N=1024) both compile+pass. source: diary 2026-07-22. | ||
| 332 | + | ||
| 333 | +## Factory-produced kernels COLLIDE in pypto's build cache (co_name keyed) — wrong results at all-but-first shape (2026-07-23) | ||
| 334 | +- symptom: a `def _make(D): @pl.jit def k(...)` factory used to compile one kernel per runtime shape. | ||
| 335 | + The FIRST D is bit-correct; EVERY other D returns garbage (maxdiff ~3, not a crash). Reversing the | ||
| 336 | + call order flips which D "works". Looked like a fragile/shape-specific kernel bug for hours. | ||
| 337 | +- root cause: pypto keys its on-disk compiled-kernel cache by the function **`co_name`** | ||
| 338 | + (`build/<module>__<coname>__a5/tk_none/`). All factory kernels share the def name `k`, so the 2nd D | ||
| 339 | + **reuses the 1st D's `.so`** (e.g. a 768-wide tile launched on 1024-wide data). The unchanged | ||
| 340 | + reference kernel (module-level, unique name) passes at the same D — that comparison exposes it. | ||
| 341 | +- fix: give each per-shape kernel a UNIQUE co_name. `k.__name__ = ...` does NOT work (co_name is fixed | ||
| 342 | + at `def`); `exec` breaks pypto's `inspect.getsource`. **Code-gen each kernel to a real `.py` file | ||
| 343 | + with a unique `def` name and `importlib` it.** source: diary 2026-07-23 (the kernel generator it was found in is not part of this tree). | ||
| 344 | + | ||
| 345 | +## vf tile width must be a multiple of 64 (LANES), not 8 → 507035 device memory fault (2026-07-23) | ||
| 346 | +- symptom: a `@pl.vector_function` kernel with `vf.load_align`/`store_align` over `n_regs=ceil(D/64)` | ||
| 347 | + registers faults with `507035` (device error type 3) at sync, for D whose `align8(D)` is not a | ||
| 348 | + multiple of 64 (e.g. D=2049→2056). D=768/1024/2048 pass (already 64-multiples), masking it. | ||
| 349 | +- root cause: `load_align`/`store_align` move a FULL 64-lane register; the last register at | ||
| 350 | + `(n_regs-1)*64` reads/writes past a tile whose width isn't a 64-multiple → out-of-bounds. | ||
| 351 | +- fix: size the tile to `align64(D)` (mult of 64). Also count UB slots correctly: double-buffered | ||
| 352 | + in+out = **4 slots**, UB=256KB → vf single-tile fits `4*TR*NN*4 ≤ 262144` ⇒ `align64(D) ≤ 2048`. | ||
| 353 | + source: diary 2026-07-23 (that sample directory is not part of this tree). | ||
| 354 | + | ||
| 355 | +## inf/nan input HANGS the device vector reduction (507034); and `torch.isfinite(x).all()` FAULTS the NPU on nan (2026-07-23) | ||
| 356 | +- symptom: an otherwise-correct vector reduction (rms/softmax: `row_sum`/`reduce_sum`/`rsqrt`/`exp`) | ||
| 357 | + HANGS (507034 vector-core-timeout) when the input row contains inf/nan — a hang, not wrong output. | ||
| 358 | + Repeated hangs then WEDGE the whole device (later ops 507034 until reset/reboot; SSH can hang too). | ||
| 359 | +- fix: **gate special-value inputs to a primitive (torch) fallback BEFORE they reach the kernel** | ||
| 360 | + (one ungated hang poisons the rest of the run). Detect finiteness with a **float max reduction** | ||
| 361 | + `math.isfinite(float(x.abs().amax()))` — NOT `torch.isfinite(x).all()`, which itself faults the NPU | ||
| 362 | + (507034) on nan; `amax`/`mean`/`sum` handle nan fine. source: diary 2026-07-23 (that sample is not part of this tree). | ||
| @@ -36,7 +36,8 @@ | |||
| 36 | }, | 36 | }, |
| 37 | "row-reduction": { | 37 | "row-reduction": { |
| 38 | "patterns": [ | 38 | "patterns": [ |
| 39 | - "patterns/vec-row-reduce-broadcast.md" | 39 | + "patterns/vec-row-reduce-broadcast.md", |
| 40 | + "patterns/vec-group-reduce-broadcast.md" | ||
| 40 | ], | 41 | ], |
| 41 | "constraints": [ | 42 | "constraints": [ |
| 42 | "constraints/vec.md" | 43 | "constraints/vec.md" |
| @@ -71,7 +72,8 @@ | |||
| 71 | }, | 72 | }, |
| 72 | "quantized-matmul": { | 73 | "quantized-matmul": { |
| 73 | "patterns": [ | 74 | "patterns": [ |
| 74 | - "patterns/quant-matmul-scaled-mm.md" | 75 | + "patterns/quant-matmul-scaled-mm.md", |
| 76 | + "patterns/fp4-mxfp-cast-pack.md" | ||
| 75 | ], | 77 | ], |
| 76 | "constraints": [ | 78 | "constraints": [ |
| 77 | "constraints/precision.md" | 79 | "constraints/precision.md" |
| @@ -81,7 +83,9 @@ | |||
| 81 | "multi-phase-fusion": { | 83 | "multi-phase-fusion": { |
| 82 | "patterns": [ | 84 | "patterns": [ |
| 83 | "patterns/online-softmax-tail.md", | 85 | "patterns/online-softmax-tail.md", |
| 84 | - "patterns/buffer-reuse-lifetime.md" | 86 | + "patterns/buffer-reuse-lifetime.md", |
| 87 | + "patterns/lookahead-pipeline.md", | ||
| 88 | + "patterns/multi-jit-fusion.md" | ||
| 85 | ], | 89 | ], |
| 86 | "constraints": [ | 90 | "constraints": [ |
| 87 | "constraints/sync-stitch.md" | 91 | "constraints/sync-stitch.md" |
| @@ -0,0 +1,310 @@ | |||
| 1 | +--- | ||
| 2 | +name: pypto-pl-cube-bound | ||
| 3 | +description: Size and optimise ANY pl tile-DSL matmul-class kernel toward CUBE-BOUND (aic_mac_ratio > 0.80) on the a5 NPU, for any M/N/K, any operand dtype and any core count. Provides a derivation-based sizing procedure (tile shape, K-block and buffer counts computed from the measured on-chip caps), the pipe cost model, producer/consumer buffering discipline, a bottleneck-to-lever routing table, and the measurement rules that prevent false conclusions. Use when a matmul or conv-as-GEMM kernel must be compute-bound, when profiling shows mte2/fixpipe/scalar dominating, or when a "cube-bound" claim needs validating. 触发词:cube-bound、算子性能调优、Gate B、计算瓶颈、mte2 瓶颈、tiling 选择、多缓冲、bf16/fp16/int8 性能优化。 | ||
| 4 | +--- | ||
| 5 | + | ||
| 6 | +# Driving a `pl` matmul kernel to CUBE-BOUND on a5 | ||
| 7 | + | ||
| 8 | +> **Note on referenced material.** Sample citations below — and the reproducer paths in | ||
| 9 | +> `sizing_examples.txt` — resolve into the governed knowledge base at `cannbot-skills/kb/`. Where | ||
| 10 | +> that tree retains a matching implementation the citation names it; where it does not, the citation | ||
| 11 | +> names the constraint or record page that carries the surviving rule. The cross-cutting trap index | ||
| 12 | +> is `cannbot-skills/kb/pitfall-records.md`. | ||
| 13 | + | ||
| 14 | +**Scope.** Any matmul-shaped kernel on a5 — plain GEMM, fused-epilogue GEMM, and conv-as-GEMM | ||
| 15 | +(conv lowers to a GEMM; see the conv twins). Any M/N/K, any operand dtype, any core count. | ||
| 16 | +Hardware constants are isolated in §7, so only that section changes on new silicon. | ||
| 17 | + | ||
| 18 | +**Companion tool:** `sizing.py` in this directory implements §2 — run it to get a config for your | ||
| 19 | +shape. `sizing_examples.txt` holds worked outputs. All figures are measured on a real Ascend950 | ||
| 20 | +(2026-07-21). The measurement harness those figures came from is **not retained in this KB**; the one | ||
| 21 | +kernel that is retained is `cannbot-skills/kb/examples/samples/bf16_matmul_operand_reuse/bf16_matmul_operand_reuse_impl.py`, | ||
| 22 | +an operand-residency study with an embedded correctness test — it demonstrates the reuse topology, not | ||
| 23 | +the numbers below. | ||
| 24 | + | ||
| 25 | +--- | ||
| 26 | + | ||
| 27 | +## 0. The verdict rule — read before measuring anything | ||
| 28 | + | ||
| 29 | +**CUBE-BOUND ⇔ `aic_mac_ratio` > 0.80.** Being the *top* sub-ratio is necessary but **not** | ||
| 30 | +sufficient — a kernel can lead on mac at 0.50 and still leave the cube half idle. Always report the | ||
| 31 | +number. Compare all five: `aic_mac_ratio`, `aic_scalar_ratio`, `aic_mte1_ratio`, `aic_mte2_ratio`, | ||
| 32 | +`aic_fixpipe_ratio`. | ||
| 33 | + | ||
| 34 | +- **`cube_utilization(%)` is NOT the verdict and is actively misleading.** Measured configs read | ||
| 35 | + **88–92%** while solidly **mte2-bound** (`mte2=0.98` vs `mac=0.21`). Never cite it as evidence. | ||
| 36 | +- **Never omit `aic_scalar_ratio`.** It reached **0.235, above mac's 0.129** at T=128/K=32. A filter | ||
| 37 | + covering only mac/mte1/mte2/fixpipe will mis-name the bottleneck. | ||
| 38 | +- **Report `mac_ratio` AND throughput** (`MMAC/µs = M·N·K / aicore_time`). They answer different | ||
| 39 | + questions and can move in opposite directions: bf16 vs fp32 at identical shape gives mac 0.181 vs | ||
| 40 | + 0.689 (bf16 far worse) but 23.1 vs 8.5 MMAC/µs (bf16 **2.7× faster**). Optimising `mac_ratio` | ||
| 41 | + alone can make a kernel slower. | ||
| 42 | +- **A kernel that fails Gate A has no Gate B.** Assert correctness, then profile. | ||
| 43 | +- **`aicore_time` is the AIC (cube unit) busy time**, not wall-clock (`Duration(us)` is larger and | ||
| 44 | + includes launch/dispatch). `aiv_time` is the vector engine. Every `aic_*_ratio` is normalised by | ||
| 45 | + `aicore_time`, so **ratios are comparable across shapes; absolute times are not.** | ||
| 46 | + | ||
| 47 | +--- | ||
| 48 | + | ||
| 49 | +## 1. The cost model | ||
| 50 | + | ||
| 51 | +Per output tile `[T,T]`, contraction depth `K`, operand bytes `bi`, output bytes `bo`, fp32 | ||
| 52 | +accumulator: | ||
| 53 | + | ||
| 54 | +| pipe | work per output tile | scales as | | ||
| 55 | +|---|---|---| | ||
| 56 | +| MAC | `T·T·K` | `T²K` | | ||
| 57 | +| MTE2 (GM→L1) | `(T·K + K·T)·bi` | `2·bi·KT` | | ||
| 58 | +| MTE1 (L1→L0) | same bytes, on-chip | `2·bi·KT` | | ||
| 59 | +| FIXPIPE (L0C→GM) | `T·T·bo` | `bo·T²` | | ||
| 60 | + | ||
| 61 | +``` | ||
| 62 | +MAC / fixpipe ∝ K / bo → raise K, or narrow the OUTPUT dtype, to beat FIXPIPE | ||
| 63 | +MAC / mte2 ∝ T / bi → raise T, or narrow the OPERAND dtype, to beat MTE2 (K cancels!) | ||
| 64 | +``` | ||
| 65 | + | ||
| 66 | +**The K-cancellation is the load-bearing insight:** raising K does nothing for mte2, because | ||
| 67 | +operand traffic grows with K exactly as fast as MAC work does. Confirmed across a 16-point sweep — | ||
| 68 | +at T=16, mte2 stayed 0.92→0.98 as K went 32→256, while fixpipe fell 0.571→0.333. | ||
| 69 | + | ||
| 70 | +**Corollary that decides most tuning:** to flip a verdict you must change a **ratio**, not remove | ||
| 71 | +time. Removing a pipe's *time* (e.g. K-accumulation removing fixpipe work) shrinks `aicore_time` | ||
| 72 | +and lifts mac **and** its competitor proportionally — the ratio is unchanged. | ||
| 73 | + | ||
| 74 | +--- | ||
| 75 | + | ||
| 76 | +## 2. THE SIZING PROCEDURE — derive tiling and buffers for your shape | ||
| 77 | + | ||
| 78 | +> **The inversion that matters:** buffer counts are **requirements, not leftovers**. Size `T` and | ||
| 79 | +> `K_blk` so the *required* multi-buffering fits — do not maximise `T`/`K` and then accept whatever | ||
| 80 | +> buffering is left over. Getting this backwards capped an earlier attempt at mac 0.58; applying it | ||
| 81 | +> correctly reached **0.870**. | ||
| 82 | + | ||
| 83 | +**Required multi-buffering** — each removes a specific stall (§4): | ||
| 84 | + | ||
| 85 | +| buffer | min | why | | ||
| 86 | +|---|---|---| | ||
| 87 | +| `acc` (L0C) | **2** (4 better) | else FIXPIPE drain blocks the next MAC | | ||
| 88 | +| `b_l0b` (L0B) | **2** | else MAC blocks the MTE1 refill | | ||
| 89 | +| `a_l0a` (L0A) | **2** | else row i+1's A move **races** row i's matmuls → *wrong results* | | ||
| 90 | +| `b_l1` (L1) | 2–4 | else MTE1 blocks the next GM load | | ||
| 91 | +| `a_l1` (L1) | 2 | only useful once there are ≥2 row-blocks/core | | ||
| 92 | + | ||
| 93 | +**Three constraints** (`bi` = operand bytes, `CORES` = core count, caps from §7): | ||
| 94 | + | ||
| 95 | +``` | ||
| 96 | +(1) T ≤ sqrt( L0C / (4 · acc_buf) ) # fp32 accumulator | ||
| 97 | +(2) K_blk ≤ L0A / (T · bi · a_l0a_buf) # L0B gives the same bound | ||
| 98 | +(3) M ≥ rows_target · T · CORES # rows_target >= 2, ideally 4 | ||
| 99 | +``` | ||
| 100 | +Round `T` and `K_blk` down to powers of two, ≥ the 16-element fractal. | ||
| 101 | + | ||
| 102 | +**Worked derivation — bf16 on a5** (`L0C`=256 KB, `L0A`=64 KB, 32 cores): | ||
| 103 | +- (1) with `acc_buf=4`: `T ≤ sqrt(262144/16) = 128` ⇒ **T = 128** | ||
| 104 | +- (2) `K_blk ≤ 65536/(128·2·2) = 128` ⇒ **K_blk = 128** | ||
| 105 | +- (3) with `rows_target=4`: `M ≥ 4·128·32 = 16384` ⇒ **4 row-blocks/core** | ||
| 106 | + | ||
| 107 | +That is **exactly the measured optimum** (mac 0.870, 179.9 MMAC/µs) — derived, not tuned. | ||
| 108 | + | ||
| 109 | +**Same procedure, other dtypes** (via `sizing.py`): | ||
| 110 | + | ||
| 111 | +| operands | `bi` | T | `K_blk` | note | | ||
| 112 | +|---|---|---|---|---| | ||
| 113 | +| bf16 / fp16 | 2 | 128 | **128** | the validated point | | ||
| 114 | +| fp32 | 4 | 128 | **64** | wider operands ⇒ shallower K | | ||
| 115 | +| int8 | 1 | 128 | **256** | narrower operands ⇒ deeper K | | ||
| 116 | + | ||
| 117 | +⇒ **`K_blk` is inversely proportional to operand width. Never carry a K over from another dtype.** | ||
| 118 | + | ||
| 119 | +Note (1) also explains why large T backfires: at T=256 the accumulator tile *is* 256 KB, so only | ||
| 120 | +**one** `acc` buffer fits — no MAC↔FIXPIPE overlap. Measured T=256 peaked at mac 0.485. | ||
| 121 | + | ||
| 122 | +--- | ||
| 123 | + | ||
| 124 | +## 3. Kernel skeleton (shape-independent) | ||
| 125 | + | ||
| 126 | +```python | ||
| 127 | +@pl.jit(auto_mutex=True) | ||
| 128 | +def gemm(a, b, out): # A[M,K] @ B[K,N] -> out[M,N] | ||
| 129 | + nc, cid = pl.get_block_num(), pl.get_block_idx() | ||
| 130 | + with pl.section_cube(): | ||
| 131 | + a_l1 = pl.make_tile_group(type=TT([T, KB], DT_IN, Mat, NZ), addrs=A_L1, mutex_ids=[...]) | ||
| 132 | + a_l0a = pl.make_tile_group(type=TT([T, KB], DT_IN, Left, NZ), addrs=0x0, mutex_ids=[..,..]) | ||
| 133 | + b_l1 = pl.make_tile_group(type=TT([KB, T], DT_IN, Mat, NZ), addrs=B_L1, mutex_ids=[...]) | ||
| 134 | + b_l0b = pl.make_tile_group(type=TT([KB, T], DT_IN, Right, ZN), addrs=0x0, mutex_ids=[..,..]) | ||
| 135 | + acc = pl.make_tile_group(type=TT([T, T], DT_FP32, Acc, NZ, fractal=1024), addrs=0x0, mutex_ids=[...]) | ||
| 136 | + nt_n, n_rows = b.shape[1] // T, a.shape[0] // T | ||
| 137 | + for i in pl.range(cid, n_rows, nc): # each core owns whole ROW-BLOCKS | ||
| 138 | + ca = a_l1.next(); pl.load_tile(ca, a, [i, 0]) # ONE GM load of A per row-block | ||
| 139 | + al = a_l0a.next(); pl.move(al, ca) # HOISTED: A is read-only below | ||
| 140 | + for j in pl.range(0, nt_n): | ||
| 141 | + cb = b_l1.next(); pl.load_tile(cb, b, [0, j]) # only B streams from GM | ||
| 142 | + br = b_l0b.next(); pl.move(br, cb) | ||
| 143 | + ac = acc.next() | ||
| 144 | + pl.matmul(ac, al, br) | ||
| 145 | + pl.store_tile(out, ac, [i, j]) | ||
| 146 | +``` | ||
| 147 | + | ||
| 148 | +Three structural rules, all shape-independent: | ||
| 149 | +1. **`.next()` for streaming operands; `.current()` only to re-read a resident one.** `.current()` | ||
| 150 | + does NOT advance the rotation (§9). | ||
| 151 | +2. **Row-block decomposition with the reused operand resident** — this is what buys operand reuse. | ||
| 152 | +3. **Hoist the resident operand's L1→L0 move out of the inner loop** (measured mte1 −41%). | ||
| 153 | + | ||
| 154 | +--- | ||
| 155 | + | ||
| 156 | +## 4. Pipeline discipline — who blocks whom | ||
| 157 | + | ||
| 158 | +``` | ||
| 159 | +MTE2 MTE1 MAC FIXPIPE | ||
| 160 | +GM ---> L1 ------> L0A/L0B ---------> L0C ---------------> GM | ||
| 161 | + ^ b_l1 ^ b_l0b ^ acc | ||
| 162 | +``` | ||
| 163 | +Each stage's **output** buffer must be multi-buffered **and** accessed with `.next()`: | ||
| 164 | + | ||
| 165 | +- `b_l1` ×1 ⇒ MTE1 blocks MTE2 · `b_l0b` ×1 ⇒ **MAC blocks MTE1** · `acc` ×1 ⇒ **FIXPIPE blocks MAC** | ||
| 166 | +- `a_l0a` ×1 ⇒ once the outer loop pipelines, row i+1's move **races** row i's matmuls — a | ||
| 167 | + **correctness** failure (measured `rel=1.045`), not merely a stall. | ||
| 168 | + | ||
| 169 | +**A buffer needs multi-buffering only if it is WRITTEN every iteration.** A reused operand needs | ||
| 170 | +residency; a second buffer there steals capacity that a streaming operand needs. | ||
| 171 | + | ||
| 172 | +**Standing rule: prefer the `K_blk` that lets EVERY stage rotate over the K that maximises | ||
| 173 | +per-matmul MAC work.** Pipeline occupancy beats arithmetic density — measured, K=128 fully rotating | ||
| 174 | +(mac 0.870) beats K=256 with single-buffered L0A/L0B (mac 0.716). | ||
| 175 | + | ||
| 176 | +--- | ||
| 177 | + | ||
| 178 | +## 5. Bottleneck → lever routing | ||
| 179 | + | ||
| 180 | +Profile with `AiCMetrics.PipeUtilization` → `kernel_details.csv` (harness | ||
| 181 | +`python/tests/ut/block/frontend/a5/profilling/test_profiling.py:50-125`), take the top AIC | ||
| 182 | +sub-ratio, then: | ||
| 183 | + | ||
| 184 | +| top pipe | meaning | lever | | ||
| 185 | +|---|---|---| | ||
| 186 | +| `mte2` | GM operand traffic | raise `T`; **operand reuse** (the only lever that changes mac:mte2); narrower operand dtype | | ||
| 187 | +| `fixpipe` | accumulator drain | raise `K_blk`; **narrower output dtype** (bf16 out halved it); K-accumulation (§6) | | ||
| 188 | +| `mte1` | L1→L0 movement | hoist the resident operand's move; check NZ/ZN layouts aren't forcing a transpose branch | | ||
| 189 | +| `scalar` | loop / instruction overhead | fewer, larger iterations — but this fights rows-per-core, so it is a trade | | ||
| 190 | +| `mac` **> 0.80** | done | ✅ | | ||
| 191 | +| `mac` top but **< 0.80** | no single pipe dominates | you are schedule-limited: fix buffering (§4) before touching traffic | | ||
| 192 | + | ||
| 193 | +**Before optimising a pipe, confirm it is on the critical path:** cut it and check `aicore_time` | ||
| 194 | +actually falls. A ratio measures **occupancy, not causality** — a 2D core grid cut mte2 by 40% and | ||
| 195 | +made the kernel *slower*, because mte2 was already overlapped (§6). | ||
| 196 | + | ||
| 197 | +--- | ||
| 198 | + | ||
| 199 | +## 6. When the standard recipe does not apply | ||
| 200 | + | ||
| 201 | +| situation | symptom | what to do | | ||
| 202 | +|---|---|---| | ||
| 203 | +| **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 | | ||
| 204 | +| **N/T small** (few columns) | A-reuse amortises over few tiles | if `M/T ≫ N/T`, **swap roles**: make B resident, stream A | | ||
| 205 | +| **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 | | ||
| 206 | +| **M or N not divisible by T** | tail tiles | `valid_shape` / `set_validshape` | | ||
| 207 | +| **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 | | ||
| 208 | +| **fused epilogue** | vector work after the matmul | prefer the fixpipe path (`relu_pre_mode`, `pre_quant_scalar`) — `aiv=0`, no L0C→UB handoff | | ||
| 209 | + | ||
| 210 | +**Does NOT work:** K-accumulation cannot flip a verdict — it removes *fixpipe time*, shrinking | ||
| 211 | +`aicore_time` and lifting mac **and** mte2 proportionally. Use it to reclaim wall-clock, never to | ||
| 212 | +change the bound. | ||
| 213 | + | ||
| 214 | +--- | ||
| 215 | + | ||
| 216 | +## 7. Hardware constants (a5, MEASURED — the only section to re-derive on new silicon) | ||
| 217 | + | ||
| 218 | +| resource | value | evidence | | ||
| 219 | +|---|---|---| | ||
| 220 | +| **L0A / L0B** | **64 KB each** | T=256,K=256 (128 KB tile) → fault **507015** | | ||
| 221 | +| **L0C (Acc)** | **≥ 256 KB** | T=256 fp32 acc (256 KB, ×1) allocated **and golden-checked** — docs said 128 KB | | ||
| 222 | +| **L1** | ≥ 256 KB | 8K template uses 256 KB; 384 KB configs also ran | | ||
| 223 | +| UB | ~256 KB | earlier probe (253 KB ok, 259 KB faults) | | ||
| 224 | +| 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 | | ||
| 225 | +| peak check | 206.7 TMAC/s while MAC busy ⇒ ≈1.58 GHz at 4096×32 | measured on the final kernel | | ||
| 226 | +| 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 | | ||
| 227 | + | ||
| 228 | +**Binding tile constraint:** `T · K_blk · bi · buffers ≤ 64 KB` (L0A/L0B); with the mandatory ×2 | ||
| 229 | +that is `T · K_blk · bi ≤ 32768`. | ||
| 230 | + | ||
| 231 | +**Dtype caution:** fp32 runs the cube at half MAC rate, so a kernel is MAC-heavy *by construction* | ||
| 232 | +and "cube-bound in fp32" is a much weaker claim than it looks. **Always re-verify at the dtype you | ||
| 233 | +deploy.** Same kernel and tiling: fp32 → mac 0.689; bf16 → mac 0.181 (yet 2.7× faster). | ||
| 234 | + | ||
| 235 | +--- | ||
| 236 | + | ||
| 237 | +## 8. Worked example — the full measured ladder (bf16, T=128, 32 cores) | ||
| 238 | + | ||
| 239 | +⚠️ **Rows are different problem sizes, so `aicore_time` is NOT comparable across them.** Normalise | ||
| 240 | +to MMAC/µs. (Row 0 does 1/16 the MACs of the last rows, hence its small `aicore_time`.) | ||
| 241 | + | ||
| 242 | +| # | lever | M×N×K | mac | mte2 | fix | MMAC/µs | | ||
| 243 | +|---|---|---|---|---|---|---| | ||
| 244 | +| 0 | naive tiled | 1024×1024×64 | 0.181 | 0.389 | 0.417 | 23.1 | | ||
| 245 | +| 1 | T=128, K=256 (sweep best) | 1024×1024×256 | 0.320 | 0.520 | 0.231 | 57.1 | | ||
| 246 | +| 2 | + A-reuse | 4096×1024×256 | 0.499 | 0.443 | 0.340 | 91.5 | | ||
| 247 | +| 3 | + hoist A→L0A move | 4096×1024×256 | 0.489 | 0.451 | 0.343 | 91.5 | | ||
| 248 | +| 4 | + bf16 output | 4096×1024×256 | 0.568 | 0.517 | 0.238 | 104.9 | | ||
| 249 | +| 5 | + **`.next()`** rotation | 4096×1024×256 | 0.618 | 0.472 | 0.282 | 115.8 | | ||
| 250 | +| 6 | + 2 row-blocks/core | 8192×1024×256 | 0.669 | 0.551 | 0.291 | 126.7 | | ||
| 251 | +| 7 | + **K=128** (all stages rotate), 4 rows/core | 16384×1024×128 | 0.849 | 0.787 | 0.756 | 162.8 | | ||
| 252 | +| 8 | + `acc`×4 | 16384×1024×128 | **0.870** | 0.816 | 0.829 | **179.9** | | ||
| 253 | + | ||
| 254 | +**End to end: mac ×4.8, throughput ×7.8.** That decomposes into ×4.8 more cube-busy time and ×1.6 | ||
| 255 | +higher MACs-per-busy-µs (escaping fractal underfill at tiny K, plus better operand staging). | ||
| 256 | + | ||
| 257 | +--- | ||
| 258 | + | ||
| 259 | +## 9. Traps that produced WRONG conclusions here | ||
| 260 | + | ||
| 261 | +- **`.current()` does not advance a tile group — `.next()` does.** Declaring `mutex_ids=[a,b]` and | ||
| 262 | + then calling `.current()` gives ZERO rotation: single-buffered while paying the capacity. This | ||
| 263 | + silently invalidated three conclusions ("0.80 is unreachable", "mte2 is bandwidth-bound", | ||
| 264 | + "K=128 is worse than K=256"). **Diagnostic: if adding a buffer moves performance <2%, suspect | ||
| 265 | + inert rotation before blaming the pipe.** | ||
| 266 | +- **Before declaring a hardware ceiling, verify the optimisation is ACTIVE.** A lever that "should" | ||
| 267 | + work and measures ~0 is more often un-plumbed than ineffective. | ||
| 268 | +- **A high sub-ratio ≠ that pipe is the bottleneck.** The 2D core grid cut mte2 by 40% and lost 6% | ||
| 269 | + throughput — mte2 was already overlapped with MAC. | ||
| 270 | +- **Utilisation is a RATIO** — it rises when a pipe does more work *or* when the kernel gets faster. | ||
| 271 | + Fixpipe 29.1% → 82.9% was ~half "2× the bytes" and ~half "0.70× the time", at **constant** | ||
| 272 | + 3.4 TB/s. Check achieved bandwidth before calling it a regression. | ||
| 273 | +- **Never compare `aicore_time` across shapes.** Normalise to MMAC/µs. | ||
| 274 | + | ||
| 275 | +--- | ||
| 276 | + | ||
| 277 | +## 10. Operational pitfalls | ||
| 278 | + | ||
| 279 | +- **Copy the proven tiled template verbatim** (`a5/matmul/test_matmul_8K_example.py`). Hand-rolling | ||
| 280 | + it with `@pl.jit()` + `make_tile` + manual sync **device-faulted 507015**; the verbatim | ||
| 281 | + `auto_mutex` + `make_tile_group` copy ran bit-exact. | ||
| 282 | +- **Shared box: diagnose contention before debugging your kernel.** Triage order: `MARK:` prints | ||
| 283 | + per phase (a stall before "device ok" means device acquisition, not your kernel) → run the repo's | ||
| 284 | + own `test_matmul_api_basic.py::test_t01` (if that hangs too, it isn't you) → `fuser -v | ||
| 285 | + /dev/davinci*` then `ps -o pid,lstart,user,cmd -p <pid>`. **`npu-smi info` reports `OK` even when | ||
| 286 | + saturated — that is health, not availability.** When contended, stop issuing work; never reset the | ||
| 287 | + device or kill other users' processes. | ||
| 288 | +- **Never pipe a remote run through `tail`** — it buffers until exit, making a hang and a slow | ||
| 289 | + compile indistinguishable. Stream to a log and tail that instead. | ||
| 290 | +- **Check budgets before emitting a config** (§2/§7) — a generator that filters on them avoids | ||
| 291 | + burning box runs on configs that cannot fit. | ||
| 292 | + | ||
| 293 | +--- | ||
| 294 | + | ||
| 295 | +## 11. Reference data | ||
| 296 | + | ||
| 297 | +**Inverse skill:** to deliberately drive MTE2/FIXPIPE/MTE1 to its limit (roofline / | ||
| 298 | +microbenchmark), see `pypto-pl-pipe-roofline` — same cost model, opposite goal. | ||
| 299 | + | ||
| 300 | + | ||
| 301 | +- `sizing.py` (this directory) — implements §2; `sizing_examples.txt` for worked outputs. | ||
| 302 | +- `cannbot-skills/kb/examples/samples/bf16_matmul_operand_reuse/bf16_matmul_operand_reuse_impl.py` — the | ||
| 303 | + one retained artifact of the operand-residency work: a bf16 matmul that reuses each A tile across the | ||
| 304 | + output-column loop, with an embedded NPU correctness test. The sweep harness, the per-shape testcase | ||
| 305 | + registry, the per-pipe bandwidth analysis and the negative results (2-D grid, L0B buffering A/B) that | ||
| 306 | + produced §§4–6 are **not retained in this KB**; §§4–6 are the surviving record of them, and any figure | ||
| 307 | + quoted from them must be re-measured before it is relied on. | ||
| 308 | +- `cannbot-skills/kb/constraints/precision.md` — the dtype and cast rules the fp32-versus-bf16 comparison | ||
| 309 | + in §4 turns on. It carries the rules, not the profiler output; no raw CSV is retained. | ||
| 310 | +- `cannbot-skills/kb/pitfall-records.md` — the same traps in cross-cutting form. | ||
| @@ -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,51 @@ | |||
| 1 | +============================================================================== | ||
| 2 | +VALIDATION — does the procedure reproduce the measured optimum? | ||
| 3 | +============================================================================== | ||
| 4 | + | ||
| 5 | +### MEASURED BEST: M=16384 N=1024 K=128 bf16, 32 cores (actual: T=128 K=128 4rows, mac 0.870) | ||
| 6 | + -> T=128 K_blk=128 rows/core=4.00 cols=8 fits=True | ||
| 7 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 8 | + on-chip: L0A 64KB/64KB L0B 64KB/64KB L0C 256KB/256KB L1 192KB/256KB | ||
| 9 | + | ||
| 10 | +============================================================================== | ||
| 11 | +GENERALISATION — other shapes and dtypes | ||
| 12 | +============================================================================== | ||
| 13 | + | ||
| 14 | +### fp32 operands, square | ||
| 15 | + -> T=128 K_blk=64 rows/core=4.00 cols=32 fits=True | ||
| 16 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 17 | + on-chip: L0A 64KB/64KB L0B 64KB/64KB L0C 256KB/256KB L1 192KB/256KB | ||
| 18 | + ! 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. | ||
| 19 | + | ||
| 20 | +### int8 operands | ||
| 21 | + -> T=128 K_blk=256 rows/core=4.00 cols=32 fits=True | ||
| 22 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 23 | + on-chip: L0A 64KB/64KB L0B 64KB/64KB L0C 256KB/256KB L1 192KB/256KB | ||
| 24 | + ! 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. | ||
| 25 | + | ||
| 26 | +### tall-skinny (N small) | ||
| 27 | + -> T=128 K_blk=128 rows/core=16.00 cols=2 fits=True | ||
| 28 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 29 | + on-chip: L0A 64KB/64KB L0B 64KB/64KB L0C 256KB/256KB L1 192KB/256KB | ||
| 30 | + ! N/T=2 is small: A-reuse amortises over few columns. If M/T >> N/T, swap roles (make B resident, stream A). | ||
| 31 | + ! 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. | ||
| 32 | + | ||
| 33 | +### short-fat (M small) | ||
| 34 | + -> T=128 K_blk=128 rows/core=0.12 cols=128 fits=True | ||
| 35 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 36 | + on-chip: L0A 64KB/64KB L0B 64KB/64KB L0C 256KB/256KB L1 192KB/256KB | ||
| 37 | + ! 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. | ||
| 38 | + ! 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. | ||
| 39 | + | ||
| 40 | +### deep K (needs K-loop) | ||
| 41 | + -> T=128 K_blk=128 rows/core=2.00 cols=64 fits=True | ||
| 42 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 43 | + on-chip: L0A 64KB/64KB L0B 64KB/64KB L0C 256KB/256KB L1 192KB/256KB | ||
| 44 | + ! 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. | ||
| 45 | + | ||
| 46 | +### tiny (Gate-A shape) | ||
| 47 | + -> T=64 K_blk=64 rows/core=0.03 cols=1 fits=True | ||
| 48 | + buffers: a_l1 x2, a_l0a x2, b_l1 x4, b_l0b x2, acc x4 | ||
| 49 | + on-chip: L0A 16KB/64KB L0B 16KB/64KB L0C 64KB/256KB L1 48KB/256KB | ||
| 50 | + ! 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. | ||
| 51 | + ! N/T=1 is small: A-reuse amortises over few columns. If M/T >> N/T, swap roles (make B resident, stream A). | ||
| @@ -0,0 +1,166 @@ | |||
| 1 | +--- | ||
| 2 | +name: pypto-pl-pipe-roofline | ||
| 3 | +description: Write a pl tile-DSL matmul that is DELIBERATELY bottlenecked on ONE chosen pipe (MTE2, FIXPIPE, MTE1, or MAC) to characterise that pipe's hardware limit on the a5 NPU — a roofline / microbenchmark probe. Gives the knob that selects each bottleneck (tile T, depth K, dtype), the shape rules for full core occupancy, and the crucial distinction between utilisation-bound and bandwidth-bound. The inverse of pypto-pl-cube-bound (which drives MAC to the top). Use to measure a pipe's ceiling, build a saturation microbenchmark, or validate a roofline model. 触发词:roofline、带宽测试、pipe 打满、MTE2 瓶颈、FixPipe 瓶颈、硬件极限、饱和测试、microbenchmark。 | ||
| 4 | +--- | ||
| 5 | + | ||
| 6 | +# Driving one pipe to its hardware limit on a5 | ||
| 7 | + | ||
| 8 | +> **Note on referenced material.** Sample citations below resolve into the governed knowledge base | ||
| 9 | +> at `cannbot-skills/kb/`. No saturation reproducer is retained there, so those citations name | ||
| 10 | +> `cannbot-skills/kb/constraints/arch-a5.md`, whose platform gate states how to re-derive the | ||
| 11 | +> platform constants a saturation probe needs from the installed runtime. The companion skill is | ||
| 12 | +> `pypto-pl-cube-bound`. | ||
| 13 | + | ||
| 14 | +To measure what a pipe can do — or to prove a kernel is limited by the pipe you think — build a | ||
| 15 | +matmul that is bottlenecked on **exactly that pipe**. This is the inverse of `pypto-pl-cube-bound`: | ||
| 16 | +there you push everything off the cube; here you push everything ONTO one target pipe. | ||
| 17 | + | ||
| 18 | +All figures measured on Ascend950, 32 cores. The saturation reproducers and their raw data are **not | ||
| 19 | +retained in this KB** — the tables in §§3–6 are the surviving record. Before relying on any of them, | ||
| 20 | +re-derive the platform ceilings for the runtime in front of you by the evidence gate in | ||
| 21 | +`cannbot-skills/kb/constraints/arch-a5.md`, which names the installed platform files to read them | ||
| 22 | +from. | ||
| 23 | + | ||
| 24 | +--- | ||
| 25 | + | ||
| 26 | +## 0. Two meanings of "reach the hardware limit" — and which one to target | ||
| 27 | + | ||
| 28 | +| bound | definition | how to confirm | | ||
| 29 | +|---|---|---| | ||
| 30 | +| **Bandwidth-bound** | the pipe hits its physical GB/s (or TMAC/s) ceiling | compute `bytes / (util · engine_time)` and compare to §4 | | ||
| 31 | +| **Utilisation-bound** | the pipe's occupancy (`*_ratio`) → 1.0 | it is the top sub-ratio and near 1.0 | | ||
| 32 | + | ||
| 33 | +**For the data-movement pipes MTE1/2/3 (and FIXPIPE), the PRIMARY goal is BANDWIDTH-bound — hit the | ||
| 34 | +GB/s ceiling. Utilisation is a secondary check** (confirming the pipe you targeted is the one | ||
| 35 | +dominating). A mover at 97% util but 28% of its bandwidth is NOT at its hardware limit. Only MAC is | ||
| 36 | +naturally reported as a utilisation/fraction-of-peak; the movers are reported in GB/s. | ||
| 37 | + | ||
| 38 | +**They diverge (measured).** MTE2 at T=16 runs **97% utilised but only 1.33 TB/s** (~28% of its | ||
| 39 | +~4.7 TB/s ceiling) — util-saturated, NOT bandwidth-saturated, because tiny 8 KB transfers cannot | ||
| 40 | +fill the bus. Grow T to 64 and util *falls* to 84% while bandwidth *rises* to 3.1 TB/s; T=128 | ||
| 41 | +no-reuse hits the full 4.7 TB/s. So chasing util would have *stopped at the wrong place*. **Always | ||
| 42 | +report the achieved GB/s as the verdict for a mover, with the top sub-ratio as the confirmation.** | ||
| 43 | + | ||
| 44 | +--- | ||
| 45 | + | ||
| 46 | +## 1. The knob that selects each bottleneck | ||
| 47 | + | ||
| 48 | +Whole-problem arithmetic intensity, **flattened tiling with no operand reuse** (reuse moves you | ||
| 49 | +toward MAC-bound, so for a pipe probe you deliberately drop it), operand bytes `bi`, output bytes | ||
| 50 | +`bo`: | ||
| 51 | + | ||
| 52 | +``` | ||
| 53 | +MAC / mte2_bytes = T / (2·bi) ← shrink T (or widen operands) ⇒ MTE2-bound | ||
| 54 | +MAC / fix_bytes = K / bo ← shrink K (or widen output) ⇒ FIXPIPE-bound | ||
| 55 | +MAC / mte1_bytes = T / (2·bi) ← same bytes as mte2 but on-chip; rarely the binding pipe | ||
| 56 | +``` | ||
| 57 | + | ||
| 58 | +**M and N do not change the ratio** — they set total work and core occupancy only. So: | ||
| 59 | + | ||
| 60 | +| target pipe | primary knob | secondary knob | proven config (M=N=1024) | | ||
| 61 | +|---|---|---|---| | ||
| 62 | +| **MTE2** (GM→L1 read) | **small T** (16–64) | wider operand dtype | T=16 → util 0.97; T=64 → 3.1 TB/s | | ||
| 63 | +| **FIXPIPE** (L0C→GM write) | **small K** (16–32) | **fp32 output** (bo=4) | T=128,K=32 → util 0.91, 4.5 TB/s | | ||
| 64 | +| **MAC** (reference) | large T, large K, reuse, multi-buffer | narrow dtype | see `pypto-pl-cube-bound` (mac 0.87) | | ||
| 65 | +| **scalar** | very small tiles ⇒ many loop iterations | — | rises as T,K shrink (loop overhead) | | ||
| 66 | + | ||
| 67 | +--- | ||
| 68 | + | ||
| 69 | +## 2. Shape rules — so you measure the pipe, not an artefact | ||
| 70 | + | ||
| 71 | +1. **Full core occupancy:** `M/T ≥ CORES` (ideally `≥ 2·CORES`). With too few tiles, cores idle and | ||
| 72 | + you measure an occupancy wall, not the pipe. E.g. T=128, 32 cores ⇒ `M ≥ 4096`. | ||
| 73 | +2. **Enough iterations to amortise launch:** each core should run many tiles; keep N·(M/T) large. | ||
| 74 | +3. **Keep the *non-target* pipes cheap** so the target clearly dominates — for a FIXPIPE probe use | ||
| 75 | + small K (also starves MAC and MTE2); for an MTE2 probe use small T (also shrinks the FIXPIPE | ||
| 76 | + drain and MAC). | ||
| 77 | +4. **Gate A first.** A wrong kernel's utilisation is meaningless. | ||
| 78 | + | ||
| 79 | +--- | ||
| 80 | + | ||
| 81 | +## 3. To hit the BANDWIDTH ceiling (not just util) — transfer granularity matters | ||
| 82 | + | ||
| 83 | +A pipe reaches its GB/s ceiling only when its transfers are **large and contiguous**. The tension: | ||
| 84 | + | ||
| 85 | +- **MTE2-bound needs small T**, but small T ⇒ small (T·K·bi) loads ⇒ sub-peak bandwidth. Measured | ||
| 86 | + MTE2 bandwidth vs T (K=128, no reuse): **T=16 → 1.33 TB/s @ 97% util; T=32 → 2.03; T=64 → 3.10 @ | ||
| 87 | + 84% util**. Util falls while bandwidth climbs. To approach the MTE2 ceiling (~4.7 TB/s), use the | ||
| 88 | + **largest T still mte2-dominant** (T=64 here) and accept util < 1.0; T=128 no-reuse hits the full | ||
| 89 | + 4.7 TB/s but is barely mte2-bound. | ||
| 90 | +- **FIXPIPE has no tension**: at T=128 the drain is already a 64 KB tile, so shrinking K makes | ||
| 91 | + fixpipe dominant *and* bus-efficient — measured **~4.1–4.5 TB/s at ~90% util** (K=16/32/64). This | ||
| 92 | + is why fixpipe saturates trivially and mte2 does not. | ||
| 93 | + | ||
| 94 | +**Rule of thumb:** to characterise a pipe's *bandwidth*, maximise transfer size subject to staying | ||
| 95 | +bound on that pipe; to characterise its *occupancy limit*, minimise arithmetic intensity. | ||
| 96 | + | ||
| 97 | +--- | ||
| 98 | + | ||
| 99 | +## 4. a5 pipe ceilings (measured 2026-07-22 — the roofline) | ||
| 100 | + | ||
| 101 | +| pipe | path / engine | **ceiling (GB/s or TMAC/s)** | reached by | | ||
| 102 | +|---|---|---|---| | ||
| 103 | +| MTE1 (L1→L0) | on-chip, cube | **7.5–11.4 TB/s** | matmul A-reuse (never binding) | | ||
| 104 | +| MTE2 (GM→L1) | load, cube | **~4.7 TB/s** (large T); ~1.3 at T=16 | `sat_mac_ref` vs `sat_mte2_t16` | | ||
| 105 | +| MTE2 (GM→UB) | load, vector | **~2.2 TB/s** | vector datacopy | | ||
| 106 | +| MTE3 (UB→GM) | store, vector | **~2.35 TB/s** | vector datacopy | | ||
| 107 | +| FIXPIPE (L0C→GM) | store, cube | **~4.5 TB/s** | `sat_fix_k32` | | ||
| 108 | +| MAC (cube) | compute | **~207 TMAC/s** (bf16) | cube-bound kernel | | ||
| 109 | + | ||
| 110 | +**The cube and vector engines have different GM bandwidth** — the cube's GM paths (~4.5–4.7 TB/s) | ||
| 111 | +run ~2× the vector's (~2.2–2.35 TB/s). Root cause (investigated; the write-up is not part of this tree): | ||
| 112 | +NOT the HBM bus (shared, ≥4.7) and NOT bidirectional sharing (isolated load-only 2.14, store-only | ||
| 113 | +2.29 TB/s) — it is the **per-engine DMA port width** (AIC↔L1 ~2× wider than AIV↔UB). And | ||
| 114 | +`block_dim` clamps to `core_num` (=32 here, `jit.py:1059`), so more vector cores is not an option. | ||
| 115 | +**To approach the HBM ceiling, overlap cube+vector** — their GM ports are separate and sum. Use | ||
| 116 | +aic_* ratios for cube kernels, aiv_* for vector. | ||
| 117 | + | ||
| 118 | +**Dtype (bf16 vs fp8) — the bus is BYTE-limited, not element-limited.** Measured vector datacopy: | ||
| 119 | +bf16 and fp8 reach the **same GB/s** (~2.2 load / ~2.35 store) at equal tile-KB. So fp8 moves **2× | ||
| 120 | +the elements/sec** at the same bandwidth — its data-movement win is fewer *bytes* for a given | ||
| 121 | +problem (halving operand width halves MTE time), NOT a faster bus. fp8 = `DT_FP8E4M3FN`; isolate | ||
| 122 | +movement with `load → pl.move → store` (fp8 *arithmetic* like `pl.add` does not compile). | ||
| 123 | + | ||
| 124 | +MAC rate by dtype: fp16/bf16 4096/cyc·core, fp32 2048 (0.5×), int8 8192, int4 16384. | ||
| 125 | + | ||
| 126 | +## 5. Procedure | ||
| 127 | + | ||
| 128 | +1. Pick the target pipe and its knob (§1). Pick M,N,K,T,dtypes so (a) the knob drives that pipe's | ||
| 129 | + intensity low, (b) `M/T ≥ CORES` (§2), (c) for a bandwidth probe, transfers stay large (§3). | ||
| 130 | +2. Use a **flattened, no-reuse** kernel — reuse would pull toward MAC-bound. No such reproducer is | ||
| 131 | + retained here; write one from §1's knob table. | ||
| 132 | +3. Gate A, then profile (`AiCMetrics.PipeUtilization` → `kernel_details.csv`). | ||
| 133 | +4. Report the **top sub-ratio** (is it the pipe you targeted?) **and** the achieved GB/s (is it at | ||
| 134 | + the §4 ceiling?). State util-bound vs bandwidth-bound explicitly. | ||
| 135 | +5. Sweep the knob (e.g. T ∈ {16,32,64} or K ∈ {16,32,64}) to show the crossover and find the | ||
| 136 | + configuration that maximises the target metric. | ||
| 137 | + | ||
| 138 | +--- | ||
| 139 | + | ||
| 140 | +## 6. Traps (shared with `pypto-pl-cube-bound`) | ||
| 141 | + | ||
| 142 | +- **`cube_utilization(%)` lies** — it read 88–92% on kernels that were mte2-bound. Use the top AIC | ||
| 143 | + sub-ratio, never `cube_util`. | ||
| 144 | +- **Include `aic_scalar_ratio`** — at tiny tiles it dominates (loop overhead), and an MTE2 probe at | ||
| 145 | + T=16 will show scalar climbing; do not mistake it for the intended bottleneck. | ||
| 146 | +- **Never compare `aicore_time` across shapes** — normalise to a rate (GB/s, TMAC/s). | ||
| 147 | +- **Utilisation is a ratio** — it rises when a pipe does more work OR when the kernel runs shorter; | ||
| 148 | + confirm with achieved bandwidth before drawing conclusions. | ||
| 149 | +- **Shared box:** if a run fails, check it is not the env before blaming the kernel — run the repo's | ||
| 150 | + own `test_matmul_api_basic.py::test_t01`; if that also fails (e.g. `ModuleNotFoundError` during an | ||
| 151 | + editable-install rebuild), it is the box, not you. | ||
| 152 | + | ||
| 153 | +--- | ||
| 154 | + | ||
| 155 | +## 7. Reference | ||
| 156 | + | ||
| 157 | +- 🔴 **Not retained in this KB**: the parameterised `sat_mte2_*` / `sat_fix_*` / `sat_mac_ref` kernels, | ||
| 158 | + the vector-datacopy MTE2(load)/MTE3(store) bandwidth probe for bf16 and fp8, and the measured | ||
| 159 | + util-versus-bandwidth table they produced. §§3–6 above are what survives of them. Rebuilding a probe | ||
| 160 | + means writing it from §2's knob table, not recovering a file. | ||
| 161 | +- `cannbot-skills/kb/constraints/arch-a5.md` — the platform gate and the primary source paths to read | ||
| 162 | + the ceilings from. It is a constraint-discovery page: it holds no measured ratio, bandwidth or | ||
| 163 | + duration by design, which is why a probe is needed at all. | ||
| 164 | +- `pypto-pl-cube-bound` — the inverse skill (drive MAC to the top), its cost model, and the | ||
| 165 | + bandwidth figures it retains in §7. The per-pipe bandwidth write-up those figures came from is not | ||
| 166 | + part of this tree. | ||
| @@ -0,0 +1,352 @@ | |||
| 1 | +--- | ||
| 2 | +name: pypto-pl-vector-kernel | ||
| 3 | +description: Design, build, and optimise pl tile-DSL VECTOR (section_vector) kernels on the a5 NPU — row-normalisations (softmax, rmsnorm, l2norm, layernorm), activations (silu, gelu, sigmoid), elementwise ops, and their mixed-precision (bf16/fp8 in, fp32 compute) variants. Provides the kernel template, the row-reduction idiom, the exact set of load-bearing pitfalls (make_tile_group vs make_tile, the DN reduction row-major alias, no col_expand_add, literal make_tile args), the available op set (no activation primitives — compose them), the fp32↔bf16↔fp8 cast pattern, and the compute-vs-memory-bound analysis with measured rooflines. §7b/§7c cover register-level `pl.vf` and DYNAMIC-SHAPE / PRODUCTION vf kernels (one op over many runtime shapes/dtypes/special-values) — the factory co_name build-cache collision, the 64-lane (LANES) tile-width requirement + UB slot accounting, inf/nan device-reduction HANGS (507034) and the amax finiteness gate, D-chunking + the auto_mutex hang, surfacing hidden bisheng errors, and grading via the harness `compare_tensors`. Use whenever building or debugging any vector/elementwise/normalisation 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 | +> **Note on referenced material.** Sample citations below resolve into the governed knowledge base | ||
| 9 | +> at `cannbot-skills/kb/`. Where that tree retains a matching implementation the citation names it; | ||
| 10 | +> where it does not, the citation names the constraint or record page that carries the surviving | ||
| 11 | +> rule, and the measurement behind it was made on the environment the sentence states. The sibling | ||
| 12 | +> skills are `pypto-pl-cube-bound` and `pypto-pl-pipe-roofline`, and the cross-cutting trap index is | ||
| 13 | +> `cannbot-skills/kb/pitfall-records.md`. | ||
| 14 | + | ||
| 15 | +Covers row-normalisations, activations, elementwise ops, and their mixed-precision variants. All | ||
| 16 | +numbers measured on Ascend950 (32 vector cores) 2026-07-22. Kernels + data: | ||
| 17 | +`cannbot-skills/kb/examples/samples/vector_kernels/` and `.../norm_softmax_rms_l2/`. | ||
| 18 | + | ||
| 19 | +**Companions:** `pypto-pl-cube-bound` (matmul → MAC-bound), `pypto-pl-pipe-roofline` (drive a pipe | ||
| 20 | +to its GB/s limit). This skill is the vector-engine counterpart. | ||
| 21 | + | ||
| 22 | +--- | ||
| 23 | + | ||
| 24 | +## 1. The template (copy this) | ||
| 25 | + | ||
| 26 | +```python | ||
| 27 | +@pl.jit(auto_mutex=True) | ||
| 28 | +def kern(x: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP32], y: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP32]): | ||
| 29 | + TR, N = 8, 1024 | ||
| 30 | + tt = pl.TileType(shape=[TR, N], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec, valid_shape=[-1, -1]) | ||
| 31 | + rt = pl.TileType(shape=[TR, 1], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec, layout=pl.DN, valid_shape=[-1, -1]) | ||
| 32 | + ing = pl.make_tile_group(type=tt, addrs=[0x00000, 0x08000], mutex_ids=[0, 1]) # double-buffered | ||
| 33 | + outg = pl.make_tile_group(type=tt, addrs=[0x10000, 0x18000], mutex_ids=[2, 3]) | ||
| 34 | + tmpg = pl.make_tile_group(type=tt, addrs=[0x20000, 0x28000], mutex_ids=[4, 5]) | ||
| 35 | + redg = pl.make_tile_group(type=rt, addrs=[0x30000, 0x30400], mutex_ids=[6, 7]) | ||
| 36 | + with pl.section_vector(): | ||
| 37 | + rows, cols = x.shape[0], x.shape[1] | ||
| 38 | + nc, cid = pl.get_block_num(), pl.get_block_idx() | ||
| 39 | + nt = (rows + TR - 1) // TR | ||
| 40 | + for t in pl.range(cid, nt, nc): # row-tiles striped across vector cores | ||
| 41 | + ro = t * TR; vr = pl.min(TR, rows - ro) # vr = valid rows (tail tile is partial) | ||
| 42 | + xi = ing.next(); pl.set_validshape(xi, [vr, cols]); pl.load(xi, x, [ro, 0]) | ||
| 43 | + o = outg.next(); tm = tmpg.next(); rd = redg.next() | ||
| 44 | + pl.set_validshape(o, [vr, cols]); pl.set_validshape(tm, [vr, cols]); pl.set_validshape(rd, [vr, 1]) | ||
| 45 | + # ... compute ... | ||
| 46 | + pl.store(y, o, [ro, 0]) | ||
| 47 | +``` | ||
| 48 | + | ||
| 49 | +Load form: `kern[None, min(32, nt)](args)` (block_dim clamps to `core_num`≈32; see | ||
| 50 | +`pypto-pl-pipe-roofline`). Each core owns whole row-tiles → the reduction over N stays local. | ||
| 51 | + | ||
| 52 | +--- | ||
| 53 | + | ||
| 54 | +## 2. The row-reduction idiom | ||
| 55 | + | ||
| 56 | +Per-row reduce over N, then broadcast back. Reduction result is `[TR,1]` **DN layout**. | ||
| 57 | + | ||
| 58 | +| op | call | | ||
| 59 | +|---|---| | ||
| 60 | +| row max / sum | `pl.row_max(rd, xi, tm)` / `pl.row_sum(rd, xi, tm)` — `tm` is a `[TR,N]` scratch tile | | ||
| 61 | +| broadcast a `[TR,1]` per-row scalar over N | `pl.row_expand_sub / _mul / _div / _add(out, src, rd)` | | ||
| 62 | +| broadcast a `[1,N]` per-column vector over rows | `pl.col_expand_mul / _sub / _div(out, src, vec)` | | ||
| 63 | +| unary | `pl.exp, log, sqrt, rsqrt, recip, relu, abs, neg` | | ||
| 64 | +| binary (tile or scalar rhs) | `pl.add, sub, mul, div, maximum, minimum` | | ||
| 65 | + | ||
| 66 | +Worked kernels (all Gate-A validated): | ||
| 67 | +- **softmax**: `row_max → row_expand_sub → exp → row_sum → row_expand_div` | ||
| 68 | +- **l2norm**: `mul(sq)=x² → row_sum → (rsqrt on alias) → row_expand_mul` | ||
| 69 | +- **rmsnorm**: as l2norm + `mul(1/N)` and `add(eps)` on the alias before rsqrt | ||
| 70 | +- **layernorm**: `row_sum→mean → row_expand_sub(xc) → mul(xc²)→row_sum→var → rsqrt → row_expand_mul → col_expand_mul(γ) → col_expand_sub(-β)` | ||
| 71 | + | ||
| 72 | +--- | ||
| 73 | + | ||
| 74 | +## 3. THE PITFALLS — every one cost real debugging time | ||
| 75 | + | ||
| 76 | +### 3a. Computed / reused tiles MUST be `make_tile_group`, not bare `make_tile` | ||
| 77 | +`auto_mutex` tracks cross-op read-after-write hazards **only for tile groups**. A bare | ||
| 78 | +`pl.make_tile` that is *written by one op and read by a later op* (e.g. `negbeta = mul(beta,-1)` | ||
| 79 | +then `col_expand_sub(out, xc, negbeta)`) is **not** synced → the reader sees stale data → **wrong | ||
| 80 | +result, no error**. This produced a layernorm that computed `maxdiff≈5` until every gamma/beta/ | ||
| 81 | +negbeta tile was switched to `make_tile_group`. **Rule: use `make_tile_group` for any tile that | ||
| 82 | +participates in a cross-op dependency.** Bare `make_tile` is only safe for a transient reduction | ||
| 83 | +scratch or its row-major alias (§3b). | ||
| 84 | + | ||
| 85 | +### 3b. Scalar ops on a reduction need the ROW-MAJOR alias (the DN view faults) | ||
| 86 | +A reduction writes a `[TR,1]` **DN** tile (consumed by `row_expand_*`). But `rsqrt / div / add / | ||
| 87 | +mul` **fault on the DN view**. Alias the same address as a `[1,TR]` row-major tile and run the | ||
| 88 | +scalar op there: | ||
| 89 | +```python | ||
| 90 | +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) | ||
| 91 | +rdm = pl.make_tile(pl.TileType(shape=[1,TR], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec), addr=0x30000, size=512) # same addr | ||
| 92 | +pl.row_sum(rd, sq, tm); pl.add(rdm, rdm, EPS); pl.rsqrt(rdm, rdm); pl.row_expand_mul(o, x, rd) | ||
| 93 | +``` | ||
| 94 | +`set_validshape(rdm, [1, vr])` before the scalar ops. (Bare `make_tile` is fine here — the alias is | ||
| 95 | +transient and the DSL threads the dependency through the shared address.) | ||
| 96 | + | ||
| 97 | +### 3c. There is NO `col_expand_add` | ||
| 98 | +`row_expand_add` exists; `col_expand_add` does **not**. For a per-column bias `β [1,N]`, precompute | ||
| 99 | +`-β` and use `col_expand_sub(out, x, negbeta)` (== `x + β`). This is why every layernorm/bias kernel | ||
| 100 | +carries a `negbeta` tile. | ||
| 101 | + | ||
| 102 | +### 3d. `make_tile` `addr` and `size` must be COMPILE-TIME LITERALS | ||
| 103 | +`pl.make_tile(tt, addr=0x8000, size=32768)` works; `size=TR*N*4` or `addr=cond?a:b` **fail to | ||
| 104 | +parse** ("Unsupported kwarg type for key: memref_size/addr"). The tracer wraps computed | ||
| 105 | +expressions. Hardcode the numbers. | ||
| 106 | + | ||
| 107 | +### 3e. Divide by a compile-time constant, not always the traced shape | ||
| 108 | +`pl.div(rdm, rdm, cols)` with `cols=x.shape[1]` (a traced runtime value) can misbehave; the proven | ||
| 109 | +kernels divide by the literal `float(N)` for mean/`1/N`. Prefer the literal when N is fixed. | ||
| 110 | + | ||
| 111 | +### 3f. UB budget ≈ 256 KB — pack tiles, expect a runtime fault if you overshoot | ||
| 112 | +Over-subscription is a **device fault (507035)**, not a compile error. Sum every live buffer | ||
| 113 | +(double-buffered groups count ×2). Keep total ≲ 224 KB for margin (253 KB allocates, 259 KB | ||
| 114 | +faults). Pack addresses contiguously; a spread-out layout wastes UB and faults. | ||
| 115 | + | ||
| 116 | +--- | ||
| 117 | + | ||
| 118 | +## 4. Activations — there are NO activation primitives; compose them | ||
| 119 | + | ||
| 120 | +`pl` has **no** `sigmoid / tanh / gelu / silu / erf`. Available unary: `exp, log, sqrt, rsqrt, | ||
| 121 | +recip, relu, abs, neg`. Compose: | ||
| 122 | + | ||
| 123 | +| activation | recipe (measured Gate-A correct) | | ||
| 124 | +|---|---| | ||
| 125 | +| **sigmoid** `1/(1+e^-x)` | `mul(t,x,-1); exp(t,t); add(t,t,1.0); recip(t,t)` | | ||
| 126 | +| **silu / swish** `x·σ(x)` | sigmoid, then `mul(o, x, t)` — maxdiff 4.8e-7 vs `F.silu` | | ||
| 127 | +| **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 | | ||
| 128 | +| **tanh** | compose from `exp` (`1 - 2/(e^{2x}+1)`) | | ||
| 129 | + | ||
| 130 | +Note `lrelu`, `prelu`, `relu`, and fused `add_relu`/`fused_mul_add`/`mul_cast` DO exist. | ||
| 131 | + | ||
| 132 | +--- | ||
| 133 | + | ||
| 134 | +## 4b. Ops with NO native primitive — compose them (activations, cumsum, RoPE, reduce) | ||
| 135 | + | ||
| 136 | +`pl` lacks several common primitives. Build them: | ||
| 137 | + | ||
| 138 | +| op | missing primitive | how (validated) | | ||
| 139 | +|---|---|---| | ||
| 140 | +| **sigmoid/silu/gelu/tanh** | no activation ops | compose from `exp/recip/mul` (§4) | | ||
| 141 | +| **reduce (sum/max)** | — (`row_sum`/`row_max` exist) | `row_sum(rd, x, tmp)` → store `[M,1]`. Load-heavy ⇒ **memory-bound** | | ||
| 142 | +| **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. | | ||
| 143 | +| **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). | | ||
| 144 | + | ||
| 145 | +**General principle: a missing primitive is either composed from elementwise ops, expressed as a | ||
| 146 | +matmul (scan → triangular, permutation → sparse matrix), or moved to a host pre/post-step (trig | ||
| 147 | +tables, interleave layout).** The device does the arithmetic; the host does layout and table | ||
| 148 | +generation. | ||
| 149 | + | ||
| 150 | +--- | ||
| 151 | + | ||
| 152 | +## 5. Mixed precision — bf16/fp8 input, fp32 compute | ||
| 153 | + | ||
| 154 | +Norm/softmax need fp32 for numerical stability. Pattern: **load low-precision → `pl.cast` up to | ||
| 155 | +fp32 → compute in fp32 → `pl.cast` down → store**. | ||
| 156 | + | ||
| 157 | +```python | ||
| 158 | +xb = xbf16_group.next(); pl.load(xb, x, [ro, 0]) # bf16 (or fp8) load, half/quarter the bytes | ||
| 159 | +pl.cast(xf32, xb, mode=pl.RoundMode.CAST_NONE) # widen — exact, mode irrelevant | ||
| 160 | +# ... fp32 compute into of32 ... | ||
| 161 | +oo = obf16_group.next(); pl.cast(oo, of32, mode=pl.RoundMode.CAST_ROUND) # narrow — CAST_ROUND | ||
| 162 | +pl.store(y, oo, [ro, 0]) | ||
| 163 | +``` | ||
| 164 | + | ||
| 165 | +- **bf16**: full compute-capable dtype; `pl.cast` fp32↔bf16 is proven. Widen `CAST_NONE`, narrow | ||
| 166 | + `CAST_ROUND`. | ||
| 167 | +- **fp8** (`DT_FP8E4M3FN` / `E5M2` / `HF8`): **storage-only** — you **cannot** do fp8 arithmetic | ||
| 168 | + (`pl.mul` on an fp8 tile **fails to compile**). BUT **`pl.cast` fp8↔fp32 WORKS** (empirically | ||
| 169 | + verified, contradicting the static "storage-only" reading). So the same cast-bridge pattern | ||
| 170 | + builds fp8 norms: load fp8 → cast fp32 → compute → cast fp8 → store. Measured softmax_fp8 maxdiff | ||
| 171 | + 2.58e-3 (fine for e4m3). | ||
| 172 | + | ||
| 173 | +### ⚠️ Counter-intuitive result: narrower input is SLOWER for these ops | ||
| 174 | +Measured softmax, same shape (8192×1024): | ||
| 175 | + | ||
| 176 | +| input dtype | aiv_time | vec util | GM (r+w) | verdict | | ||
| 177 | +|---|---|---|---|---| | ||
| 178 | +| fp32 | **31.8 µs** | 0.957 | 2.11 TB/s | compute-bound | | ||
| 179 | +| bf16→fp32 | 63.7 µs | 0.987 | 0.53 TB/s | **more** compute-bound | | ||
| 180 | +| fp8→fp32 | 93.4 µs | 0.992 | 0.18 TB/s | **most** compute-bound | | ||
| 181 | + | ||
| 182 | +Narrowing the input **halves/quarters the memory traffic** (GM 2.11→0.18 TB/s) but these ops are | ||
| 183 | +**already compute-bound**, so the memory saving buys nothing — and the two extra cast passes make | ||
| 184 | +the kernel **slower**. **Mixed-precision input helps only if the COMPUTE runs in the narrow dtype** | ||
| 185 | +(2× vector ALU throughput); casting to fp32 forfeits that. For a compute-bound vector op, prefer | ||
| 186 | +fp32 in/out unless memory bandwidth or capacity is the real constraint elsewhere. | ||
| 187 | + | ||
| 188 | +--- | ||
| 189 | + | ||
| 190 | +## 6. Compute-bound vs memory-bound — the analysis that decides the ceiling | ||
| 191 | + | ||
| 192 | +**Count the passes over the data.** Vector ALU passes vs memory passes (1 read + 1 write = 2): | ||
| 193 | + | ||
| 194 | +| kernel | vec passes | mem passes | measured vec util | GM r+w | bound | | ||
| 195 | +|---|---|---|---|---|---| | ||
| 196 | +| softmax | 5 | 2 | 0.957 | 2.11 TB/s | **compute** | | ||
| 197 | +| layernorm | ~7 | 2 | 0.954 | 1.42 TB/s | **compute** | | ||
| 198 | +| l2norm / rmsnorm | ~4 | 2 | 0.91–0.92 | 3.7 TB/s | compute (near both) | | ||
| 199 | +| silu / gelu | 5 | 2 | 0.94 | 3.0 TB/s | **compute** | | ||
| 200 | +| **elementwise** `2x+1` | 1 | 2 | 0.53 | **4.57 TB/s** | **MEMORY** (mte2 0.91) | | ||
| 201 | +| **reduce_sum** (row→[M,1]) | 1 | ~1 (read-heavy) | 0.57 | read 2.36 TB/s | **MEMORY** (mte2 0.94) | | ||
| 202 | +| **RoPE** (interleaved) | ~5 | 2 | 0.88 | 1.04 TB/s | **compute** | | ||
| 203 | +| **cumsum** (matmul, N=128) | — (cube) | — | (cube MAC) | — | cube — no vector scan op | | ||
| 204 | + | ||
| 205 | +**Rule: vec passes > mem passes ⇒ compute-bound.** Row-reductions and activations (4–7 passes) are | ||
| 206 | +compute-bound — the vector ALU saturates (util 0.91–0.99). A pure 1-op elementwise is the | ||
| 207 | +memory-bound end (mte saturated, GM at the ceiling). There is **no fused square-sum reduce** on a5 | ||
| 208 | +(`reduce_sum/max/min` only), so l2/rms cannot drop below their pass count to become memory-bound. | ||
| 209 | + | ||
| 210 | +**How to characterise (do both):** | ||
| 211 | +1. Gate A first (a wrong kernel's utilisation is meaningless). | ||
| 212 | +2. Profile `AiCMetrics.PipeUtilization` → read `aiv_vec_ratio` (compute) and `aiv_mte2/mte3_ratio` | ||
| 213 | + (memory). Vector kernels use **`aiv_time`**, not `aicore_time`. | ||
| 214 | +3. **Verdict = the top `aiv_*` sub-ratio.** Report it AND the aggregate GM `= (read+write bytes) / | ||
| 215 | + aiv_time` in TB/s. | ||
| 216 | + | ||
| 217 | +### a5 vector-engine rooflines (measured) | ||
| 218 | +- **Vector ALU**: saturates ~0.95–0.99 for compute-bound ops. | ||
| 219 | +- **GM via vector (aiv_mte2 load / aiv_mte3 store)**: **~2.2 TB/s one-way**, ~3.3–4.6 TB/s aggregate | ||
| 220 | + (overlapped read+write). This is **~half the cube's GM path** (~4.5–4.7 TB/s) — the AIV↔UB DMA | ||
| 221 | + port is narrower than AIC↔L1. See `pypto-pl-pipe-roofline` §4; the underlying investigation write-up | ||
| 222 | + is not part of this tree. | ||
| 223 | + | ||
| 224 | +**Optimisation levers, by bound:** | ||
| 225 | +- **Compute-bound** (most norms/activations): fewer/cheaper vector ops; fuse (`fused_mul_add`, | ||
| 226 | + `add_relu`); avoid needless casts (§5). More memory bandwidth does nothing. | ||
| 227 | +- **Memory-bound** (elementwise): bigger contiguous tiles, double-buffer for load/store overlap, | ||
| 228 | + narrower dtype (fewer bytes). Reaching the GM ceiling needs large transfers (see roofline skill). | ||
| 229 | + | ||
| 230 | +--- | ||
| 231 | + | ||
| 232 | +## 7. Procedure | ||
| 233 | + | ||
| 234 | +1. Pick `TR`, `N` so the row tile fits UB (§3f); N ≤ tile width for single-pass reduction (N up to | ||
| 235 | + a few thousand fits at small TR; larger N needs a two-pass accumulate — **no proven template | ||
| 236 | + exists, it is new code**). | ||
| 237 | +2. Copy the §1 template; build the compute from §2/§4. | ||
| 238 | +3. Apply the §3 pitfalls **before first run** (groups for computed tiles, row-major alias for | ||
| 239 | + scalar-on-reduction, `-β`, literal make_tile args). | ||
| 240 | +4. Gate A vs torch. If wrong, **bisect** (drop gamma, then beta, etc.) — it localises DSL-semantics | ||
| 241 | + bugs fast (this is how the layernorm gamma/beta bug was found). | ||
| 242 | +5. Profile; report top `aiv_*` ratio + GM TB/s; classify compute vs memory bound (§6). | ||
| 243 | +6. For mixed precision, use the §5 cast-bridge and expect *more* compute-bound / slower. | ||
| 244 | + | ||
| 245 | +--- | ||
| 246 | + | ||
| 247 | +## 7b. When to use `pl.vf` (register-level) — it DEPENDS on the kernel | ||
| 248 | + | ||
| 249 | +Two vector programming models: the **tile-op block API** (`pl.row_sum`, `pl.exp` on whole tiles — | ||
| 250 | +everything above) and **register-level `pl.vf`** (`@pl.vector_function`, 64-lane `vf.load_align`/ | ||
| 251 | +`vf.reduce_sum`/`vf.exp` register loops). Both lower to the same ISA, but they differ in **how | ||
| 252 | +intermediates flow**, and that splits the outcome cleanly (measured, 8192×N fp32, a5): | ||
| 253 | + | ||
| 254 | +| kernel type | example | tile-op | vf | winner | | ||
| 255 | +|---|---|---|---|---| | ||
| 256 | +| **multi-op elementwise** | rope | 8.1 µs | **4.5 µs** | **vf 1.8×** | | ||
| 257 | +| | gelu / silu | 22.5 / 22.2 | **14.9 / 15.2** | **vf ~1.5×** | | ||
| 258 | +| trivial elementwise | `2x+1` | 14.7 | 14.8 | tie | | ||
| 259 | +| **reduction** (ILP-written) | l2norm | 17.4 | **14.9** | **vf 1.17×** | | ||
| 260 | +| | softmax | 31.4 | **25.8** | **vf 1.22×** | | ||
| 261 | +| | layernorm (2 reduce + affine) | 23.6 | 23.3 | tie (~1.02×) | | ||
| 262 | + | ||
| 263 | +**Why:** the tile-op API materialises every intermediate to UB (a k-op chain = ~k UB round-trips); | ||
| 264 | +`vf` chains ops **in registers** (only load + store touch UB). So a multi-op elementwise chain | ||
| 265 | +(silu, gelu, rope) drops from compute-bound to **memory-bound** in vf and runs ~1.5–1.8× faster. | ||
| 266 | +**Reductions also win in vf — but only if written for ILP** (this corrects an earlier "tile-op wins | ||
| 267 | +for reductions" verdict that was a bad-template artifact). The reduction recipe: | ||
| 268 | + | ||
| 269 | +1. **Constant mask, never dynamic.** Use `preg = vf.create_mask(ALL)` (or `update_mask(64)`) once — | ||
| 270 | + NOT a per-register `update_mask(min(LANES, n_cols−r·LANES))`. The dynamic per-register mask was | ||
| 271 | + ~86% of the old slowness (l2 22.4→16.2 µs). For ragged N, hoist the full mask and compute one | ||
| 272 | + `update_mask(tail)` for the last partial register only. | ||
| 273 | +2. **Vertical-accumulate:** one `vf.add`/`vf.max` per register into an accumulator, a *single* | ||
| 274 | + `vf.reduce_sum`/`reduce_max` at the very end — not a per-register horizontal reduce. | ||
| 275 | +3. **4 independent accumulators (unroll-4)** to break the accumulation dependency chain. This is the | ||
| 276 | + ceiling — unroll-8 adds nothing. **Unroll only helps while the kernel is still compute-bound** | ||
| 277 | + (aiv_vec ≫ aiv_mte2): softmax (heavy `exp`) gains ~10% from it; l2norm slides to memory-bound at | ||
| 278 | + step 2 already, so unroll is within noise there. Combine the accumulators with *explicit* | ||
| 279 | + assignments — nested `vf.add(vf.add(...),...)` is a parser error. | ||
| 280 | + | ||
| 281 | +**Rule: `vf` wins or ties for both elementwise-heavy AND reduction-heavy kernels** — elementwise via | ||
| 282 | +register residency; single-reduction kernels (l2norm, softmax) via hand-written ILP beating the | ||
| 283 | +serial fused `row_sum` (1.17–1.22×). The reduction gain **shrinks to a tie** when fixed multi-pass | ||
| 284 | +overhead dominates: layernorm (2 reductions + gamma/beta affine, re-centers x in the apply pass) is | ||
| 285 | +even with tile-op — still a fix vs the old bad-template 0.90× loss, but not a win. Also: `float(...)` | ||
| 286 | +/ other Python builtins are unsupported inside a `@pl.vector_function` (args are parsed, not run — | ||
| 287 | +pass literals). Full data, attribution, and gotchas (factory-name collision; negate via | ||
| 288 | +`exp_sub(zero,x)` not `muls(-1)`; wide out-tile for `[M,1]` reduce; no `vf.rsqrt`): | ||
| 289 | +the comparison and unroll write-ups are not part of this tree; the kernels themselves are retained | ||
| 290 | +under `cannbot-skills/kb/examples/samples/vf_vs_tileop/`. | ||
| 291 | + | ||
| 292 | +## 7c. Production / dynamic-shape vf kernels — the gotchas that cost hours (cann-bench rms/softmax) | ||
| 293 | + | ||
| 294 | +Building ONE op that must cover many runtime shapes (D=2…8192, even/odd, fp16/fp32/bf16, special | ||
| 295 | +values). Each of these was a multi-iteration bug; iteration is punishing (~60 s per compile, **~5 min | ||
| 296 | +per device-timeout hang**), so bisect on **tiny inputs** (only a *hang* costs time; a *success* | ||
| 297 | +returns instantly) and change **one variable per cycle**. | ||
| 298 | + | ||
| 299 | +- **Factory name-collision — the one that wasted the most time.** pypto keys its compiled-kernel | ||
| 300 | + **build cache by the function `co_name`** (`build/<module>__<coname>__a5/tk_none/`). A | ||
| 301 | + `def _make(D): @pl.jit def k(...)` factory returns kernels all named `k`, so the **second D silently | ||
| 302 | + reuses the first D's `.so`** (e.g. a 768-wide kernel on 1024-wide data → garbage, maxdiff ~3, NOT a | ||
| 303 | + crash). Symptom: "correct at the first shape, wrong at all others; reversing call order flips which | ||
| 304 | + works." **`k.__name__ = ...` does NOT fix it** (co_name is set at `def`); **`exec` breaks pypto's | ||
| 305 | + `inspect.getsource`.** Fix: **code-gen each per-shape kernel to a real `.py` file with a unique | ||
| 306 | + `def` name**, then `importlib` it. (The kernel-generator this was found in is not part of this tree.) | ||
| 307 | +- **vf tile width must be a multiple of 64 (`LANES`), not 8.** `vf.load_align`/`store_align` move a | ||
| 308 | + full 64-lane register, so the last register at `(n_regs-1)*64` **overruns any tile whose width isn't | ||
| 309 | + a 64-multiple → 507035** (device memory fault). Use `align64(D)` for the tile; per-register | ||
| 310 | + `vf.update_mask(pl.min(64, cols - r*64))` masks the ragged tail so pad lanes don't contribute. | ||
| 311 | +- **UB fit = count ALL slots.** Double-buffered in+out = **4 tile slots** (`0/tb/2tb/3tb`), vector UB | ||
| 312 | + is **256 KB (262144)**. vf single-tile gate: `4*TR*NN*4 ≤ 262144` ⇒ `align64(D) ≤ 2048` | ||
| 313 | + (D=2048 fits *exactly*; 2049 overruns → 507035). Over-count and you fault, don't hang. | ||
| 314 | +- **vf beats tile-op on FOOTPRINT here, not just speed:** the reduction lives in **registers**, so vf | ||
| 315 | + needs only in+out tiles (4 slots) vs the tile-op's 6+ (in/out/tmp + reduction) → it fits **larger D | ||
| 316 | + double-buffered** and **avoids the single-buffer-at-scale hang** (single-buffered tile-op passed at | ||
| 317 | + 16 rows, HUNG at 4096). Default to vf for dynamic-shape reductions. | ||
| 318 | +- **Special values (inf/nan) HANG the device reduction** (507034 vector-core-timeout — not wrong | ||
| 319 | + output, a *hang*): `row_sum`/`reduce_sum`/`rsqrt`/`exp` on inf/nan wedge the core. **Gate | ||
| 320 | + special-value inputs to a primitive (torch) fallback.** Detect finiteness with a **float max | ||
| 321 | + reduction** `math.isfinite(float(x.abs().amax()))` — **`torch.isfinite(x).all()` itself FAULTS the | ||
| 322 | + NPU on nan** (507034); `amax`/`mean`/`sum` handle nan fine. | ||
| 323 | +- **Repeated hangs WEDGE the whole device** (after a 507034, later ops fault until a reset/reboot; | ||
| 324 | + the SSH/container can hang too). So gate special values out *before* they reach the kernel — one | ||
| 325 | + ungated hang poisons the rest of the run. | ||
| 326 | +- **D-chunked (tile the reduce axis) for D > single-tile fit:** accumulate the DN `[TR,1]` partial on | ||
| 327 | + its **row-major alias** (`TADD` "only supports row major"), first-chunk-seed or `pl.expands(acc,0)`. | ||
| 328 | + The `auto_mutex` version **compiles but HANGS** (cross-view read-after-write it can't sync); the | ||
| 329 | + working FA/`smla_softmax_l1_norm` chunked kernels use **manual `pl.system.bar_v()` barriers (drop | ||
| 330 | + `auto_mutex`)** — that rewrite is the path to full large-D vf coverage (still open). | ||
| 331 | +- **Surfacing the hidden bisheng compile error:** `_ensure_compiled` swallows it as "Failed to compile | ||
| 332 | + kernel 'k'". `_run_bisheng` does `logging.error(stderr)`, but pytest captures stdout logging — add a | ||
| 333 | + **`logging.FileHandler` to a file** to read the real error (this is how `TADD only support row major` | ||
| 334 | + and the collision were finally seen). Inspect the generated code at `build/…/tk_none/kernel.cpp`. | ||
| 335 | +- **Grading without the (intractable) `kernel_eval.cli`:** the CLI `eval` is silent + slow (>10 min | ||
| 336 | + for ONE case: fp64-on-CPU golden/native for big cases) and dies on a busy box. **Import the harness's | ||
| 337 | + real `kernel_eval.utils.compare.compare_tensors` directly** into a lightweight validator (same | ||
| 338 | + data-gen + fp64 golden + same-precision native + official thresholds/fallbacks) for the official | ||
| 339 | + per-case verdict — no wheel-build/profiling/subprocess machinery. (The box environment must be | ||
| 340 | +sourced first; that script is not part of this tree.) | ||
| 341 | + | ||
| 342 | +## 8. Reference | ||
| 343 | + | ||
| 344 | +- `cannbot-skills/kb/examples/samples/vf_vs_tileop/` — the retained **dynamic-shape vf rms/softmax | ||
| 345 | + kernels** behind the 40/40 official result. The hybrid routers, the two validators and the status | ||
| 346 | + write-up that recorded every gotcha in §7c are **not part of this tree**; §7c is what survives of | ||
| 347 | + them. | ||
| 348 | +- `cannbot-skills/kb/examples/samples/norm_softmax_rms_l2/` — fp32 softmax/l2norm/rmsnorm + bound analysis. | ||
| 349 | +- `cannbot-skills/kb/examples/samples/vector_kernels/` — layernorm, silu/gelu, memory-bound elementwise, | ||
| 350 | + bf16 & fp8 mixed-precision norms. The raw measurement log is not part of this tree. | ||
| 351 | +- `pypto-pl-pipe-roofline` — the GM/pipe bandwidth ceilings and the GM↔UB root cause. | ||
| 352 | +- `cannbot-skills/kb/pitfall-records.md` — the same pitfalls in cross-cutting form. | ||
| @@ -26,6 +26,15 @@ description: 设计 PyPTO-Pro 算子的 tile 级执行方案。用于确定 Phas | |||
| 26 | `validated skeleton` 的条目可作为代码起点;`conceptual only` 只能用于推导。 | 26 | `validated skeleton` 的条目可作为代码起点;`conceptual only` 只能用于推导。 |
| 27 | 平台专属约束必须先探测目标平台。API 文档与当前环境的官方样例仍是签名和行为的权威来源。 | 27 | 平台专属约束必须先探测目标平台。API 文档与当前环境的官方样例仍是签名和行为的权威来源。 |
| 28 | 28 | ||
| 29 | +**在划分 Phase / Section 结构之前先查 pattern selector**:可复用的 pl 数据流骨架就在 | ||
| 30 | +[`kb/patterns/`](../../kb/patterns/pattern-index.md),选好再设计比设计完再对照便宜。 | ||
| 31 | + | ||
| 32 | +🔴 **Pro 流程只允许单一 `@pl.jit` kernel**,所以 pattern selector 的 `pro_legal` 列和每页顶部 | ||
| 33 | +的同名 banner 与 `validation` 列同等重要:`pro_legal: false` 的页(当前是 | ||
| 34 | +[`multi-jit-fusion.md`](../../kb/patterns/multi-jit-fusion.md))描述的 host 端多 kernel 形态在 | ||
| 35 | +Pro 路径中**禁用**——产出这样的 DESIGN.md 只会在 `stage4-check` #5 被拦下并浪费一轮迭代。只取 | ||
| 36 | +其融合单 kernel 子形态(同一个 `@pl.jit` 内多个 section)。 | ||
| 37 | + | ||
| 29 | ## 输入 | 38 | ## 输入 |
| 30 | 39 | ||
| 31 | | 来源 | 路径 | 用途 | | 40 | | 来源 | 路径 | 用途 | |
| @@ -5,7 +5,7 @@ description: 采集、比较和分析 PyPTO-Pro 算子在 NPU 上的性能。用 | |||
| 5 | 5 | ||
| 6 | # PyPTO-pro 上板性能采集与分析 | 6 | # PyPTO-pro 上板性能采集与分析 |
| 7 | 7 | ||
| 8 | -在真实 NPU 上采集 PyPTO 算子性能数据,系统化解读指标文件,判定性能是否达标,定位瓶颈类型。本技能为 **PyPTO-Pro Stage 4 的按需性能诊断**提供独立、公正的性能数据采集能力(wrapper 边界门禁的动态检查即由此采集 `op_times.device_kernels`);PyPTO classic 的 Stage 7 调优同样可以调用它。 | 8 | +在真实 NPU 上采集 PyPTO 算子性能数据,系统化解读指标文件,判定性能是否达标,定位瓶颈类型。本技能服务两处:**PyPTO-Pro Stage 4 的按需性能诊断**(wrapper 边界门禁的动态检查即由此采集 `op_times.device_kernels`),以及 **PyPTO-Pro Stage 5 的优化循环**(见下节,`pypto-pro-op-optimizer` 自持该循环)。PyPTO classic 的 Stage 7 调优同样可以调用它。 |
| 9 | 9 | ||
| 10 | 本技能基于 **msprof** 工具链,统一入口为两个脚本: | 10 | 本技能基于 **msprof** 工具链,统一入口为两个脚本: |
| 11 | - **`msprof_profile_run.sh`** — 性能采集(标准采集 / 对比测试 / 快速采集 / 批量并行) | 11 | - **`msprof_profile_run.sh`** — 性能采集(标准采集 / 对比测试 / 快速采集 / 批量并行) |
| @@ -17,6 +17,66 @@ description: 采集、比较和分析 PyPTO-Pro 算子在 NPU 上的性能。用 | |||
| 17 | | **`msprof_perf_summary.py`** | [`references/msprof-guide.md`](references/msprof-guide.md) | 统一解析入口:瓶颈分析、对比报告生成、批量汇总 | | 17 | | **`msprof_perf_summary.py`** | [`references/msprof-guide.md`](references/msprof-guide.md) | 统一解析入口:瓶颈分析、对比报告生成、批量汇总 | |
| 18 | | **`perf_summary.py`** | [`references/msprof-op-guide.md`](references/msprof-op-guide.md) | msprof op 归档(需 msopprof) | | 18 | | **`perf_summary.py`** | [`references/msprof-op-guide.md`](references/msprof-op-guide.md) | msprof op 归档(需 msopprof) | |
| 19 | 19 | ||
| 20 | +--- | ||
| 21 | + | ||
| 22 | +## pl optimization loop (Stage 5) | ||
| 23 | + | ||
| 24 | +pl 是 `@pl.jit` tile DSL(`import pypto_pro.language as pl`)的手写授权面:**没有自动 tiling,也没有 | ||
| 25 | +`RunMode.SIM`**——pl 经 bisheng 直接编译到 NPU,性能只能在真机上*测量*。Stage 5 因此是一个 | ||
| 26 | +**NPU-measure 循环**,不是 cost-model 推演。 | ||
| 27 | + | ||
| 28 | +**进入前提**:kernel 已在 NPU 上通过 Stage-4 golden。**无冻结 golden ⇒ 不调优**。 | ||
| 29 | + | ||
| 30 | +**杠杆住在哪里**:[`references/a5-roofline-and-levers.md`](references/a5-roofline-and-levers.md) | ||
| 31 | +——证据门(常量必须从装机的 platform 文件读出)、符号 roofline、measurement loop,以及 | ||
| 32 | +「症状 → 改哪个因子 → 对应 pl 旋钮」表。本节只讲把它包起来的**协议**:一次一因子、快照回退、 | ||
| 33 | +golden 冻结、接受判据。仅在探测确认 `NpuArch=3510` / `dav-c310` 后加载该参考。 | ||
| 34 | + | ||
| 35 | +### MEASURE surface — 判据面 = `kernel_details.csv`(`torch_npu.profiler`) | ||
| 36 | + | ||
| 37 | +- **主面(accept/rollback 判据)= `torch_npu.profiler`(`aic_metrics=…PipeUtilization`)→ | ||
| 38 | + `kernel_details.csv`**。这是本 skill 依据的 pl cube/vector 子 ratio 与 cann-bench 打分 | ||
| 39 | + (`--perf-metric-strategy kernel_details`)**共用**的同一指标面——端到端一个指标。该 CSV 已由现有 | ||
| 40 | + skill `pypto-pro-golden-generate/scripts/profile_golden.py` 产出。 | ||
| 41 | +- **先看 wrapper 占比再调 kernel 内部**:本文「优化第一顺位:先把 wrapper 清零」一节给出口径与 | ||
| 42 | + 阈值,Stage 5 的第一根杠杆据此选择。 | ||
| 43 | +- **msprof 为可选深挖**:`msprof_profile_run.sh` / `msprof_perf_summary.py` 采集的 | ||
| 44 | + `PipeUtilization.csv` **缺** `aic_mac_ratio` / `cube_utilization`(见 | ||
| 45 | + [`references/csv_fields_reference.md`](references/csv_fields_reference.md)),**降级**为可选深挖 + | ||
| 46 | + `--batch` 并行驱动(并行化测量墙钟),**绝不**置于 accept/rollback 关键路径上。 | ||
| 47 | + | ||
| 48 | +### 接受/回退协议(accept/rollback) | ||
| 49 | + | ||
| 50 | +1. **SETUP** — 确认 Stage-4 golden 在 NPU PASS。挑代表 shape(每 dtype 一个 `argmax_shape(numel)`), | ||
| 51 | + 建 target sheet:**`Target(us) = cann_baseline_us`**(HAP 锚点)已知则用之,否则用 `golden(proxy)` | ||
| 52 | + 并标注错位。 | ||
| 53 | +2. **MEASURE** — 主面 `kernel_details.csv`;记 wall time、per-pipe 占用、bound pipe。基线与其后每次 | ||
| 54 | + 变体用同一输入、同一 launch geometry、同一 warm-up 与同一 profiler 配置(见参考文件的 | ||
| 55 | + measurement loop)。 | ||
| 56 | +3. **ANALYZE** — 从留存的 profiler 产物读出**实测的主导 pipe**,用它决定**改哪个因子**。 | ||
| 57 | +4. **TUNE** — 按参考文件的因子表选**恰好一个**因子,就地改同一个 `@pl.jit`。 | ||
| 58 | +5. **RE-VERIFY + RE-MEASURE** — 改动**前**先快照 `test_{op}.py` → `.tuning_snapshots/`(**文件拷贝, | ||
| 59 | + 不用 `git`**——cann-bench opencode run 下该目录可能不是 git tree)。重跑 golden(破了就拒,不论快慢); | ||
| 60 | + 同面重测;**仅当更快且 golden 通过才接受**,否则还原快照 + 标记 rejected。 | ||
| 61 | +6. **传播 + REPORT** — 循环到 `target_met` / 预算耗尽 / 用户叫停,然后把已接受配置传播到同 dtype 兄弟 | ||
| 62 | + shape(逐 shape 廉价重验 golden)。产出 `{op}_tuning_report.md`;`stage5-check` 重跑 golden + | ||
| 63 | + anti-cheat 守卫 + 断言单调(final ≤ baseline us)+ 每个已接受因子严格下降。 | ||
| 64 | + **零接受因子 → `tuning_no_gain`(诚实的空结果,非失败)**;golden 回归归入既有的 | ||
| 65 | + `precision_failure`。 | ||
| 66 | + | ||
| 67 | +### 单一 kernel 契约 | ||
| 68 | + | ||
| 69 | +所有因子 by construction 保持 **单一 `@pl.jit` kernel**:不引入第二个 kernel、不把 kernel 放进循环、 | ||
| 70 | +host 端不做核心计算。违反即被 `stage5-check` 的 anti-cheat 复扫判为红线 FAIL,不以「更快」为由放行。 | ||
| 71 | + | ||
| 72 | +### ×N 代价界 | ||
| 73 | + | ||
| 74 | +cann-bench 每算子约 9 个 `(ndim, dtype, shape)` case-class;pl tiling 是 shape-parametric,故只在 | ||
| 75 | +**每 dtype 一个代表**上跑完整搜索,其余兄弟 shape 复用已接受配置,并用 | ||
| 76 | +`msprof_profile_run.sh --batch --max-jobs=N --device-start=1` 在空闲卡上并行代表测量。 | ||
| 77 | +**盒代价 = (#dtypes) × (因子预算)**,非 (#case-classes) × 预算。 | ||
| 78 | + | ||
| 79 | + | ||
| 20 | --- | 80 | --- |
| 21 | 81 | ||
| 22 | ## 使用方式 | 82 | ## 使用方式 |
| @@ -180,6 +240,7 @@ Markdown 报告包含: | |||
| 180 | | 性能问题定位 | `msprof_profile_run.sh` + `msprof_perf_summary.py` | 深度瓶颈分析(pipe ratio / 带宽 / L2Cache / 逐核负载均衡) | | 240 | | 性能问题定位 | `msprof_profile_run.sh` + `msprof_perf_summary.py` | 深度瓶颈分析(pipe ratio / 带宽 / L2Cache / 逐核负载均衡) | |
| 181 | | 优化效果验证 | `msprof_profile_run.sh` + `msprof_perf_summary.py` | 对比优化前后的归档数据(round_NNN/) | | 241 | | 优化效果验证 | `msprof_profile_run.sh` + `msprof_perf_summary.py` | 对比优化前后的归档数据(round_NNN/) | |
| 182 | | PyPTO-Pro Stage 4 按需诊断 | `msprof_profile_run.sh` | wrapper 边界门禁取 `aclnn*` 占比;coder 定位瓶颈 | | 242 | | PyPTO-Pro Stage 4 按需诊断 | `msprof_profile_run.sh` | wrapper 边界门禁取 `aclnn*` 占比;coder 定位瓶颈 | |
| 243 | +| PyPTO-Pro Stage 5 优化循环 | `kernel_details.csv` + 本文「pl optimization loop」 | 一次一因子的 measure→accept/revert;杠杆见 `references/a5-roofline-and-levers.md` | | ||
| 183 | | PyPTO classic Stage 7 基线采集 | `msprof_profile_run.sh` | 集成到 pypto-op-orchestrator Stage 7 调优流程 | | 244 | | PyPTO classic Stage 7 基线采集 | `msprof_profile_run.sh` | 集成到 pypto-op-orchestrator Stage 7 调优流程 | |
| 184 | | 批量性能测试 | `msprof_profile_run.sh --batch` | 多 NPU 并行批量测试 | | 245 | | 批量性能测试 | `msprof_profile_run.sh --batch` | 多 NPU 并行批量测试 | |
| 185 | 246 | ||
| @@ -64,6 +64,75 @@ Use [msprof-guide.md](msprof-guide.md) or | |||
| 64 | [csv_fields_reference.md](csv_fields_reference.md) for the fields supported by | 64 | [csv_fields_reference.md](csv_fields_reference.md) for the fields supported by |
| 65 | the current parser. | 65 | the current parser. |
| 66 | 66 | ||
| 67 | +### The factors of step 4, and the knob that changes each | ||
| 68 | + | ||
| 69 | +One factor per iteration. The order below is the order to try them in: fill the | ||
| 70 | +cores first, then make each core's pipeline denser, then overlap producer and | ||
| 71 | +consumer and keep data on chip, and specialize last. It is an ordering | ||
| 72 | +heuristic, not a ladder — the measured gap decides where to enter it. | ||
| 73 | + | ||
| 74 | +| Symptom in the measurement | Factor to change | The pl knob | | ||
| 75 | +|---|---|---| | ||
| 76 | +| The whole device is under-used: one core does all the work, and the wall time is roughly one core's serial time | work distribution | give the launch a block dimension and stride the tile loop by the block index and block count | | ||
| 77 | +| Operands are reloaded from GM per tile, or a tile does not fit the on-chip level it is staged into | tile shape | enlarge the explicit tile shape against the measured on-chip budgets, and stage fewer, larger slices | | ||
| 78 | +| Load and compute alternate instead of overlapping; the timeline has memory gaps | buffering | give the staged tile group more than one slot and advance it once per iteration rather than reading the current slot | | ||
| 79 | +| The reduction axis is too large to stage at once, or the accumulator round-trips to GM between blocks | accumulation structure | accumulate on chip across the reduction loop and store once, with only the last block finalizing | | ||
| 80 | +| Dependent sections stall waiting for each other across cores | pipelining | declare the sections as pipeline stages with a preload depth, after validating the same decomposition serially | | ||
| 81 | +| An intermediate is stored to GM and immediately loaded back by the next section | on-chip residency | declare the shared tile group outside the sections and hand it to the consumer directly | | ||
| 82 | +| Non-compute kernels (host-side casts, transposes, pads) are a large share of measured device time | the wrapper boundary | move the transform inside the kernel; see [`kb/constraints/wrapper-boundary.md`](../../../kb/constraints/wrapper-boundary.md) | | ||
| 83 | +| One general kernel carries runtime branches a known shape or dtype would fold away | specialization | compile a specialized variant per tiling key so the fields become IR constants | | ||
| 84 | + | ||
| 85 | +🔴 **High-rollback combination:** on-chip accumulation over a mixed-precision | ||
| 86 | +reduction loses precision fast. Accumulate in FP32 before trying anything | ||
| 87 | +narrower, and re-run the golden. | ||
| 88 | + | ||
| 89 | +### The specialization knob, concretely | ||
| 90 | + | ||
| 91 | +Specialization is the one factor whose API is easy to half-remember. The kernel | ||
| 92 | +declares a tiling key; the key declares fields with a bit width and the value set | ||
| 93 | +each may take; the launch names a concrete value per field. Every concrete key | ||
| 94 | +folds its fields into the IR as constants and compiles its own kernel, so the | ||
| 95 | +tile choices above can be tuned per key. Two bounds that reject a design early: | ||
| 96 | +the key's fields total **at most 64 bits**, and the key exposes a validity | ||
| 97 | +predicate that rejects an illegal field combination **at launch**, not at | ||
| 98 | +compile time. Confirm the spelling against the installed runtime's tiling-key | ||
| 99 | +module before writing it. | ||
| 100 | + | ||
| 101 | +### A cheap proxy for "will a bigger tile help" | ||
| 102 | + | ||
| 103 | +Before measuring, rank tile candidates by per-core GM traffic. For a contraction | ||
| 104 | +`[M, K] x [K, N]` tiled `[m, k, n]`, the left operand is reloaded `ceil(N/n)` | ||
| 105 | +times and the right operand `ceil(M/m)` times, so | ||
| 106 | + | ||
| 107 | +```text | ||
| 108 | +reload_proxy = M*K*ceil(N/n) + K*N*ceil(M/m) # lower is better | ||
| 109 | +``` | ||
| 110 | + | ||
| 111 | +It is arithmetic on the shape, not a simulation, and it says nothing about | ||
| 112 | +latency — but it orders candidates before any of them costs a device run, and it | ||
| 113 | +is why larger tiles, on-chip accumulation and cross-section residency all help | ||
| 114 | +for the same underlying reason. | ||
| 115 | + | ||
| 116 | +### Knobs that do not exist here | ||
| 117 | + | ||
| 118 | +Do not spend an iteration looking for these; the graph frontend has them and this | ||
| 119 | +surface does not, because there is no auto-tiler, no compiler multi-buffer or | ||
| 120 | +L1-reuse pass, no graph stitching, no dispatch scheduler and no simulator: | ||
| 121 | + | ||
| 122 | +| Reached for | Why it is absent | What the author does instead | | ||
| 123 | +|---|---|---| | ||
| 124 | +| a request for cube or vector tile shapes | no auto-tiler to request them from | place every tile explicitly | | ||
| 125 | +| a multi-buffer or L1-reuse setting | no compiler pass to enable | give the group slots and advance it; keep the operand resident by hand | | ||
| 126 | +| a stitch bound or a dispatch-scheduler mode | no graph stitching and no dispatch scheduler | on-chip residency | | ||
| 127 | +| `loop_unroll` / `unroll_list` | **no verified unroll control** — the range primitive takes start, stop and step only | none confirmed | | ||
| 128 | +| an L2 layout constraint on the tile grid | no auto tile-grid to lay out; L2 affinity is not a knob here | reachable only by hand through loop and load order, unverified | | ||
| 129 | +| a narrow-dtype or reformat pass to toggle | not a knob — there is no quantization or format pass | write the low-precision contraction or the split; see [`kb/patterns/quant-matmul-scaled-mm.md`](../../../kb/patterns/quant-matmul-scaled-mm.md) and [`kb/constraints/precision.md`](../../../kb/constraints/precision.md) | | ||
| 130 | +| a simulator baseline before touching hardware | this surface compiles straight to the device | measure on the device, as the loop above requires | | ||
| 131 | + | ||
| 132 | +Two things this page states are **hypotheses to confirm on hardware**, not | ||
| 133 | +measurements: the accumulator fractal value's role as a *tuning* knob rather than | ||
| 134 | +a correctness requirement, and the magnitude a tiling-key specialization is worth. | ||
| 135 | + | ||
| 67 | ## Scope of retained examples | 136 | ## Scope of retained examples |
| 68 | 137 | ||
| 69 | The KB's | 138 | The KB's |
| @@ -0,0 +1,51 @@ | |||
| 1 | +# pl-routing-table — Stage-5 static router (engine/topology → pl skill + pattern + pro_legal) | ||
| 2 | + | ||
| 3 | +Route a Stage-4 kernel/spec to (a) the right `pypto-pl-*` skill, (b) a matching `cannbot-skills/kb/patterns/*` | ||
| 4 | +skeleton, (c) sample dirs + pitfall rows. **MVP = a static markdown decision table** (engine + | ||
| 5 | +topology is a tiny space); promote it to a routing tool (none is written yet) when fixture drift justifies the | ||
| 6 | +guard (plan Item 3.3). | ||
| 7 | + | ||
| 8 | +**Routing signal** (plan Item 3): `grep -c 'section_cube\|section_vector'` on the kernel (kernels | ||
| 9 | +literally contain `with pl.section_cube():` / `section_vector():`) + topology | ||
| 10 | +(reduction/activation/elementwise/normalization/matmul/conv/attention/quant/…) + dtype. The `pypto-pl-*` | ||
| 11 | +skills' 触发词 lists already **are** the classifier: `section_vector` → `pypto-pl-vector-kernel`; | ||
| 12 | +matmul/GEMM/conv-as-GEMM → `pypto-pl-cube-bound` (+`sizing.py`); characterise-a-pipe / ambiguous → | ||
| 13 | +`pypto-pl-pipe-roofline`. | ||
| 14 | + | ||
| 15 | +## 🔴 Anti-cheat carve-out (pro_legal filter) | ||
| 16 | + | ||
| 17 | +The Pro verifier mandates **one `@pl.jit` kernel** (stage4-check 5). Any `pro_legal=false` row | ||
| 18 | +(**`multi-jit-fusion`** and any >1-kernel pattern) is **filtered before candidates are presented**: | ||
| 19 | +the router returns `excluded(multi-kernel)` and **falls back to the cube-bound levers** | ||
| 20 | +(`pl_skill = pypto-pl-cube-bound`). The optimizer prompt forbids introducing a second kernel. Pro-legal | ||
| 21 | +patterns: online-softmax-tail, cube-only, vec-row/group-reduce-broadcast, buffer-reuse-lifetime, | ||
| 22 | +lookahead-pipeline, quant-matmul-scaled-mm, fp4-mxfp-cast-pack, batched-2d-contraction. | ||
| 23 | + | ||
| 24 | +**Fallback skill for a filtered (`pro_legal=false`) row = `pypto-pl-cube-bound`.** | ||
| 25 | + | ||
| 26 | +## Decision table | ||
| 27 | + | ||
| 28 | +| topology | engine | pl_skill | pattern | pro_legal | sample_dirs | pitfall_rows | | ||
| 29 | +|---|---|---|---|---|---|---| | ||
| 30 | +| reduction | vector | pypto-pl-vector-kernel | vec-row-reduce-broadcast | true | norm_softmax_rms_l2; vector_kernels/reduce_sum | 3b; 3f | | ||
| 31 | +| normalization | vector | pypto-pl-vector-kernel | vec-row-reduce-broadcast | true | norm_softmax_rms_l2; vector_kernels | 3a; 3b; 3c | | ||
| 32 | +| group_reduction | vector | pypto-pl-vector-kernel | vec-group-reduce-broadcast | true | vector_kernels | 3b | | ||
| 33 | +| activation | vector | pypto-pl-vector-kernel | buffer-reuse-lifetime | true | vector_kernels | 3f | | ||
| 34 | +| elementwise | vector | pypto-pl-vector-kernel | buffer-reuse-lifetime | true | vector_kernels | 3f | | ||
| 35 | +| cast_pack | vector | pypto-pl-vector-kernel | fp4-mxfp-cast-pack | true | vector_kernels | 3f | | ||
| 36 | +| matmul | cube | pypto-pl-cube-bound | cube-only | true | matmul_float_mmad; bf16_matmul_operand_reuse | 9; 10 | | ||
| 37 | +| conv | cube | pypto-pl-cube-bound | cube-only | true | (none retained — lower to GEMM and reuse matmul_float_mmad) | 6 | | ||
| 38 | +| batched_contraction | cube | pypto-pl-cube-bound | batched-2d-contraction | true | matmul_float_mmad | - | | ||
| 39 | +| quant_matmul | cube | pypto-pl-cube-bound | quant-matmul-scaled-mm | true | matmul_quant_int8 | - | | ||
| 40 | +| attention | cube | pypto-pl-cube-bound | online-softmax-tail | true | (none retained — softmax covers the single-tile base case only) | - | | ||
| 41 | +| pipe_probe | cube | pypto-pl-pipe-roofline | buffer-reuse-lifetime | true | (none retained — re-derive the ceiling per the arch-a5 platform gate) | - | | ||
| 42 | +| multi_jit_fusion | cube | - | multi-jit-fusion | false | fused_matmul_add | - | | ||
| 43 | + | ||
| 44 | +**Corrected pitfall labels** (plan Item 3): **507035 = 64-lane (LANES) tile-width / UB-slot fault**; | ||
| 45 | +the **co_name build-cache collision is a SEPARATE, no-error-code pitfall** (v1 mislabeled it); | ||
| 46 | +**507034 = inf/nan reduction hang**. See `cannbot-skills/kb/pitfall-records.md`. | ||
| 47 | + | ||
| 48 | +**Notes.** `pl_skill = -` marks an excluded (`pro_legal=false`) row — the router presents the fallback | ||
| 49 | +`pypto-pl-cube-bound` instead. `engine` is derived from topology (the generalization signal); for a | ||
| 50 | +fused op the dominant engine (`aicore_time` ≫ `aiv_time` ⇒ cube) is used. `pitfall_rows` cite § | ||
| 51 | +anchors in the vector skill / verifier checklist. | ||
| @@ -0,0 +1,52 @@ | |||
| 1 | +# routing-fixtures — labeled Stage-5 router fixtures (in-corpus + HELD-OUT) | ||
| 2 | + | ||
| 3 | +Labeled fixtures for `scripts/test_routing_fixtures.py`, which parses `pl-routing-table.md` + these | ||
| 4 | +tables and asserts the router's engine recall, `pl_skill` precision, and zero `pro_legal=false` | ||
| 5 | +leakage (plan Item 5b). | ||
| 6 | + | ||
| 7 | +**Columns:** `op | topology | dtype | gold_engine | gold_pl_skill | gold_pattern | gold_pro_legal | source`. | ||
| 8 | +`gold_pl_skill` is the **presented** candidate the router should return — for the carve-out row that is | ||
| 9 | +the cube-bound **fallback**, not the excluded pattern's (absent) skill. | ||
| 10 | + | ||
| 11 | +**Bars:** engine recall = 1.0 on **both** A and B (held-out recall = 1.0 = the real generalization | ||
| 12 | +test); `pl_skill` precision ≥ 0.90 (A) / ≥ 0.80 (B); carve-out `pro_legal=false` leakage = 0. | ||
| 13 | + | ||
| 14 | +## Table A — in-corpus (sanity floor, source-cited to validated samples) | ||
| 15 | + | ||
| 16 | +Labels source-cited to the retained samples under `cannbot-skills/kb/examples/samples/`. A `source` | ||
| 17 | +cell reading "no retained sample" means this KB holds no runnable reference for that topology and the | ||
| 18 | +label is derived from the operator's mathematics, exactly as in Table B. Includes the deliberate | ||
| 19 | +**carve-out row** (fused matmul+relu presented as a multi-kernel split → router must return | ||
| 20 | +`excluded(multi-kernel); fallback=cube-bound`). | ||
| 21 | + | ||
| 22 | +| op | topology | dtype | gold_engine | gold_pl_skill | gold_pattern | gold_pro_legal | source | | ||
| 23 | +|---|---|---|---|---|---|---|---| | ||
| 24 | +| softmax | normalization | fp32 | vector | pypto-pl-vector-kernel | vec-row-reduce-broadcast | true | samples/softmax; samples/norm_softmax_rms_l2 | | ||
| 25 | +| rmsnorm | normalization | fp32 | vector | pypto-pl-vector-kernel | vec-row-reduce-broadcast | true | samples/norm_softmax_rms_l2 | | ||
| 26 | +| l2norm | normalization | fp32 | vector | pypto-pl-vector-kernel | vec-row-reduce-broadcast | true | samples/norm_softmax_rms_l2 | | ||
| 27 | +| layernorm | normalization | fp32 | vector | pypto-pl-vector-kernel | vec-row-reduce-broadcast | true | samples/vector_kernels/layernorm_impl.py | | ||
| 28 | +| silu | activation | fp32 | vector | pypto-pl-vector-kernel | buffer-reuse-lifetime | true | samples/vector_kernels (silu) | | ||
| 29 | +| gelu | activation | fp32 | vector | pypto-pl-vector-kernel | buffer-reuse-lifetime | true | samples/vector_kernels (gelu) | | ||
| 30 | +| elementwise_2x_plus_1 | elementwise | fp32 | vector | pypto-pl-vector-kernel | buffer-reuse-lifetime | true | samples/vector_kernels (elementwise) | | ||
| 31 | +| reduce_sum | reduction | fp32 | vector | pypto-pl-vector-kernel | vec-row-reduce-broadcast | true | samples/vector_kernels/reduce_sum_impl.py | | ||
| 32 | +| matmul_float_mmad | matmul | fp32 | cube | pypto-pl-cube-bound | cube-only | true | samples/matmul_float_mmad | | ||
| 33 | +| bf16_cube_bound_areuse | matmul | bf16 | cube | pypto-pl-cube-bound | cube-only | true | samples/bf16_matmul_operand_reuse | | ||
| 34 | +| matmul_quant_int8 | quant_matmul | int8 | cube | pypto-pl-cube-bound | quant-matmul-scaled-mm | true | samples/matmul_quant_int8 | | ||
| 35 | +| conv2d_relu | conv | fp16 | cube | pypto-pl-cube-bound | cube-only | true | math: conv lowers to GEMM (im2col); no retained sample | | ||
| 36 | +| pipe_saturation | pipe_probe | bf16 | cube | pypto-pl-pipe-roofline | buffer-reuse-lifetime | true | probe shape, no retained sample | | ||
| 37 | +| fused_matmul_relu_split | multi_jit_fusion | bf16 | cube | pypto-pl-cube-bound | multi-jit-fusion | false | samples/fused_matmul_add (CARVE-OUT: multi-kernel → fallback cube-bound) | | ||
| 38 | + | ||
| 39 | +## Table B — HELD-OUT (ops NOT in samples and NOT in the catalog, labeled from the math) | ||
| 40 | + | ||
| 41 | +Breaks the label/router circularity that makes in-corpus recall tautological. Each label is derived | ||
| 42 | +from the operator's mathematics, not from a stored sample. | ||
| 43 | + | ||
| 44 | +| op | topology | dtype | gold_engine | gold_pl_skill | gold_pattern | gold_pro_legal | source | | ||
| 45 | +|---|---|---|---|---|---|---|---| | ||
| 46 | +| mish | activation | fp32 | vector | pypto-pl-vector-kernel | buffer-reuse-lifetime | true | math: x·tanh(softplus(x)) — elementwise activation, section_vector | | ||
| 47 | +| group_norm | group_reduction | fp32 | vector | pypto-pl-vector-kernel | vec-group-reduce-broadcast | true | math: per-group mean/var reduce+broadcast | | ||
| 48 | +| batched_matmul | batched_contraction | bf16 | cube | pypto-pl-cube-bound | batched-2d-contraction | true | math: collapse batch on host, 2D matmul per batch | | ||
| 49 | +| conv1d | conv | fp16 | cube | pypto-pl-cube-bound | cube-only | true | math: conv lowers to GEMM (im2col) | | ||
| 50 | +| scaled_mm_fp8 | quant_matmul | fp8 | cube | pypto-pl-cube-bound | quant-matmul-scaled-mm | true | math: fp8 matmul with fp32 accumulate + scale | | ||
| 51 | +| logsumexp | normalization | fp32 | vector | pypto-pl-vector-kernel | vec-row-reduce-broadcast | true | math: row max→sub→exp→row sum→log (reduce+broadcast) | | ||
| 52 | +| dropout_scale | elementwise | fp32 | vector | pypto-pl-vector-kernel | buffer-reuse-lifetime | true | math: elementwise mask·x·(1/keep_prob) | | ||
| @@ -0,0 +1,151 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +"""Stage-5 pl-router fixture harness (pure stdlib, CPU-only). | ||
| 3 | + | ||
| 4 | +Parses ``references/pl-routing-table.md`` (the static decision table) and | ||
| 5 | +``references/routing-fixtures.md`` (Table A in-corpus + Table B held-out), routes each fixture | ||
| 6 | +through the table, and asserts the plan Item-5b bars: | ||
| 7 | + | ||
| 8 | + * engine recall == 1.0 on BOTH Table A and Table B (held-out recall = the real generalization test) | ||
| 9 | + * pl_skill precision >= 0.90 (A) / >= 0.80 (B) | ||
| 10 | + * zero pro_legal=false leakage (the multi-jit-fusion carve-out must be filtered → cube-bound fallback) | ||
| 11 | + | ||
| 12 | +Prints metrics; exits non-zero on any miss. | ||
| 13 | +""" | ||
| 14 | +import os | ||
| 15 | +import sys | ||
| 16 | + | ||
| 17 | +HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 18 | +REFS = os.path.join(HERE, "..", "references") | ||
| 19 | +FALLBACK_SKILL = "pypto-pl-cube-bound" # presented when a matched row is pro_legal=false | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def parse_tables(path): | ||
| 23 | + """Return list of (heading, rows) where rows are lists of stripped cells.""" | ||
| 24 | + tables, heading, header, rows = [], None, None, [] | ||
| 25 | + for line in open(path, encoding="utf-8"): | ||
| 26 | + s = line.strip() | ||
| 27 | + if s.startswith("#"): | ||
| 28 | + if header and rows: | ||
| 29 | + tables.append((heading, header, rows)) | ||
| 30 | + heading, header, rows = s.lstrip("# ").strip(), None, [] | ||
| 31 | + continue | ||
| 32 | + if s.startswith("|"): | ||
| 33 | + cells = [c.strip() for c in s.strip("|").split("|")] | ||
| 34 | + if set("".join(cells)) <= set("-: "): # separator row | ||
| 35 | + continue | ||
| 36 | + if header is None: | ||
| 37 | + header = cells | ||
| 38 | + else: | ||
| 39 | + rows.append(cells) | ||
| 40 | + elif header and rows: | ||
| 41 | + tables.append((heading, header, rows)) | ||
| 42 | + heading, header, rows = heading, None, [] | ||
| 43 | + if header and rows: | ||
| 44 | + tables.append((heading, header, rows)) | ||
| 45 | + return tables | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +def load_routing_table(): | ||
| 49 | + for heading, header, rows in parse_tables(os.path.join(REFS, "pl-routing-table.md")): | ||
| 50 | + if "topology" in header and "pl_skill" in header: | ||
| 51 | + idx = {h: i for i, h in enumerate(header)} | ||
| 52 | + return { | ||
| 53 | + r[idx["topology"]]: { | ||
| 54 | + "engine": r[idx["engine"]], | ||
| 55 | + "pl_skill": r[idx["pl_skill"]], | ||
| 56 | + "pattern": r[idx["pattern"]], | ||
| 57 | + "pro_legal": r[idx["pro_legal"]].lower() == "true", | ||
| 58 | + } | ||
| 59 | + for r in rows | ||
| 60 | + } | ||
| 61 | + raise SystemExit("FATAL: routing decision table not found in pl-routing-table.md") | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def route(table, topology): | ||
| 65 | + """Router: match topology → routing decision dict, or None. | ||
| 66 | + | ||
| 67 | + ``raw_pro_legal`` is the matched table row's flag *before* filtering; ``filtered`` says the router | ||
| 68 | + replaced a pro_legal=false row with the cube-bound fallback. ``pattern`` is the IDENTIFIED pattern | ||
| 69 | + (kept even when filtered, so pattern recall can still score the carve-out correctly).""" | ||
| 70 | + row = table.get(topology) | ||
| 71 | + if row is None: | ||
| 72 | + return None | ||
| 73 | + raw_legal = row["pro_legal"] | ||
| 74 | + if not raw_legal: # carve-out: filter, fall back to cube-bound | ||
| 75 | + return {"engine": row["engine"], "skill": FALLBACK_SKILL, "pattern": row["pattern"], | ||
| 76 | + "raw_pro_legal": False, "filtered": True} | ||
| 77 | + return {"engine": row["engine"], "skill": row["pl_skill"], "pattern": row["pattern"], | ||
| 78 | + "raw_pro_legal": True, "filtered": False} | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +def load_fixture_tables(): | ||
| 82 | + out = {} | ||
| 83 | + for heading, header, rows in parse_tables(os.path.join(REFS, "routing-fixtures.md")): | ||
| 84 | + if "gold_engine" not in header: | ||
| 85 | + continue | ||
| 86 | + idx = {h: i for i, h in enumerate(header)} | ||
| 87 | + label = "A" if heading.startswith("Table A") else "B" if heading.startswith("Table B") else heading | ||
| 88 | + out[label] = [{k: r[idx[k]] for k in idx} for r in rows] | ||
| 89 | + return out | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +def evaluate(table, name, fixtures, skill_bar, pattern_bar=0.80): | ||
| 93 | + engine_hit = {} # gold_engine -> [correct, total] (per-class recall) | ||
| 94 | + skill_correct = pattern_correct = leakage = 0 | ||
| 95 | + for fx in fixtures: | ||
| 96 | + res = route(table, fx["topology"]) | ||
| 97 | + assert res is not None, f"[{name}] no routing row for topology={fx['topology']!r} (op={fx['op']})" | ||
| 98 | + g_engine = fx["gold_engine"] | ||
| 99 | + rec = engine_hit.setdefault(g_engine, [0, 0]) | ||
| 100 | + rec[1] += 1 | ||
| 101 | + rec[0] += (res["engine"] == g_engine) | ||
| 102 | + skill_correct += (res["skill"] == fx["gold_pl_skill"]) | ||
| 103 | + pattern_correct += (res["pattern"] == fx["gold_pattern"]) # top-1 pattern (plan 5b) | ||
| 104 | + # leakage: a pro_legal=false raw row that was NOT filtered = an illegal candidate surfaced. | ||
| 105 | + # Derived from the RAW pre-filter flag, so it is 0 only because the filter actually fires. | ||
| 106 | + leakage += (not res["raw_pro_legal"]) and (not res["filtered"]) | ||
| 107 | + n = len(fixtures) | ||
| 108 | + engine_recall = min((c / t) for c, t in engine_hit.values()) | ||
| 109 | + skill_prec = skill_correct / n | ||
| 110 | + pattern_top1 = pattern_correct / n | ||
| 111 | + print(f"[{name}] n={n} engine_recall={engine_recall:.3f} " | ||
| 112 | + f"pl_skill_precision={skill_prec:.3f} pattern_top1={pattern_top1:.3f} " | ||
| 113 | + f"pro_legal_leakage={leakage}") | ||
| 114 | + for eng, (c, t) in sorted(engine_hit.items()): | ||
| 115 | + print(f" engine[{eng}] recall={c}/{t}") | ||
| 116 | + fails = [] | ||
| 117 | + if engine_recall < 1.0: | ||
| 118 | + fails.append(f"{name} engine_recall {engine_recall:.3f} < 1.0") | ||
| 119 | + if skill_prec < skill_bar: | ||
| 120 | + fails.append(f"{name} pl_skill_precision {skill_prec:.3f} < {skill_bar}") | ||
| 121 | + if pattern_bar is not None and pattern_top1 < pattern_bar: | ||
| 122 | + fails.append(f"{name} pattern_top1 {pattern_top1:.3f} < {pattern_bar}") | ||
| 123 | + if leakage != 0: | ||
| 124 | + fails.append(f"{name} pro_legal=false leakage {leakage} != 0") | ||
| 125 | + return fails | ||
| 126 | + | ||
| 127 | + | ||
| 128 | +def main(): | ||
| 129 | + table = load_routing_table() | ||
| 130 | + fx = load_fixture_tables() | ||
| 131 | + print(f"routing table: {len(table)} topologies; fixtures: " | ||
| 132 | + + ", ".join(f"{k}={len(v)}" for k, v in sorted(fx.items()))) | ||
| 133 | + fails = [] | ||
| 134 | + fails += evaluate(table, "A", fx["A"], skill_bar=0.90, pattern_bar=0.80) # pattern top-1 bar: A only | ||
| 135 | + fails += evaluate(table, "B", fx["B"], skill_bar=0.80, pattern_bar=None) | ||
| 136 | + # explicit carve-out proof: the multi-jit-fusion fixture must be filtered to the fallback | ||
| 137 | + carve = [f for f in fx["A"] if f["topology"] == "multi_jit_fusion"] | ||
| 138 | + assert carve, "FATAL: Table A is missing the multi_jit_fusion carve-out row" | ||
| 139 | + c = route(table, "multi_jit_fusion") | ||
| 140 | + if not (c["filtered"] and c["raw_pro_legal"] is False and c["skill"] == FALLBACK_SKILL): | ||
| 141 | + fails.append(f"carve-out not filtered to fallback (skill={c['skill']}, filtered={c['filtered']})") | ||
| 142 | + else: | ||
| 143 | + print(f"carve-out OK: multi_jit_fusion (raw pro_legal=false) filtered → fallback {c['skill']}") | ||
| 144 | + if fails: | ||
| 145 | + print("\nFAIL:\n " + "\n ".join(fails)) | ||
| 146 | + sys.exit(1) | ||
| 147 | + print("\nPASS: all routing-fixture bars met.") | ||
| 148 | + | ||
| 149 | + | ||
| 150 | +if __name__ == "__main__": | ||
| 151 | + main() | ||
| @@ -1,6 +1,6 @@ | |||
| 1 | { | 1 | { |
| 2 | "name": "pypto-pro-op-orchestrator", | 2 | "name": "pypto-pro-op-orchestrator", |
| 3 | - "description": "PyPTO-Pro 算子 Stage 1-4 多智能体开发工作流。", | 3 | + "description": "PyPTO-Pro 算子 Stage 1-5 多智能体开发工作流。", |
| 4 | "version": "2.0.0", | 4 | "version": "2.0.0", |
| 5 | "author": { | 5 | "author": { |
| 6 | "name": "CANNBot" | 6 | "name": "CANNBot" |
| @@ -13,6 +13,7 @@ | |||
| 13 | "./agents/pypto-pro-op-mathematician.md", | 13 | "./agents/pypto-pro-op-mathematician.md", |
| 14 | "./agents/pypto-pro-op-architect.md", | 14 | "./agents/pypto-pro-op-architect.md", |
| 15 | "./agents/pypto-pro-op-coder.md", | 15 | "./agents/pypto-pro-op-coder.md", |
| 16 | - "./agents/pypto-pro-op-verifier.md" | 16 | + "./agents/pypto-pro-op-verifier.md", |
| 17 | + "./agents/pypto-pro-op-optimizer.md" | ||
| 17 | ] | 18 | ] |
| 18 | } | 19 | } |
| @@ -1,6 +1,6 @@ | |||
| 1 | --- | 1 | --- |
| 2 | name: pypto-pro-op-orchestrator | 2 | name: pypto-pro-op-orchestrator |
| 3 | -description: "PyPTO-Pro 算子开发编排者。驱动 Stage 1–4,调度专属子代理(子代理自行加载对应 skill),并在每个 Stage 结束后调度 pypto-pro-op-verifier 执行检查清单。从不亲自编写 kernel 代码或执行检查。" | 3 | +description: "PyPTO-Pro 算子开发编排者。驱动 Stage 1–5,调度专属子代理(子代理自行加载对应 skill),并在每个 Stage 结束后调度 pypto-pro-op-verifier 执行检查清单。从不亲自编写 kernel 代码或执行检查。" |
| 4 | mode: primary | 4 | mode: primary |
| 5 | skills: | 5 | skills: |
| 6 | - pypto-docs-search | 6 | - pypto-docs-search |
| @@ -10,6 +10,7 @@ agents: | |||
| 10 | - pypto-pro-op-mathematician | 10 | - pypto-pro-op-mathematician |
| 11 | - pypto-pro-op-planner | 11 | - pypto-pro-op-planner |
| 12 | - pypto-pro-op-verifier | 12 | - pypto-pro-op-verifier |
| 13 | + - pypto-pro-op-optimizer | ||
| 13 | tools: | 14 | tools: |
| 14 | read: true | 15 | read: true |
| 15 | write: true | 16 | write: true |
| @@ -113,6 +114,7 @@ print(f'清理完成:保留 {len(whitelist)} 个官方指定样例,删除 {r | |||
| 113 | | 2 | `pypto-pro-op-mathematician` | pypto-pro-golden-generate | | 114 | | 2 | `pypto-pro-op-mathematician` | pypto-pro-golden-generate | |
| 114 | | 3 | `pypto-pro-op-architect` | pypto-pro-op-design | | 115 | | 3 | `pypto-pro-op-architect` | pypto-pro-op-design | |
| 115 | | 4 | `pypto-pro-op-coder` | pypto-pro-op-develop | | 116 | | 4 | `pypto-pro-op-coder` | pypto-pro-op-develop | |
| 117 | +| 5 | `pypto-pro-op-optimizer` | pypto-pro-op-perf-tune、pypto-pl-vector-kernel、pypto-pl-cube-bound、pypto-pl-pipe-roofline、pypto-pro-environment-check | | ||
| 116 | 118 | ||
| 117 | **原理**:专属 subagent 的 .md(`$CANNBOT_CONFIG_ROOT/agents/pypto-pro-op-*.md`)会话启动时自动作为该子代理的 system prompt 加载,自带角色边界、文件归属与全局硬性规则。因此 orchestrator **无需**在 dispatch prompt 中重复粘贴规则块——规则已内置于子代理 system prompt,比逐字粘贴 dispatch prompt 更可靠(system prompt 始终在场,不依赖每次正确粘贴)。 | 119 | **原理**:专属 subagent 的 .md(`$CANNBOT_CONFIG_ROOT/agents/pypto-pro-op-*.md`)会话启动时自动作为该子代理的 system prompt 加载,自带角色边界、文件归属与全局硬性规则。因此 orchestrator **无需**在 dispatch prompt 中重复粘贴规则块——规则已内置于子代理 system prompt,比逐字粘贴 dispatch prompt 更可靠(system prompt 始终在场,不依赖每次正确粘贴)。 |
| 118 | 120 | ||
| @@ -123,7 +125,7 @@ print(f'清理完成:保留 {len(whitelist)} 个官方指定样例,删除 {r | |||
| 123 | ## 核心循环 | 125 | ## 核心循环 |
| 124 | 126 | ||
| 125 | ``` | 127 | ``` |
| 126 | -init → state_transition(init, opDir="custom/<op>", stage=1, max_stage=4) | 128 | +init → state_transition(init, opDir="custom/<op>", stage=1, max_stage=5) |
| 127 | (创建算子目录 + 初始化状态机) | 129 | (创建算子目录 + 初始化状态机) |
| 128 | 130 | ||
| 129 | Stage 1 → 调度 pypto-pro-op-planner(加载 skill pypto-pro-op-plan) | 131 | Stage 1 → 调度 pypto-pro-op-planner(加载 skill pypto-pro-op-plan) |
| @@ -144,10 +146,19 @@ Stage 3 → 调度 pypto-pro-op-architect(加载 skill pypto-pro-op-design) | |||
| 144 | Stage 4 → 调度 pypto-pro-op-coder(加载 skill pypto-pro-op-develop) | 146 | Stage 4 → 调度 pypto-pro-op-coder(加载 skill pypto-pro-op-develop) |
| 145 | → 产出 test_{op}.py (kernel + test 单文件), 运行验证通过 | 147 | → 产出 test_{op}.py (kernel + test 单文件), 运行验证通过 |
| 146 | → 调度 pypto-pro-op-verifier(stage4-check) | 148 | → 调度 pypto-pro-op-verifier(stage4-check) |
| 147 | - → PASS: state_transition(complete_stage, stage=4)(校验 SPEC.md 冻结 + 算子开发完成) / FAIL 回退 / env_error 分流 | 149 | + → PASS: state_transition(complete_stage, stage=4)(校验 SPEC.md 冻结 + 算子开发正确性完成) / FAIL 回退 / env_error 分流 |
| 150 | + | ||
| 151 | +Stage 5 → 调度 pypto-pro-op-optimizer(加载 skill pypto-pro-op-perf-tune + 3 个 pypto-pl-*) | ||
| 152 | + → 在 NPU 上 measure→lever→re-measure,就地优化那一个 @pl.jit kernel(optimizer 自持整个 ITER 循环) | ||
| 153 | + → 产出 TUNING_STATE.md, {op}_tuning_report.md(golden 永不回归) | ||
| 154 | + → 调度 pypto-pro-op-verifier(stage5-check) | ||
| 155 | + → PASS / tuning_no_gain: state_transition(complete_stage, stage=5)(算子完成) | ||
| 156 | + → tuning_regressed: 重新调度 optimizer(不推进) / precision_failure: rollback_to_stage(4) / env_error 分流 | ||
| 148 | ``` | 157 | ``` |
| 149 | 158 | ||
| 150 | -正常流程下编排者只需 **init → complete_stage(1) → complete_stage(2) → complete_stage(3) → complete_stage(4)**。跨 Stage 回退用 `rollback_to_stage`。 | 159 | +正常流程下编排者只需 **init → complete_stage(1) → … → complete_stage(5)**。跨 Stage 回退用 `rollback_to_stage`。 |
| 160 | + | ||
| 161 | +**Stage 5 默认开启**:cann-bench 的 perf 权重 w=0.5,可评分差距几乎全在性能,故默认运行优化。编排者无可靠手段判断“是否在 cann-bench 下被调用”(首次对话只暴露自由文本 prompt),因此**默认开、显式退出**:用户 prompt 命中 off-switch token 集 `{跳过优化, skip optimization, correctness-only, 仅正确性}` 之一时,Stage-4 PASS 后直接 `complete_stage(4)` 并结束,跳过 Stage 5。未来若出现结构化 `optimize=true|false` dispatch 字段则以其为准(前向兼容,当前无此字段)。 | ||
| 151 | 162 | ||
| 152 | ## 注意事项 | 163 | ## 注意事项 |
| 153 | 164 | ||
| @@ -169,7 +180,7 @@ Stage 4 → 调度 pypto-pro-op-coder(加载 skill pypto-pro-op-develop) | |||
| 169 | 180 | ||
| 170 | | Action | 使用时机 | 参数 | | 181 | | Action | 使用时机 | 参数 | |
| 171 | |---|---|---| | 182 | |---|---|---| |
| 172 | -| `init` | 启动新算子首次调用(创建目录 + 初始化状态机) | `opDir`, `stage=1`, `max_stage=4` | | 183 | +| `init` | 启动新算子首次调用(创建目录 + 初始化状态机) | `opDir`, `stage=1`, `max_stage=5` | |
| 173 | | `complete_stage` | verifier 返回 PASS 后推进。自动把下一 Stage 置为 `in_progress`,正常流程无需显式 `start_stage` | `opDir`, `stage` | | 184 | | `complete_stage` | verifier 返回 PASS 后推进。自动把下一 Stage 置为 `in_progress`,正常流程无需显式 `start_stage` | `opDir`, `stage` | |
| 174 | | `fail_stage` | 子代理报告不可恢复失败,或编排器穷尽方案后放弃算子(见 Stage 4 放弃路径) | `opDir`, `stage`, `reason` | | 185 | | `fail_stage` | 子代理报告不可恢复失败,或编排器穷尽方案后放弃算子(见 Stage 4 放弃路径) | `opDir`, `stage`, `reason` | |
| 175 | | `start_stage` | `fail_stage` 后重新进入该 Stage(重试) | `opDir`, `stage`, `reason?` | | 186 | | `start_stage` | `fail_stage` 后重新进入该 Stage(重试) | `opDir`, `stage`, `reason?` | |
| @@ -227,7 +238,7 @@ Stage 4 → 调度 pypto-pro-op-coder(加载 skill pypto-pro-op-develop) | |||
| 227 | 238 | ||
| 228 | **③ 正常交付**(test_{op}.py 已更新)→ 调度 `pypto-pro-op-verifier`(模式 `stage4-check`)执行检查清单(verifier 先静态扫描,后动态运行 `python custom/<op>/test_{op}.py`)。verifier 裁决后再分三类: | 239 | **③ 正常交付**(test_{op}.py 已更新)→ 调度 `pypto-pro-op-verifier`(模式 `stage4-check`)执行检查清单(verifier 先静态扫描,后动态运行 `python custom/<op>/test_{op}.py`)。verifier 裁决后再分三类: |
| 229 | 240 | ||
| 230 | -- **verifier PASS** → `complete_stage(4)`,算子开发完成。 | 241 | +- **verifier PASS** → `complete_stage(4)`,正确性完成,进入 Stage 5(除非命中 off-switch,见「核心循环」)。 |
| 231 | - **verifier env_error** → 按①环境分流处理。 | 242 | - **verifier env_error** → 按①环境分流处理。 |
| 232 | - **verifier FAIL** → 据 `failure_category` 路由: | 243 | - **verifier FAIL** → 据 `failure_category` 路由: |
| 233 | 244 | ||
| @@ -248,6 +259,29 @@ dispatch prompt 中必须包含:失败项的具体描述、复现方式、初 | |||
| 248 | 259 | ||
| 249 | --- | 260 | --- |
| 250 | 261 | ||
| 262 | +## Stage 5:性能优化 | ||
| 263 | + | ||
| 264 | +**调度**:`pypto-pro-op-optimizer` 子代理,在 Stage-4 PASS 后**一次性**调度。子代理加载 skill `pypto-pro-op-perf-tune`,并按 kernel 引擎自行加载 `pypto-pl-vector-kernel` / `pypto-pl-cube-bound` / `pypto-pl-pipe-roofline`。整个 measure→lever→re-measure 的 ITER 循环由 optimizer 自持——粒度太细,不适合逐步 dispatch,编排者只在入口和出口各介入一次。 | ||
| 265 | + | ||
| 266 | +**编排者不做的事**:不亲自测性能、不亲自选杠杆、不亲自改 kernel。与其他 Stage 同理,只下达任务、收产物、据 verifier verdict 决策。 | ||
| 267 | + | ||
| 268 | +**门禁验证**:调度 `pypto-pro-op-verifier`(模式 `stage5-check`)执行检查清单(先静态扫产物与 diary,后动态运行 `python custom/<op>/test_{op}.py` 复验 golden 与 anti-cheat)。 | ||
| 269 | + | ||
| 270 | +**optimizer 返回后的分流**: | ||
| 271 | + | ||
| 272 | +| verdict | 含义 | 动作 | | ||
| 273 | +|---|---|---| | ||
| 274 | +| `PASS` | 有已接受杠杆,final us ≤ baseline us,golden 与 anti-cheat 干净 | `complete_stage(5)`,算子完成 | | ||
| 275 | +| `tuning_no_gain` | 诚实空结果:零接受杠杆,代码已还原基线,产物齐备且 golden 与 anti-cheat 干净 | `complete_stage(5)`,算子完成——**这不是失败**,不重回 Stage 4 | | ||
| 276 | +| `tuning_regressed` | final us > baseline us | 不推进;重新调度 optimizer 还原基线快照 / 回退最后一个已接受杠杆,直到 final ≤ baseline | | ||
| 277 | +| `precision_failure` | 优化破坏了 golden | `rollback_to_stage(target_stage=4, ...)` 回退修复 | | ||
| 278 | +| `cheating` / `perf_violation` | 优化引入第二个 kernel / 循环调用 kernel / host 端核心计算 | 红线:不推进,re-dispatch optimizer 从基线快照重来,dispatch prompt 引用 verifier 证据原文 | | ||
| 279 | +| `env_error` | torch_npu / npu-smi / CANN 环境异常 | 按 Stage 4 的①环境分流处理(硬件→换卡;软件→停机反馈用户) | | ||
| 280 | + | ||
| 281 | +**预算界定退出**:Stage 5 按 target 达成 / N 个连续无收益杠杆 / 用户叫停三者之一收尾。反复 `tuning_regressed` 且穷尽方案时,走与 Stage 4 相同的诚实失败出口——`fail_stage(stage=5, reason=...)` 并向用户汇报,**不得**为了推进而接受一个更慢的 kernel。 | ||
| 282 | + | ||
| 283 | +--- | ||
| 284 | + | ||
| 251 | ## 首次用户对话 | 285 | ## 首次用户对话 |
| 252 | 286 | ||
| 253 | 当用户要求开发 PyPTO-Pro 算子时,先询问: | 287 | 当用户要求开发 PyPTO-Pro 算子时,先询问: |
| @@ -255,5 +289,8 @@ dispatch prompt 中必须包含:失败项的具体描述、复现方式、初 | |||
| 255 | - 算子名称 | 289 | - 算子名称 |
| 256 | - 数学公式 / 计算逻辑 | 290 | - 数学公式 / 计算逻辑 |
| 257 | - 输入 / 输出 tensor 的 dtype (shape不需要向用户确认,在design阶段会进行设计,除非主动提供) | 291 | - 输入 / 输出 tensor 的 dtype (shape不需要向用户确认,在design阶段会进行设计,除非主动提供) |
| 292 | +- (可选)是否需要性能优化(Stage 5)——**默认开启**,无需追问;仅当用户主动提供时记录 | ||
| 293 | + | ||
| 294 | +**off-switch(不阻塞 Stage 1)**:若用户 prompt 命中 `{跳过优化, skip optimization, correctness-only, 仅正确性}` 任一 token,则本次流程在 Stage-4 PASS 后完成、跳过 Stage 5。此判定**仅记录**,**绝不因等待用户澄清优化偏好而延迟启动 Stage 1**——缺省即默认开启。 | ||
| 258 | 295 | ||
| 259 | 随后 `state_transition(init)` 初始化状态机,启动 Stage 1。 | 296 | 随后 `state_transition(init)` 初始化状态机,启动 Stage 1。 |
| @@ -0,0 +1,108 @@ | |||
| 1 | +--- | ||
| 2 | +name: pypto-pro-op-optimizer | ||
| 3 | +description: "Stage 5 pl-native 性能优化执行者。在 Stage-4 golden PASS 后被 orchestrator 一次性调度,独立拥有完整的 measure→lever→re-measure ITER 循环:在真实 NPU 上冻结 golden、测基线、读热点、应用恰好一个杠杆、重验 golden、重测、接受或回退。绝不引入第二个 kernel。产出 TUNING_STATE.md + {op}_tuning_report.md,返回结构化结果供 verifier(stage5-check)门禁。" | ||
| 4 | +mode: subagent | ||
| 5 | +skills: | ||
| 6 | + - pypto-pro-op-perf-tune | ||
| 7 | + - pypto-pl-vector-kernel | ||
| 8 | + - pypto-pl-cube-bound | ||
| 9 | + - pypto-pl-pipe-roofline | ||
| 10 | + - pypto-pro-environment-check | ||
| 11 | +tools: | ||
| 12 | + read: true | ||
| 13 | + write: true | ||
| 14 | + edit: true | ||
| 15 | + bash: true | ||
| 16 | +--- | ||
| 17 | + | ||
| 18 | +# pypto-pro-op-optimizer — Stage 5 pl-native 性能优化执行者 | ||
| 19 | + | ||
| 20 | +你是 Stage 5 的执行者。orchestrator 在 Stage-4 verifier PASS 后**一次性**调度你(Pro 节奏:one dispatch → verifier gate)。你**独立拥有整个 measure→lever→re-measure 的 ITER 循环**——它粒度太细,不适合逐步 dispatch。你在真实 NPU 上把已通过 golden 的单一 `@pl.jit` kernel 调快,产出调优报告与状态账本,返回结构化摘要给 orchestrator,由 `pypto-pro-op-verifier`(`stage5-check`)做门禁。 | ||
| 21 | + | ||
| 22 | +Stage 5 是 Pro 流程**第一个可选阶段**(预算界定退出:target 达成 / N 个无收益杠杆 / 用户叫停),与正确性强制的 Stage 1–4 不同。你借用 PLAIN 编排器 Stage-7 优化器的**形状**(target sheet + 一次一杠杆的 ITER + 接受/回退 + 调优报告),但引擎是 **pl-native 的 NPU-measure 循环**——pl **没有** `RunMode.SIM`,没有 cost-model swimlane,经 bisheng 直编 NPU,性能只能在真机上测。 | ||
| 23 | + | ||
| 24 | +## ⛔ 核心约束(红线) | ||
| 25 | + | ||
| 26 | +1. **单一 kernel 铁律(anti-cheat 契约)**:**只能优化单一 `@pl.jit` kernel;不得引入第二个 kernel 或将 kernel 放入循环;multi-jit-fusion 等多 kernel 模式禁止。** 所有杠杆 by construction 保持这一契约(就地改同一个 `@pl.jit`)。host 端不得做任何核心计算;`{op}_wrapper` 只调用一次 kernel。任何形式的作弊(host 做核心计算、多 kernel 分担、wrapper/循环多次调用 kernel)都会被 `stage5-check` 与 Stage-4 anti-cheat 守卫(checks 5/6/7/13)捕获并 FAIL。 | ||
| 27 | +2. **你是 subagent,不是编排者。** **禁止调用 `state_transition` 工具**——账本只有编排者能写(见 `AGENTS.md` 「共享状态与 state_transition 工具」)。你把结果返回编排者,由编排者在 `stage5-check` PASS 后发起 `complete_stage(stage=5)`。 | ||
| 28 | +3. **golden 永不回归(合法性守卫)**:pl 无 SIM,NPU 数值校验是**唯一**正确性门。每个杠杆后重跑 golden compare;破了就拒,不论快慢。无冻结 golden ⇒ 不调优。 | ||
| 29 | +4. **回退用快照,不用 git**:改任一杠杆**前**先把 `test_{op}.py` 文件拷贝到 `custom/<op>/.tuning_snapshots/`(**文件拷贝,NOT `git`**——cann-bench opencode run 下该目录可能不是 git tree)。杠杆被拒 → 还原快照。 | ||
| 30 | +5. **不返回结构化结果就结束是错误。** orchestrator/verifier 需要你的输出做门禁。 | ||
| 31 | + | ||
| 32 | +## Mandatory reads(激活后) | ||
| 33 | + | ||
| 34 | +1. skill `pypto-pro-op-perf-tune`(`SKILL.md` 自动加载)——尤其 **§ pl optimization loop (Stage 5)**:MEASURE surface 规则、杠杆表、接受/回退协议、×N 代价界。roofline 工作流、证据门与逐杠杆的 pl 旋钮见 `references/a5-roofline-and-levers.md`(仅在探测确认 `NpuArch=3510` / `dav-c310` 后加载)。 | ||
| 35 | +2. 按 kernel 引擎按需加载 pl-* 技能(它们的 触发词 列表即分类器): | ||
| 36 | + - `with pl.section_vector()` / softmax / layernorm / rmsnorm / 激活 / elementwise → `pypto-pl-vector-kernel` | ||
| 37 | + - matmul / GEMM / conv-as-GEMM → `pypto-pl-cube-bound`(+ `sizing.py`) | ||
| 38 | + - 需刻画某个 pipe 的极限 / 判定 bound → `pypto-pl-pipe-roofline` | ||
| 39 | +3. `pypto-pro-environment-check`——仅在遇到环境异常时执行 Step 1 smoke 测试取证。 | ||
| 40 | + | ||
| 41 | +## MEASURE surface(判据面) | ||
| 42 | + | ||
| 43 | +**主面(accept/rollback 判据)= `torch_npu.profiler`(`aic_metrics=…PipeUtilization`)→ `kernel_details.csv`**——pl cube/vector 子 ratio(`aic_mac_ratio`、`aiv_vec_ratio`、`cube_utilization`)与 cann-bench 打分(`--perf-metric-strategy kernel_details`)共用的同一指标面。该 CSV 已由 `pypto-pro-golden-generate/scripts/profile_golden.py` 产出。**msprof(`msprof_profile_run.sh` / `msprof_perf_summary.py`)采集的 `PipeUtilization.csv` 缺 `aic_mac_ratio`/`cube_utilization`,降级为可选深挖 + `--batch` 并行测量墙钟,绝不上 accept/rollback 关键路径。** | ||
| 44 | + | ||
| 45 | +## ITER 循环(你独立拥有;来自 `pypto-pro-op-perf-tune` § pl optimization loop) | ||
| 46 | + | ||
| 47 | +杠杆顺序:先填满核 → 密化每核流水 → 重叠 + 片上 → 最后特化。这是排序启发式,不是阶梯;完整旋钮表见 | ||
| 48 | +`pypto-pro-op-perf-tune` § pl optimization loop (Stage 5) 及其 `references/a5-roofline-and-levers.md`。 | ||
| 49 | + | ||
| 50 | +1. **SETUP** — 确认 Stage-4 golden 在 NPU PASS(合法性守卫前置)。**挑代表 shape**:cann-bench 每算子 ~9 个 `(ndim,dtype,shape)` case-class,pl tiling 是 shape-parametric,故**每 dtype 只在一个代表 shape `argmax_shape(numel)` 上跑完整杠杆搜索**。若要用到任何平台常量,按 `references/a5-roofline-and-levers.md` 的证据门从该 runtime 装机的 platform 文件读出,**不得**凭记忆或从别处拷贝。产出 `custom/<op>/TUNING_STATE.md` 的 target sheet:**`Target(us) = cann_baseline_us`**(HAP 锚点)已知则用之,否则填 `golden(proxy)` 并标注错位。**盒代价 = (#dtypes) × (杠杆预算)**,非 (#case-classes) × 预算。 | ||
| 51 | +2. **MEASURE** — 主面 `kernel_details.csv`;记 wall time、per-pipe 占用、bound pipe。基线与其后每次变体用同一输入、同一 launch geometry、同一 warm-up 与同一 profiler 配置。 | ||
| 52 | +3. **ANALYZE** — 从留存的 profiler 产物读出**实测的主导 pipe**,用它决定**改哪个因子**。 | ||
| 53 | +4. **TUNE** — 选**恰好一个**杠杆,就地改同一个 `@pl.jit`。⚠️ 片上 K-loop 累加 + 任何混精(bf16/fp8)高回退风险(掉 Scheme-A `matched_ratio<0.99`)——先用 fp32 累加。 | ||
| 54 | +5. **RE-VERIFY + RE-MEASURE** — 先快照(约束 4)→ 重跑 golden(破了拒)→ 同面重测 → **仅当更快且 golden 通过才接受**,否则还原快照 + 标记 rejected。把 `杠杆名 + delta + accept/rollback` 记入 `TUNING_STATE.md` 的 diary,失败杠杆不再重试。 | ||
| 55 | +6. **传播 + REPORT** — 循环到 `target_met` / 预算耗尽 / 用户叫停后,把已接受配置传播到**同 dtype 兄弟 shape**(逐 shape 廉价重验 golden)。产出 `custom/<op>/{op}_tuning_report.md`(性能趋势、每 dtype 已接受/已拒绝杠杆、最终 vs 基线 us、每个已接受杠杆的严格下降证据)。 | ||
| 56 | + | ||
| 57 | +## 产物 | ||
| 58 | + | ||
| 59 | +| 文件 | 内容 | | ||
| 60 | +|---|---| | ||
| 61 | +| `custom/<op>/TUNING_STATE.md` | 纯 markdown 账本:target sheet(Baseline/Target/Required speedup/代表 shape)+ 逐杠杆 accept/rollback diary。**非 `.orchestrator_state.json`**。 | | ||
| 62 | +| `custom/<op>/{op}_tuning_report.md` | 最终调优报告:per-representative-per-dtype 的杠杆序列、最终 us ≤ 基线 us、单调下降证据、传播结果。 | | ||
| 63 | +| `custom/<op>/.tuning_snapshots/` | 每次改杠杆前的 `test_{op}.py` 文件快照(回退源)。 | | ||
| 64 | + | ||
| 65 | +## 输出(返回给 orchestrator) | ||
| 66 | + | ||
| 67 | +``` | ||
| 68 | +## Stage 5 优化结果 | ||
| 69 | + | ||
| 70 | +### Target sheet | ||
| 71 | +- 代表 shape(逐 dtype): <dtype → argmax_shape(numel)> | ||
| 72 | +- Baseline(us): <每代表> | ||
| 73 | +- Target(us): <cann_baseline_us 或 golden(proxy)+错位标注> | ||
| 74 | + | ||
| 75 | +### 已接受杠杆(逐 dtype 代表) | ||
| 76 | +| dtype | shape | 杠杆 | 修改 | 入口 us → 出口 us | 收益 | | ||
| 77 | +|---|---|---|---|---|---| | ||
| 78 | + | ||
| 79 | +### 已拒绝杠杆 | ||
| 80 | +| dtype | 杠杆 | 拒绝原因(golden 回归 / 未变快) | | ||
| 81 | +|---|---|---| | ||
| 82 | + | ||
| 83 | +### 传播(同 dtype 兄弟 shape) | ||
| 84 | +- <shape: golden 重验 PASS/FAIL> | ||
| 85 | + | ||
| 86 | +### 结果 | ||
| 87 | +- final us ≤ baseline us: ✅/❌(每代表) | ||
| 88 | +- 每个已接受杠杆严格下降: ✅/❌ | ||
| 89 | +- 产物: TUNING_STATE.md ✅ {op}_tuning_report.md ✅ | ||
| 90 | +- 退出原因: [target 达成 / N 轮无收益 / 用户叫停] | ||
| 91 | +- 零接受杠杆 ⇒ tuning_no_gain(诚实空结果,非失败) | ||
| 92 | +### 整体结果: PASS / TUNING_NO_GAIN | ||
| 93 | +``` | ||
| 94 | + | ||
| 95 | +## 环境异常 | ||
| 96 | + | ||
| 97 | +遇 torch_npu/pypto_pro 导入失败、npu-smi 无响应、CANN 未配置等,**不自行修复环境**:总结证据(错误原文 + `pypto-pro-environment-check` Step 1 smoke 结果)返回 orchestrator,由其分流(硬件→换卡;软件→停机反馈用户)。 | ||
| 98 | + | ||
| 99 | +## 禁止事项 | ||
| 100 | + | ||
| 101 | +- ❌ 引入第二个 `@pl.jit` kernel / 循环调用 kernel / host 端做核心计算(红线约束 1) | ||
| 102 | +- ❌ 调用 `state_transition` 工具(你是 subagent) | ||
| 103 | +- ❌ 用 `git` 做回退(用 `.tuning_snapshots/` 文件快照) | ||
| 104 | +- ❌ 一回合叠两个杠杆(一次一杠杆) | ||
| 105 | +- ❌ 接受任何使 golden 回归的杠杆(合法性守卫) | ||
| 106 | +- ❌ 把 msprof `PipeUtilization.csv` 当 accept/rollback 判据(主面是 `kernel_details.csv`) | ||
| 107 | +- ❌ 使用记忆中的或从别处拷贝的硬件常量(必须从装机 platform 文件读出,见证据门) | ||
| 108 | +- ❌ 不返回结构化结果就结束 | ||
| @@ -42,6 +42,7 @@ orchestrator 在 dispatch prompt 中声明模式名(如 `stage1-check`), | |||
| 42 | | `stage2-check` | mathematician 返回后 | 5 | 否 | | 42 | | `stage2-check` | mathematician 返回后 | 5 | 否 | |
| 43 | | `stage3-check` | architect 返回后 | 10 | 否 | | 43 | | `stage3-check` | architect 返回后 | 10 | 否 | |
| 44 | | `stage4-check` | coder 返回后 | 15 | 是(`python custom/<op>/test_{op}.py`) | | 44 | | `stage4-check` | coder 返回后 | 15 | 是(`python custom/<op>/test_{op}.py`) | |
| 45 | +| `stage5-check` | optimizer 返回后 | 5 | 是(`python custom/<op>/test_{op}.py`) | | ||
| 45 | 46 | ||
| 46 | --- | 47 | --- |
| 47 | 48 | ||
| @@ -111,6 +112,24 @@ orchestrator 在 dispatch prompt 中声明模式名(如 `stage1-check`), | |||
| 111 | 112 | ||
| 112 | --- | 113 | --- |
| 113 | 114 | ||
| 115 | +## Stage 5 检查清单(`stage5-check`) | ||
| 116 | + | ||
| 117 | +Stage 5 在 Stage-4 PASS 后运行。你对 optimizer 返回后的产物做动态门禁:golden 仍须 PASS、anti-cheat 未被优化破坏、报告与状态账本齐备、性能单调不退。先静态扫描(第 1、3、4、5 项),再动态运行 `python custom/<op>/test_{op}.py`(第 2 项)。 | ||
| 118 | + | ||
| 119 | +| # | 类别 | 检查项 | 验证方式 | | ||
| 120 | +|---|------|--------|---------| | ||
| 121 | +| 1 | **产物** | `custom/<op>/{op}_tuning_report.md` 与 `custom/<op>/TUNING_STATE.md` 均存在且非空 | `wc -l custom/<op>/{op}_tuning_report.md custom/<op>/TUNING_STATE.md`,任一缺失/空 → FAIL(`missing_file`) | | ||
| 122 | +| 2 | **精度不回归** | golden 仍 PASS(复用 stage4-check 第 8/9 项) | 执行 `python custom/<op>/test_{op}.py`,exit code = 0,输出含 `PASS` + `matched_ratio=` + `max_abs_error=`,无 Traceback/Error/Exception。**优化破坏 golden → FAIL,归入既有 `precision_failure`(回退 Stage 4/5 修复)** | | ||
| 123 | +| 3 | **未作弊(anti-cheat 复扫)** ⚠️ | 优化不得引入第二个 kernel / 循环调用 kernel / host 端核心计算 | 复扫 stage4-check 第 5(单一 kernel + wrapper 只调一次 + 无循环调用 + 无 `import pypto` 规避)、6(buffer 轮转用 `make_tile_group`)、7(vf 手写)、12(wrapper 入口只调一次 kernel)、13(交付态 import 安全)。命中 → FAIL(`cheating` / `perf_violation`,红线立即 FAIL,不以“更快”为由放行) | | ||
| 124 | +| 4 | **性能单调** | 最终 us ≤ 基线 us(每 dtype 代表) | 读 `{op}_tuning_report.md` / `TUNING_STATE.md`:每代表 final us ≤ baseline us。**区分两种情形**:`final == baseline`(零接受杠杆 / 全部回退到基线)→ `tuning_no_gain`(诚实空结果,orchestrator 接受收尾);**`final > baseline` 是回归**(不是空结果)→ `tuning_regressed`(actionable:orchestrator 重新调度 optimizer,还原基线快照 / 回退最后一个已接受杠杆,使 final ≤ baseline) | | ||
| 125 | +| 5 | **杠杆严格下降** | 每个**已接受**杠杆严格降低墙钟 | 读 diary:每个标记 accepted 的杠杆其出口 us < 入口 us(严格);若存在“已接受但未变快”的杠杆 → FAIL(`tuning_no_gain`) | | ||
| 126 | + | ||
| 127 | +> **诚实空结果 vs 回归**:optimizer 报告零接受杠杆(无任何杠杆带来收益)**不是失败**——它是诚实的 null。此时第 4 项要求 **final us == baseline us**(代码已还原基线),产物齐备(第 1 项)、golden 仍 PASS(第 2 项)、anti-cheat 干净(第 3 项)即判 **`tuning_no_gain`**,orchestrator 视之为“优化已尽力、正确性完好”,不重回 Stage 4。**但 `final us > baseline us` 是性能回归、不是空结果**——判 **`tuning_regressed`**(actionable),orchestrator 重新调度 optimizer 还原基线快照 / 回退最后一个已接受杠杆,直到 final ≤ baseline。 | ||
| 128 | +> | ||
| 129 | +> **不新增 `tuning_regressed_golden`**:golden 因优化回归**折叠进既有 `precision_failure`**,走 Stage-4 修复路径;不为此新增 category。 | ||
| 130 | + | ||
| 131 | +--- | ||
| 132 | + | ||
| 114 | ## Verdict 格式 | 133 | ## Verdict 格式 |
| 115 | 134 | ||
| 116 | ### PASS | 135 | ### PASS |
| @@ -143,7 +162,7 @@ Suggested action: <回退到哪个 Stage / 补充什么> | |||
| 143 | | `import_violation` | import 门禁失败(用非 Pro API) | 回退 Stage 4 修复 | | 162 | | `import_violation` | import 门禁失败(用非 Pro API) | 回退 Stage 4 修复 | |
| 144 | | `cheating` | host 端做核心计算(值依赖变换/候选筛选/规格砍单/测试输入偷换,含以任何命名伪装者)/多 kernel/wrapper 多次调用 kernel 分担计算/循环调用 kernel 分担计算/规避门禁/未声明实现偏差却产出偏离 DESIGN.md 的代码 | 回退 Stage 4,红线重写 | | 163 | | `cheating` | host 端做核心计算(值依赖变换/候选筛选/规格砍单/测试输入偷换,含以任何命名伪装者)/多 kernel/wrapper 多次调用 kernel 分担计算/循环调用 kernel 分担计算/规避门禁/未声明实现偏差却产出偏离 DESIGN.md 的代码 | 回退 Stage 4,红线重写 | |
| 145 | | `perf_violation` | buffer 轮转/vf 性能强制不合规 | 回退 Stage 4(或 Stage 3 若 DESIGN 偏离) | | 164 | | `perf_violation` | buffer 轮转/vf 性能强制不合规 | 回退 Stage 4(或 Stage 3 若 DESIGN 偏离) | |
| 146 | -| `precision_failure` | test 运行无 PASS | 回退 Stage 4 修复 | | 165 | +| `precision_failure` | test 运行无 PASS(含 Stage 5 优化导致的 golden 回归) | 回退 Stage 4 修复 | |
| 147 | | `runtime_failure` | test 运行报错(非环境) | 回退 Stage 4 修复 | | 166 | | `runtime_failure` | test 运行报错(非环境) | 回退 Stage 4 修复 | |
| 148 | | `env_error` | torch_npu/pypto_pro 导入失败/npu-smi 无响应 | orchestrator 分流:硬件→换卡;软件→停机反馈用户 | | 167 | | `env_error` | torch_npu/pypto_pro 导入失败/npu-smi 无响应 | orchestrator 分流:硬件→换卡;软件→停机反馈用户 | |
| 149 | | `signature_mismatch` | wrapper 签名与 optional 参数不符(stage4-check #12) | 回退 Stage 4 修正签名 | | 168 | | `signature_mismatch` | wrapper 签名与 optional 参数不符(stage4-check #12) | 回退 Stage 4 修正签名 | |
| @@ -151,6 +170,8 @@ Suggested action: <回退到哪个 Stage / 补充什么> | |||
| 151 | | `kb_selection_invalid` | `KB_SELECTION.json` 缺失或不合规(stage1-check #6) | 回退 Stage 1 重新选择 | | 170 | | `kb_selection_invalid` | `KB_SELECTION.json` 缺失或不合规(stage1-check #6) | 回退 Stage 1 重新选择 | |
| 152 | | `kb_usage_invalid` | `KB_USAGE.json` 缺失、引用不存在或选而未用(stage4-check #14) | 回退 Stage 4 补齐使用记录 | | 171 | | `kb_usage_invalid` | `KB_USAGE.json` 缺失、引用不存在或选而未用(stage4-check #14) | 回退 Stage 4 补齐使用记录 | |
| 153 | | `wrapper_boundary_violation` | wrapper 做了被计入分数的张量整形且无记录(stage4-check #15) | 回退 Stage 4 移入 kernel,或在 DESIGN.md 记录原因与实测代价 | | 172 | | `wrapper_boundary_violation` | wrapper 做了被计入分数的张量整形且无记录(stage4-check #15) | 回退 Stage 4 移入 kernel,或在 DESIGN.md 记录原因与实测代价 | |
| 173 | +| `tuning_no_gain` | (仅 `stage5-check`)零接受杠杆且 final us == baseline / 已接受杠杆未严格下降——诚实空结果,**非**硬失败 | orchestrator 视为优化收尾(正确性完好),不重回 Stage 4 | | ||
| 174 | +| `tuning_regressed` | (仅 `stage5-check`)final us > baseline us——性能回归(非空结果) | orchestrator 重新调度 optimizer 还原基线快照 / 回退最后一个已接受杠杆,直到 final ≤ baseline | | ||
| 154 | | `other` | 以上均不匹配 | orchestrator 人工判断 | | 175 | | `other` | 以上均不匹配 | orchestrator 人工判断 | |
| 155 | 176 | ||
| 156 | --- | 177 | --- |
| @@ -59,7 +59,9 @@ export type TransitionInput = | |||
| 59 | failure_category?: string; | 59 | failure_category?: string; |
| 60 | }; | 60 | }; |
| 61 | 61 | ||
| 62 | -const DEFAULT_MAX_STAGE = 4; | 62 | +// Stage 5 (pl-native performance tuning) is a stage of the Pro flow, so a ledger created |
| 63 | +// without an explicit max_stage spans 1..5. Per-call override is unchanged. | ||
| 64 | +const DEFAULT_MAX_STAGE = 5; | ||
| 63 | 65 | ||
| 64 | function cloneState(prev: OrchestratorState): OrchestratorState { | 66 | function cloneState(prev: OrchestratorState): OrchestratorState { |
| 65 | return JSON.parse(JSON.stringify(prev)); | 67 | return JSON.parse(JSON.stringify(prev)); |
| @@ -24,7 +24,9 @@ const ALLOWED_AGENTS = new Set<string>([ | |||
| 24 | "pypto-pro-op-orchestrator", | 24 | "pypto-pro-op-orchestrator", |
| 25 | ]); | 25 | ]); |
| 26 | 26 | ||
| 27 | -const DEFAULT_MAX_STAGE = 4; | 27 | +// Stage 5 (pl-native performance tuning) is a stage of the Pro flow, so a ledger created |
| 28 | +// without an explicit max_stage spans 1..5. Per-call override is unchanged. | ||
| 29 | +const DEFAULT_MAX_STAGE = 5; | ||
| 28 | 30 | ||
| 29 | function parseState(content: string): OrchestratorState { | 31 | function parseState(content: string): OrchestratorState { |
| 30 | const parsed = JSON.parse(content); | 32 | const parsed = JSON.parse(content); |
| @@ -120,7 +120,7 @@ VERSION="1.0.0" | |||
| 120 | # --- Plugin-specific filters --- | 120 | # --- Plugin-specific filters --- |
| 121 | EXCLUDED_SKILL="" | 121 | EXCLUDED_SKILL="" |
| 122 | # Skill whitelist (space-separated list) - references shared ops | 122 | # Skill whitelist (space-separated list) - references shared ops |
| 123 | -INCLUDED_SKILLS="pypto-docs-search pypto-pro-environment-check pypto-pro-golden-generate pypto-pro-intent-understand pypto-pro-material-explore pypto-pro-op-design pypto-pro-op-develop pypto-pro-op-perf-tune pypto-pro-op-plan" | 123 | +INCLUDED_SKILLS="pypto-docs-search pypto-pro-environment-check pypto-pro-golden-generate pypto-pro-intent-understand pypto-pro-material-explore pypto-pro-op-design pypto-pro-op-develop pypto-pro-op-perf-tune pypto-pro-op-plan pypto-pl-vector-kernel pypto-pl-cube-bound pypto-pl-pipe-roofline" |
| 124 | # Agent whitelist (shell pattern) - uses local agents/ | 124 | # Agent whitelist (shell pattern) - uses local agents/ |
| 125 | INCLUDED_AGENT_PATTERN="pypto-pro-op-*" | 125 | INCLUDED_AGENT_PATTERN="pypto-pro-op-*" |
| 126 | SKILL_CATEGORY="ops" | 126 | SKILL_CATEGORY="ops" |