| @@ -38,17 +38,22 @@ description: 实现、调试并自验证 PyPTO-Pro 算子 kernel。用于 Stage | |||
| 38 | 38 | ||
| 39 | ## 按需读取的资源 | 39 | ## 按需读取的资源 |
| 40 | 40 | ||
| 41 | -| 场景 | 资源 | | 41 | +本表是本 skill 资源索引的唯一来源(含加载时机)。 |
| 42 | -|---|---| | 42 | + |
| 43 | -| 纯 Vector 的主要编码参考 | [templates/pure_vec_impl_template.py.tmpl](templates/pure_vec_impl_template.py.tmpl);选择方式见步骤 4 | | 43 | +| 资源 | 用途 | 加载时机 | |
| 44 | -| 纯 Cube 的主要编码参考 | PRO_MATERIAL_INDEX.md §B 列出的官方 `matmul_perf_asw_4k_dynamic` 样例(`$PYPTO_DEVKIT_DIR/pro_ops/matmul/test_matmul_perf_asw_4k_dn_move_offset_dynamic.py`) | | 44 | +|---|---|---| |
| 45 | -| 通用、CV 融合或多 Module 文件骨架 | [templates/impl_template.py.tmpl](templates/impl_template.py.tmpl) | | 45 | +| [templates/pure_vec_impl_template.py.tmpl](templates/pure_vec_impl_template.py.tmpl) | 纯 vec 通用骨架;使用前按目标 API 与 DESIGN.md 核对 | 纯 vec 算子生成代码前 | |
| 46 | -| Vector reduction | [references/vf-reduction-perf.md](references/vf-reduction-perf.md) | | 46 | +| `$PYPTO_DEVKIT_DIR/pro_ops/matmul/test_matmul_perf_asw_4k_dn_move_offset_dynamic.py` | **纯 cube 算子候选实现起点**——两级 K 分块 + move offset + 嵌套四分支 K 累加 + 尾块处理 + ASW 蛇形调度;仅在该路径存在且目标版本匹配时使用 | 纯 cube 算子生成代码前 | |
| 47 | -| wrapper 动态反作弊检查 | [pypto-pro-op-perf-tune](../pypto-pro-op-perf-tune/SKILL.md);只检查 profile 中的 device op,不评价性能 | | 47 | +| [templates/impl_template.py.tmpl](templates/impl_template.py.tmpl) | kernel 文件骨架(tile 声明 + section + Module + 测试函数)——**通用**(含 CV 融合 / 多 Module / 跨核流水);CV 融合算子当前无专用模板,走此通用骨架,按「开发流程」各步执行 | 生成代码前必读 | |
| 48 | -| 验证失败 | [references/debugging-methodology.md](references/debugging-methodology.md) | | 48 | +| [references/debugging-methodology.md](references/debugging-methodology.md) | 调试方法论:**先确认失败可信** → 症状快查表 → 分层 review → 定位技术(最小复现/消融/单原语替换/差异属性)→ 升级切换 → **修正后验证** + 诊断纪律 | 验证失败进入 debug 状态时必读 | |
| 49 | -| KB 选择与使用格式 | [KB CONTRACT](../../pypto-pro-op-kb/CONTRACT.md);它是完整合同的唯一来源 | | 49 | +| [references/vf-reduction-perf.md](references/vf-reduction-perf.md) | Vector reduction 的数值安全、正确 API 形态与性能注意事项 | 实现或调优 Vector reduction 时 | |
| 50 | -| API/样例不足 | [KB ROUTER](../../pypto-pro-op-kb/ROUTER.md) 每次只选择与当前决策直接相关的参考 | | 50 | +| [references/cv-matmul-direct-buffering.md](references/cv-matmul-direct-buffering.md) | Cube 累加器在同一 launch 内被 Vector epilogue 消费时的轮转缓冲与 `auto_mutex` 形态 | 实现 CV 直连 matmul 时 | |
| 51 | -| 运行前选择空闲卡 | [scripts/list_idle_chip_ids.sh](scripts/list_idle_chip_ids.sh) | | 51 | +| [templates/cv_matmul_direct_buffering.py.tmpl](templates/cv_matmul_direct_buffering.py.tmpl) | 上一行的可替换代码骨架 | 同上 | |
| 52 | +| [templates/fp32-chain-precision-fragments.py.tmpl](templates/fp32-chain-precision-fragments.py.tmpl) | fp32 链路的精度安全片段 | 需要与 CPU 参考逐位对齐时 | | ||
| 53 | +| [../../pypto-pro-op-kb/ROUTER.md](../../pypto-pro-op-kb/ROUTER.md) | 按任务选择一个补充约束、pattern 或 validated study kernel | API 文档与官方样例不足时 | | ||
| 54 | +| [scripts/list_idle_chip_ids.sh](scripts/list_idle_chip_ids.sh) | 查找空闲 NPU chip | 运行前按需执行 | | ||
| 55 | +| [pypto-pro-op-perf-tune](../pypto-pro-op-perf-tune/SKILL.md) | wrapper 动态反作弊检查:只检查 profile 中的 device op,不评价性能 | 需要验证 wrapper 未绕过 kernel 时 | | ||
| 56 | +| [KB CONTRACT](../../pypto-pro-op-kb/CONTRACT.md) | KB 选择与使用格式的完整合同,唯一来源 | 写 `KB_SELECTION.json` / `KB_USAGE.json` 前 | | ||
| 52 | 57 | ||
| 53 | 参考之间是互补关系:DESIGN.md 决定“实现什么”,纯 Vector 模板或 Cube 官方样例提供“如何写”的主要起点,`KB_SELECTION.json` 已选参考补充必须落实的 pattern 和约束;三者不得相互替代。模板和样例不是 API 或性能事实源,使用时仍须核对目标版本 API 文档;与 DESIGN.md 或已选 KB 冲突的参考片段直接弃用,只有上游合同本身无法同时落实时才按根因分流,Stage 4 不自行改合同。标为 conceptual 的片段不得直接复制成交付代码。 | 58 | 参考之间是互补关系:DESIGN.md 决定“实现什么”,纯 Vector 模板或 Cube 官方样例提供“如何写”的主要起点,`KB_SELECTION.json` 已选参考补充必须落实的 pattern 和约束;三者不得相互替代。模板和样例不是 API 或性能事实源,使用时仍须核对目标版本 API 文档;与 DESIGN.md 或已选 KB 冲突的参考片段直接弃用,只有上游合同本身无法同时落实时才按根因分流,Stage 4 不自行改合同。标为 conceptual 的片段不得直接复制成交付代码。 |
| 54 | 59 | ||
| @@ -0,0 +1,161 @@ | |||
| 1 | +# CV matmul direct handoff and rotating buffers | ||
| 2 | + | ||
| 3 | +Use this reference for A5 Cube matmul kernels whose accumulator is consumed by | ||
| 4 | +a Vector epilogue in the same launch. It states the double-buffer shape in | ||
| 5 | +PyPTO-Pro terms -- `make_tile_group + auto_mutex`; it is not a drop-in | ||
| 6 | +operator. | ||
| 7 | + | ||
| 8 | +## Buffer map | ||
| 9 | + | ||
| 10 | +For a two-level K loop, start from the target SDK's official dynamic-ASW roles: | ||
| 11 | + | ||
| 12 | +| role | depth | cursor operation | | ||
| 13 | +|---|---:|---| | ||
| 14 | +| A/B Mat (L1) | 4 | `.next()` once per non-empty K1 iteration | | ||
| 15 | +| A/B Left/Right (L0) | 2 | `.next()` once per non-empty K0 iteration | | ||
| 16 | +| int32 Acc (L0C) | 1 | `.current()` once per output tile | | ||
| 17 | +| direct int32 Vec tile | 1 | `.current()` once per output tile | | ||
| 18 | + | ||
| 19 | +A scalar `addrs=` value is the first TileGroup slot base. PyPTO-Pro lays later | ||
| 20 | +slots contiguously by physical tile bytes. Prove the high-water mark with the | ||
| 21 | +largest compile-time tile family; do not count only the logical tail window. | ||
| 22 | +L0A, L0B and L0C are different memories, while both Mat operands share L1. | ||
| 23 | + | ||
| 24 | +Assign every simultaneously live TileGroup a unique mutex ID. In a fused | ||
| 25 | +cross-core kernel, reserve the logical READY/FREE IDs and their AIV mirrors | ||
| 26 | +before assigning buffer IDs; on the validated A5 mapping, logical 0/1 occupy | ||
| 27 | +physical 0/1/16/17. | ||
| 28 | + | ||
| 29 | +## Direct Acc-to-Vector handoff | ||
| 30 | + | ||
| 31 | +If the final accumulator uses `pl.move(..., acc_to_vec_mode=...)` instead of an | ||
| 32 | +Acc store: | ||
| 33 | + | ||
| 34 | +- leave `phase` unspecified on `pl.matmul` and `pl.matmul_acc`; a TMOV has no | ||
| 35 | + `STPhase.Final` peer to reset the Acc unit flag; | ||
| 36 | +- pin a compact Acc to its full physical window before the first matmul and do | ||
| 37 | + not narrow it before TMOV; use `[tile_m, tile_n]` so a gated wider family is | ||
| 38 | + not silently decoded with the baseline TN; | ||
| 39 | +- use the matching hardware split only when each AIV share fits UB and final GM | ||
| 40 | + stores cannot share an unaligned 32-byte beat; otherwise select a proven | ||
| 41 | + single-AIV family; | ||
| 42 | +- retain a matching-runtime-proven M-to-FIX dependency. Older deployments may | ||
| 43 | + require the explicit `sync_src/sync_dst(M,FIX)` compatibility pair even when | ||
| 44 | + a newer auto-mutex test shows the Acc release/FIX acquire edge. | ||
| 45 | + | ||
| 46 | +For a one-slot Cube-to-Vector credit protocol, each AIV primes MTE3 FREE once, | ||
| 47 | +waits READY once per task, and returns MTE3 FREE after the conditional output | ||
| 48 | +store. Empty shares still return their credit. Cube waits both physical FREE | ||
| 49 | +credits before TMOV, sets both READY credits after TMOV, and drains one final | ||
| 50 | +FREE pair after the loop. For `T` tasks per core the balance is `T+1` FREE | ||
| 51 | +events and `T` READY events in each direction. Inspect generated CCE: the | ||
| 52 | +validated specializations contain two MTE3 FREE sites, no V FREE site and place | ||
| 53 | +the per-task FREE after TSTORE. | ||
| 54 | + | ||
| 55 | +## Wide-tile resource check | ||
| 56 | + | ||
| 57 | +Evaluate `(TM,TK1,TN)` candidates symbolically before codegen: | ||
| 58 | + | ||
| 59 | +```text | ||
| 60 | +L1 bytes = depth_l1 * (TM*TK1 + TK1*TN) * operand_bytes | ||
| 61 | +L0A bytes = depth_l0 * TM*TK0 * operand_bytes | ||
| 62 | +L0B bytes = depth_l0 * TK0*TN * operand_bytes | ||
| 63 | +L0C bytes = TM*TN*accumulator_bytes | ||
| 64 | +UB direct = hardware_share_rows*hardware_share_cols*accumulator_bytes | ||
| 65 | +``` | ||
| 66 | + | ||
| 67 | +Reducing L1 depth from four to two is valid only as a separate measured | ||
| 68 | +candidate. A larger TK/TN can consume the saved capacity; do not assume either | ||
| 69 | +choice is faster. | ||
| 70 | + | ||
| 71 | +### Gating a wider tile family behind a tiling key | ||
| 72 | + | ||
| 73 | +Prefer a new tiling-key bit over changing the baseline family globally. The | ||
| 74 | +gate is a compile-time predicate over shape and mode, of the form: | ||
| 75 | + | ||
| 76 | +```text | ||
| 77 | +wide_n = M >= <m_min> and K >= <k_min> and N % <wide_tile> == 0 | ||
| 78 | + and not <per-token mode> and <baseline occupancy> >= <cores> | ||
| 79 | +tile_n = <wide_tile> if wide_n else <base_tile> | ||
| 80 | +``` | ||
| 81 | + | ||
| 82 | +Every threshold in it is per-operator and per-target: derive each from the | ||
| 83 | +resource check above and the measured occupancy, and re-derive them when either | ||
| 84 | +changes. What generalises is the *structure* — admit the wide tile only where | ||
| 85 | +it is both resource-safe and occupancy-positive, and only for the modes whose | ||
| 86 | +epilogue can absorb it. | ||
| 87 | + | ||
| 88 | +Propagate `tile_n` into every physical allocation and compact-window assertion, | ||
| 89 | +and record the worst-case byte high-water marks for L1, L0A, L0B, L0C and UB of | ||
| 90 | +the map you validated; they move with the tile and are not transferable between | ||
| 91 | +maps. | ||
| 92 | + | ||
| 93 | +**Do not reuse a wide key for small or decode shapes.** A candidate can pass | ||
| 94 | +codegen and full bit-exact correctness and still regress the small-shape probes | ||
| 95 | +by more than 1.5x, because a wide tile on a short reduction buys nothing and | ||
| 96 | +costs occupancy. Correctness is not evidence that the key is safe to widen. | ||
| 97 | + | ||
| 98 | +### Beat-safe N-tail dual-AIV gate | ||
| 99 | + | ||
| 100 | +With a 2-byte output and a full 256-column share, adjacent row segments have: | ||
| 101 | + | ||
| 102 | +```text | ||
| 103 | +gap_bytes = (N - 256) * 2 | ||
| 104 | +``` | ||
| 105 | + | ||
| 106 | +Enumerate all 32 possible byte offsets when proving beat ownership. **A gap of | ||
| 107 | +at least 32 B is sufficient for disjoint 32 B beats**; below that, two AIVs can | ||
| 108 | +share a beat and the split is unsound — construct the overlapping-beat | ||
| 109 | +counterexample rather than assuming the margin. | ||
| 110 | + | ||
| 111 | +That inequality, not a width list, is the gate: the smallest admissible | ||
| 112 | +unaligned `N` is the smallest one whose `gap_bytes` reaches 32, and every | ||
| 113 | +narrower tail keeps the single-AIV path. Aligned `N` already uses its normal | ||
| 114 | +family, so the dual-AIV split only ever applies to unaligned widths at or above | ||
| 115 | +that threshold. Recompute the threshold when the output dtype changes — it is | ||
| 116 | +`2 B` per element in the expression above. | ||
| 117 | + | ||
| 118 | +## Mandatory promotion gates | ||
| 119 | + | ||
| 120 | +1. Compile representative dtype, tail-mode and tile-family keys. Inspect C++ | ||
| 121 | + for the expected slot addresses, cursor modulo, TLOAD/TEXTRACT/TMATMUL chain, | ||
| 122 | + one Acc TMOV, no GM workspace and no Acc phase. | ||
| 123 | +2. On the authorized device under the required lock, compare bit-exactly across | ||
| 124 | + K around both K0 and K1 boundaries, M/N tails, multiple output tiles, batch, | ||
| 125 | + optional epilogue inputs and repeated same-core reuse. | ||
| 126 | +3. Measure the exact kernel with msprof/`kernel_details.csv`. Wrapper Event | ||
| 127 | + intervals are only a directional probe. | ||
| 128 | +4. Promote only tile families that improve the measured shapes; add a host | ||
| 129 | + metadata gate for resource-unsafe or occupancy-poor geometries. | ||
| 130 | + | ||
| 131 | +**What the correctness evidence has to cover.** A 4xL1/2xL0 rotation is | ||
| 132 | +established bit-exact only against K values that straddle every boundary the | ||
| 133 | +rotation has (1, one below / at / one above each K tile, and at least one value | ||
| 134 | +past two full cycles), plus M/N tails, multi-tile reuse and batch. Anything less | ||
| 135 | +leaves a boundary the rotation never crossed. | ||
| 136 | + | ||
| 137 | +**Performance stays a per-operator profiler decision.** A double-buffered | ||
| 138 | +rotation is worth roughly 1.2-1.7x on kernel-only medians for a mid-size | ||
| 139 | +geometry, but the spread across shapes is wider than the mean, and a wider K/N | ||
| 140 | +tile is rejected whenever its *ranking* is unstable across shapes rather than | ||
| 141 | +when its mean is worse -- an unstable ranking means the next shape decides the | ||
| 142 | +winner. | ||
| 143 | + | ||
| 144 | +**Expect the end-to-end gain to be smaller than the kernel gain.** Startup and | ||
| 145 | +pipeline costs dominate the shapes that remain slow, so a kernel ratio well | ||
| 146 | +above 1 can leave the end-to-end figure nearly flat. That gap is a | ||
| 147 | +pipeline/startup problem; it is not evidence for promoting an unvalidated wide | ||
| 148 | +tile. Removing compatibility syncs, changing the initial credit protocol, | ||
| 149 | +changing K1 depth, or specialising the VF epilogue are separate candidates, each | ||
| 150 | +requiring the full locked-device promotion gates. | ||
| 151 | + | ||
| 152 | +**Do not compare aggregate figures whose baseline you do not control.** A | ||
| 153 | +baseline that moves between measurements makes the comparison meaningless. The | ||
| 154 | +evidence that a gated revision is real is *agreement between two independent | ||
| 155 | +measurements of it* -- a direct device-kernel comparison against the preceding | ||
| 156 | +source, and a held-lock A/B on the same device, landing on the same ratio within | ||
| 157 | +noise. Agreement is the evidence; either figure alone is not. | ||
| 158 | + | ||
| 159 | +Use the layers in this order: same-device held-lock A/B first, then device-kernel | ||
| 160 | +times measured in the same run as their own baseline. Discard measurements from | ||
| 161 | +a device you did not hold exclusively. | ||
| @@ -74,9 +74,8 @@ copying a call; names and signatures may differ across SDK versions. | |||
| 74 | 74 | ||
| 75 | ## <a id="no-branch"></a>Do not branch inside a vector function | 75 | ## <a id="no-branch"></a>Do not branch inside a vector function |
| 76 | 76 | ||
| 77 | -Transferred from measured EasyASC work on the same A5 silicon (a different DSL | 77 | +This is a property of the vector unit, not of any DSL over it: the vector pipe |
| 78 | -over the same vector unit). The hardware claim is a property of the unit, not | 78 | +has no branch, so an `if` inside a vector function |
| 79 | -of the DSL: the vector pipe has no branch, so an `if` inside a vector function | ||
| 80 | lowers to predicated execution — both arms issue, every lane pays for both, and | 79 | lowers to predicated execution — both arms issue, every lane pays for both, and |
| 81 | the loop around them pays the mask bookkeeping. A vector function that branches | 80 | the loop around them pays the mask bookkeeping. A vector function that branches |
| 82 | per iteration is far slower than one that does not. | 81 | per iteration is far slower than one that does not. |
| @@ -101,78 +100,14 @@ Write the alternative out of the vector function instead: | |||
| 101 | followed by `vf.select` is a data-path operation, not a branch — and masks | 100 | followed by `vf.select` is a data-path operation, not a branch — and masks |
| 102 | measured free (see the cost model below). | 101 | measured free (see the cost model below). |
| 103 | 102 | ||
| 104 | -## <a id="call-overhead"></a>Per-call overhead and loop form | ||
| 105 | - | ||
| 106 | -EasyASC-measured on Ascend 950; the instruction-level premise that EasyASC | ||
| 107 | -micro ≈ pypto-pro `vf.*` is unverified, so treat the numbers as hypotheses and | ||
| 108 | -the structure as the default until a probe on this DSL says otherwise. | ||
| 109 | - | ||
| 110 | -- **A vector-function call costs on the order of 180 cycles before any work | ||
| 111 | - issues.** A pooling case written as one call per output row spent that per | ||
| 112 | - row; moving the row loop *inside* the vector function and hoisting the | ||
| 113 | - lane-group loop out of it — one call per lane group instead of | ||
| 114 | - rows × groups — cut the small cases 2–3.6x. Shape the work inside the | ||
| 115 | - vector function; do not wrap a call in a per-row loop. | ||
| 116 | -- **Loop form: a constant trip count beats an unrolled constant beats a | ||
| 117 | - runtime-variable bound**, which is the slowest. If a loop's trip count is one | ||
| 118 | - of a few known values, specialising the kernel on it is a real lever; if it | ||
| 119 | - is genuinely dynamic, budget for the loop overhead. | ||
| 120 | -- **EasyASC's in-vf scalar path has no division and no modulo** (add, sub, | ||
| 121 | - mul, min, max only) — a per-row index needing `//` or `%` arrives as a | ||
| 122 | - recurrence: step the remainder and quotient forward with adds and a clamped | ||
| 123 | - 0/1 carry (`carry = max(0, min(1, r - d + 1))`). Whether pypto-pro's | ||
| 124 | - vector-function scalar path shares the restriction is a probe, not an | ||
| 125 | - assumption — check the installed API page before designing the recurrence | ||
| 126 | - in or out. Related, and measured on this DSL: the backend has no 64-bit | ||
| 127 | - integer division at all (see | ||
| 128 | - [`pypto-pro-op-kb/patterns/vec-tensorlist-fixed-arity.md`](../../../pypto-pro-op-kb/patterns/vec-tensorlist-fixed-arity.md)). | ||
| 129 | - | ||
| 130 | -## <a id="load-cost-model"></a>Load-issue cost model — a hypothesis to re-probe, not a fact | ||
| 131 | - | ||
| 132 | -EasyASC-measured on Ascend 950, solved from four builds of one fp32 | ||
| 133 | -accumulation loop that differed only in body: roughly **25 cycles per | ||
| 134 | -full-register UB→register load issue and 0.4 cycles per register ALU op**. | ||
| 135 | -Readings, if the model transfers: | ||
| 136 | - | ||
| 137 | -- **Deleting arithmetic buys almost nothing.** Cutting seven ALU ops per tap | ||
| 138 | - to one — on the phase that owned 60% of the kernel — moved the operator | ||
| 139 | - 2.5%. Compensated (Kahan) summation is nearly free; do not trade accuracy | ||
| 140 | - for it. | ||
| 141 | -- **Masks are free.** Compare + select, and masked variants of cast/add, all | ||
| 142 | - measured 1.00x when removed. | ||
| 143 | -- **What costs is a load issue, not the bytes.** Pairing two taps into one | ||
| 144 | - iteration (same loads per element, half the iterations) measured neutral; | ||
| 145 | - adding a *second* load per tap cost ~20%. | ||
| 146 | -- **fp16/bf16 pay double per issue**: the unpacking load moves 64 values per | ||
| 147 | - issue because the cast consumes only the even lanes, so a half-precision tap | ||
| 148 | - costs a full issue for half the data. | ||
| 149 | -- Consequence: the only lever on such a loop is **fewer load issues per input | ||
| 150 | - element**. | ||
| 151 | - | ||
| 152 | -Two reasons this must be re-probed before spending on it: the cross-DSL | ||
| 153 | -premise above, and this KB's own scan measurements | ||
| 154 | -([`pypto-pro-op-kb/patterns/vec-scan-prefix-dependent.md`](../../../pypto-pro-op-kb/patterns/vec-scan-prefix-dependent.md)) | ||
| 155 | -put an aligned `vf.load_align` at under 1 ns (~1.6 cycles) per register in a | ||
| 156 | -different loop structure — the two figures cannot both govern the same loop. | ||
| 157 | -(EasyASC also measured its gather at parity with its ordinary load; pypto-pro's | ||
| 158 | -own measurement puts `vf.gather` at 20–35x an aligned load at real dependency | ||
| 159 | -depth, so that claim is deliberately **not** ported.) | ||
| 160 | - | ||
| 161 | -**Named re-probe** (one board session, control build included): four builds of | ||
| 162 | -one fp32 `vf` accumulation loop over a fixed UB tile, differing only in body — | ||
| 163 | -(a) 1 load + 1 ALU, (b) 1 load + 5 ALU, (c) 1 load + 7 ALU, (d) 2 loads + | ||
| 164 | -6 ALU. Solve the two coefficients from (a)–(c); (d) tests whether the second | ||
| 165 | -load issue is what costs. Until it runs, use the model only to rank | ||
| 166 | -candidates, never to reject one. | ||
| 167 | - | ||
| 168 | ## <a id="reviewable-examples"></a>Reviewable examples | 103 | ## <a id="reviewable-examples"></a>Reviewable examples |
| 169 | 104 | ||
| 170 | - Tile-operation softmax: | 105 | - Tile-operation softmax: |
| 171 | - [`../../../pypto-pro-op-kb/examples/samples/softmax/softmax_impl.py`](../../../pypto-pro-op-kb/examples/samples/softmax/softmax_impl.py) | 106 | + [`pypto-pro-op-kb/examples/samples/softmax/softmax_impl.py`](../../../pypto-pro-op-kb/examples/samples/softmax/softmax_impl.py) |
| 172 | - Vector-function softmax: | 107 | - Vector-function softmax: |
| 173 | - [`../../../pypto-pro-op-kb/examples/samples/vf_vs_tileop/vf_softmax_impl.py`](../../../pypto-pro-op-kb/examples/samples/vf_vs_tileop/vf_softmax_impl.py) | 108 | + [`pypto-pro-op-kb/examples/samples/vf_vs_tileop/vf_softmax_impl.py`](../../../pypto-pro-op-kb/examples/samples/vf_vs_tileop/vf_softmax_impl.py) |
| 174 | - Other validated vector-function compositions: | 109 | - Other validated vector-function compositions: |
| 175 | - [`../../../pypto-pro-op-kb/examples/kernel-index.md`](../../../pypto-pro-op-kb/examples/kernel-index.md) | 110 | + [`pypto-pro-op-kb/examples/kernel-index.md`](../../../pypto-pro-op-kb/examples/kernel-index.md) |
| 176 | 111 | ||
| 177 | These examples establish API usage only for their recorded environment. They | 112 | These examples establish API usage only for their recorded environment. They |
| 178 | are not proof that the same implementation level is fastest for another | 113 | are not proof that the same implementation level is fastest for another |
| @@ -0,0 +1,69 @@ | |||
| 1 | +# A5 CV matmul buffer skeleton. Fill every {{...}} from DESIGN.md and verify | ||
| 2 | +# against the target SDK's official matmul/Acc-to-Vector samples. | ||
| 3 | + | ||
| 4 | +@pl.jit(auto_mutex=True, arch="a5", tiling_key={{TILING_KEY}}) | ||
| 5 | +def {{KERNEL}}({{PARAMETERS}}): | ||
| 6 | + direct_group = pl.make_tile_group( | ||
| 7 | + type=pl.TileType( | ||
| 8 | + shape=[{{VEC_ROWS}}, {{VEC_COLS}}], | ||
| 9 | + dtype=pl.DT_INT32, | ||
| 10 | + target_memory=pl.MemorySpace.Vec, | ||
| 11 | + valid_shape=[-1, -1], | ||
| 12 | + compact=1, | ||
| 13 | + ), | ||
| 14 | + addrs={{DIRECT_ADDR}}, | ||
| 15 | + mutex_ids=[{{DIRECT_MUTEX}}], | ||
| 16 | + ) | ||
| 17 | + | ||
| 18 | + with pl.section_cube(): | ||
| 19 | + a_l1_group = pl.make_tile_group( | ||
| 20 | + type={{A_L1_TILE_TYPE}}, addrs={{A_L1_ADDR}}, | ||
| 21 | + mutex_ids=[{{A_L1_MUTEX_0}}, {{A_L1_MUTEX_1}}, | ||
| 22 | + {{A_L1_MUTEX_2}}, {{A_L1_MUTEX_3}}], | ||
| 23 | + ) | ||
| 24 | + b_l1_group = pl.make_tile_group( | ||
| 25 | + type={{B_L1_TILE_TYPE}}, addrs={{B_L1_ADDR}}, | ||
| 26 | + mutex_ids=[{{B_L1_MUTEX_0}}, {{B_L1_MUTEX_1}}, | ||
| 27 | + {{B_L1_MUTEX_2}}, {{B_L1_MUTEX_3}}], | ||
| 28 | + ) | ||
| 29 | + a_l0_group = pl.make_tile_group( | ||
| 30 | + type={{A_L0_TILE_TYPE}}, addrs={{A_L0_ADDR}}, | ||
| 31 | + mutex_ids=[{{A_L0_MUTEX_0}}, {{A_L0_MUTEX_1}}], | ||
| 32 | + ) | ||
| 33 | + b_l0_group = pl.make_tile_group( | ||
| 34 | + type={{B_L0_TILE_TYPE}}, addrs={{B_L0_ADDR}}, | ||
| 35 | + mutex_ids=[{{B_L0_MUTEX_0}}, {{B_L0_MUTEX_1}}], | ||
| 36 | + ) | ||
| 37 | + acc_group = pl.make_tile_group( | ||
| 38 | + type={{ACC_TILE_TYPE}}, addrs={{ACC_ADDR}}, | ||
| 39 | + mutex_ids=[{{ACC_MUTEX}}], | ||
| 40 | + ) | ||
| 41 | + | ||
| 42 | + for {{TASK}} in pl.range({{CORE_ID}}, {{TOTAL_TILES}}, {{CORE_COUNT}}): | ||
| 43 | + acc = acc_group.current() | ||
| 44 | + pl.set_validshape(acc, [{{PHYSICAL_TM}}, {{SELECTED_TILE_N}}]) | ||
| 45 | + for {{K1_INDEX}} in pl.range(0, {{K1_TILES}}): | ||
| 46 | + a_l1 = a_l1_group.next() | ||
| 47 | + b_l1 = b_l1_group.next() | ||
| 48 | + {{LOAD_L1_WITH_REAL_TAILS}} | ||
| 49 | + for {{K0_INDEX}} in pl.range(0, {{INNER_K0_TILES}}): | ||
| 50 | + a_l0 = a_l0_group.next() | ||
| 51 | + b_l0 = b_l0_group.next() | ||
| 52 | + {{MOVE_L1_TO_L0_WITH_REAL_TAILS}} | ||
| 53 | + {{PHASE_FREE_MATMUL_OR_MATMUL_ACC}} | ||
| 54 | + | ||
| 55 | + {{WAIT_BOTH_VECTOR_FREE_CREDITS}} | ||
| 56 | + {{M_TO_FIX_COMPATIBILITY_DEPENDENCY}} | ||
| 57 | + direct = direct_group.current() | ||
| 58 | + pl.move(direct, acc, acc_to_vec_mode={{PROVEN_SPLIT_MODE}}) | ||
| 59 | + {{SET_BOTH_VECTOR_READY_CREDITS}} | ||
| 60 | + | ||
| 61 | + {{DRAIN_BOTH_VECTOR_FREE_CREDITS}} | ||
| 62 | + | ||
| 63 | + with pl.section_vector(): | ||
| 64 | + {{PRIME_FREE_CREDIT}} | ||
| 65 | + for {{TASK}} in pl.range({{VECTOR_CORE_ID}}, {{TOTAL_TILES}}, {{CORE_COUNT}}): | ||
| 66 | + {{WAIT_READY_CREDIT}} | ||
| 67 | + direct = direct_group.current() | ||
| 68 | + {{VF_EPILOGUE_AND_VALID_STORE}} | ||
| 69 | + {{RETURN_MTE3_FREE_CREDIT_AFTER_CONDITIONAL_OUTPUT_STORE}} | ||
| @@ -0,0 +1,81 @@ | |||
| 1 | +# PyPTO-Pro FP32-chain precision fragments | ||
| 2 | +# | ||
| 3 | +# Use only after replaying the candidate dataflow against the configured | ||
| 4 | +# comparator proves that stagewise BF16 storage fails. These are composable | ||
| 5 | +# fragments, not a standalone kernel. Shapes, addresses, mutex ids, phases, | ||
| 6 | +# event ids, and API signatures still come from DESIGN.md and the installed SDK. | ||
| 7 | +# | ||
| 8 | +# Source: the fp32-precision entries of | ||
| 9 | +# ../../../pypto-pro-op-kb/references/pypto-pro-framework-findings.md. Cite the | ||
| 10 | +# entry by title rather than by number -- that page is renumbered as entries are | ||
| 11 | +# added, so a number recorded here goes stale silently. | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +# A. Deep-K projection: partition K blocks into four independent FP32 L0C | ||
| 15 | +# accumulators, then store all four FP32 partials. The four bodies must be | ||
| 16 | +# written explicitly so every accumulator has a statically named first/last | ||
| 17 | +# phase; require n_k_blocks % 4 == 0. This first body is the copy pattern for | ||
| 18 | +# acc1/acc2/acc3 with k_block offsets +1/+2/+3. | ||
| 19 | +for q in pl.range(0, n_k_blocks // 4): | ||
| 20 | + k_block = q * 4 | ||
| 21 | + # Load/move lhs0 and rhs0 for k_block into their selected groups. | ||
| 22 | + if q == 0: | ||
| 23 | + pl.matmul(acc0, lhs0, rhs0, phase=pl.AccPhase.Partial) | ||
| 24 | + elif q == n_k_blocks // 4 - 1: | ||
| 25 | + pl.matmul_acc(acc0, acc0, lhs0, rhs0, phase=pl.AccPhase.Final) | ||
| 26 | + else: | ||
| 27 | + pl.matmul_acc(acc0, acc0, lhs0, rhs0, phase=pl.AccPhase.Partial) | ||
| 28 | + # Repeat explicitly for acc1/acc2/acc3. Do not use acc[part] or a runtime | ||
| 29 | + # part loop: PyPTO-Pro tile objects are compile-time handles, not a list | ||
| 30 | + # that can be dynamically indexed by a pl.range induction variable. | ||
| 31 | +# Recombine downstream as (p0 + p1) + (p2 + p3), not left-to-right. | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +# B. Encode a computed FP32 Cube operand as three BF16 residual terms. The | ||
| 35 | +# intermediate widen/subtract stays FP32. CAST_ROUND here is the validated | ||
| 36 | +# residual encoding mode; do not replace it with the final-output mode. | ||
| 37 | +pl.cast(term1_bf16, source_fp32, mode=pl.RoundMode.CAST_ROUND) | ||
| 38 | +pl.cast(term1_fp32, term1_bf16, mode=pl.RoundMode.CAST_NONE) | ||
| 39 | +subtract_vf(source_fp32, term1_fp32, residual_fp32) | ||
| 40 | +pl.cast(term2_bf16, residual_fp32, mode=pl.RoundMode.CAST_ROUND) | ||
| 41 | +pl.cast(term2_fp32, term2_bf16, mode=pl.RoundMode.CAST_NONE) | ||
| 42 | +subtract_vf(residual_fp32, term2_fp32, residual2_fp32) | ||
| 43 | +pl.cast(term3_bf16, residual2_fp32, mode=pl.RoundMode.CAST_ROUND) | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +# C. If one K128 three-term contraction still fails only at final BF16 | ||
| 47 | +# boundaries, keep the physical K128 Mat/Left/Right types but contract two | ||
| 48 | +# compact K64 windows into distinct FP32 accumulators. Repeat the three-term | ||
| 49 | +# chain for k_offset 0 and 64; never alias the two live L0C values. | ||
| 50 | +pl.set_validshape(mat_lhs, [valid_m, 64]) | ||
| 51 | +pl.set_validshape(mat_rhs, [64, valid_n]) | ||
| 52 | +pl.set_validshape(lhs_k0, [valid_m, 64]) | ||
| 53 | +pl.set_validshape(rhs_k0, [64, valid_n]) | ||
| 54 | +pl.move(lhs_k0, mat_lhs, offset=[0, 0]) | ||
| 55 | +pl.move(rhs_k0, mat_rhs, offset=[0, 0]) | ||
| 56 | +pl.matmul(acc_k0, lhs_k0, rhs_k0, phase=pl.AccPhase.Partial) | ||
| 57 | +# Move K0 term2, then term3 through lhs_k0 and close with Partial, Final. | ||
| 58 | +# Repeat explicitly for acc_k1/lhs_k1/rhs_k1 using offsets [0,64]/[64,0]. | ||
| 59 | +# Store acc_k0 and acc_k1 to distinct FP32 GM workspaces with STPhase.Final. | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +# D. Add FP32 K partials in VF and perform the only protocol conversion with | ||
| 63 | +# RNE. On A5 CAST_ROUND is tie-away; PyTorch BF16 output conversion is RNE. | ||
| 64 | +add_fp32_vf(k0_fp32, k1_fp32, total_fp32, valid_rows, valid_cols) | ||
| 65 | +pl.cast(output_bf16_tile, total_fp32, mode=pl.RoundMode.CAST_RINT) | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +# E. Materialize a BF16-high / FP32-low decomposition with Tile casts when a | ||
| 69 | +# cancellation-sensitive consumer needs a hard rounding boundary. Do not use | ||
| 70 | +# vf.astype(... CAST_RINT) for FP32->BF16: the CANN 9.1 backend lowers it to an | ||
| 71 | +# invalid ROUND_N vcvt mode. Repeat this pair for every partial, then combine | ||
| 72 | +# highs and lows with explicit pairwise trees in a basic VF helper. | ||
| 73 | +pl.cast(high_bf16, partial_fp32, mode=pl.RoundMode.CAST_RINT) | ||
| 74 | +pl.cast(high_fp32, high_bf16, mode=pl.RoundMode.CAST_NONE) | ||
| 75 | +subtract_vf(partial_fp32, high_fp32, low_fp32) | ||
| 76 | +# high = (high0 + high1) + (high2 + high3) | ||
| 77 | +# low = (low0 + low1) + (low2 + low3) | ||
| 78 | +# total = high + low | ||
| 79 | +# This removes only the local reduction error. It cannot reconstruct rounding | ||
| 80 | +# already accumulated inside the upstream Cube partials, so validate the | ||
| 81 | +# cancellation cases on every target CANN/hardware combination. | ||
| @@ -165,12 +165,6 @@ Markdown 报告包含: | |||
| 165 | | [`references/msprof-guide.md`](references/msprof-guide.md) | `msprof`:构建 / 采集 / 归档 / **主 Bound 判定** / 瓶颈 | 选用 `msprof` 时 | | 165 | | [`references/msprof-guide.md`](references/msprof-guide.md) | `msprof`:构建 / 采集 / 归档 / **主 Bound 判定** / 瓶颈 | 选用 `msprof` 时 | |
| 166 | | [`references/csv_fields_reference.md`](references/csv_fields_reference.md) | CSV 字段定义与阈值 | 理解指标含义时 | | 166 | | [`references/csv_fields_reference.md`](references/csv_fields_reference.md) | CSV 字段定义与阈值 | 理解指标含义时 | |
| 167 | 167 | ||
| 168 | -> **性能分析顺序**:① 探测目标平台;② 若目标为 A5,按 | ||
| 169 | -> [`references/a5-roofline-and-levers.md`](references/a5-roofline-and-levers.md) | ||
| 170 | -> 建立带来源的假设;③ 用 msprof 实测。非 A5 或未知平台跳过 A5 模型。 | ||
| 171 | - | ||
| 172 | ---- | ||
| 173 | - | ||
| 174 | ## 适用场景总览 | 168 | ## 适用场景总览 |
| 175 | 169 | ||
| 176 | | 场景 | 推荐命令 | 说明 | | 170 | | 场景 | 推荐命令 | 说明 | |
| @@ -421,8 +415,8 @@ stride 恰为 64 元素是最坏情况:**~5–7×**(51.0 vs 7.0 µs)。 | |||
| 421 | 415 | ||
| 422 | ## 优化循环(正式 baseline 后,先完整读 [实战指南](references/optimization-playbook.md)) | 416 | ## 优化循环(正式 baseline 后,先完整读 [实战指南](references/optimization-playbook.md)) |
| 423 | 417 | ||
| 424 | -1. **候选与排序**:每轮只提一个主要假设(证据、拟改变量、预期指标、精度/容量风险、回退点),按"对验收指标的预计改善 ÷ 实现与验证成本"排序。 | 418 | +1. **候选与排序**:提假设前先按瓶颈类型查[按需阅读路由](#按需阅读路由)定位对应参考/模板(目标为 A5 → A5 Roofline 与杠杆;怀疑 ratio 被误读 → msprof op 补充指南 §4.2a–f;单核负载不均或小 shape → 多阶段任务展平),以其判据形成"证据+拟改变量+预期指标";每轮只提一个主要假设(含精度/容量风险与回退点),按"对验收指标的预计改善 ÷ 实现与验证成本"排序。 |
| 425 | -2. **瓶颈定性**:先用必要计算量、必要搬运字节、平台规格与受控 A/B 判断主要受计算、搬运或二者平衡限制;缺可复算输入时保留为候选,不伪造终态。 | 419 | +2. **瓶颈定性**:先用必要计算量、必要搬运字节、平台规格与受控 A/B 判断主要受计算、搬运或二者平衡限制;ratio 类指标按 msprof op 补充指南 §4.2a–f 的判据读,不把"流水忙"直接当作到顶;缺可复算输入时保留为候选,不伪造终态。 |
| 426 | 3. **实施与验证**:改源码 → 全量正确性(失败即归档回退)→ quick 初筛;只有稳定收益或有明确解锁价值的候选才升级正式采集。 | 420 | 3. **实施与验证**:改源码 → 全量正确性(失败即归档回退)→ quick 初筛;只有稳定收益或有明确解锁价值的候选才升级正式采集。 |
| 427 | 4. **机制核对**:用绝对时间、必要工作量、冲突/等待或 lowering 证据核对预期机制;变快但原因不符必须重新诊断,不得当作原假设的证明。 | 421 | 4. **机制核对**:用绝对时间、必要工作量、冲突/等待或 lowering 证据核对预期机制;变快但原因不符必须重新诊断,不得当作原假设的证明。 |
| 428 | 5. **晋级与组合**:候选通过全部 P0 正确性后按 `average_speedup` 判定——超过当前最佳且高于测量噪声、无新 Scalar/等待/串行化/容量/尾块问题才替换"最快且正确";逐场景回退单列且不得破坏最终目标;中性但有解锁价值的只进组合队列。随后尝试兼容/互补组合,沿当前最佳逐项扩展;瓶颈或数据流变化后重开受影响旧结论。 | 422 | 5. **晋级与组合**:候选通过全部 P0 正确性后按 `average_speedup` 判定——超过当前最佳且高于测量噪声、无新 Scalar/等待/串行化/容量/尾块问题才替换"最快且正确";逐场景回退单列且不得破坏最终目标;中性但有解锁价值的只进组合队列。随后尝试兼容/互补组合,沿当前最佳逐项扩展;瓶颈或数据流变化后重开受影响旧结论。 |
| @@ -463,5 +457,14 @@ stride 恰为 64 元素是最坏情况:**~5–7×**(51.0 vs 7.0 µs)。 | |||
| 463 | | [CSV 字段参考](references/csv_fields_reference.md) | profiler 字段、单位或阈值含义不清时;实际 CSV schema 优先 | | 457 | | [CSV 字段参考](references/csv_fields_reference.md) | profiler 字段、单位或阈值含义不清时;实际 CSV schema 优先 | |
| 464 | | [msprof op 补充指南](references/msprof-op-guide.md) | 环境明确支持 Python runner,且正式 compare 之外还需补充诊断时 | | 458 | | [msprof op 补充指南](references/msprof-op-guide.md) | 环境明确支持 Python runner,且正式 compare 之外还需补充诊断时 | |
| 465 | | [知识库路由](../pypto-pro-op-kb/ROUTER.md) | 需要历史经验、wrapper 边界、调查纪律或专题 pattern 时;历史数字只作待验证候选 | | 459 | | [知识库路由](../pypto-pro-op-kb/ROUTER.md) | 需要历史经验、wrapper 边界、调查纪律或专题 pattern 时;历史数字只作待验证候选 | |
| 460 | +| [多阶段任务展平](references/stage-task-flatten.md) | 单核负载不均、外层 tile 循环只点亮少数核时 | | ||
| 461 | +| [分阶段 matmul A/B 证据协议](references/staged-matmul-ab-protocol.md) | 要把一次 A/B 结果当作证据前 | | ||
| 462 | +| [模板:cube-output-wave-reuse](templates/cube-output-wave-reuse.py.tmpl) | 一个 Left tile 可复用到一小组输出时 | | ||
| 463 | +| [模板:cube-shared-left-output-pair](templates/cube-shared-left-output-pair.py.tmpl) | 成对输出可共享 Left/Right tile 时 | | ||
| 464 | +| [模板:typed-tilegroup-stage-reuse](templates/typed-tilegroup-stage-reuse.py.tmpl) | 需跨阶段复用同一 TileGroup 时 | | ||
| 465 | +| [模板:stage-task-flatten](templates/stage-task-flatten.py.tmpl) | 按上一行的展平结论落代码时 | | ||
| 466 | +| [模板:dual-aiv-mailbox](templates/dual-aiv-mailbox.py.tmpl) | 需要双 AIV subblock 交接时 | | ||
| 467 | +| [模板:tiling-key-resource-specialization](templates/tiling-key-resource-specialization.py.tmpl) | 需按编译期 key 特化资源、且分支不得进 IR 时 | | ||
| 468 | +| [模板:vf-broadcast-dot-panel](templates/vf-broadcast-dot-panel.py.tmpl) | 需要 VF 广播点积面板时 | | ||
| 466 | 469 | ||
| 467 | 平台探测失败或平台不是 A5 时,跳过 A5 常量,继续用当前平台资料与实测;任何参考资料中的案例收益、阈值和代码都不能直接写成本算子的已验证结论。 | 470 | 平台探测失败或平台不是 A5 时,跳过 A5 常量,继续用当前平台资料与实测;任何参考资料中的案例收益、阈值和代码都不能直接写成本算子的已验证结论。 |
| @@ -1,28 +1,10 @@ | |||
| 1 | # A5 roofline workflow | 1 | # A5 roofline workflow |
| 2 | 2 | ||
| 3 | -## Contents | ||
| 4 | - | ||
| 5 | -- [Evidence gate](#evidence-gate) | ||
| 6 | -- [Primary source paths](#primary-source-paths) | ||
| 7 | -- [Derive, do not transcribe](#derive-dont-transcribe) | ||
| 8 | -- [The scoring anchor is not the hardware roofline](#scoring-anchor) | ||
| 9 | -- [Calibration measurements](#calibration-measurements) | ||
| 10 | -- [The vector-only ceiling](#vector-only-ceiling) | ||
| 11 | -- [Symbolic roofline](#symbolic-roofline) | ||
| 12 | -- [Measurement loop](#measurement-loop) | ||
| 13 | -- [A5 原语代价表(每 64 lane 寄存器)](#a5-primitive-costs) | ||
| 14 | -- [Measured levers, ranked by what they actually returned](#measured-levers) | ||
| 15 | -- [Scope of retained examples](#example-scope) | ||
| 16 | -- [When the local levers plateau: structural levers](#structural-levers) | ||
| 17 | -- [When to stop](#when-to-stop) | ||
| 18 | -- [Provenance of the numbers on this page](#provenance) | ||
| 19 | - | ||
| 20 | - | ||
| 21 | Load this reference only after the runtime or build configuration confirms an | 3 | Load this reference only after the runtime or build configuration confirms an |
| 22 | A5 target (`NpuArch=3510` / `dav-c310`). It must not supply constants or tuning | 4 | A5 target (`NpuArch=3510` / `dav-c310`). It must not supply constants or tuning |
| 23 | rules to an unknown or non-A5 target. | 5 | rules to an unknown or non-A5 target. |
| 24 | 6 | ||
| 25 | -## <a id="evidence-gate"></a>Evidence gate | 7 | +## Evidence gate |
| 26 | 8 | ||
| 27 | Before calculating a roofline: | 9 | Before calculating a roofline: |
| 28 | 10 | ||
| @@ -34,7 +16,7 @@ Before calculating a roofline: | |||
| 34 | If any input is unavailable, leave the numerical estimate unverified and use | 16 | If any input is unavailable, leave the numerical estimate unverified and use |
| 35 | the profiler result as the only tuning basis. | 17 | the profiler result as the only tuning basis. |
| 36 | 18 | ||
| 37 | -## <a id="primary-source-paths"></a>Primary source paths | 19 | +## Primary source paths |
| 38 | 20 | ||
| 39 | Resolve these under the installed, version-recorded PyPTO/CANN tree; do not copy | 21 | Resolve these under the installed, version-recorded PyPTO/CANN tree; do not copy |
| 40 | values from another checkout: | 22 | values from another checkout: |
| @@ -50,17 +32,21 @@ The files are primary evidence for the matching installed version only. If a | |||
| 50 | path or key differs, search the installed source and record the replacement; | 32 | path or key differs, search the installed source and record the replacement; |
| 51 | do not infer a value. | 33 | do not infer a value. |
| 52 | 34 | ||
| 53 | -## <a id="derive-dont-transcribe"></a>Derive, do not transcribe | 35 | +## Derive, do not transcribe |
| 54 | 36 | ||
| 55 | -`tools/roofline_a5.py` parses whichever ini matches the detected SKU and derives | 37 | +Read the cube, HBM, UB, L1 and L0 figures out of the platform ini that ships |
| 56 | -the cube, HBM, UB, L1 and L0 figures from it, so no constant needs to live in | 38 | +with the runtime you are measuring, so no constant lives in this page and |
| 57 | -this page and detach from the installed version: | 39 | +detaches from the installed version: |
| 58 | 40 | ||
| 59 | ``` | 41 | ``` |
| 60 | -python tools/roofline_a5.py --op <op> --sku <ini stem> | 42 | +<pypto root>/framework/src/platform/parser/simulation_platform/platform_config/<SKU>.ini |
| 61 | -python tools/roofline_a5.py --selfcheck | ||
| 62 | ``` | 43 | ``` |
| 63 | 44 | ||
| 45 | +Resolve `<SKU>` from the detected device rather than assuming it, and record | ||
| 46 | +which ini you read alongside the number. The derivation is deliberately stated | ||
| 47 | +as arithmetic over the ini rather than delegated to a tool: it is the part that | ||
| 48 | +has to stay reproducible from this repository alone. | ||
| 49 | + | ||
| 64 | The derivations it applies, so they can be checked rather than trusted: | 50 | The derivations it applies, so they can be checked rather than trusted: |
| 65 | 51 | ||
| 66 | ``` | 52 | ``` |
| @@ -77,78 +63,59 @@ wrong one is wrong by that factor. `950DT` and `950PR` at the same core count ar | |||
| 77 | not interchangeable, and `platform.py` reports only `DAV_3510` plus core counts, | 63 | not interchangeable, and `platform.py` reports only `DAV_3510` plus core counts, |
| 78 | which narrows to two SKUs rather than one. Record which ini was used. | 64 | which narrows to two SKUs rather than one. Record which ini was used. |
| 79 | 65 | ||
| 80 | -## <a id="scoring-anchor"></a>The scoring anchor is not the hardware roofline | 66 | +## Calibration measurements |
| 81 | - | ||
| 82 | -`cann-bench` scores each case with a saturating ratio, not a speedup | ||
| 83 | -(`kernel_eval/benches/cann_scoring.py`): | ||
| 84 | - | ||
| 85 | -``` | ||
| 86 | -score_i = (T_baseline - T_HW) / ((T_cand - T_HW) + (T_baseline - T_HW)) | ||
| 87 | -``` | ||
| 88 | - | ||
| 89 | -Both anchors are per-`(op, case_id)` in `tasks/metadata/<hardware>.json`, and | ||
| 90 | -`<hardware>` comes from `resolve_hardware(torch.npu.get_device_name(...))` — | ||
| 91 | -where **only names beginning `Ascend950PR` map to `950pr`**. A box reporting | ||
| 92 | -anything else finds no metadata, gets no anchors, and earns no performance | ||
| 93 | -points at all. Check that before interpreting a zero. | ||
| 94 | - | ||
| 95 | -Two consequences: | ||
| 96 | - | ||
| 97 | -- **The anchors travel with the task, not with the box.** Running on hardware | ||
| 98 | - with more cores or bandwidth than the anchor assumed makes `T_HW` easier to | ||
| 99 | - approach; less makes it harder. Neither changes the score, only what it means. | ||
| 100 | -- **`T_HW` is theoretical peak and generally unreachable.** A score below 1.0 is | ||
| 101 | - the normal case; calibrate against measurement, not against the anchor. | ||
| 102 | - | ||
| 103 | -## <a id="calibration-measurements"></a>Calibration measurements | ||
| 104 | 67 | ||
| 105 | Measured ratios, not platform constants, recorded with provenance because the | 68 | Measured ratios, not platform constants, recorded with provenance because the |
| 106 | evidence gate above requires it. | 69 | evidence gate above requires it. |
| 107 | 70 | ||
| 108 | -**Model versus published anchor** (`roofline_a5.py --selfcheck` against | 71 | +**A byte-count model is a floor, not a prediction.** It prices the traffic and |
| 109 | -`tasks/metadata/950pr.json`, SKU `950PR_957x`): | 72 | +nothing else, so it will sit below any figure that also prices vector work in |
| 73 | +the epilogue, weight streaming rather than peak bandwidth, or a cube bound that | ||
| 74 | +binds before memory does. Establish *which* resource binds before optimising | ||
| 75 | +against the model, and recompute per case: the same kernel changes which | ||
| 76 | +resource binds at different shapes, and the spread within one operator can be | ||
| 77 | +as wide as the spread between operators. | ||
| 110 | 78 | ||
| 111 | -| operator | model / `t_hw_us` | reading | | 79 | +**Price causal work explicitly, or the model is wrong by up to 2x.** A model |
| 112 | -|---|---|---| | 80 | +that counts the full attention rectangle overstates a causally masked kernel. |
| 113 | -| `add_rms_norm_dynamic_quant` | 0.97 (0.96–1.00) | anchor is the pure memory roofline | | 81 | +For mask `j <= i + (S_kv - S)` the kept fraction is |
| 114 | -| `mla` | 1.06 (1.03–1.14) | anchor is memory or cube, whichever binds | | ||
| 115 | -| `dequant_swiglu_quant` | 0.69 (0.62–1.00) | anchor ~1.45x more conservative than bytes alone: it prices vector work (the `exp` in SiLU) | | ||
| 116 | -| `mla_prolog` | 0.62 (0.55–1.14) | anchor ~1.6x more conservative: weight streaming, not peak bandwidth | | ||
| 117 | - | ||
| 118 | -Where the anchor is *more* conservative than the byte count, the case has more | ||
| 119 | -attainable headroom than a naive memory roofline suggests. | ||
| 120 | - | ||
| 121 | -**The anchors discount causal work.** Adding a bottom-right-aligned causal | ||
| 122 | -fraction to the `mla` model moved it from 1.22 (worst case 2.28) to 1.06 (worst | ||
| 123 | -1.14). The kept fraction for mask `j <= i + (S_kv - S)` is | ||
| 124 | `(S*(S_kv-S+1) + S*(S-1)/2) / (S*S_kv)` — about 0.5 when `S == S_kv`, about 1.0 | 82 | `(S*(S_kv-S+1) + S*(S-1)/2) / (S*S_kv)` — about 0.5 when `S == S_kv`, about 1.0 |
| 125 | -when `S << S_kv`. Skipping masked work is therefore required to reach the anchor | 83 | +when `S << S_kv`. So skipping masked work is required on square cases and buys |
| 126 | -on square cases and buys nothing on short-query ones. | 84 | +nothing on short-query ones, and a model that ignores the mask can be off by |
| 85 | +roughly the reciprocal of that fraction. | ||
| 127 | 86 | ||
| 128 | -**Achievable fraction of peak.** Independent A5 measurements: an aligned-plane | 87 | +**Achievable fraction of peak.** Measured on A5: an aligned-plane MTE2 read |
| 129 | -MTE2 read reaches ~1.7 TB/s, and a tuned vector-only Ascend-C | 88 | +reaches ~1.7 TB/s, and a tuned vector-only kernel on a memory-bound normalise + |
| 130 | -`AddRmsNormDynamicQuant` reaches 1.17 TB/s (8192x8192 fp16 in 401 us), which its | 89 | +quantise shape (8192x8192 fp16, 401 us) reaches 1.17 TB/s and is described by |
| 131 | -authors describe as sitting at the memory roof. CANN's own kernel for that case | 90 | +its authors as sitting at the memory roof, while an untuned kernel for the same |
| 132 | -manages 0.69 TB/s. The corresponding `t_hw_us` implies 2.80 TB/s. | 91 | +shape manages 0.69 TB/s. |
| 133 | 92 | ||
| 134 | -## <a id="vector-only-ceiling"></a>The vector-only ceiling | 93 | +Two things to take from that, both independent of who wrote either kernel: |
| 94 | +**the roof a real kernel reaches is well below theoretical peak**, so calibrate | ||
| 95 | +against a measured ceiling rather than the peak; and **the tuned/untuned gap on | ||
| 96 | +one shape is the size of the prize**, which is the number worth estimating | ||
| 97 | +before committing to a tuning round. | ||
| 98 | + | ||
| 99 | +## The vector-only ceiling | ||
| 135 | 100 | ||
| 136 | If the per-core `ddr_rate` split is physical, a kernel using only | 101 | If the per-core `ddr_rate` split is physical, a kernel using only |
| 137 | `section_vector()` can reach at most the vector-core share — roughly half the | 102 | `section_vector()` can reach at most the vector-core share — roughly half the |
| 138 | -aggregate on `950PR`. On `add_rms_norm_dynamic_quant` case 1 that caps the score | 103 | +aggregate on `950PR`. On a memory-bound case that needs ~1.59 TB/s to hit a |
| 139 | -near 0.77 however clean the kernel is, because score 0.8 needs 1.59 TB/s against | 104 | +given target, a ~1.48 TB/s vector-only theoretical ceiling puts the target out |
| 140 | -a ~1.48 TB/s vector-only theoretical ceiling. | 105 | +of reach however clean the kernel is. Compute both numbers before committing to |
| 106 | +a vector-only design: if the requirement exceeds the vector share, the deficit | ||
| 107 | +is structural and no kernel-side work reaches it. | ||
| 141 | 108 | ||
| 142 | Treat this as a hypothesis, not a constant. The same ini block lists | 109 | Treat this as a hypothesis, not a constant. The same ini block lists |
| 143 | `ddr_rate=31` beside `ub_to_ddr_rate=128` for AICore and `16` beside `40` for | 110 | `ddr_rate=31` beside `ub_to_ddr_rate=128` for AICore and `16` beside `40` for |
| 144 | VectorCore; the units are not self-consistent, and the reading above is simply | 111 | VectorCore; the units are not self-consistent, and the reading above is simply |
| 145 | -the one that reproduces the published anchors. | 112 | +the one consistent with measured aggregate bandwidth. |
| 146 | 113 | ||
| 147 | **Settle it by measurement:** a pure-DMA copy of identical bytes, vector-only | 114 | **Settle it by measurement:** a pure-DMA copy of identical bytes, vector-only |
| 148 | versus cube+vector, nothing else varied, with a control variant in the same run. | 115 | versus cube+vector, nothing else varied, with a control variant in the same run. |
| 149 | Design around the answer only afterwards. | 116 | Design around the answer only afterwards. |
| 150 | 117 | ||
| 151 | -## <a id="symbolic-roofline"></a>Symbolic roofline | 118 | +## Symbolic roofline |
| 152 | 119 | ||
| 153 | Use version- and SKU-specific values read from the source above: | 120 | Use version- and SKU-specific values read from the source above: |
| 154 | 121 | ||
| @@ -163,7 +130,7 @@ This ranks hypotheses; it does not establish actual latency. Reload counts, | |||
| 163 | launch overhead, dependencies, occupancy, and compiler scheduling can change | 130 | launch overhead, dependencies, occupancy, and compiler scheduling can change |
| 164 | the result. | 131 | the result. |
| 165 | 132 | ||
| 166 | -## <a id="measurement-loop"></a>Measurement loop | 133 | +## Measurement loop |
| 167 | 134 | ||
| 168 | 1. Freeze a passing correctness test. | 135 | 1. Freeze a passing correctness test. |
| 169 | 2. Capture a baseline with the same input, launch geometry, warm-up, and | 136 | 2. Capture a baseline with the same input, launch geometry, warm-up, and |
| @@ -182,7 +149,7 @@ Use [msprof-guide.md](msprof-guide.md) or | |||
| 182 | [csv_fields_reference.md](csv_fields_reference.md) for the fields supported by | 149 | [csv_fields_reference.md](csv_fields_reference.md) for the fields supported by |
| 183 | the current parser. | 150 | the current parser. |
| 184 | 151 | ||
| 185 | -## <a id="a5-primitive-costs"></a>A5 原语代价表(每 64 lane 寄存器) | 152 | +## A5 原语代价表(每 64 lane 寄存器) |
| 186 | 153 | ||
| 187 | 这张表决定绝大多数 dataflow 决策,**设计阶段就要用**。它从 `pypto-pro-op-perf-tune/SKILL.md` | 154 | 这张表决定绝大多数 dataflow 决策,**设计阶段就要用**。它从 `pypto-pro-op-perf-tune/SKILL.md` |
| 188 | 移到本页,因为它是 target 相关的实测值,而核心 Skill 对任意目标都会加载。 | 155 | 移到本页,因为它是 target 相关的实测值,而核心 Skill 对任意目标都会加载。 |
| @@ -211,7 +178,7 @@ the current parser. | |||
| 211 | 即使两种写法 op 数完全相同,**UB 寻址也会占到 83%、算术只占 17%** | 178 | 即使两种写法 op 数完全相同,**UB 寻址也会占到 83%、算术只占 17%** |
| 212 | (证据:一个连续扫描算子,64 元素 13 op)。 | 179 | (证据:一个连续扫描算子,64 元素 13 op)。 |
| 213 | 180 | ||
| 214 | -## <a id="measured-levers"></a>Measured levers, ranked by what they actually returned | 181 | +## Measured levers, ranked by what they actually returned |
[P1] 删除了下游 skill 强制要求读取的 A5 原语代价表 问题:这个新标题替换位置删除了完整的 “A5 原语代价表”,但 perf-tune 和 develop skill 仍把该节作为设计前必读依据,并继续引用其中数值。 影响:工作流会导航到不存在的知识节点;保留下来的代价结论失去 target、测量时间和适用范围。 证据: 建议:恢复该节,或迁移到新的 canonical、target-gated 页面并一次性更新所有消费者、锚点和 provenance。 ![]() ![]() | |||
| 215 | 182 | ||
| 216 | From two attention-family operators taken from correct-but-slow to the | 183 | From two attention-family operators taken from correct-but-slow to the |
| 217 | bandwidth roof. Each was chosen from a per-kernel profile, never guessed, and | 184 | bandwidth roof. Each was chosen from a per-kernel profile, never guessed, and |
| @@ -270,11 +237,12 @@ what improved was L2 pressure rather than DRAM traffic. | |||
| 270 | 237 | ||
| 271 | **Know when to stop.** After these, the kernels moved 604 MB in 351 us | 238 | **Know when to stop.** After these, the kernels moved 604 MB in 351 us |
| 272 | (**1.72 TB/s**), 125 MB in 72 us (1.74 TB/s) and 234 MB in 139 us (1.68 TB/s), | 239 | (**1.72 TB/s**), 125 MB in 72 us (1.74 TB/s) and 234 MB in 139 us (1.68 TB/s), |
| 273 | -against a ~1.6 TB/s weight-anchored roof. At that point nothing further is | 240 | +against a ~1.6 TB/s roof for a weight-streaming access pattern. At that point |
| 241 | +nothing further is | ||
| 274 | available by making a kernel faster — only by making it move fewer bytes. Say so | 242 | available by making a kernel faster — only by making it move fewer bytes. Say so |
| 275 | and stop, rather than continuing to tune. | 243 | and stop, rather than continuing to tune. |
| 276 | 244 | ||
| 277 | -## <a id="example-scope"></a>Scope of retained examples | 245 | +## Scope of retained examples |
| 278 | 246 | ||
| 279 | The KB's | 247 | The KB's |
| 280 | [BF16 operand-reuse implementation](../../../pypto-pro-op-kb/examples/samples/bf16_matmul_operand_reuse/bf16_matmul_operand_reuse_impl.py) | 248 | [BF16 operand-reuse implementation](../../../pypto-pro-op-kb/examples/samples/bf16_matmul_operand_reuse/bf16_matmul_operand_reuse_impl.py) |
| @@ -282,7 +250,7 @@ demonstrates one reuse topology and embeds a correctness test. It does not prove | |||
| 282 | that an operator is cube-bound or that the topology is faster on another shape | 250 | that an operator is cube-bound or that the topology is faster on another shape |
| 283 | or target. Profile the current kernel. | 251 | or target. Profile the current kernel. |
| 284 | 252 | ||
| 285 | -## <a id="structural-levers"></a>When the local levers plateau: structural levers | 253 | +## When the local levers plateau: structural levers |
| 286 | 254 | ||
| 287 | Every lever above preserves the algorithm — it re-times, de-duplicates, or | 255 | Every lever above preserves the algorithm — it re-times, de-duplicates, or |
| 288 | re-lays-out work that already exists. When those plateau against a traffic or | 256 | re-lays-out work that already exists. When those plateau against a traffic or |
| @@ -323,7 +291,7 @@ numbers do not): | |||
| 323 | These are larger edits that usually move reduction or cast order: apply one at | 291 | These are larger edits that usually move reduction or cast order: apply one at |
| 324 | a time and re-verify correctness at the new boundary before measuring. | 292 | a time and re-verify correctness at the new boundary before measuring. |
| 325 | 293 | ||
| 326 | -## <a id="when-to-stop"></a>When to stop | 294 | +## When to stop |
| 327 | 295 | ||
| 328 | Stop at a wall proven with data: the moved bytes are irreducible — each read or | 296 | Stop at a wall proven with data: the moved bytes are irreducible — each read or |
| 329 | written once, each feeding the contract — **and** occupancy is at the device | 297 | written once, each feeding the contract — **and** occupancy is at the device |
| @@ -331,15 +299,98 @@ limit for the parallelism the algorithm exposes. Record the measurement that | |||
| 331 | proves it. "`MTE2` is at 98%" alone does not; "`MTE2` is at 98% and every byte it | 299 | proves it. "`MTE2` is at 98%" alone does not; "`MTE2` is at 98% and every byte it |
| 332 | moves is read exactly once" does. | 300 | moves is read exactly once" does. |
| 333 | 301 | ||
| 334 | -## <a id="provenance"></a>Provenance of the numbers on this page | 302 | +## Provenance of the numbers on this page |
| 335 | 303 | ||
| 336 | -The ratios in "Calibration measurements" are reproducible without hardware: | 304 | +The model in "Calibration measurements" is reproducible without hardware: |
| 337 | -`roofline_a5.py --selfcheck` recomputes them from the installed platform ini and | 305 | +recompute it from the installed platform ini. It is arithmetic over the platform |
| 338 | -`tasks/metadata/950pr.json`. They are model-versus-anchor comparisons, not | 306 | +constants, not profiler output, and should be recomputed rather than quoted from |
| 339 | -profiler output. | 307 | +here. |
| 340 | 308 | ||
| 341 | The achievable-bandwidth figures are cited measurements from other A5 work, kept | 309 | The achievable-bandwidth figures are cited measurements from other A5 work, kept |
| 342 | -because the anchor alone gives no sense of what fraction of it is reachable. They | 310 | +because a theoretical roof alone gives no sense of what fraction is reachable. They |
| 343 | are scenario-specific: do not treat 1.17 TB/s as a target for a different | 311 | are scenario-specific: do not treat 1.17 TB/s as a target for a different |
| 344 | operator or shape. Any *new* bandwidth or duration claim added here needs a | 312 | operator or shape. Any *new* bandwidth or duration claim added here needs a |
| 345 | version-tagged profiler artifact and the command that produced it. | 313 | version-tagged profiler artifact and the command that produced it. |
| 314 | + | ||
| 315 | +## The per-register mask is a first-class cost, and hoisting it can be the whole win | ||
| 316 | + | ||
| 317 | +Established with an ablation ladder -- a load/store-only floor rung, then each | ||
| 318 | +compute stage added back -- with ABAB pairing inside one lock window and control | ||
| 319 | +drift held under ~0.3%. Re-derive it the same way on any target before quoting | ||
| 320 | +the numbers below. | ||
| 321 | + | ||
| 322 | +**`pl.min` + `vf.update_mask` costs 10.3-13.6 ns per register group.** Against | ||
| 323 | +this page's own primitive table -- arithmetic ~0.3 ns, `load_align`/`store_align` | ||
| 324 | +under 1 ns -- that puts the *mask that guards the arithmetic* in `vf.gather`'s | ||
| 325 | +class (~20 ns), i.e. **30-45x the work it protects**. A loop that recomputes the | ||
| 326 | +predicate every register group is therefore paying for masking, not for | ||
| 327 | +computing, and no amount of buffering or blocking touches that cost. | ||
| 328 | + | ||
| 329 | +**Splitting the register loop** into a full-register path that takes the | ||
| 330 | +all-lanes predicate, plus a zero-or-one-trip tail that keeps the mask, measured | ||
| 331 | +on the floor rung: | ||
| 332 | + | ||
| 333 | +| 形态 | 观察 | | ||
| 334 | +|---|---| | ||
| 335 | +| 大而访存受限的 shape | 提升有限(约 1.1x):本就接近访存上限,掩码不是主要成本 | | ||
| 336 | +| 中等 shape | 约 2x | | ||
| 337 | +| 小而落在 L2 内的 shape | 约 3x:掩码开销占比最高,且不受访存上限压制 | | ||
| 338 | + | ||
| 339 | +The ratio flip is the mechanism self-proof: a vector-bound rung became a | ||
| 340 | +genuinely memory-bound one. The speedups differ because the 8192 case hits the | ||
| 341 | +DDR wall and stops while the smaller two are L2-resident -- **a fixed | ||
| 342 | +per-element saving shows up as wildly different ratios depending on which side | ||
| 343 | +of the 128 MiB L2 the working set sits.** | ||
| 344 | + | ||
| 345 | +**It is value-equivalent, so the ordinary correctness suite applies**: on a full | ||
| 346 | +register `vf.update_mask(64)` *is* the all-lanes predicate and | ||
| 347 | +`vf.select(v, ident, all)` is the identity, accumulation order is untouched, and | ||
| 348 | +the tail keeps both. Bit-exact, not within-tolerance -- which matters when an | ||
| 349 | +output is passing *at* its threshold. | ||
| 350 | + | ||
| 351 | +**Two caveats, both measured.** This page's mask-hoisting entry elsewhere | ||
| 352 | +reports only +5% and a 3-4% *loss* on 8/16-column tiles: narrow tiles amortise | ||
| 353 | +the hoist over 2-4 registers and can lose. Measure the short-axis cases | ||
| 354 | +separately rather than assuming, and dispatch per width if they disagree. And a | ||
| 355 | +zero-length tail is a live hazard: `vf.update_mask(0)` reaching a | ||
| 356 | +`vf.select`/`vf.reduce_*` inside a zero-trip tail body has produced device | ||
| 357 | +fault 507035; clamp the tail extent to at least 1 (harmless, since the loop is | ||
| 358 | +zero-trip exactly there). | ||
| 359 | + | ||
| 360 | +### Two corollaries about reading a floor rung | ||
| 361 | + | ||
| 362 | +- **A load/store-only rung is not automatically "the memory floor."** Check its | ||
| 363 | + own pipe row first: the rung above had `aiv_vec_ratio` 0.658 against | ||
| 364 | + `aiv_mte2_ratio` 0.337, so it was a *minimal-VF* floor, and every ratio taken | ||
| 365 | + against it was a ratio against vector work. Cross-DSL closure made the error | ||
| 366 | + visible: another DSL's **complete** kernel beat this do-nothing rung on the | ||
| 367 | + same shape, while the hoisted rung then beat that complete kernel. | ||
| 368 | +- **Stall headroom lives in the floor rung, not the full kernel.** Measured | ||
| 369 | + bubble (`1 - aiv_vec_time/aiv_time`) was 34.2% at the floor and **0.8%** at | ||
| 370 | + the full kernel on the same shape: the bubble is absorbed as stages are added. | ||
| 371 | + "The floor has 147 us of stall, so deeper buffering can win 147 us" does not | ||
| 372 | + follow -- deeper buffering only pays where `1 - aiv_vec_ratio` is large in the | ||
| 373 | + *shipping* kernel. | ||
| 374 | + | ||
| 375 | +## Cube cores cannot be borrowed as DMA engines on this DSL | ||
| 376 | + | ||
| 377 | +Two independent reasons, both measured or read off the installed source, on | ||
| 378 | +PyPTO-Pro 26.0: | ||
| 379 | + | ||
| 380 | +- **L1 cannot be written back to GM.** `pypto_pro/ir/op/block_ops.py:233` | ||
| 381 | + restricts `store`/`store_tile` sources to Vec (UB) or Acc (L0C), and `:465`'s | ||
| 382 | + `move` paths (`Mat->Left, Mat->Right, Acc->Vec, Vec->Vec`) give L1 no route to | ||
| 383 | + UB either. GM->L1 loads are fine (`:668`), so the only cube->GM path is | ||
| 384 | + GM->L1->L0A/L0B->L0C->GM, i.e. through the matmul accumulator. **The doc page | ||
| 385 | + `store.md:17` lists "L1/UB Tile" as valid sources; the installed code | ||
| 386 | + disagrees, and the code is what runs.** | ||
| 387 | +- **Merely declaring `pl.section_cube()` costs 1.88x on the vector path** -- | ||
| 388 | + the launch drops from 56 blocks to 28 (803.5 us vs 427.2 us on the same | ||
| 389 | + vector-only work). The cube assist is a net loss before the store | ||
| 390 | + restriction even applies. | ||
| 391 | + | ||
| 392 | +Also measured while testing this: **there is abundant spare DDR bandwidth on a | ||
| 393 | +vector-bound kernel.** A read-only contention probe on the same shape took | ||
| 394 | ++28.6% bytes for +7.6% time -- the extra reads were served at 26% of the | ||
| 395 | +saturated rate, a marginal 2.21 TB/s. So on this operator family a | ||
| 396 | +vector-issue-bound verdict cannot be re-explained as a bandwidth shortage. | ||
| @@ -149,16 +149,45 @@ Cube 和 Vector 类型指令的详细占比和计算量。 | |||
| 149 | 149 | ||
| 150 | ### 数据搬运量 | 150 | ### 数据搬运量 |
| 151 | 151 | ||
| 152 | -| 字段名 | 含义 | | 152 | +> **在 CANN 9.2.0 / A5(Ascend950PR)上,下表的字节字段全部不存在。** |
| 153 | -|--------|------| | 153 | +> 一手核实(同机、同一次采集):`read_main_memory_datas`、 |
| 154 | -| read_main_memory_datas(KB) | 读主存储器总量 | | 154 | +> `write_main_memory_datas`、`GM_to_L1_datas`、`L2_to_L1_datas` 在 |
| 155 | -| write_main_memory_datas(KB) | 写主存储器总量 | | 155 | +> `ai_core_op_summary.db` 里 **ABSENT**。实际存在的是带宽字段(GB/s): |
| 156 | -| GM_to_L1_datas(KB) | GM→L1 搬运量 | | 156 | +> `ai{c,v}_{l1_write,main_mem_read,main_mem_write}_bw`。 |
| 157 | -| L1_to_GM_datas(KB)(estimate) | L1→GM 搬运量(估算) | | 157 | +> |
| 158 | -| L0C_to_L1_datas(KB) | L0C→L1 搬运量 | | 158 | +> 而且**不要把 `main_mem_*_bw` 积分当作 DRAM 流量**:在一个权重流式的 attention 类算子 |
| 159 | -| L0C_to_GM_datas(KB) | L0C→GM 搬运量 | | 159 | +> 几何上这样积分得到 **90.1 KB/row,而该 shape 的 cold(distinct 字节)下限是 |
| 160 | -| GM_to_UB_datas(KB) | GM→UB 搬运量 | | 160 | +> 877.5 KB/row——低于物理最小值 9.7 倍**,且它随行数几乎不变而下限却下降 3 倍, |
| 161 | -| UB_to_GM_datas(KB) | UB→GM 搬运量 | | 161 | +> 连形状都不对。 |
| 162 | +> | ||
| 163 | +> **可用替代(requested 侧,已三次验证,其中一次是在“差值”而非“量级”上)**: | ||
| 164 | +> `aic_l1_write_bw × 28 × aic_total_time`。用它闭合*请求*字节,残差显式写出; | ||
| 165 | +> 一个健康的闭合会随编译期图切换而同步跳变(r2 与 r3 相差 +12%,实测同步), | ||
| 166 | +> 且残差在数十倍行数范围内保持为**单一乘性因子**而非漂移。 | ||
| 167 | +> | ||
| 168 | +> 两个附带坑:`aic_mte2_time` 在 **`PipeUtilization`** 表而非 `Memory` 表 | ||
| 169 | +> (每条 arm 要扫两次);`*_local_l2_*` 计数器仍然闭合不了(推出的 line size | ||
| 170 | +> 会从 240 漂到 150 B、写少 8 倍,`local` 似乎只代表一个 slice)。 | ||
| 171 | +> | ||
| 172 | +> **定价系数必须自己标定,不能沿用别处的数。** "1% 时间 ≈ 多少 KB/row 的 requested | ||
| 173 | +> Cube 读"这个系数随算子、tiling key 与 dtype 变化,跨算子搬运会整体错一个量级; | ||
| 174 | +> 曾有一批候选因沿用旧系数而被高估约 5 倍。做法:在当前算子的当前配置上量一次, | ||
| 175 | +> 记下配置与系数,配置一变就重新标定。 | ||
| 176 | + | ||
| 177 | +> **平台可用性**:下表的 `*_datas(KB)` 字节字段仅存在于 **非 A5 或 CANN < 9.2** 的 | ||
| 178 | +> 采集中;A5 / CANN 9.2.0 上这些列不存在(见上方告警),只有带宽类字段可用。 | ||
| 179 | +> 按本表采集前先确认平台,不要在 A5 上等待这些列。 | ||
| 180 | + | ||
| 181 | +| 字段名 | 含义 | 平台 | | ||
| 182 | +|--------|------|------| | ||
| 183 | +| read_main_memory_datas(KB) | 读主存储器总量 | 非 A5 / CANN<9.2 | | ||
| 184 | +| write_main_memory_datas(KB) | 写主存储器总量 | 非 A5 / CANN<9.2 | | ||
| 185 | +| GM_to_L1_datas(KB) | GM→L1 搬运量 | 非 A5 / CANN<9.2 | | ||
| 186 | +| L1_to_GM_datas(KB)(estimate) | L1→GM 搬运量(估算) | 非 A5 / CANN<9.2 | | ||
| 187 | +| L0C_to_L1_datas(KB) | L0C→L1 搬运量 | 非 A5 / CANN<9.2 | | ||
| 188 | +| L0C_to_GM_datas(KB) | L0C→GM 搬运量 | 非 A5 / CANN<9.2 | | ||
| 189 | +| GM_to_UB_datas(KB) | GM→UB 搬运量 | 非 A5 / CANN<9.2 | | ||
| 190 | +| UB_to_GM_datas(KB) | UB→GM 搬运量 | 非 A5 / CANN<9.2 | | ||
| 162 | 191 | ||
| 163 | ### 带宽利用率 | 192 | ### 带宽利用率 |
| 164 | 193 | ||
| @@ -123,6 +123,131 @@ python3 $CANNBOT_CONFIG_ROOT/skills/pypto-pro-op-perf-tune/scripts/perf_summary. | |||
| 123 | | **DoubleBuffer 效果** | MTE2/VEC 重叠 >30% | 重叠 10-30% | 重叠 <5% | | 123 | | **DoubleBuffer 效果** | MTE2/VEC 重叠 >30% | 重叠 10-30% | 重叠 <5% | |
| 124 | | **带宽利用率** | `bw_usage_rate` >60% | 30-60% | <30% | | 124 | | **带宽利用率** | `bw_usage_rate` >60% | 30-60% | <30% | |
| 125 | 125 | ||
| 126 | +### 4.2a 这些 ratio 是**重叠占比**,不是时间的划分——不能当屋顶用 | ||
| 127 | + | ||
| 128 | +`aiv_scalar_ratio` = `aiv_scalar_time / aiv_time`,其余 ratio 同理。各条流水**并发执行**, | ||
| 129 | +所以四个占比**相加通常大于 1**:strided kernel 上实测合计可达 **2.0–2.6**。 | ||
| 130 | + | ||
| 131 | +后果很直接:**`scalar_ratio = 0.67` 不代表"67% 的时间被标量卡住"**,它只说明标量流水在 67% 的 | ||
| 132 | +时间里是忙的——而同一段时间里向量与 MTE 也可能各自忙着。把它读成"标量是瓶颈"是这一族 | ||
| 133 | +指标最常见的误判,代价通常不是白做一轮,而是**做反一轮**:按错误归因排出的优化方向, | ||
| 134 | +往往正好避开真正的瓶颈。 | ||
| 135 | + | ||
| 136 | +**判据**:某条流水是不是瓶颈,看的是**它是否饱和**(接近 1.0)以及**去掉它的工作量会不会变快**, | ||
| 137 | +不是看它在几个占比里最大。可靠的做法是**隔离扫描**——每次只删掉一个构造,测时间变化: | ||
| 138 | + | ||
| 139 | +> 一组典型的隔离扫描结果(六个变体各差一个构造):把**全部算术**删光只快 1.0–4.7%; | ||
| 140 | +> 去掉 int64 索引输出(16 字节里的 8 字节)只快 0.6–5.0%;**打断串行依赖反而更慢**。 | ||
| 141 | +> 而把**每个 2-D 描述符从 1 行改成 8 行**直接买到 **1.77–2.31x**,再把状态搬进寄存器到 **1.91–2.63x**。 | ||
| 142 | +> 真正的成本是「每个归约行一个 DMA 描述符」——三个 ratio 里没有任何一个指向它。 | ||
| 143 | + | ||
| 144 | +一个推论:当所有流水都不饱和(本例修完后**无一超过 0.56**),算子既不是计算 bound 也不是带宽 | ||
| 145 | +bound,而是**受制于发起的操作数量**(描述符、launch)。这种情形下再调 tile 宽度或算术都不会动, | ||
| 146 | +要动的是"发多少次"。 | ||
| 147 | + | ||
| 148 | +### 4.2b 高 `vec_ratio` 可能是陷阱,不是"到顶" | ||
| 149 | + | ||
| 150 | +上表把 `vec_ratio > 90% 且无优化空间` 列为"严重问题",这是对的,但它**不能反过来读成"vec_ratio 高就说明算得满、没救了"**。 | ||
| 151 | +向量单元 100% 忙,只说明**发射槽被占满**,不说明**槽里装的是有用的工作**。 | ||
| 152 | + | ||
| 153 | +一个反例:某个 1-D 输入的 case 读到 | ||
| 154 | +**`vec_ratio 0.996`,却只跑到 roof 的 0.2%**。原因是该拓扑把 64 条车道分给 64 个不同的**行**, | ||
| 155 | +而这个 case 只有 1 行——它在满负荷地计算 **63 条无用车道**。只看 ratio 会判定"已达计算 bound、 | ||
| 156 | +无优化空间",实际有 **45 倍**的空间:固定 job 数与元素总数、只改变行数,耗时从 1473.98 µs 降到 32.63 µs, | ||
| 157 | +且随 `min(rows, 64)` 线性。 | ||
| 158 | + | ||
| 159 | +**判据**:`vec_ratio` 高时,必须再问一句**有效车道占用率**——参与计算的车道里有几条产出了会被写回的结果。 | ||
| 160 | +可用的验证手段是一次**隔离扫描**:把元素总数与 job 数固定住,只改变能填满车道的那个维度; | ||
| 161 | +如果耗时随之线性下降,那么之前的高 ratio 是空转,不是饱和。 | ||
| 162 | + | ||
| 163 | +同一轮还给出另一条:`Block Num` 显示的是**launch 网格**,不是真正干活的核数,不能拿它判断占用率。 | ||
| 164 | + | ||
| 165 | +### 4.2c 饱和的 `mte2_ratio` 不等于带宽 bound——先看每个描述符搬了多少连续字节 | ||
| 166 | + | ||
| 167 | +`mte2_ratio` 逼近 1.0 常被读作"总线跑满"。**它只说明 DMA 在发描述符,不说明它在搬字节。** | ||
| 168 | + | ||
| 169 | +**判据**:把 ratio 与**实测达成带宽**放在一起看。 | ||
| 170 | + | ||
| 171 | +> 流水已饱和、而达成带宽仍随每行连续字节数上升 ⇒ **描述符 bound**,不是带宽 bound。 | ||
| 172 | + | ||
| 173 | +**如何自证**(隔离扫描,任何算子都能做):只改片段宽度这一个 tiling key,保持元素总数、 | ||
| 174 | +dtype、算法与 launch 网格不变,量每档的达成带宽。承载结论的是**"随片段宽度单调上升"**, | ||
| 175 | +不是任何单点数值——单点会被单次发射的离散度淹没(同一配置重复读数差 10% 量级并不罕见), | ||
| 176 | +所以引用单调性与量级(典型跨度可达数倍),不要把某一档的接近程度当精度声明。 | ||
| 177 | + | ||
| 178 | +**必须排除的替代解释**:片段宽度与车道占用率会被同一个旋钮同时改变,两种故事都能拟合。 | ||
| 179 | +要分开,就找**片段宽度相同、车道占用率不同**的两点比较,或反过来。 | ||
| 180 | + | ||
| 181 | +**收敛到的做法**:把多行打进一个 2-D 描述符。 | ||
| 182 | + | ||
| 183 | +**边界**:片段宽度**除不尽**时会崩——尾巴要独占一个 register row 并走一整趟 strided pass, | ||
| 184 | +可以反而更慢。规则是"越宽越好,直到尾巴变病态",看的是 `I mod wb`。 | ||
| 185 | + | ||
| 186 | +### 4.2c-2 描述符尺寸的膝点在 2-4 KB,且这条曲线只在**数值已验证正确**的代码上才作数 | ||
| 187 | + | ||
| 188 | +**规则**:单靠描述符尺寸就可能有数倍差距,一行新代码都不用写。成本主要是**每个描述符的固定 | ||
| 189 | +开销**,因此曲线形如「固定/tile + 每 KB 增量」,膝点落在 **2-4 KB**,之后基本走平。 | ||
| 190 | + | ||
| 191 | +**如何自证**:固定总字节数、行数与算术,只改每描述符字节数,扫一条完整曲线并拟合。 | ||
| 192 | +同一轮加一个"把算术全删光"的对照——若删光后时间几乎不变,说明该路径上算术不是成本。 | ||
| 193 | + | ||
| 194 | +**流程判据(这条比数值更重要)**:**ladder 的形状只有在数值已验证正确的代码上才作数。** | ||
| 195 | +一个数值错误的原型可以给出看似真实的极值:在坏原型上做的扫描里,同一配置重复两次读数 | ||
| 196 | +可能差三成以上,噪声会伪装成拐点,指向的最优点与修好后完全不同。 | ||
| 197 | + | ||
| 198 | +判定与动作: | ||
| 199 | +- 同一配置重复两次差异过大(例如 30% 量级)⇒ **该轮不足以判定极值**,先降噪再谈形状。 | ||
| 200 | +- 极值必须在**最终代码**上复测,不得沿用原型结论。 | ||
| 201 | +- 先证明数值正确,再读性能曲线;顺序反了,整轮作废。 | ||
| 202 | + | ||
| 203 | +### 4.2d strided **store** 比 strided **load** 贵得多——不要拿 load 的价给 store 计价 | ||
| 204 | + | ||
| 205 | +**规则**:同一几何下 strided store 的单位成本**显著高于** strided load(实测量级 3x 起), | ||
| 206 | +且**几何越窄越糟**(窄几何下可达 7x)。 | ||
| 207 | + | ||
| 208 | +**如何自证**:在同一次采集里分别测 load-only 与 store-only 探针,几何、dtype、核数一致, | ||
| 209 | +单位统一到 ns/elem/core。 | ||
| 210 | + | ||
| 211 | +**这条会直接改变设计结论**:一个"一读两写"的三趟 strided 方案,若用实测 *load* 成本给三趟 | ||
| 212 | +统一计价,可以算出明显优于现行方案;换成实测 store 重算后,仅已测项就已劣化,方案实际是负的。 | ||
| 213 | +**误差不在算术,在把一条流水的价格套给了另一条。** | ||
| 214 | + | ||
| 215 | +**同轮可复用的一条**:提高流水线深度(buffer 数)对这条路径几乎无效——每描述符延迟不可重叠时, | ||
| 216 | +深度翻十倍买到的可能不足 1%。先确认延迟能否重叠,再投入深度。 | ||
| 217 | + | ||
| 218 | +**做法**:strided dataflow 的成本模型里,load 与 store **分别实测,不得互相代入**; | ||
| 219 | +写宽度更大的那一趟(如 int64 索引)尤其不能用窄 dtype 的价去估。 | ||
| 220 | + | ||
| 221 | +### 4.2e apparatus control 必须踩在被测对象的同一条路径上 | ||
| 222 | + | ||
| 223 | +**规则**:共享机器**非均匀降级**——同一块卡、同一份代码,某类循环可能只慢 1.4x, | ||
| 224 | +而 bulk/strided 路径同时慢 3-14x。因此"总控制项复现了"**不等于**"这次测量可信"。 | ||
| 225 | + | ||
| 226 | +**判据**:要给 strided/bulk 路径定价,control 就必须是 strided/bulk 的那一项。 | ||
| 227 | +拿一个跑在别的流水上的 control 代签,**等于没有 control**。 | ||
| 228 | + | ||
| 229 | +**典型失效方式**:设计文档只规定"某个总控制项回到基线即可信",于是某一轮该控制项通过、 | ||
| 230 | +而同轮的 strided 控制项偏离数倍,门槛放行了一次本该作废的测量。 | ||
| 231 | + | ||
| 232 | +**做法**: | ||
| 233 | +- control 集合要**覆盖被测的每一条流水**,不是一个总闸。 | ||
| 234 | +- 全部 control 同轮复现(例如 1.5% 以内)才认这一轮;任一项偏离即整轮作废,不做挑选性采信。 | ||
| 235 | +- 把 control 读数与被测读数**记在同一份记录里**,事后才能判断当时是否可信。 | ||
| 236 | + | ||
| 237 | +### 4.2f 性能扫描的正确性闸门要用容差,绝不能用 bit-exact | ||
| 238 | + | ||
| 239 | +**规则**:改 tile 几何会改变归约结合序,**末位差是预期行为**,不是 bug。 | ||
| 240 | +用 `torch.equal` 当闸门、并在采样前 `exit`,会把完全有效的实验臂整条丢掉。 | ||
| 241 | + | ||
| 242 | +**判据**:`ndiff`(不等元素数)**本身分不清"舍入"和"算错"**——不等元素占比可以高达两位数百分比, | ||
| 243 | +而最大绝对误差仍在 1e-07 量级。必须同时报 `maxabs` / `maxrel` 才能判。 | ||
| 244 | + | ||
| 245 | +**做法**: | ||
| 246 | +- 闸门报 **`ndiff` + `maxabs` + `maxrel` 三个数**,只在**大到不可能是舍入**时才判失败。 | ||
| 247 | +- **任何情况下都不要在采样之前退出**——先拿到时间,再判要不要采信。 | ||
| 248 | +- 阈值按 dtype 与归约长度定,不要跨 dtype 复用同一个数。 | ||
| 249 | + | ||
| 250 | + | ||
| 126 | ### 4.3 不同算子类型的预期 ratio 分布 | 251 | ### 4.3 不同算子类型的预期 ratio 分布 |
| 127 | 252 | ||
| 128 | | 算子类型 | 主导流水 | 预期 ratio | 异常信号 | | 253 | | 算子类型 | 主导流水 | 预期 ratio | 异常信号 | |
| @@ -0,0 +1,90 @@ | |||
| 1 | +# 多阶段单 kernel 的任务展平 | ||
[P2] 新增参考页没有进入任何 owning skill 或 KB 路由 问题:该文件只向下链接模板,没有来自 perf-tune skill、ROUTER、索引或其他正式入口的 incoming link;同批新增的 fp32-chain、部分 direct-buffering 模板和 repo tools 也存在类似问题。 影响:正常工作流无法发现这些产物,是否属于正式契约不明确,后续内容腐化也不会触发消费者或门禁。 证据:在 #444 独立树和两个 PR 的组合树中检索入口,均没有 owning skill/KB router 指向本页。 建议:为每个正式产物定义 owner、入口、适用条件和验证方式;实验性材料迁入 investigations 区;没有消费者的文件不要作为正式工作流内容合入。 ![]() ![]() | |||
| 2 | + | ||
| 3 | +当一个融合 kernel 含 Cube → Vector → Cube 等全局依赖阶段时,按 row tile 启动 block | ||
| 4 | +很容易让小 shape 只占用一个 AIC/AIV。先枚举 public shapes 的 `row_tiles`、`block_dim` 和各阶段 | ||
| 5 | +独立输出任务数;若输出任务远多于 block,优先展平任务,而不是先改 tile 大小。 | ||
| 6 | + | ||
| 7 | +## 调度骨架 | ||
| 8 | + | ||
| 9 | +1. 把每个阶段的互斥输出映射为一维任务:`task = row_tile * output_tiles + output_tile`。 | ||
| 10 | +2. 用 `pl.range(core_id, total_tasks, num_cores)` 跨 block 分配;每个 GM 输出区间必须只有一个写者。 | ||
| 11 | +3. wrapper 为整次 launch 选择一个固定 block 集,不能按阶段改变参与者。 | ||
| 12 | +4. 阶段间用成对的 `pl.system.sync_all(core_type=pl.SyncCoreType.MIX)`:生产端 section | ||
| 13 | + 结束前一次、消费端 section 开始时一次。 | ||
| 14 | +5. 所有已启动 block 和 AIV subblock 都必须到达相同顺序、相同数量的 barrier;数据 guard 只能包住 | ||
| 15 | + load/compute/store,不能包住 barrier。 | ||
| 16 | + | ||
| 17 | +片段见 [`../templates/stage-task-flatten.py.tmpl`](../templates/stage-task-flatten.py.tmpl)。 | ||
| 18 | + | ||
| 19 | +## 单因素验证纪律 | ||
| 20 | + | ||
| 21 | +- 第一次拓扑实验只改任务所有权与同步,不改 K 分拆、FP32/BF16 workspace、累加树或舍入模式。 | ||
| 22 | +- 静态穷举每个 shape 的写区间,证明无缺口、无重复;同时数 value-producing DSL 调用的种类和数量。 | ||
| 23 | +- 真板先跑含 row tail、小 shape、最大 workspace、独立 epsilon、全零输入的集合,再跑完整 public。 | ||
| 24 | +- 本机通过不能替代 evaluation server:设备子型、CANN、PyPTO、Python 版本任一不同,都要线上复验。 | ||
| 25 | + | ||
| 26 | +## 固定输入、成组输出的 Cube 复用 | ||
| 27 | + | ||
| 28 | +展平为单输出任务后,如果多个相邻输出 tile 共享同一个左输入,可以把 owner 改成 | ||
| 29 | +`(partition, output_wave)`,一个任务保留一份 Mat/Left 并驱动最多四个独立 Acc。MlaProlog | ||
| 30 | +的 down projection 由此把每个 row tile、每个 K wave 的 token Mat/Left 搬运从 68 次降到 | ||
| 31 | +20 次,而 weight Mat/Right、MMA、最终 GM store 和 FP32 加法树均不变。 | ||
| 32 | + | ||
| 33 | +这类改动的门禁不是“输出结果看起来相同”,而是逐项证明: | ||
| 34 | + | ||
| 35 | +1. 每个 `(row_tile, partition, output_tile)` 仍恰好一个 owner;尾 wave 不重复或漏写。 | ||
| 36 | +2. 每个 Acc 只累加固定 partition 的 `k = q * partitions + partition`,且 `q` 严格递增。 | ||
| 37 | +3. consumer 仍按原树组合 partitions,例如 `(p0 + p1) + (p2 + p3)`。 | ||
| 38 | +4. 峰值同时存活的 MatB、Right 与 Acc slot 不超过 TileGroup slot 数;不能把“下一轮会复用” | ||
| 39 | + 当作当前 live interval 已结束。 | ||
| 40 | +5. 小 shape 的任务数可能从输出数增至 `partitions * ceil(outputs/group)`;同时核算并行度和 | ||
| 41 | + 调度开销,不能只报搬运减少比例。 | ||
| 42 | + | ||
| 43 | +如果为了复用而把多个 partition 累加进同一个 Acc,或用 atomic 把 partial 提前合并,就已经 | ||
| 44 | +改变数值 ABI,不再是本节的低风险调度优化。 | ||
| 45 | + | ||
| 46 | +片段见 [`../templates/cube-output-wave-reuse.py.tmpl`](../templates/cube-output-wave-reuse.py.tmpl)。 | ||
| 47 | + | ||
| 48 | +若优化模式必须更换 TileGroup、mutex 或 Cube 指令链,不能把 runtime shape 条件直接包在链外。 | ||
| 49 | +提交契约要求单 JIT/单 launch 时,使用编译期 tiling key,并检查每个 key 的 IR 已消除 key | ||
| 50 | +引用。片段见 | ||
| 51 | +[`../templates/tiling-key-resource-specialization.py.tmpl`](../templates/tiling-key-resource-specialization.py.tmpl)。 | ||
| 52 | + | ||
| 53 | +## AIV 兼容性门禁 | ||
| 54 | + | ||
| 55 | +如果旧目标版本呈现严格的半行错误,先检查 AIV `pl.get_block_idx()` 的可见编号:不同 A5 | ||
| 56 | +设备子型/CANN 快照可能分别暴露物理 block id 或交错 AIV id。只让 subblock 0 工作、再直接按 | ||
| 57 | +raw `core_id` 分 row/head/chunk,在前一种约定可覆盖全部任务,在后一种约定只覆盖偶数编号。 | ||
| 58 | + | ||
| 59 | +当前框架提供 `get_subblock_num` 时,AIV 的 `get_block_idx()` 是交错编号,先还原物理 block: | ||
| 60 | + | ||
| 61 | +```python | ||
| 62 | +HAS_SUBBLOCK_NUM = hasattr(pl, "get_subblock_num") | ||
| 63 | +raw_core_id = pl.get_block_idx() | ||
| 64 | +if HAS_SUBBLOCK_NUM: | ||
| 65 | + physical_id = raw_core_id // pl.get_subblock_num() | ||
| 66 | +else: | ||
| 67 | + physical_id = raw_core_id | ||
| 68 | +``` | ||
| 69 | + | ||
| 70 | +`HAS_SUBBLOCK_NUM` 必须是模块加载期 Python 常量,使旧 parser 不解析不存在的 API 分支。Cube | ||
| 71 | +与 Vector task loop 都统一用 `physical_id`,避免同一 kernel-scope block-id 表达式在两类 engine | ||
| 72 | +降低后产生不同 owner。含 GM load/store 的纯 Vector 路径只让 `sub_id == 0` 执行,并用 | ||
| 73 | +`physical_id` 分配 row/head/chunk;官方 | ||
| 74 | +文档明确同一 physical block 的两个 AIV subblock 共享 MTE,不能把它们当作两个独立 GM worker。 | ||
| 75 | +所有未选中的 subblock 仍必须参加 MIX barrier。先静态穷举两种编号模型,再在两个目标版本实测。 | ||
| 76 | + | ||
| 77 | +这不是通用的 PyPTO-Pro 语义保证;必须把失败/通过的设备子型、CANN/PyPTO 版本和 case 窗口 | ||
| 78 | +写入报告,不能从一台 A5 外推所有 A5。 | ||
| 79 | + | ||
| 80 | +## 常见失败 | ||
| 81 | + | ||
| 82 | +| 现象 | 优先检查 | | ||
| 83 | +|---|---| | ||
| 84 | +| 小 shape 很慢,大 shape 接近基线 | wrapper 的 `block_dim` 是否只跟 row tiles 绑定 | | ||
| 85 | +| barrier 后间歇脏数据或死锁 | barrier 是否在 guard 内;各 section 的调用数/顺序是否一致 | | ||
| 86 | +| `T<=tile` 通过、`T>=2*tile` 严格一半错误 | AIV raw `core_id` 是否只覆盖了偶数逻辑 worker | | ||
| 87 | +| GM ownership 完整但结果偶发脏值 | 是否让同一 physical block 的两个 AIV 独立发起 GM traffic | | ||
| 88 | +| 每隔固定行数丢半块 | subblock 所有权、物理 Tile 高度与 `load_tile` 地址单位 | | ||
| 89 | +| 精度随拓扑变化 | 是否意外改变 K 累加顺序、partial 合并树或最终 cast | | ||
| 90 | +| 本机有 `kernel_details.csv` 但没有 PyPTO 行 | profiler 与当前 PyPTO/CANN 快照不兼容;保留精度证据,性能改用目标 server 或匹配版本的 msprof | | ||
| @@ -0,0 +1,224 @@ | |||
| 1 | +# 分阶段 matmul A/B 证据协议 | ||
| 2 | + | ||
| 3 | +一次分阶段 Cube matmul 的 A/B 比较要成立,必须满足下列每一项。把它当判据清单读, | ||
| 4 | +不是当表格填——它约束的是"这次比较能不能作为证据",不是记录格式。 | ||
| 5 | +配套的精度与性能门在知识库的「分阶段 Cube matmul gates」一页,先读那一页。 | ||
| 6 | + | ||
| 7 | +两条贯穿全篇的规则: | ||
| 8 | + | ||
| 9 | +- **每次只改一个数值或调度变量。** 同时动两个,结果对任何一个都不构成证据。 | ||
| 10 | +- **不适用的项要写明理由,不能跳过。** 略过的项在事后审阅时等同于"已检查并通过", | ||
| 11 | + 而这正是无法复盘的开始。 | ||
| 12 | + | ||
| 13 | +下面每一项都是事后判断该轮测量是否可信所必需的;缺一项,该轮结论的强度就降一级。 | ||
| 14 | + | ||
| 15 | +## Identity | ||
| 16 | + | ||
| 17 | +- Date | ||
| 18 | +- Source SHA A / B | ||
| 19 | +- Target / physical NPU | ||
| 20 | +- CANN / PyPTO-Pro | ||
| 21 | +- Environment setup | ||
| 22 | +- Official task/checker SHA | ||
| 23 | +- Lock path, device:inode, holder PID: (记录实测值) | ||
| 24 | + | ||
| 25 | +## Frozen contract and hypothesis | ||
| 26 | + | ||
| 27 | +- Official shapes and value domains | ||
| 28 | +- Stage equation | ||
| 29 | +- Input -> accumulator -> output dtype | ||
| 30 | +- A reduction tree | ||
| 31 | +- B reduction tree | ||
| 32 | +- Only changed variable | ||
| 33 | +- Expected precision effect | ||
| 34 | +- Expected performance effect | ||
| 35 | +- Range/shape assumptions not guaranteed by contract | ||
| 36 | +## Static and generated-code gates | ||
| 37 | + | ||
| 38 | +- [ ] Wrapper signature and output contract are unchanged. | ||
| 39 | +- [ ] Wrapper performs no tensor arithmetic and preserves the allowed JIT/launch count. | ||
| 40 | +- [ ] Cube LHS/RHS dtypes match; no implicit BF16 -> FP16 load or mixed matmul dtype. | ||
| 41 | +- [ ] Any BF16 -> FP16 RHS is first materialized by AIV into ordinary FP16 GM. | ||
| 42 | +- [ ] Generated code confirms operand dtype/layout, K extent, phases, and final cast mode. | ||
| 43 | +- [ ] Every reused Acc range records exactly one handoff protocol: | ||
| 44 | + (记录实测值). Hardware mode pairs producer `AccPhase` with | ||
| 45 | + consumer `STPhase` and closes both sides with `Final`; software mode keeps | ||
| 46 | + producer and consumer phase-free and uses one TileGroup mutex. The two modes | ||
| 47 | + are never mixed. | ||
| 48 | +- [ ] Generated CCE proves the selected Acc protocol. Hardware mode has a | ||
| 49 | + phase-bearing M producer and phase-bearing FIX consumer over matching blocks. | ||
| 50 | + Software mode has matched get/release around both M operations and the FIX | ||
| 51 | + drain with the same Acc mutex id. Reject phased M + ordinary phase-less | ||
| 52 | + Acc-to-Vec `TMOV`, mismatched mutex ids, missing release, or raw `make_tile` | ||
| 53 | + without mutex ownership. | ||
| 54 | +- [ ] Workspace maximum bytes and conversion GM traffic are recorded: (记录实测值). | ||
| 55 | +- [ ] Any pack/re-layout records full-shape bytes per call, writer ownership, | ||
| 56 | + barrier cost, and measured overlap; contraction FLOPs are not reported alone. | ||
| 57 | +- [ ] `pl.load_tile` tile-block offsets and `pl.load` absolute element offsets | ||
| 58 | + are not mixed; non-tile-aligned GM loads have an A5 MTE/tail gate. | ||
| 59 | +- [ ] Each GM/Mat/Acc region has one proved writer or a documented atomic protocol. | ||
| 60 | +- [ ] A shape-specialized graph that omits a fixed partial never reads its | ||
| 61 | + `torch.empty` GM buffer; every absent term is initialized locally before use, | ||
| 62 | + with the required VF store/load barrier. | ||
| 63 | +- [ ] Local-memory live intervals, mutex IDs, and capacity pass: (记录实测值). | ||
| 64 | +- [ ] Every `pl.move` has physically compatible source/destination TileTypes; | ||
| 65 | + `valid_shape` is not used to justify a physical-shape mismatch, and `offset` | ||
| 66 | + is used only to extract a destination-sized sub-rectangle from the source. | ||
| 67 | +- [ ] Every TileGroup has at least as many physical slots as the maximum number | ||
| 68 | + of simultaneously live values; two `next()` values consumed together never | ||
| 69 | + come from a one-slot group. | ||
| 70 | +- [ ] Reused Vec scratch in a pipelined load/cast/store loop is a TileGroup in | ||
| 71 | + the auto-mutex ownership graph, not a bare address-disjoint `make_tile`. | ||
| 72 | +- [ ] Typed TileGroups that reuse one physical arena have distinct mutex IDs, | ||
| 73 | + disjoint live stages, and an unconditional hard barrier between stages. | ||
| 74 | +- [ ] Tail ownership and untouched sentinel regions pass: (记录实测值). | ||
| 75 | +- [ ] For every multi-wave split, each wave's start/end is derived from the | ||
| 76 | + physical tensor equation; the wave union is disjoint and equals the total | ||
| 77 | + tile/chunk extent. Head counts are converted through the actual per-head | ||
| 78 | + width before they are used as vector-chunk counts. | ||
| 79 | +- [ ] Every launched AIC/AIV lane reaches the same unconditional synchronization points. | ||
| 80 | +- [ ] A repeated local-mailbox task ends with zero outstanding READY/FREE/ | ||
| 81 | + STORE-FREE credit and a `bar_all()` on both engines after their final event; | ||
| 82 | + the gate covers the real uneven per-core task depth and maximum dynamic depth. | ||
| 83 | + `bar_all()` is recorded as local `PIPE_ALL`, not MIX or event re-seeding. | ||
| 84 | +- [ ] Each `pl.section_cube` / `pl.section_vector` recomputes the scalar row | ||
| 85 | + offsets, worker IDs, and worker counts it consumes; it does not capture a | ||
| 86 | + scalar first defined in another section. Target compilation has no | ||
| 87 | + undeclared SSA identifier in generated C++. | ||
| 88 | +- [ ] A VF store/load dependency has the required `vf.mem_bar(VST_VLD)`. | ||
| 89 | +- [ ] No runtime shape branch changes the Cube/resource topology. | ||
| 90 | +- [ ] If topology varies, every `tiling_key` IR is separately inspected and contains no runtime key reference. | ||
| 91 | +- [ ] The pre-lock host smoke imports every helper used by the real input | ||
| 92 | + factory and asserts required symbols without allocating an NPU Tensor; the | ||
| 93 | + first actual input-factory call remains inside the device lock. | ||
| 94 | +- [ ] The staged SHA manifest includes every transitive input-factory/helper | ||
| 95 | + module needed by each isolated profiler process; a missing helper is a | ||
| 96 | + pre-launch environment failure, not a kernel or performance result. | ||
| 97 | +- [ ] One outer `flock lockfile command` or re-exec owns the lock for the full | ||
| 98 | + compile/run/profile process tree. `device:inode` and the non-`*` `lslocks` | ||
| 99 | + holder PID (not a `WRITE*` waiter) match at start/end, and no competing | ||
| 100 | + same-device process appears. A printed | ||
| 101 | + `LOCK_ACQUIRED` line alone is not accepted; any holder/inode drift invalidates | ||
| 102 | + the complete timing run. | ||
| 103 | +- [ ] The wrapper retains no Tensor-derived GM buffer, prepacked weight, or | ||
| 104 | + persistent workspace across calls; caches contain only code or | ||
| 105 | + value-independent metadata and do not key on `weakref`, `_version`, or | ||
| 106 | + `data_ptr()`. | ||
| 107 | + | ||
| 108 | +Related templates: | ||
| 109 | +[stage-task flatten](stage-task-flatten.py.tmpl), | ||
| 110 | +[exact-order shared-left output pair](cube-shared-left-output-pair.py.tmpl), | ||
| 111 | +[dual-AIV mailbox](dual-aiv-mailbox.py.tmpl), and | ||
| 112 | +[tiling-key specialization](tiling-key-resource-specialization.py.tmpl). | ||
| 113 | + | ||
| 114 | +## FP16 range and special-value audit | ||
| 115 | + | ||
| 116 | +| boundary | contract bound or observed range | smallest nonzero | NaN | +Inf/-Inf | evidence | | ||
| 117 | +|---|---:|---:|---:|---:|---| | ||
| 118 | +| source input/weight/gamma | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | | ||
| 119 | +| BF16 before FP16 cast | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | | ||
| 120 | +| FP16 workspace | 值域 | 最小非零 | NaN 计数 | Inf 计数 | (记录实测值) | | ||
| 121 | +| FP32 accumulator/output | 值域 | 最小非零 | NaN 计数 | Inf 计数 | (记录实测值) | | ||
| 122 | + | ||
| 123 | +- [ ] Every analytic bound cites a contract premise; premises true only of the | ||
| 124 | + sampled data are labelled unproven. | ||
| 125 | +- [ ] FP16 overflow, underflow, and non-finite propagation are checked before promotion. | ||
| 126 | +- [ ] Exact ties/adjacent values validate terminal `CAST_RINT` against Torch BF16 RNE when used. | ||
| 127 | + | ||
| 128 | +## Precision A/B | ||
| 129 | + | ||
| 130 | +Use identical deterministic inputs. Compare the changed intermediate FP32 | ||
| 131 | +stage before terminal conversion, then run the unmodified official checker. | ||
| 132 | +`max_abs` is diagnostic only. | ||
| 133 | + | ||
| 134 | +| case/domain | variant | intermediate max_abs | overall MERE / MARE | normal errors/ref | small errors/ref | cancel errors/ref | NaN positions | result | | ||
| 135 | +|---|---|---:|---|---:|---:|---:|---:|---| | ||
| 136 | +| 每个用例 | A | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | | ||
| 137 | +| 每个用例 | B | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | | ||
| 138 | + | ||
| 139 | +- [ ] Normal, small-value, and cancellation domains all pass. | ||
| 140 | +- [ ] The comparator receives the target-dtype native reference for every | ||
| 141 | + output; if unavailable, fallback counts are labelled diagnostic-only. | ||
| 142 | +- [ ] For a scheduling-only candidate, run candidate and production from | ||
| 143 | + separate processes and separate build directories on identical seeds, then | ||
| 144 | + require an exact output comparison before performance profiling. Do not | ||
| 145 | + load same-name JIT variants into one process or reuse one build directory. | ||
| 146 | +- [ ] If a synthetic absolute oracle rejects both a candidate and its known | ||
| 147 | + accepted production control with identical regional statistics, record the | ||
| 148 | + synthetic domain as an independent range-risk probe; do not attribute the | ||
| 149 | + failure to the candidate until the differential control is complete. | ||
| 150 | +- [ ] Aligned/non-aligned tails and sentinels pass. | ||
| 151 | +- [ ] Unsampled-shape probes preserve the actual batch/sequence pair as well as | ||
| 152 | + the flattened row count, and include reduced-K domains that change the | ||
| 153 | + number of legal partials. | ||
| 154 | +- [ ] Alternating shapes/keys pass in one process without `161002` or stale state. | ||
| 155 | +- [ ] A pass on the sampled shapes is not described as proof for unsampled ones. | ||
| 156 | +- [ ] Bounded JIT/load/launch/synchronize liveness is reported separately from | ||
| 157 | + local-comparator precision; neither is promoted to a claim about unsampled | ||
| 158 | + shapes. | ||
| 159 | +- [ ] A stalled remote stage is correlated with process/event evidence | ||
| 160 | + before it is called a kernel hang. | ||
| 161 | +- [ ] The input to the changed stage was compared before changing its | ||
| 162 | + consumer; an upstream error is not attributed to the new consumer. | ||
| 163 | +- [ ] If another residual term is proposed, the current remainder is nonzero | ||
| 164 | + on the failing positions and the new term changes those positions. | ||
| 165 | + | ||
| 166 | +## Performance A/B | ||
| 167 | + | ||
| 168 | +Keep target, physical NPU, environment, lock, inputs, warmup, and measurement | ||
| 169 | +method identical. Include cast/widen/workspace traffic rather than timing only | ||
| 170 | +the contraction. | ||
| 171 | + | ||
| 172 | +- Warmup / repeats | ||
| 173 | +- Timing source and synchronization | ||
| 174 | +- Baseline definition | ||
| 175 | +- Conversion overlap/extra traffic | ||
| 176 | +- Full-weight pack/re-layout bytes per call | ||
| 177 | +- Aligned tile load versus absolute-element load evidence | ||
| 178 | +- Static logical bytes / task descriptors before and after | ||
| 179 | +- Slowest physical-core output chain before and after | ||
| 180 | +| case | A device times (us) | B device times (us) | A statistic | B statistic | B/A | notes | | ||
| 181 | +|---|---|---|---:|---:|---:|---| | ||
| 182 | +| 每个用例 | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | (记录实测值) | | ||
| 183 | + | ||
| 184 | +- [ ] Logical L1/GM bytes, issue counts, and task descriptors are labelled as | ||
| 185 | + static upside bounds, not measured speedups. | ||
| 186 | +- [ ] Replacing GM with an on-chip mailbox records physical message width, | ||
| 187 | + Acc-chain/mutex count, aligned-load and shared-left/RHS reuse deltas, | ||
| 188 | + per-core task depth, final drains and both engines' local barriers. Reduced | ||
| 189 | + logical bytes alone cannot approve the candidate. | ||
| 190 | +- [ ] A mailbox FREE/ACK is emitted immediately after the last mailbox read; | ||
| 191 | + generated code proves no later read, while residual casts/stores use disjoint | ||
| 192 | + scratch. Early release never removes the final zero-credit drain. | ||
| 193 | +- [ ] If the slowest physical-core output chain is unchanged, promotion uses a | ||
| 194 | + repeated target A5 B/A/A/B run against the frozen exact control in separate | ||
| 195 | + build directories; simulator timing or static counts cannot satisfy this gate. | ||
| 196 | +- [ ] Every ABBA arm uses deterministic inputs with matching fingerprints or | ||
| 197 | + an explicitly frozen input factory and seed. Profiler warnings and CSV | ||
| 198 | + coverage are recorded; an incomplete trace is not used as roofline evidence. | ||
| 199 | +- [ ] If a shape dispatch is added, report hit-domain and fallback-domain | ||
| 200 | + ratios separately. An aggregate result must not hide a regression in the | ||
| 201 | + newly selected kernel path. | ||
| 202 | +- [ ] A local target-board ABBA is a promotion gate, not a substitute for an | ||
| 203 | + official evaluation-server terminal result when that server defines the | ||
| 204 | + aggregate. Record the exact revision, per-case elapsed values, | ||
| 205 | + baseline and hardware floors. If the official hit-domain result reverses | ||
| 206 | + the local sign beyond repeat drift, reject or narrow the dispatch and retain | ||
| 207 | + the frozen server-best package. | ||
| 208 | +- [ ] Cross-run comparisons use the per-case elapsed values from the two named | ||
| 209 | + runs. Do not assume that a baseline you do not control, the hardware | ||
| 210 | + floor, the task bundle or the environment is unchanged merely because the | ||
| 211 | + operator and source baseline have the same label. | ||
| 212 | + | ||
| 213 | +## Decision | ||
| 214 | + | ||
| 215 | +Reject B immediately for an official precision failure, NaN-position mismatch, | ||
| 216 | +FP16 non-finite outside the contract, ownership/sentinel failure, resource | ||
| 217 | +error, or unexplained generated-code change. Retain B only when repeated device | ||
| 218 | +timing improves under the same conditions. | ||
| 219 | + | ||
| 220 | +- Decision | ||
| 221 | +- Evidence-backed reason | ||
| 222 | +- Remaining unverified risk | ||
| 223 | +- Logs/artifacts | ||
| 224 | +- Next single-variable probe | ||
| @@ -0,0 +1,76 @@ | |||
| 1 | +# PyPTO-Pro Cube fragment: reuse one fixed left tile across a small output | ||
| 2 | +# wave without changing partition ownership or the FP32 reduction tree. | ||
| 3 | +# Replace constants/types/groups from DESIGN.md; this is not standalone code. | ||
| 4 | + | ||
| 5 | +OUTPUT_GROUP = 4 | ||
| 6 | +output_waves = (output_tiles + OUTPUT_GROUP - 1) // OUTPUT_GROUP | ||
| 7 | +tasks_per_row = partitions * output_waves | ||
| 8 | +total_tasks = row_tiles * tasks_per_row | ||
| 9 | + | ||
| 10 | +# Keep explicit handles because TileGroup has a rotating `next()` cursor, not | ||
| 11 | +# random indexing. Four Acc slots must remain live until the whole K loop ends. | ||
| 12 | +acc0 = acc_group.next() | ||
| 13 | +acc1 = acc_group.next() | ||
| 14 | +acc2 = acc_group.next() | ||
| 15 | +acc3 = acc_group.next() | ||
| 16 | + | ||
| 17 | +for task in pl.range(physical_id, total_tasks, num_cores): | ||
| 18 | + mt = task // tasks_per_row | ||
| 19 | + local_task = task % tasks_per_row | ||
| 20 | + partition = local_task // output_waves | ||
| 21 | + output_wave = local_task % output_waves | ||
| 22 | + nt_base = output_wave * OUTPUT_GROUP | ||
| 23 | + | ||
| 24 | + for q in pl.range(0, k_waves): | ||
| 25 | + k_block = q * partitions + partition | ||
| 26 | + | ||
| 27 | + # One Mat/Left tile is shared only by outputs from the same partition | ||
| 28 | + # and K block. Do not rotate it until every live Acc has consumed it. | ||
| 29 | + a_mat = a_mat_group.next() | ||
| 30 | + a_left = a_left_group.next() | ||
| 31 | + pl.load_tile(a_mat, input_2d, [mt, k_block]) | ||
| 32 | + pl.move(a_left, a_mat) | ||
| 33 | + | ||
| 34 | + # Write the phase sequence out per Acc. Do NOT factor it into a Python | ||
| 35 | + # helper: the parser cannot follow a helper call inside a `@pl.jit` | ||
| 36 | + # body -- the body is an AST that is never executed, so the call | ||
| 37 | + # surfaces as a pybind "incompatible constructor arguments" error far | ||
| 38 | + # from the mistake. Inline it, or lift it to a value the parser can see. | ||
| 39 | + # | ||
| 40 | + # Phase, per Acc chain, using the two ends of the K loop rather than a | ||
| 41 | + # branch ladder: `q == 0` opens with `pl.matmul`, every later block | ||
| 42 | + # accumulates, and the *last* block must close with `AccPhase.Final`. | ||
| 43 | + # An accumulator left on `AccPhase.Partial` stays open and faults the | ||
| 44 | + # device, so the closing block cannot be reachable only when the loop | ||
| 45 | + # runs more than once -- a single-block K loop (k_waves * partitions | ||
| 46 | + # == 1) has to open and close on the same iteration. | ||
| 47 | + is_first = q == 0 and partition == 0 | ||
| 48 | + is_last = q == k_waves - 1 and partition == partitions - 1 | ||
| 49 | + acc_phase = pl.AccPhase.Final if is_last else pl.AccPhase.Partial | ||
| 50 | + | ||
| 51 | + # for each live output lane, guarded by its tail check: | ||
| 52 | + # if is_first: | ||
| 53 | + # pl.matmul(accN, a_left, rhs_right, phase=acc_phase) | ||
| 54 | + # else: | ||
| 55 | + # pl.matmul_acc(accN, accN, a_left, rhs_right, phase=acc_phase) | ||
| 56 | + # Keep the calls unrolled so every lane has a stable Acc handle and the | ||
| 57 | + # tail guards stay visible; replace `rhs_right` with the Right tile this | ||
| 58 | + # lane's `nt` maps to, loaded from its own group. | ||
| 59 | + if nt_base < output_tiles: | ||
| 60 | + ... # lane 0 -> acc0 | ||
| 61 | + if nt_base + 1 < output_tiles: | ||
| 62 | + ... # lane 1 -> acc1 | ||
| 63 | + if nt_base + 2 < output_tiles: | ||
| 64 | + ... # lane 2 -> acc2 | ||
| 65 | + if nt_base + 3 < output_tiles: | ||
| 66 | + ... # lane 3 -> acc3 | ||
| 67 | + | ||
| 68 | + # Each [mt, partition, nt] partial remains a unique GM destination. | ||
| 69 | + if nt_base < output_tiles: | ||
| 70 | + pl.store_tile(partial_3d, acc0, [mt, partition, nt_base]) | ||
| 71 | + if nt_base + 1 < output_tiles: | ||
| 72 | + pl.store_tile(partial_3d, acc1, [mt, partition, nt_base + 1]) | ||
| 73 | + if nt_base + 2 < output_tiles: | ||
| 74 | + pl.store_tile(partial_3d, acc2, [mt, partition, nt_base + 2]) | ||
| 75 | + if nt_base + 3 < output_tiles: | ||
| 76 | + pl.store_tile(partial_3d, acc3, [mt, partition, nt_base + 3]) | ||
| @@ -0,0 +1,156 @@ | |||
| 1 | +# PyPTO-Pro A5 Acc -> Vec mailbox skeleton. | ||
| 2 | +# Replace tile types, valid shapes and bodies from DESIGN.md. This fragment is | ||
| 3 | +# intentionally one-slot: READY publishes data and FREE supplies backpressure. | ||
| 4 | +# Use one shared TileGroup object in both sections. A manual Vec make_tile plus | ||
| 5 | +# events is not a substitute for mutex ownership on current A5 PyPTO-Pro. | ||
| 6 | +# | ||
| 7 | +# HARD GATE: this skeleton is not validated by compiling or returning from a | ||
| 8 | +# real-block launch. Before using it in a full operator, run a bounded | ||
| 9 | +# production-shaped probe that checks both liveness and bit-exact aligned/odd | ||
| 10 | +# tails, including untouched invalid-row sentinels. Any timeout, device error, | ||
| 11 | +# mismatch, sentinel overwrite, or missing tail rejects Stage A and must not | ||
| 12 | +# proceed to the full operator. | ||
| 13 | +# If production carries a FREE/READY token through pl.system.sync_all(), the | ||
| 14 | +# probe must contain the same seed -> first wave -> MIX barrier -> second-wave | ||
| 15 | +# reuse. Matching total set/wait counts and a barrier-free probe do not prove | ||
| 16 | +# cross-barrier token lifetime. After a device error, close that source SHA; | ||
| 17 | +# change the protocol and use a new SHA before any retry. | ||
| 18 | +# Before generated-code performance work, run the smallest selected production | ||
| 19 | +# case under a 300-second wall-clock watchdog. Source/static/math PASS does not | ||
| 20 | +# prove liveness. A timeout, stuck launch, or sustained AIC/Aicube activity | ||
| 21 | +# with AIV idle is a runtime NO-GO; preserve CCE/counters and skip ABBA. | ||
| 22 | + | ||
| 23 | +READY_EVENT = 0 | ||
| 24 | +MAILBOX_FREE_EVENT = 1 | ||
| 25 | + | ||
| 26 | +# Declare shared Acc/Vec groups once at kernel scope, before either section. | ||
| 27 | +# A group created inside section_vector and referenced by section_cube lowers | ||
| 28 | +# to an unregistered block.current on the current A5 frontend. Use unique mutex | ||
| 29 | +# ids in [0, 31] and disjoint addresses in each memory space. Both sections call | ||
| 30 | +# current() on this exact one-slot group; never create a second cursor with the | ||
| 31 | +# same mutex id. | ||
| 32 | +vec_mailbox_g = pl.make_tile_group( | ||
| 33 | + type=vec_mailbox_type, | ||
| 34 | + addrs=VEC_MAILBOX_ADDR, | ||
| 35 | + mutex_ids=[VEC_MAILBOX_MUTEX], | ||
| 36 | +) | ||
| 37 | + | ||
| 38 | +with pl.section_cube(): | ||
| 39 | + vec_mailbox_cube = vec_mailbox_g.current() | ||
| 40 | + # Both AIV lanes seed FREE before the first producer wait. | ||
| 41 | + pl.system.wait_cross_core( | ||
| 42 | + pipe=pl.PipeType.FIX, | ||
| 43 | + event_id=MAILBOX_FREE_EVENT, | ||
| 44 | + sync_mode=pl.CrossCoreSyncMode.INTRA_BLOCK, | ||
| 45 | + ) | ||
| 46 | + | ||
| 47 | + cube_producer_body(acc_tile) | ||
| 48 | + pl.move( | ||
| 49 | + vec_mailbox_cube, | ||
| 50 | + acc_tile, | ||
| 51 | + acc_to_vec_mode=pl.AccToVecMode.DualModeSplitM, | ||
| 52 | + ) | ||
| 53 | + pl.system.set_cross_core( | ||
| 54 | + pipe=pl.PipeType.FIX, | ||
| 55 | + event_id=READY_EVENT, | ||
| 56 | + sync_mode=pl.CrossCoreSyncMode.INTRA_BLOCK, | ||
| 57 | + ) | ||
| 58 | + | ||
| 59 | +with pl.section_vector(): | ||
| 60 | + vec_mailbox_aiv = vec_mailbox_g.current() | ||
| 61 | + sub_id = pl.get_subblock_idx() | ||
| 62 | + valid_m_even = (valid_m + 1) // 2 * 2 | ||
| 63 | + vec0_rows = valid_m_even // 2 | ||
| 64 | + if sub_id == 0: | ||
| 65 | + sub_row_base = 0 | ||
| 66 | + sub_rows = vec0_rows | ||
| 67 | + else: | ||
| 68 | + sub_row_base = vec0_rows | ||
| 69 | + sub_rows = valid_m - vec0_rows | ||
| 70 | + | ||
| 71 | + # Do not replace this logical split with sub_id * physical_half. A | ||
| 72 | + # block_dim launch that returns proves only liveness, not odd-tail mapping. | ||
| 73 | + | ||
| 74 | + # Every subblock participates even when sub_rows == 0. | ||
| 75 | + pl.system.set_cross_core( | ||
| 76 | + pipe=pl.PipeType.V, | ||
| 77 | + event_id=MAILBOX_FREE_EVENT, | ||
| 78 | + sync_mode=pl.CrossCoreSyncMode.INTRA_BLOCK, | ||
| 79 | + ) | ||
| 80 | + | ||
| 81 | + pl.system.wait_cross_core( | ||
| 82 | + pipe=pl.PipeType.V, | ||
| 83 | + event_id=READY_EVENT, | ||
| 84 | + sync_mode=pl.CrossCoreSyncMode.INTRA_BLOCK, | ||
| 85 | + ) | ||
| 86 | + | ||
| 87 | + if sub_rows > 0: | ||
| 88 | + vector_consumer_body( | ||
| 89 | + vec_mailbox_aiv, sub_row_base, sub_rows, vector_scratch_or_output, | ||
| 90 | + ) | ||
| 91 | + | ||
| 92 | + # This example finishes reading the mailbox on V. If GM MTE3 reads the | ||
| 93 | + # mailbox directly, release on MTE3 instead. If VF first copies into a | ||
| 94 | + # separate BF16 store tile, release the mailbox here on V and protect the | ||
| 95 | + # store tile with a different FREE event produced on MTE3. Never alternate | ||
| 96 | + # V and MTE3 producers on one FREE event to represent two resources. | ||
| 97 | + pl.system.set_cross_core( | ||
| 98 | + pipe=pl.PipeType.V, | ||
| 99 | + event_id=MAILBOX_FREE_EVENT, | ||
| 100 | + sync_mode=pl.CrossCoreSyncMode.INTRA_BLOCK, | ||
| 101 | + ) | ||
| 102 | + | ||
| 103 | +# Stage-A probe acceptance pseudocode (keep outside the kernel): | ||
| 104 | +# for valid_m in required_aligned_and_odd_tails: | ||
| 105 | +# run_with_watchdog(real_block_dim, production_task_mapping) | ||
| 106 | +# assert bit_exact(valid_rows) | ||
| 107 | +# assert invalid_rows_unchanged() | ||
| 108 | +# only_then_run_full_operator() | ||
| 109 | +# | ||
| 110 | +# For a cross-barrier production topology, extend the probe before acceptance: | ||
| 111 | +# seed_free_tokens() | ||
| 112 | +# run_first_message_wave() | ||
| 113 | +# pl.system.sync_all(core_type=pl.SyncCoreType.MIX) | ||
| 114 | +# run_second_message_wave_with_the_same_tokens() | ||
| 115 | +# | ||
| 116 | +# REPEATED-TASK CLOSURE (optional, required when one physical core runs more | ||
| 117 | +# than one logical mailbox task in the same epoch): | ||
| 118 | +# | ||
| 119 | +# AIC task end: | ||
| 120 | +# wait(MAILBOX_FREE_EVENT) # drain the final mailbox ack | ||
| 121 | +# wait(STORE_FREE_EVENT) # drain the final MTE3/store ack | ||
| 122 | +# pl.system.bar_all() # local PIPE_ALL after final event op | ||
| 123 | +# | ||
| 124 | +# AIV task end: | ||
| 125 | +# set(STORE_FREE_EVENT, MTE3) # final store lifetime is complete | ||
| 126 | +# pl.system.bar_all() # local PIPE_ALL after final event op | ||
| 127 | +# | ||
| 128 | +# After the drains, outstanding event credit is zero. A later task may omit | ||
| 129 | +# its first FREE wait only because the previous task and both local barriers | ||
| 130 | +# proved the physical resources reusable; it is NOT consuming a saved/FIFO | ||
| 131 | +# event token. The remaining messages wait on acknowledgements generated by | ||
| 132 | +# their own task. Do not put either bar_all under `sub_rows > 0`. | ||
| 133 | +# | ||
| 134 | +# This closure does not allow tokens to cross sync_all(MIX), and `bar_all()` is | ||
| 135 | +# not a replacement for MIX. A real gate must exercise per-core depths just | ||
| 136 | +# below and at the observed failure threshold, the production uneven owner | ||
| 137 | +# distribution, and the maximum dynamic task count. MlaProlog needed depths | ||
| 138 | +# 3, 4, uneven 4/5, and dynamic 36/37 (1024 tasks over 28 cores). | ||
| 139 | + | ||
| 140 | +# DUAL-RING AMORTIZATION (optional, after the one-ring protocol is proved): | ||
| 141 | +# | ||
| 142 | +# for message_id in physical_band: | ||
| 143 | +# ring = message_id & 1 | ||
| 144 | +# # ring 0/1 use disjoint Acc slots, Vec addresses, mutexes and event ids | ||
| 145 | +# wait(FREE_EVENT[ring]) | ||
| 146 | +# publish(MAILBOX[ring]) | ||
| 147 | +# set(READY_EVENT[ring]) | ||
| 148 | +# consume(MAILBOX[ring]) | ||
| 149 | +# set(FREE_EVENT[ring]) | ||
| 150 | +# wait(FREE_EVENT[0]) | ||
| 151 | +# wait(FREE_EVENT[1]) | ||
| 152 | +# pl.system.bar_all() # once per engine after its last event operation | ||
| 153 | +# | ||
| 154 | +# Do not alias either ring or share its READY/FREE pair. Audit generated CCE by | ||
| 155 | +# physical address/mutex/event identity through last-read -> FREE -> next READY, | ||
| 156 | +# then require full official-shape bit-exact in addition to the microprobe. | ||
| @@ -0,0 +1,99 @@ | |||
| 1 | +# PyPTO-Pro multi-stage task-flatten fragments. | ||
| 2 | +# This is not a standalone kernel. Replace shapes, groups and stage bodies | ||
| 3 | +# from DESIGN.md. Keep the numerical dataflow unchanged in the first sweep. | ||
| 4 | + | ||
| 5 | +HAS_SUBBLOCK_NUM = hasattr(pl, "get_subblock_num") | ||
| 6 | +# Keep this False until a locked target run proves that both AIV subblocks may | ||
| 7 | +# issue the stage's address-disjoint GM traffic. The conservative path below | ||
| 8 | +# uses only subblock 0. This is a module-load Python constant, not a runtime | ||
| 9 | +# branch in the generated kernel. | ||
| 10 | +USE_BOTH_AIV_SUBBLOCKS = False | ||
| 11 | +# Core identity is derived *inside each section*, never once at kernel scope. | ||
| 12 | +# `get_block_idx()` lowers differently for AIC and AIV, so a single kernel-scope | ||
| 13 | +# value captured by both sections is not one number -- it is two, and the Cube | ||
| 14 | +# and Vector owner maps silently disagree. The cost of recomputing it is a | ||
| 15 | +# scalar; the cost of sharing it is a wrong owner map that still runs. | ||
| 16 | +# | ||
| 17 | +# Current AIV backends expose 2 * physical_block + subblock. Older snapshots | ||
| 18 | +# exposed physical_block directly and did not have get_subblock_num(). Because | ||
| 19 | +# HAS_SUBBLOCK_NUM is a module-load Python constant, the old parser drops the | ||
| 20 | +# unsupported branch before constructing IR. | ||
| 21 | + | ||
| 22 | +with pl.section_cube(): | ||
| 23 | + cube_raw_core_id = pl.get_block_idx() | ||
| 24 | + cube_num_cores = pl.get_block_num() | ||
| 25 | + if HAS_SUBBLOCK_NUM: | ||
| 26 | + physical_id = cube_raw_core_id // pl.get_subblock_num() | ||
| 27 | + else: | ||
| 28 | + physical_id = cube_raw_core_id | ||
| 29 | + | ||
| 30 | + total_cube_tasks = row_tiles * output_tiles | ||
| 31 | + if physical_id < cube_num_cores: | ||
| 32 | + for task in pl.range(physical_id, total_cube_tasks, cube_num_cores): | ||
| 33 | + mt = task // output_tiles | ||
| 34 | + nt = task % output_tiles | ||
| 35 | + # Load and compute exactly one disjoint [mt, nt] output tile. | ||
| 36 | + # Write the stage body inline: the parser walks a `@pl.jit` body as | ||
| 37 | + # an AST and never executes it, so it cannot follow a call into a | ||
| 38 | + # plain Python helper. | ||
| 39 | + ... # loads, matmul phase chain and store for [mt, nt] | ||
| 40 | + | ||
| 41 | + # Producer side: every launched AIC reaches this barrier. | ||
| 42 | + pl.system.sync_all(core_type=pl.SyncCoreType.MIX) | ||
| 43 | + | ||
| 44 | +with pl.section_vector(): | ||
| 45 | + # Consumer side paired with the preceding Cube barrier. | ||
| 46 | + pl.system.sync_all(core_type=pl.SyncCoreType.MIX) | ||
| 47 | + # Same rule as the Cube section: derive identity here, not at kernel scope. | ||
| 48 | + vec_raw_core_id = pl.get_block_idx() | ||
| 49 | + vec_num_cores = pl.get_block_num() | ||
| 50 | + if HAS_SUBBLOCK_NUM: | ||
| 51 | + physical_id = vec_raw_core_id // pl.get_subblock_num() | ||
| 52 | + else: | ||
| 53 | + physical_id = vec_raw_core_id | ||
| 54 | + sub_id = pl.get_subblock_idx() | ||
| 55 | + | ||
| 56 | + # Conservative path: both AIV subblocks may share MTE, so only subblock 0 | ||
| 57 | + # issues GM traffic. Use this until the exact target/stage has a dual-lane | ||
| 58 | + # correctness and liveness proof. | ||
| 59 | + if not USE_BOTH_AIV_SUBBLOCKS and sub_id == 0 and physical_id < vec_num_cores: | ||
| 60 | + total_vec_tasks = row_tiles * output_chunks | ||
| 61 | + for task in pl.range(physical_id, total_vec_tasks, vec_num_cores): | ||
| 62 | + mt = task // output_chunks | ||
| 63 | + chunk = task % output_chunks | ||
| 64 | + ... # vector stage body, written inline (see the Cube note above) | ||
| 65 | + | ||
| 66 | + # Proven dual-lane path: flatten independent logical groups over every raw | ||
| 67 | + # AIV worker. `group_rows` is part of the numerical ABI: keep the same | ||
| 68 | + # per-group payload/reduction order and narrow only valid rows on the tail. | ||
| 69 | + # Before setting USE_BOTH_AIV_SUBBLOCKS=True, exhaustively prove one writer | ||
| 70 | + # per group and run alternating-shape A5 tests for MTE/stale-output faults. | ||
| 71 | + if USE_BOTH_AIV_SUBBLOCKS: | ||
| 72 | + subblock_count = pl.get_subblock_num() | ||
| 73 | + aiv_worker = physical_id * subblock_count + sub_id | ||
| 74 | + aiv_workers = vec_num_cores * subblock_count | ||
| 75 | + group_rows = 4 | ||
| 76 | + logical_groups = (rows + group_rows - 1) // group_rows | ||
| 77 | + for group in pl.range(aiv_worker, logical_groups, aiv_workers): | ||
| 78 | + row_off = group * group_rows | ||
| 79 | + valid_rows = pl.min(group_rows, rows - row_off) | ||
| 80 | + vector_group_body(row_off, valid_rows) | ||
| 81 | + | ||
| 82 | + # Never move this barrier into the sub_id or tail guard. | ||
| 83 | + pl.system.sync_all(core_type=pl.SyncCoreType.MIX) | ||
| 84 | + | ||
| 85 | +with pl.section_cube(): | ||
| 86 | + # Paired consumer side for the preceding Vector barrier. | ||
| 87 | + pl.system.sync_all(core_type=pl.SyncCoreType.MIX) | ||
| 88 | + # Next flattened Cube stage follows the same unique-writer pattern. | ||
| 89 | + ... # next flattened Cube stage, written inline | ||
| 90 | + | ||
| 91 | +# Multi-wave vector ownership must be expressed in the vector chunk domain. | ||
| 92 | +# Do not use a head count as a chunk count. For example, a 72/56 head split | ||
| 93 | +# with per_head_width=512 and vector_width=128 owns 288/224 chunks, not 72/56 | ||
| 94 | +# and not a doubled 576/448. Audit both disjointness and exact total coverage. | ||
| 95 | +chunks_per_head = per_head_width // vector_width | ||
| 96 | +wave0_chunks = wave0_heads * chunks_per_head | ||
| 97 | +wave1_chunks = wave1_heads * chunks_per_head | ||
| 98 | +total_chunks = total_heads * chunks_per_head | ||
| 99 | +assert wave0_chunks + wave1_chunks == total_chunks | ||
| @@ -0,0 +1,37 @@ | |||
| 1 | +# PyPTO-Pro single-JIT compile-time resource specialization. | ||
| 2 | +# Keep the wrapper at one launch and verify every emitted key-specific IR. | ||
| 3 | + | ||
| 4 | +from pypto_pro.runtime.tilingkey import TilingKeyField | ||
| 5 | + | ||
| 6 | + | ||
| 7 | +class KernelModeKey: | ||
| 8 | + KernelMode = TilingKeyField(bits=1, values=[0, 1]) | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +@pl.jit(auto_mutex=True, tiling_key=KernelModeKey) | ||
| 12 | +def fused_kernel(public_tensor, conservative_workspace, optimized_workspace): | ||
| 13 | + # KernelMode is injected by the frontend. The branch must disappear from | ||
| 14 | + # emitted IR; do not replace it with a runtime tensor-shape condition. | ||
| 15 | + # | ||
| 16 | + # Both branch bodies are written out here in full. A `@pl.jit` body is an | ||
| 17 | + # AST the parser walks but never executes, so it cannot follow a call into | ||
| 18 | + # a plain Python helper -- the call surfaces as a pybind "incompatible | ||
| 19 | + # constructor arguments" error far from the mistake. Eliminating the branch | ||
| 20 | + # at compile time does not change that: whichever body survives still has | ||
| 21 | + # to be inline. Inline it, or lift it to a value the parser can see. | ||
| 22 | + if KernelMode == 0: # noqa: F821 | ||
[P1] tiling-key 分支仍调用了不可解析的普通 helper 问题:两个编译期分支的主体是普通 Python helper 调用;即使 tiling key 能消除分支,也不能证明 parser 会内联或跟随这些 helper。 影响:两个 key 都可能在 JIT 解析阶段失败,所谓 key-specific resource chain 无法生成。 证据:同仓 framework findings 已验证普通 helper 不能作为 kernel body 的 value-producing 调用;模板没有提供受支持的 inline 装饰或生成期展开。 建议:把每个 key 的静态资源链直接写在 JIT body,或由模板生成器文本展开;CI 分别编译两个 key,并确认生成 IR 中没有 key 引用和 Python helper 调用。 ![]() ![]() | |||
| 23 | + ... # conservative chain, written inline: tile groups, loads, matmul | ||
| 24 | + # phases and stores for the resource-conservative shape | ||
| 25 | + else: | ||
| 26 | + ... # optimized chain, written inline, same contract and precision | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def wrapper(public_tensor): | ||
| 30 | + # Host scalar metadata may choose a key. Both branches still need full | ||
| 31 | + # contract, precision, ownership and capacity validation. | ||
| 32 | + mode = 1 if use_optimized_static_mode() else 0 | ||
| 33 | + conservative_workspace = allocate_conservative_workspace() | ||
| 34 | + optimized_workspace = allocate_optimized_workspace() | ||
| 35 | + fused_kernel[None, block_dim, {"KernelMode": mode}]( | ||
| 36 | + public_tensor, conservative_workspace, optimized_workspace, | ||
| 37 | + ) | ||
| @@ -0,0 +1,56 @@ | |||
| 1 | +# PyPTO-Pro typed TileGroups that reuse one physical arena across hard stages. | ||
| 2 | +# Replace symbolic IDs/addresses and prove the live intervals for the operator. | ||
| 3 | + | ||
| 4 | +RHS_BASE = 0x00000 | ||
| 5 | +NARROW_BYTES = TK * TN * 2 | ||
| 6 | +WIDE_BYTES = TK * (2 * TN) * 2 | ||
| 7 | + | ||
| 8 | +assert 2 * NARROW_BYTES <= L0B_CAPACITY | ||
| 9 | +assert WIDE_BYTES <= L0B_CAPACITY | ||
| 10 | + | ||
| 11 | +narrow_rhs_g = pl.make_tile_group( | ||
| 12 | + type=pl.TileType( | ||
| 13 | + shape=[TK, TN], dtype=pl.DT_BF16, | ||
| 14 | + target_memory=pl.MemorySpace.Right, layout=pl.ZN, | ||
| 15 | + valid_shape=[-1, -1], compact=1, | ||
| 16 | + ), | ||
| 17 | + addrs=RHS_BASE, | ||
| 18 | + # Two values are consumed together, so two physical slots are mandatory. | ||
| 19 | + mutex_ids=[NARROW_RHS_0, NARROW_RHS_1], | ||
| 20 | +) | ||
| 21 | + | ||
| 22 | +wide_rhs_g = pl.make_tile_group( | ||
| 23 | + type=pl.TileType( | ||
| 24 | + shape=[TK, 2 * TN], dtype=pl.DT_BF16, | ||
| 25 | + target_memory=pl.MemorySpace.Right, layout=pl.ZN, | ||
| 26 | + valid_shape=[-1, -1], compact=1, | ||
| 27 | + ), | ||
| 28 | + # Physical alias with narrow_rhs_g is safe only across proved hard stages. | ||
| 29 | + addrs=RHS_BASE, | ||
| 30 | + mutex_ids=[WIDE_RHS_0], | ||
| 31 | +) | ||
| 32 | + | ||
| 33 | +with pl.section_cube(): | ||
| 34 | + run_stage_1_with_narrow_rhs(narrow_rhs_g) | ||
| 35 | + | ||
| 36 | +# Every launched AIC/AIV lane must reach this unconditionally. auto_mutex does | ||
| 37 | +# not discover that two differently typed groups alias the same address. | ||
| 38 | +pl.system.sync_all(core_type=pl.SyncCoreType.MIX) | ||
| 39 | + | ||
| 40 | +with pl.section_cube(): | ||
| 41 | + run_stage_2_with_wide_rhs(wide_rhs_g) | ||
| 42 | + | ||
| 43 | +pl.system.sync_all(core_type=pl.SyncCoreType.MIX) | ||
| 44 | + | ||
| 45 | +with pl.section_cube(): | ||
| 46 | + run_stage_3_with_narrow_rhs(narrow_rhs_g) | ||
| 47 | + | ||
| 48 | +# Gate each stage on target A5. pl.move compares physical TileType shapes: | ||
| 49 | +# setting wide_rhs_g valid_shape to TN does not permit a [TK,TN] Mat -> | ||
| 50 | +# [TK,2*TN] Right move. offset extracts from a larger source; it does not place | ||
| 51 | +# a narrow source into a wider destination. | ||
| 52 | + | ||
| 53 | +# If tuning makes both stages use the exact same physical TileType, replace the | ||
| 54 | +# two declarations above with one shared group and pass that group to both | ||
| 55 | +# helpers. This saves kernel-global mutex IDs and avoids typed address aliases. | ||
| 56 | +# Do not apply this merely because valid_shape happens to match at runtime. | ||
| @@ -0,0 +1,67 @@ | |||
| 1 | +# PyPTO-Pro A5 VF scalar-broadcast dot-product fragment. | ||
| 2 | +# | ||
| 3 | +# This is not a standalone kernel. Replace panel dimensions, tile strides, | ||
| 4 | +# masks and compensation with the operator's frozen design. A normal | ||
| 5 | +# vf.load_align is a register-width load even when its offset names one scalar. | ||
| 6 | +# CCE and a one-row probe are insufficient: separately gate a multi-row loop | ||
| 7 | +# on the target A5 because repeated panel MTE loads have shown shape-sensitive | ||
| 8 | +# 507015 failures that are not visible in generated-code checks. | ||
| 9 | + | ||
| 10 | +@pl.vector_function | ||
| 11 | +def accumulate_panel_vf( | ||
| 12 | + lhs, | ||
| 13 | + weight_panel, | ||
| 14 | + high_tile, | ||
| 15 | + low_tile, | ||
| 16 | + valid_rows: pl.DT_INT64, | ||
| 17 | +): | ||
| 18 | + predicate = vf.update_mask(OUTPUT_WIDTH, dtype=pl.DT_FP32) | ||
| 19 | + for row in pl.range(0, valid_rows): | ||
| 20 | + lhs_row = row * LHS_ROW_STRIDE | ||
| 21 | + state_row = row * STATE_ROW_STRIDE | ||
| 22 | + high = vf.load_align(high_tile, state_row) | ||
| 23 | + low = vf.load_align(low_tile, state_row) | ||
| 24 | + | ||
| 25 | + for group in pl.range(0, PANEL_K // GROUP_K): | ||
| 26 | + group_sum = vf.full(0.0, predicate, dtype=pl.DT_FP32) | ||
| 27 | + for inner in pl.range(0, GROUP_K): | ||
| 28 | + k = group * GROUP_K + inner | ||
| 29 | + scalar = vf.load_align( | ||
| 30 | + lhs, | ||
| 31 | + lhs_row + k, | ||
| 32 | + dist=pl.LoadDist.BRC_B32, | ||
| 33 | + ) | ||
| 34 | + weight = vf.load_align( | ||
| 35 | + weight_panel, | ||
| 36 | + k * WEIGHT_ROW_STRIDE, | ||
| 37 | + ) | ||
| 38 | + # One VF call per statement: the API is a three-address | ||
| 39 | + # call model, so a value-producing VF call cannot be nested as | ||
| 40 | + # another call's argument. Bind each intermediate first. | ||
| 41 | + weighted = vf.mul(weight, scalar, predicate) | ||
| 42 | + group_sum = vf.add( | ||
[P1] VF 模板使用了当前 DSL 不支持的嵌套表达式 问题:这里把 影响:模板生成的数值路径会在 parser 阶段失败,无法作为可复用实现片段。 证据:本 PR 的 DSL limitations 明确记录 建议:每个 VF 调用落到独立临时变量后再传入下一条指令;为该模板增加最小实例的 parser/codegen 测试。 ![]() ![]() | |||
| 43 | + group_sum, | ||
| 44 | + weighted, | ||
| 45 | + predicate, | ||
| 46 | + ) | ||
| 47 | + | ||
| 48 | + # Optional TwoSum state. Remove only after the real checker proves | ||
| 49 | + # that cancellation is irrelevant for this output. | ||
| 50 | + updated = vf.add(high, group_sum, predicate) | ||
| 51 | + bridge = vf.sub(updated, high, predicate) | ||
| 52 | + recovered = vf.sub(updated, bridge, predicate) | ||
| 53 | + high_error = vf.sub(high, recovered, predicate) | ||
| 54 | + group_error = vf.sub(group_sum, bridge, predicate) | ||
| 55 | + carried = vf.add(high_error, group_error, predicate) | ||
| 56 | + low = vf.add( | ||
| 57 | + low, | ||
| 58 | + carried, | ||
| 59 | + predicate, | ||
| 60 | + ) | ||
| 61 | + high = updated | ||
| 62 | + | ||
| 63 | + vf.store_align(high_tile + state_row, high, predicate) | ||
| 64 | + vf.store_align(low_tile + state_row, low, predicate) | ||
| 65 | + | ||
| 66 | + # Required when a following Tile cast or VF call reads these scratch tiles. | ||
| 67 | + vf.mem_bar(mode=pl.MemBarMode.VST_VLD) | ||
| @@ -0,0 +1,294 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +"""Drive a @pl.jit kernel to codegen without an NPU, and say where it stopped. | ||
| 11 | + | ||
| 12 | +``_TileJitKernel.__call__`` splits into ``_ensure_compiled(args)`` and then the | ||
| 13 | +launch, so compilation can be driven with **CPU** tensors. Parse errors, wrong | ||
| 14 | +argument order, bad tile shapes, address problems and IR failures all surface | ||
| 15 | +here, needing neither a device nor the device lock. | ||
| 16 | + | ||
| 17 | +The point of this script is to separate two failures that both raise | ||
| 18 | +``RuntimeError``: | ||
| 19 | + | ||
| 20 | +* the kernel is wrong -- parse or IR or codegen never produced a source file; | ||
| 21 | +* the toolchain cannot build for this target -- source was generated fine and | ||
| 22 | + the backend compiler rejected it. | ||
| 23 | + | ||
| 24 | +It decides between them by looking for the generated ``kernel.cpp`` and for the | ||
| 25 | +signature of a toolchain that does not know the target architecture. | ||
| 26 | + | ||
| 27 | +Usage | ||
| 28 | +----- | ||
| 29 | + python tools/verify_codegen.py custom/<op>/test_<op>.py --op <op> | ||
| 30 | +""" | ||
| 31 | + | ||
| 32 | +from __future__ import annotations | ||
| 33 | + | ||
| 34 | +import argparse | ||
| 35 | +import importlib.util | ||
| 36 | +import logging | ||
| 37 | +import re | ||
| 38 | +import sys | ||
| 39 | +import time | ||
| 40 | +import traceback | ||
| 41 | +from pathlib import Path | ||
| 42 | + | ||
| 43 | +import torch | ||
| 44 | + | ||
| 45 | +LOGGER = logging.getLogger(__name__) | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +class VerifyError(RuntimeError): | ||
| 49 | + """A kernel this script cannot inspect -- reported, then exit 1. | ||
| 50 | + | ||
| 51 | + Raised instead of ``SystemExit`` so the helpers stay callable from another | ||
| 52 | + module: ``SystemExit`` derives from ``BaseException``, so a caller's | ||
| 53 | + ``except Exception`` does not see it and the process dies inside what was | ||
| 54 | + meant to be a recoverable call. Only ``__main__`` turns this into an exit. | ||
| 55 | + """ | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +# Signature of a backend that does not recognise the A5 target: the aicore | ||
| 59 | +# attribute is a compiler builtin on the device path, and its absence means the | ||
| 60 | +# arch flag was not honoured. Not a kernel defect. | ||
| 61 | +_TOOLCHAIN_MARKERS = ( | ||
| 62 | + "unknown type name '__aicore__'", | ||
| 63 | + "unknown type name '__gm__'", | ||
| 64 | +) | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +def load_module(path: Path): | ||
| 68 | + spec = importlib.util.spec_from_file_location(path.stem, path) | ||
| 69 | + mod = importlib.util.module_from_spec(spec) | ||
| 70 | + sys.modules[path.stem] = mod | ||
| 71 | + spec.loader.exec_module(mod) | ||
| 72 | + return mod | ||
| 73 | + | ||
| 74 | + | ||
| 75 | +# Annotations stringify with the short dtype spelling -- a 3-D dynamic fp16 | ||
| 76 | +# tensor renders roughly as three nested DYNAMIC dims followed by "fp16" -- | ||
| 77 | +# so match those rather than the DT_* constant names used in source. | ||
| 78 | +_PL_TO_TORCH = { | ||
| 79 | + "fp16": torch.float16, "float16": torch.float16, | ||
| 80 | + "bf16": torch.bfloat16, "bfloat16": torch.bfloat16, | ||
| 81 | + "fp32": torch.float32, "float32": torch.float32, | ||
| 82 | + "int8": torch.int8, "uint8": torch.uint8, | ||
| 83 | + "int32": torch.int32, "int64": torch.int64, | ||
| 84 | +} | ||
| 85 | +# Spellings are not uniform: fp16 stringifies as "fp16" but bf16 as "bfloat16". | ||
| 86 | +# Longest alternatives first so "bfloat16" is not shadowed by a shorter match. | ||
| 87 | +_DTYPE_RE = re.compile( | ||
| 88 | + r"\b(bfloat16|float16|float32|uint8|int64|int32|int8|fp16|fp32|bf16)\b") | ||
| 89 | + | ||
| 90 | + | ||
| 91 | +def kernel_function(kernel): | ||
| 92 | + """The decorated function, which is where the annotations live. | ||
| 93 | + | ||
| 94 | + ``signature(kernel)`` gives the launch wrapper's ``(*args, **kwargs)``, not | ||
| 95 | + the kernel's parameters. | ||
| 96 | + """ | ||
| 97 | + for attr in ("_func", "fn", "_fn", "func", "__wrapped__"): | ||
| 98 | + fn = getattr(kernel, attr, None) | ||
| 99 | + if fn is not None and getattr(fn, "__annotations__", None): | ||
| 100 | + return fn | ||
| 101 | + raise VerifyError("cannot find the decorated function behind the kernel object") | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +def jit_internal(kernel, name: str): | ||
| 105 | + """A ``@pl.jit`` internal, resolved by name. | ||
| 106 | + | ||
| 107 | + ``_TileJitKernel`` splits ``__call__`` into ``_normalize_launch_args`` and | ||
| 108 | + ``_ensure_compiled``; driving the second without the launch is the whole | ||
| 109 | + point of this script, and the public surface (``__call__``) compiles *and* | ||
| 110 | + launches, so it needs a device. Resolving by name -- the same way | ||
| 111 | + ``kernel_function`` above finds the decorated function -- keeps the reach | ||
| 112 | + into framework internals explicit, and turns a rename upstream into a named | ||
| 113 | + failure here instead of an AttributeError deep inside the call. | ||
| 114 | + """ | ||
| 115 | + hook = getattr(kernel, name, None) | ||
| 116 | + if hook is None: | ||
| 117 | + raise VerifyError( | ||
| 118 | + f"this pypto_pro build's kernel object has no {name!r}; the launch " | ||
| 119 | + f"path has been renamed and this script needs updating") | ||
| 120 | + return hook | ||
| 121 | + | ||
| 122 | + | ||
| 123 | +def make_args(kernel, rows: int, cols: int) -> list: | ||
| 124 | + """CPU stand-ins built from the kernel's declared annotations. | ||
| 125 | + | ||
| 126 | + Only rank and dtype matter for compilation; extents are free. The raw | ||
| 127 | + annotation is printed for any parameter that cannot be read, so a parsing | ||
| 128 | + failure is diagnosable without another round trip. | ||
| 129 | + """ | ||
| 130 | + fn = kernel_function(kernel) | ||
| 131 | + args = [] | ||
| 132 | + for name, ann_obj in fn.__annotations__.items(): | ||
| 133 | + if name == "return": | ||
| 134 | + continue | ||
| 135 | + ann = str(ann_obj) | ||
| 136 | + m = _DTYPE_RE.search(ann) | ||
| 137 | + dtype = _PL_TO_TORCH[m.group(1)] if m else None | ||
| 138 | + if dtype is None: | ||
| 139 | + raise VerifyError(f"parameter {name!r}: no dtype in annotation {ann!r}") | ||
| 140 | + if "Tensor" not in ann and "Ptr" not in ann: | ||
| 141 | + args.append(1e-6 if dtype.is_floating_point else 1) | ||
| 142 | + continue | ||
| 143 | + # Shape entries are whatever sits in the first bracketed group; count | ||
| 144 | + # them for the rank and look for a literal leading 1. | ||
| 145 | + inner = re.search(r"\[\s*([^\[\]]*?)\s*\]", ann) | ||
| 146 | + entries = [e.strip() for e in inner.group(1).split(",")] if inner else [] | ||
| 147 | + entries = [e for e in entries if e] | ||
| 148 | + rank = len(entries) or 2 | ||
| 149 | + if rank == 1: | ||
| 150 | + shape = (cols,) | ||
| 151 | + elif entries and entries[0] == "1": | ||
| 152 | + shape = (1, cols) | ||
| 153 | + else: | ||
| 154 | + shape = (rows, cols) if rank == 2 else (1,) * (rank - 2) + (rows, cols) | ||
| 155 | + args.append(torch.zeros(shape, dtype=dtype)) | ||
| 156 | + LOGGER.info(" %-12s %-52s -> %s %s", name, ann[:52], tuple(shape), dtype) | ||
| 157 | + return args | ||
| 158 | + | ||
| 159 | + | ||
| 160 | +def main(argv=None) -> int: | ||
| 161 | + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | ||
| 162 | + ap.add_argument("path", type=Path) | ||
| 163 | + ap.add_argument("--op", required=True) | ||
| 164 | + ap.add_argument("--rows", type=int, default=8) | ||
| 165 | + ap.add_argument("--cols", type=int, default=128) | ||
| 166 | + args = ap.parse_args(argv) | ||
| 167 | + | ||
| 168 | + sys.path.insert(0, str(args.path.parent)) | ||
| 169 | + LOGGER.info("== loading %s", args.path) | ||
| 170 | + try: | ||
| 171 | + mod = load_module(args.path) | ||
| 172 | + except Exception: | ||
| 173 | + LOGGER.info("RESULT: FAIL_IMPORT -- module did not import") | ||
| 174 | + traceback.print_exc() | ||
| 175 | + return 2 | ||
| 176 | + LOGGER.info(" import ok") | ||
| 177 | + | ||
| 178 | + kernel = getattr(mod, f"{args.op}_kernel", None) | ||
| 179 | + if kernel is None: | ||
| 180 | + LOGGER.info("RESULT: FAIL_IMPORT -- no %s_kernel in module", args.op) | ||
| 181 | + return 2 | ||
| 182 | + | ||
| 183 | + for entry in (f"{args.op}_wrapper", args.op): | ||
| 184 | + if not callable(getattr(mod, entry, None)): | ||
| 185 | + LOGGER.info("RESULT: FAIL_CONTRACT -- missing entry point %s", entry) | ||
| 186 | + return 2 | ||
| 187 | + LOGGER.info(" entry points %s_wrapper / %s present", args.op, args.op) | ||
| 188 | + | ||
| 189 | + LOGGER.info("== compiling with CPU tensors (%sx%s)", args.rows, args.cols) | ||
| 190 | + # Built outside the guard below: that except is for the framework rejecting | ||
| 191 | + # the arguments (FAIL_SIGNATURE), not for this script failing to read the | ||
| 192 | + # annotations. A VerifyError from make_args is now an ordinary Exception, so | ||
| 193 | + # leaving the call inside would relabel "I cannot parse this kernel" as | ||
| 194 | + # "the kernel's signature is wrong" and return 3 instead of exiting 1. | ||
| 195 | + cpu_args = tuple(make_args(kernel, args.rows, args.cols)) | ||
| 196 | + # Both hooks are resolved outside their guards for the same reason: a | ||
| 197 | + # renamed internal is a defect in this script, not in the kernel, and must | ||
| 198 | + # not be reported as FAIL_SIGNATURE or as a backend failure. | ||
| 199 | + normalize = jit_internal(kernel, "_normalize_launch_args") | ||
| 200 | + ensure_compiled = jit_internal(kernel, "_ensure_compiled") | ||
| 201 | + try: | ||
| 202 | + kargs = normalize(cpu_args, {}) | ||
| 203 | + except Exception: | ||
| 204 | + LOGGER.info("RESULT: FAIL_SIGNATURE -- launch arguments rejected") | ||
| 205 | + traceback.print_exc() | ||
| 206 | + return 3 | ||
| 207 | + LOGGER.info(" normalize ok, %d args", len(kargs)) | ||
| 208 | + | ||
| 209 | + # The backend's stderr is reported through logging, not raised, so capture | ||
| 210 | + # it -- otherwise a toolchain failure is indistinguishable from a kernel bug. | ||
| 211 | + import io | ||
| 212 | + | ||
| 213 | + captured = io.StringIO() | ||
| 214 | + handler = logging.StreamHandler(captured) | ||
| 215 | + handler.setLevel(logging.DEBUG) | ||
| 216 | + logging.getLogger().addHandler(handler) | ||
| 217 | + logging.getLogger().setLevel(logging.DEBUG) | ||
| 218 | + | ||
| 219 | + # Stamped before the build so the artifact scan below can prove an emitted | ||
| 220 | + # source belongs to *this* invocation. | ||
| 221 | + started_at = time.time() | ||
| 222 | + | ||
| 223 | + err_text = "" | ||
| 224 | + try: | ||
| 225 | + ensure_compiled(kargs) | ||
| 226 | + LOGGER.info("RESULT: PASS_COMPILE -- kernel built to a loadable library") | ||
| 227 | + return 0 | ||
| 228 | + except Exception as exc: | ||
| 229 | + err_text = f"{type(exc).__name__}: {exc}" | ||
| 230 | + finally: | ||
| 231 | + logging.getLogger().removeHandler(handler) | ||
| 232 | + err_text += "\n" + captured.getvalue() | ||
| 233 | + | ||
| 234 | + # Did codegen actually emit a source file *in this run*? | ||
| 235 | + # | ||
| 236 | + # Taking the newest build/**/kernel.cpp unconditionally let a previous run's | ||
| 237 | + # artifact stand in for this one: a kernel that failed before codegen would | ||
| 238 | + # find an older source plus its toolchain-marker log and be reported as | ||
| 239 | + # PASS_CODEGEN_TOOLCHAIN_BLOCKED, i.e. exit 0. An artifact is only evidence | ||
| 240 | + # about this kernel if this invocation wrote it, so require that. | ||
| 241 | + all_generated = sorted(Path("build").rglob("kernel.cpp")) if Path("build").is_dir() else [] | ||
| 242 | + generated = [p for p in all_generated if p.stat().st_mtime >= started_at] | ||
| 243 | + stale = len(all_generated) - len(generated) | ||
| 244 | + newest = max(generated, key=lambda p: p.stat().st_mtime) if generated else None | ||
| 245 | + | ||
| 246 | + if newest is None: | ||
| 247 | + if stale: | ||
| 248 | + LOGGER.info( | ||
| 249 | + " ignored %d pre-existing kernel.cpp under build/ -- none was written " | ||
| 250 | + "by this run", stale) | ||
| 251 | + LOGGER.info("RESULT: FAIL_CODEGEN -- no source emitted\n %s", err_text) | ||
| 252 | + return 4 | ||
| 253 | + | ||
| 254 | + text = newest.read_text(encoding="utf-8", errors="replace") | ||
| 255 | + n_lines = text.count("\n") | ||
| 256 | + LOGGER.info(" codegen emitted %s (%d lines)", newest, n_lines) | ||
| 257 | + | ||
| 258 | + # A file existing is not the same as the kernel body being translated: | ||
| 259 | + # report the emitted tile operations so an empty or signature-only source is | ||
| 260 | + # visible rather than being read as success. | ||
| 261 | + ops = re.findall(r"\b(T[A-Z][A-Za-z0-9_]*)\s*[<(]", text) | ||
| 262 | + if ops: | ||
| 263 | + counts = {} | ||
| 264 | + for o in ops: | ||
| 265 | + counts[o] = counts.get(o, 0) + 1 | ||
| 266 | + top_ops = sorted(counts.items(), key=lambda kv: -kv[1])[:10] | ||
| 267 | + summary = ", ".join(f"{k}x{v}" for k, v in top_ops) | ||
| 268 | + LOGGER.info(" emitted tile ops: %s", summary) | ||
| 269 | + else: | ||
| 270 | + LOGGER.info(" WARNING: no tile operations found in the emitted source") | ||
| 271 | + | ||
| 272 | + log = "\n".join( | ||
| 273 | + p.read_text(encoding="utf-8", errors="replace") | ||
| 274 | + for p in newest.parent.glob("*.log") | ||
| 275 | + ) | ||
| 276 | + haystack = err_text + log | ||
| 277 | + if any(m in haystack for m in _TOOLCHAIN_MARKERS): | ||
| 278 | + LOGGER.info("RESULT: PASS_CODEGEN_TOOLCHAIN_BLOCKED") | ||
| 279 | + LOGGER.info(" Source generated cleanly; the backend compiler does not know") | ||
| 280 | + LOGGER.info(" this target. Everything the DSL can check has passed.") | ||
| 281 | + return 0 | ||
| 282 | + | ||
| 283 | + LOGGER.info("RESULT: FAIL_BACKEND -- source generated but the compiler rejected it") | ||
| 284 | + LOGGER.info(" for a reason that is not the known toolchain fault:\n %s", err_text[:900]) | ||
| 285 | + return 5 | ||
| 286 | + | ||
| 287 | + | ||
| 288 | +if __name__ == "__main__": | ||
| 289 | + logging.basicConfig(level=logging.INFO, format="%(message)s") | ||
| 290 | + try: | ||
| 291 | + sys.exit(main()) | ||
| 292 | + except VerifyError as exc: | ||
| 293 | + LOGGER.error("%s", exc) | ||
| 294 | + sys.exit(1) | ||


[P1] 四个 K block 时 accumulator 永远没有 Final phase
问题:约束只要求
n_k_blocks % 4 == 0。当值恰为 4 时循环只有q == 0一次,当前if/elif只执行Partial,永远到不了 Final 分支。影响:模板生成的最小合法配置没有终止累加状态,可能无法 drain/store 或导致后续协议错误。
证据:同仓 framework findings 明确要求 accumulator 具有 terminal Final;当前分支顺序没有处理 first==last 的单迭代情况。
建议:显式处理
q == 0 && q == last,在单迭代时直接使用 Final;增加n_k_blocks=4/8的模板编译与状态机测试。