Merged
feat(conv): add PyPTO-Pro conv2d kernel sample #1129
xinweiliuAdd on 6 days ago
feat(conv): add PyPTO-Pro conv2d kernel sample #1129
Merged
Merged fromxinweiliu/pypto-gymmasterintocann/pypto-gymmaster
Total: 6 files changed+947-0
| @@ -0,0 +1,91 @@ | |||
| 1 | +--- | ||
| 2 | +name: pypto-conv-pro-high-perf | ||
| 3 | +description: 用 PyPTO-Pro 编写高性能 conv2d kernel 的方法与配置推导:按规格(fmap/weight NCHW、stride/padding/dilation、dtype、groups)正向推导 tile_shape 与分核配置,并用 CANN profiler 验证各流水占比。触发:编写 conv pypto-pro 高性能 kernel、推导 conv 算子 tile/分核配置、conv 性能调优与 profiler 验证时使用。 | ||
| 4 | +--- | ||
| 5 | + | ||
| 6 | +# Conv2D 高性能 PyPTO-Pro 实现 | ||
| 7 | + | ||
| 8 | +## 输入与输出 | ||
| 9 | + | ||
| 10 | +输入为 conv 规格列表(NCHW fmap/weight shape、stride、padding、dilation、dtype、groups)。输出为每规格的分核数与 `tile_shape=[BM, BK, BN]` 及旋钮配置(`c_out_chunk`/`l1_shape`/`l0_k`)、kernel 实现与 profiler 验证数据。 | ||
| 11 | + | ||
| 12 | +参考实现位于 gym 仓 `ops/pro/experimental/conv/`:`op_kernel/conv2d.py`(多核 kernel,含全部旋钮)、`tests/ops/experimental/conv/test_conv2d.py`(规格集与逐规格实测选优配置)。接口语义以 pto 仓 `python/pypto_pro/language/_api.py`(`img2col`/`Img2ColConfig`/`make_tile_group`/`get_block_idx`)为准。 | ||
| 13 | + | ||
| 14 | +## 实现骨架 | ||
| 15 | + | ||
| 16 | +padding 运行时化(`Img2ColConfig.padding` 接受运行时整型标量)使一个通用循环覆盖全部输出位置,不需要按窗口贴边做静态特化;kernel/stride/dilation/pad_value 仍为编译期常量,同一 tiling key 只编译一次: | ||
| 17 | + | ||
| 18 | +```text | ||
| 19 | +core_id = get_block_idx() | ||
| 20 | +chunk_idx = core_id // group_size; co_base = chunk_idx * chunk # N 维分片 | ||
| 21 | +预载:本分片 c_in_tiles×chunk 个权重槽进 L1(每核仅一次) | ||
| 22 | +for work in pl.range(row_begin, row_end): # 私有连续行区间 | ||
| 23 | + b, o = work // out_h, work % out_h | ||
| 24 | + for w0 in pl.range(0, out_w, BM * L1_M) | ||
| 25 | + 运行时 clamp 加载起点 + 四向 pad(min-window) → pos_m | ||
| 26 | + for cg(L1_K 分组) → load(fmap_l1) → for gi → for ks(l0_k 切分): | ||
| 27 | + img2col(pos_m, pos_k) → move(weight_l0, offset=[ks·k_l0, 0]) | ||
| 28 | + 首步 pl.matmul / 后续 pl.matmul_acc(l0c 累加)→ store(FixPipe 直出 NCHW) | ||
| 29 | +``` | ||
| 30 | + | ||
| 31 | +所有 tile group `depth=2`(乒乓双缓冲、互异地址、`mutex_ids='auto'`),GM→L1 加载与 img2col/matmul 流水重叠。地址表与容量断言见交付目录 `DESIGN.md`。 | ||
| 32 | + | ||
| 33 | +## 分核与展平原则(含实测教训) | ||
| 34 | + | ||
| 35 | +1. **K 方向不可分**:store 在 K 累加完成后才发生,因此 K(c_in)必须逻辑上一次全载——weight 按分片驻留时每分片仍是全 K 深度,fmap 按 l1_k 分组时每组只读一次;对 K 做分块会引发 fmap/l0c 部分和的重复搬运,属无效优化(`l0_k` 的 K 切分是 L0 步长切分、不改变 K 逻辑全载,不在此列)。 | ||
| 36 | +2. **M/N 是 L1 倍数有意义 bang 的方向**:l1_m(fmap 窗口覆盖 l1_m 个 BM 输出块)与 chunk(N 方向 c_out tile 驻留)才是有效的 L1 复用;收益前提是 L1 预算允许——若全 K 驻留迫使 M/N 缩小到 cube 利用率下降,反而劣化(大 C_in×C_out 规格:大 BN 全 K 驻留的结构 A 胜过小 BN 分 chunk 的结构 B)。 | ||
| 37 | +3. **展平维度的 div/mod 代价**:设备侧整数除/取模约几百 ns 一次。展平 (batch, row) 每核仅需 ~2 次除法(分母为编译期常量,摊薄后可忽略);再展平 w0 超级块会把每核除法次数放大数倍,实测全局慢 ~3×——**展平维度数量受每核单元数约束**:单元数/核应保持在几十以内。 | ||
| 38 | +4. **满核与拖尾**:并行单元 = B×out_h(2D 展平)。out_h < 核数时 batch 维展平消除整批空转(宽输出规格实测 +15~22%);剩余拖尾来自单元数对核数取模——N 维分核结构(已验证手段第 5 条)通过 c_out 维补满网格消除该尾差,行数不足时优先扩 chunk/c_out 分片数而非细分单元。 | ||
| 39 | + | ||
| 40 | +## K/N 放大的调优策略 | ||
| 41 | + | ||
| 42 | +1. **K 放大(BK > 16)**:仅当 `C_in % 16 == 0` 时可行(尾块补零限单 C0 帧)。BK 放大使 c_in 迭代减少、GM 载入突发加倍;**代价是 L0A 挤压 BM(`BM·K_L0 ≤ 16384`,k3 时 BK=32 → BM≤56、BK=64 → BM≤28)且裸 BK>16 触发设备 507015 崩溃**——两者都由下述 `l0_k` 解耦解决(已验证手段第 4 条),生成器应把 (BK 放大 + l0_k) 作为组合候选。1×1 卷积 K_L0=BK 不挤压 M/N:BK 16→64/128 实测 −32~70%(受控对比,M/N 不变),BK=256 收益饱和。 | ||
| 43 | +2. **N 放大(BN > 64)**:BN=128 受 L0B 双缓冲容量限制(`K_L0·BN·4 ≤ 64KiB`)——需要 weight_l0 单缓冲(depth=1,牺牲搬运流水)或更大 L0B 才可行,策略上保留候选、实现待扩展。 | ||
| 44 | +3. **L1_K(fmap 通道分组)**:`l1_k ≤ c_in_tiles`,fmap MTE2 流量 ÷ l1_k,实测 −10~35%;l1_m 空间复用在宽输入上 −40%。注意 l1_m≥2 与 l1_k≥2 联用触发 LOAD3D errcode 155、与 min-window 联用有精度问题(见边界)。 | ||
| 45 | + | ||
| 46 | +## 已验证的有效优化手段(按收益排序) | ||
| 47 | + | ||
| 48 | +1. **权重全载驻留(weight residency,整体 2.7×)**:per c_out tile 把全部 c_in 权重槽一次性预载进 L1(权重与 batch 无关,batch 循环移到预载之内),主循环只做 L1→L0B 搬运(MTE1),权重不再触 GM。实现要点:权重 tile group `depth=c_in_tiles`,预载循环与主循环的 `.next()` cursor 每 (o, w0) tile 恰好各走满一圈、自动对齐,无需运行时索引。 | ||
| 49 | +2. **fmap 提载 + c_out 内循环(fmap-hoisted chunked residency,可驻立时 +23~48%)**:fmap 窗口每个 (b, o, w0, c_in) 只读一次、被 chunk 内所有 c_out tile 复用(消除 c_out_tiles 倍重复读);权重槽布局 [c_in][c_out-in-chunk],cursor 按 (c_in 外、c_out 内) 顺序消耗;l0c `depth=chunk`(每 c_out 一个 FP32 累加器),最后一个 c_in 步用槽自身 handle 就地 store。尾块用运行时 `if` 守卫:**cursor 无条件推进保持对齐,仅 compute/store/preload 被守卫跳过**。 | ||
| 50 | +3. **min-window(BM 越过输入宽放大,单规格 −12~35%)**:当理想窗口 `W_win > W_in` 时,把 L1 加载 clamp 到整行输入(`W_win_eff = min(W_win, W_in)`,每行每 (b,o,c_in) 只载一次),右侧缺口折进运行时 `pad_right`(编译期常量 `short = max(0, W_win - W_in)`,`pad_right = d_w_bot + short`),`wo_gen` 改用 `W_win_eff` 计算。这样 BM 不再被 `W_win ≤ W_in` 锁死,`BM ≥ out_w` 时每输出行只剩一次 tile 迭代。要点:`W_win ≤ W_in` 时 `short=0`、公式与原实现完全一致(对其他规格无操作)。 | ||
| 51 | +4. **K_L0 解耦(l0_k)**:K_L1(GM→L1 粒度 = `BK·KH·KW`)与 K_L0(L0A/L0B 步长)解耦——aclnn Conv2DV2 即此策略(实测 tiling:`kAL1=288, kL0=48`)。L0 级按 `k_slices = BK·KH·KW / l0_k` 次迭代:`img2col(pos_k=组基址+ks·l0_k)` 前进 + `move(offset=[ks·l0_k, 0])` 切出权重 K 条带。收益:BM 摆脱 LOAD3D dst 限制、`c_in_tiles` 减半(GM 载入次数减半、突发加倍)、**绕开裸 BK>16 的设备 507015 崩溃**(大型 C_in 规格 BK64+l0k=288 实测 −59%)。实现要点:① weight L1 槽按索引访问 `weight_l1_buffer[ci·chunk+co]`(线性游标在 ks>0 会错指 co>0 槽导致全局精度错;索引访问同时解锁 chunk>1 联用,中大型 C_in 规格 BK32+l0k=144+chunk=2 再降 16~32%);② auto_mutex 对 offset move 按 `[槽基址+off, 槽基址+整槽大小)` 查跨界,槽 stride 必须加 padding `(k_slices−1)·k_l0·bn·2`;③ L0B 约束 `k_l0·bn·2·db ≤ 64KiB`(l0k=288 → bn ≤ 42);④ l0_k 为 `kw·16` 的倍数时权重 K 条带与 GM NCHW 块对齐。 | ||
| 52 | +5. **全行宽 tile(BM ≥ out_w,W 整行不切分)**:torch mDim 结构的对应做法——W 方向不做多 tile 切分,BM 直接取 ≥ out_w 的 16 倍数(LOAD3D dst 用 l0_k 压小,如 k3/BK16 取 l0k=48 切 3 片)。收益机制是 w0 迭代次数归一(每 tile 的 img2col/cursor/发射开销消除),实测 fmap 流量近似不变——MTE2-bound 且 out_w 大(≥160)的规格优先尝试,单规格最高 −29%。适用约束:W 较小的规格已被 min-window 覆盖、无增量。 | ||
| 53 | +6. **N 维分核 + 每核单次预载(多规格再降 20~48%)**:核心网格从 (b,o) 行单元改为「每核固定一个 c_out 分片 + 私有连续行区间」:`group_size = num_cores // c_out_chunks`,`chunk_idx = core_id // group_size`(co_base 运行时标量),行区间 `[slot×rows_per_core, …)` 连续分配;该分片的 `c_in_tiles×chunk` 个权重槽在核启动时预载**一次**,行循环内游标按 (ci, co) 消费、每行恰好对齐。收益:① 权重 MTE2 流量 ÷ c_out_chunks(原结构每 chunk 重预载、每核只摊数行);② 尾差消除(c_out_chunks×group_size 恰好整除核数);③ 行数少的规格核利用率提升;④ 同分片各核读相同 fmap 窗口,L2 命中更好。实现要点:`pl.range(start, stop)` 支持运行时空区间(空闲核零迭代自然落空);load/store 的 co 偏移运行时化即可。 | ||
| 54 | +7. **结构选型(A/B 实测选优)**:权重驻立可行性由 `c_in_tiles × chunk × K_L1·BN·2 ≤ L1 预算` 决定——C_in×C_out 乘积大(权重总量超预算)时只能走小 chunk 结构,可驻立时大 chunk 更优。两结构的 mutex/cursor 开销与 cube 利用率差异难以精确建模,按规格实测选优(逐规格 A/B 实测脚本,本地工具不入库)。 | ||
| 55 | +8. **tile 推导仍是第一层**:BK/BM/BN 推到容量与迭代次数边界——这些决定迭代次数下限,驻立优化建立在其之上。 | ||
| 56 | + | ||
| 57 | +## 配置推导(正向分析) | ||
| 58 | + | ||
| 59 | +优化主轴从工作分解与流量模型推出:并行单元 = `B × ceil(C_out/BN) × Ho`,每单元 `ceil(Wo/BM)` 次 tile 迭代,每次迭代加载一次权重(`K_L1·BN·2` 字节)与一次 fmap 窗口(`DKH·W_win_eff·BK·L1_K·2` 字节)。profiling 显示 MTE2(GM→L1)是常见瓶颈通路,因此主轴是**在容量约束内把 BM、BN、迭代次数推到边界**: | ||
| 60 | + | ||
| 61 | +1. `BK`:k1 规格 64/128(L0 不挤压 M/N);k3 规格 16 起步,放大须组合 `l0_k`。前提 `C_in % 16 == 0`。 | ||
| 62 | +2. `BM`:min-window 使 BM 不再受 `W_win ≤ W_in` 约束,按 `BM·k_l0 ≤ 16384`(LOAD3D 单指令 dst 上限)取能覆盖 `out_w` 的最小 16 倍数——`BM ≥ out_w`(全行宽)后每行一次 tile 迭代即为最优(继续增大 BM 只浪费 L0A,实测曲线平坦)。 | ||
| 63 | +3. `BN`:能整除 C_out 且满足 L0B 容量的最大值。BN 大使 c_out_tiles 与写出次数减少。 | ||
| 64 | +4. `l0_k`:BK>16 或需要大 BM 时启用;`l0_k` 为 `kw·16` 的倍数保证权重条带与 GM NCHW 块对齐。 | ||
| 65 | +5. 分核:N 维网格(已验证手段第 6 条),`c_out_chunks × group_size` 整除核数、零尾差。 | ||
| 66 | +6. 断言边界:`BM·k_l0·2·db ≤ 64KiB`(L0A)、`k_l0·BN·2·db ≤ 64KiB`(L0B)、`BM·BN·4·chunk·L1_M ≤ 256KiB`(L0C)、L1 总量 512KiB(含权重槽 stride padding)。 | ||
| 67 | + | ||
| 68 | +## profiler 验证 | ||
| 69 | + | ||
| 70 | +用 CANN `torch_npu.profiler`(msprof 后端)验证,**只看 kernel 设备耗时**(wall 口径含 ~百微秒级 host 启动开销,不可用于小 shape 对比): | ||
| 71 | + | ||
| 72 | +```python | ||
| 73 | +exp = _ExperimentalConfig(profiler_level=ProfilerLevel.Level1, aic_metrics=AiCMetrics.PipeUtilization) | ||
| 74 | +with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.NPU], experimental_config=exp) as prof: | ||
| 75 | + kernel[cores](x, w, y); torch.npu.synchronize() | ||
| 76 | +prof.export_chrome_trace(path) # 触发解析 → mindstudio_profiler_output/op_summary*.csv | ||
| 77 | +``` | ||
| 78 | + | ||
| 79 | +读 `op_summary*.csv` 的 `Task Duration`(kernel 设备耗时)与 `aic_mte1/mte2/mte3/mac/scalar/fixpipe_time(us)`、`aic_*_ratio`、`cube_utilization(%)`(各流水耗时与占比);chrome trace 里按 kernel 名聚合(排除 `Computing` 与 `HostToDevice`)。对照组用同规格同设备同口径的 torch conv2d(aclnn)。 | ||
| 80 | + | ||
| 81 | +判读:MTE2 占比高 → 加载 bound(检查重复加载与 tile 配置);MAC 占比高且 MTE2 低 → cube 饱和,转向指令形状/发射效率;FixPipe/Scalar 偏高 → 写出/标量开销,考虑加大 BN。设备测时抖动可达 10×:同配置多轮采样,取无干扰最小值或中位数,单次结果不可信。 | ||
| 82 | + | ||
| 83 | +## 边界与已知约束 | ||
| 84 | + | ||
| 85 | +- `groups != 1` 断言拒绝;bias/relu 融合未实现。 | ||
| 86 | +- `C_out % BN != 0` 尾通道会被 `c_out_tiles` 整除丢弃(BN 必须整除 C_out)。 | ||
| 87 | +- C_in 尾块补零限单 C0 帧:`BK == 16` 或 `C_in % 16 == 0`。 | ||
| 88 | +- `DKH >= H` 断言拒绝;`W_win > W_in` 已由 min-window 覆盖(不再拒绝)。 | ||
| 89 | +- `l1_m ≥ 2` 与 min-window 联用会精度错(窗口 clamp 后超块 pos_m 偏移失配);`l1_m ≥ 2` 与 `l1_k ≥ 2` 联用触发 LOAD3D errcode 155——l1_m 放大前先确认这两条。 | ||
| 90 | +- 裸 BK>16(无 l0_k 切分)触发设备 507015;调试时必须逐规格隔离进程运行(设备崩溃会污染同进程后续用例,且崩溃后同进程的后续「失败」多为连锁污染而非真实问题)。 | ||
| 91 | +- 性能测量的设备抖动可达 10×:同配置多轮采样,取无干扰最小值或中位数,单次结果不可信。 | ||
| @@ -0,0 +1,130 @@ | |||
| 1 | +# Conv2D(PyPTO-Pro)设计说明 | ||
| 2 | + | ||
| 3 | +对应实现:[op_kernel/conv2d.py](op_kernel/conv2d.py)。接口、约束与高性能指导见 [README.md](README.md),已验证情况见 [RESULTS.md](RESULTS.md)。 | ||
| 4 | + | ||
| 5 | +## 1. 编译期 / 运行时划分 | ||
| 6 | + | ||
| 7 | +`make_conv2d_kernel(conv_params, *, double_buffer, c_out_chunk, weight_l0_resident, l1_shape, l0_k)` 把全部几何闭包进 kernel 体,形成编译期常量: | ||
| 8 | + | ||
| 9 | +| 编译期常量 | 用途 | | ||
| 10 | +| :--- | :--- | | ||
| 11 | +| `BM/BK/BN`(`tile_shape`) | tile 几何;`BM ≥ out_w` 时为全行宽 tile(W 不切分) | | ||
| 12 | +| `K_L1_full = BK*KH*KW`、`k_l0`(默认 `= K_L1_full`)、`k_slices = K_L1_full / k_l0` | K_L1(GM→L1 粒度)与 K_L0(L0A/L0B 步长)解耦 | | ||
| 13 | +| `L1_M/L1_K`(`l1_shape`) | L1 级复用:M 超块覆盖 `L1_M` 个 BM 块、K 分组一次载 `L1_K` 个通道组 | | ||
| 14 | +| `DKH/DKW = (K-1)*D + 1`、`W_win = (L1_M*BM-1)*SW + DKW`、`W_win_eff = min(W_win, W_in)` | L1 fmap 窗口几何(min-window:窗口 clamp 到输入行宽) | | ||
| 15 | +| `short_win = max(0, W_win - W_win_eff)` | min-window 右缺口,运行时折入 `pad_right` | | ||
| 16 | +| `h_clamp_max = H-DKH`、`w_clamp_max = W-W_win_eff` | clamp 上限 | | ||
| 17 | +| `C_in_tiles = ceil(C_in/BK)`、`C_out_tiles = C_out/BN`、`chunk`、`c_out_chunks` | 循环次数 | | ||
| 18 | +| `group_size = max(1, 核数/c_out_chunks)`、`rows_per_core` | N 维分核几何(编译期计算,避免运行时除法) | | ||
| 19 | +| `weight_l1_stride = weight_l1_size + (k_slices-1)*k_l0*BN*2` | 权重槽跨距(见 §4) | | ||
| 20 | +| L1/L0 地址表与容量断言 | 资源计划 | | ||
| 21 | + | ||
| 22 | +运行时值只有三类:四向 `padding`、随 pad 推导的 `pos_m`/`wo_gen`、尾块有效形状 `mc`/`mc_flat`。因此 shape 边界情况不进 tiling key,同一 key 只编译一次。 | ||
| 23 | + | ||
| 24 | +## 2. Tile 类型与地址表 | ||
| 25 | + | ||
| 26 | +| Tile | 类型 | 形状 | 地址 | | ||
| 27 | +| :--- | :--- | :--- | :--- | | ||
| 28 | +| fmap L1 | `Mat / NC1HWC0` | `[1, BK·L1_K/16, DKH, W_win_eff, 16]` | `0x00000` 起,双槽 | | ||
| 29 | +| weight L1 | `Mat / FRACTAL_Z` | `[K_L1_full/16, BN/16, 16, 16]`,槽距 `weight_l1_stride` | fmap 区之后,`c_in_tiles*chunk` 槽 | | ||
| 30 | +| fmap L0A | `Left / NZ` | `[BM, k_l0]` | `0x0000`,双槽 | | ||
| 31 | +| weight L0B | `Right / ZN` | `[k_l0, BN]` | `0x0000`,双槽 | | ||
| 32 | +| l0c | `Acc / NZ / FP32` | `[BM, BN]`,`chunk*L1_M` 槽 | `0x0000` | | ||
| 33 | + | ||
| 34 | +权重槽跨距 padding 的由来:`auto_mutex` 对带 offset 的 move 按 `[槽基址+off, 槽基址+整槽大小)` 检查跨槽越界,最大 offset(`(k_slices-1)*k_l0`)的切片访问必须落在本槽跨距内,故槽距追加 `(k_slices-1)*k_l0*BN*2`。`k_slices == 1`(默认 `l0_k=None`)时跨距等于槽大小,与旧布局一致。 | ||
| 35 | + | ||
| 36 | +容量断言在 kernel 构造期执行: | ||
| 37 | + | ||
| 38 | +```text | ||
| 39 | +fmap_l1_size*db <= weight_l1_base - fmap_l1_base | ||
| 40 | +weight_l1_base + weight_l1_stride*(weight_slots-1) + size <= 524288 # L1 总量 | ||
| 41 | +BM*k_l0*2*db <= 65536 # L0A(k_l0 解耦后 BM 不再被 K_L0 挤压) | ||
| 42 | +k_l0*BN*2*db <= 65536 # L0B(l0k=288 时 BN ≤ 42) | ||
| 43 | +BM*BN*4*chunk*L1_M <= 262144 # L0C | ||
| 44 | +BM*K_L1_full <= 16384 仅在 l0_k=None 时隐含于上式;l0_k 显式给出时以 BM*k_l0 计 | ||
| 45 | +``` | ||
| 46 | + | ||
| 47 | +所有 tile group `depth=2` 乒乓(`double_buffer=False` 退化为 `depth=1`)、`mutex_ids='auto'`。 | ||
| 48 | + | ||
| 49 | +## 3. N 维分核网格(每核一个 c_out 分片 + 私有行区间) | ||
| 50 | + | ||
| 51 | +核心网格从「行单元 grid-stride」改为「c_out 分片 × 私有行区间」: | ||
| 52 | + | ||
| 53 | +```text | ||
| 54 | +group_size = 核数 // c_out_chunks # 同一分片的核心数(编译期) | ||
| 55 | +chunk_idx = core_id // group_size # 本核负责的 c_out chunk | ||
| 56 | +co_base = chunk_idx * chunk # 运行时标量(load/store 偏移用) | ||
| 57 | +row_begin = (core_id % group_size) * rows_per_core # 私有行区间 [row_begin, row_end) | ||
| 58 | +row_end = min(row_begin + rows_per_core, B*out_h) | ||
| 59 | +``` | ||
| 60 | + | ||
| 61 | +- **权重每核只预载 1 次**:`for ci in c_in_tiles → for co in chunk` 把本分片的全部权重槽载入 L1,行循环内游标按 `(ci, co)` 消费、每行恰好对齐(消费量 = `c_in_tiles*chunk`)。权重 MTE2 流量从「每 chunk 重预载、每核仅摊 ~4 行」降为每核 1 次。 | ||
| 62 | +- **零尾差**:`c_out_chunks * group_size` 恰好整除核数(对照旧行网格 132 单元/32 核 ~21% 尾差);行数少于分片数的规格核利用率同时提升。 | ||
| 63 | +- 同分片的各核读相同 fmap 窗口,L2 命中更好。 | ||
| 64 | +- 游标语义:预载用 `.next()` 消费满一圈回到槽 0;主循环按**索引访问** `weight_l1_buffer[step*chunk + c_out_idx]`(线性游标在 K 切分的 `ks>0` 轮会错指 co>0 槽,索引访问消除该错位)。 | ||
| 65 | +- 尾 chunk 的 OOB 槽仍遵循「游标无条件推进、load/store 条件守卫」。 | ||
| 66 | + | ||
| 67 | +## 4. K_L0 解耦(l0_k)与 K 切分内循环 | ||
| 68 | + | ||
| 69 | +`BK*KH*KW` 保持为 GM→L1 的载入粒度(K_L1),L0 级按 `k_slices` 步切分: | ||
| 70 | + | ||
| 71 | +```text | ||
| 72 | +for cg in c_in_groups: # L1_K 分组 | ||
| 73 | + load(fmap_l1, [b, cg*L1_K*BK, h_load, w_load]) # 一次 MTE2 载 L1_K 组 | ||
| 74 | + for gi in L1_K: | ||
| 75 | + group_k_base = gi * K_L1_full | ||
| 76 | + for ks in k_slices: | ||
| 77 | + pos_k = group_k_base + ks * k_l0 | ||
| 78 | + img2col(fmap_l0, fmap_l1, pos_m, pos_k) # L0A [BM, k_l0] | ||
| 79 | + for co in chunk: | ||
| 80 | + w_l1 = weight_l1_buffer[step*chunk + co] # 索引访问 | ||
| 81 | + move(weight_l0, w_l1, offset=[ks*k_l0, 0])# L0B [k_l0, BN] K 条带 | ||
| 82 | + step==0 && ks==0 ? matmul : matmul_acc # l0c 累加 | ||
| 83 | + 最后 (step, ks) ? store # FixPipe 直出 NCHW | ||
| 84 | +``` | ||
| 85 | + | ||
| 86 | +收益:BM 摆脱 LOAD3D 单指令 dst 限制(`BM*k_l0 ≤ 16384`,k3/BK16 的 BM 上限由 113 保持、BK32/64 可用大 BM);`c_in_tiles` 减半(GM 载入次数减半、突发加倍);绕开 BK>16 的设备 507015 崩溃。约束:`l0_k` 须整除 `BK*KH*KW` 且为 `16` 倍数(NZ/ZN 帧对齐);L0B 双缓冲 `k_l0*BN*4 ≤ 64KiB`。 | ||
| 87 | + | ||
| 88 | +## 5. min-window(W 窗口 clamp 到输入行宽) | ||
| 89 | + | ||
| 90 | +理想窗口 `W_win > W_in` 时(`BM ≥ out_w` 的全行宽 tile 必然触发):L1 加载 clamp 到整行输入(`W_win_eff = min(W_win, W_in)`,每行每 (b, o, c_in) 只载一次),右侧缺口 `short_win`(编译期常量)折入运行时 `pad_right = d_w_bot + short_win`,`wo_gen` 改用 `W_win_eff` 计算。`W_win ≤ W_in` 时 `short_win = 0`,公式退化为原始推导,对其他规格无操作。 | ||
| 91 | + | ||
| 92 | +## 6. 运行时边界推导(每组 / 每输出块) | ||
| 93 | + | ||
| 94 | +以 H 方向为例(W 方向对称,含 min-window 修正): | ||
| 95 | + | ||
| 96 | +```text | ||
| 97 | +hs = o*sh - ph # 窗口起始行,可为负 | ||
| 98 | +h_load = clamp(hs, 0, h_clamp_max) # 物理加载起点 | ||
| 99 | +d_h = hs - h_load # <0 上溢出 / >0 下溢出 / =0 正常 | ||
| 100 | +pad_top = max(-d_h, 0) + align_h | ||
| 101 | +pad_bottom = max(d_h, 0) | ||
| 102 | +pos_row = (d_h_bot + align_h) // sh | ||
| 103 | +# W 方向(min-window 版) | ||
| 104 | +pad_right = d_w_bot + short_win | ||
| 105 | +wo_gen = (W_win_eff + pad_left + pad_right - DKW) // sw + 1 | ||
| 106 | +pos_m = pos_row*wo_gen + pos_col # (Ho, Wo) 行优先展平 | ||
| 107 | +``` | ||
| 108 | + | ||
| 109 | +四个 pad 作为运行时标量传入 `Img2ColConfig.padding=[top, bottom, left, right]`;`mc = min(BM, out_w - w0)` 用 `pl.set_validshape` 收窄尾块。 | ||
| 110 | + | ||
| 111 | +## 7. 主循环流水(多核 + 双缓冲) | ||
| 112 | + | ||
| 113 | +```text | ||
| 114 | +core_id = get_block_idx(); num_cores = get_block_num() | ||
| 115 | +chunk_idx = core_id // group_size; co_base = chunk_idx * chunk | ||
| 116 | +预载:for ci in c_in_tiles → for co in chunk: load(weight_l1[slot], weights, [co_base+co)*BN, ci*BK, 0, 0]) | ||
| 117 | +for work in pl.range(row_begin, row_end): # 私有行区间 | ||
| 118 | + b_idx, o = work // out_h, work % out_h | ||
| 119 | + for w0 in pl.range(0, out_w, BM * L1_M): # W 超块(min-window 下常为 1 次迭代) | ||
| 120 | + for cg in c_in_groups: | ||
| 121 | + load(fmap_l1, ...) # L1_K 组一次载入 | ||
| 122 | + for gi → for ks → for j(L1_M) → for co in chunk: # 见 §4 | ||
| 123 | + img2col / move(offset) / matmul(_acc) / store | ||
| 124 | +``` | ||
| 125 | + | ||
| 126 | +全部 tile group `depth=2` 乒乓(`mutex_ids='auto'`):step N+1 的 GM→L1 加载与 step N 的 img2col/matmul 重叠;行循环内权重不再触 GM(L1→L0B 由 move 完成),fmap 窗口由 `L1_M/L1_K/min-window` 三级复用压到每行每组一次。 | ||
| 127 | + | ||
| 128 | +## 8. 已知局限 | ||
| 129 | + | ||
| 130 | +用户可见的约束以 [README.md](README.md) 的约束表为准;框架级限制与调优过程知识(l1_m 联用、K 切分游标语义、M 跨行展平可行性等)不在交付文档中展开。 | ||
| @@ -0,0 +1,85 @@ | |||
| 1 | +# Conv2D(PyPTO-Pro)高性能指导 | ||
| 2 | + | ||
| 3 | +`conv2d` 使用原生 PyPTO-Pro 实现 NCHW 卷积:NCHW 输入与权重经 `pl.load` 直送 L1(fmap `NC1HWC0`、权重 `FRACTAL_Z`),`pl.img2col` 把 L1 特征窗口展开到 L0A,`pl.matmul` / `pl.matmul_acc` 在 Cube 上完成乘累加,`pl.store` 以 FixPipe 直出 NCHW。**padding 是运行时值**(`Img2ColConfig.padding` 接受运行时整型标量),kernel/stride/dilation/pad_value 仍是编译期常量;一个通用双层循环即可服务全部输出位置,同一 tiling key 只编译一次。算子的目的形态是「按规格正向推导配置的高性能实现」,推导规则、验证方法与全量数据见本文与 [RESULTS.md](RESULTS.md)。 | ||
| 4 | + | ||
| 5 | +## 产品支持情况 | ||
| 6 | + | ||
| 7 | +| 项 | 取值 | | ||
| 8 | +| :--- | :--- | | ||
| 9 | +| 芯片 | Ascend 950PR / 950DT(`pl.jit` Cube 通路) | | ||
| 10 | +| 能力依赖 | `pl.jit` / `pl.Tensor` / `pl.TileType` / `pl.make_tile_group`、`MemorySpace.Mat/Left/Right/Acc`、布局 `NC1HWC0` / `FRACTAL_Z` / `NZ` / `ZN`、`pl.load` / `pl.move` / `pl.img2col`(`pl.Img2ColConfig`,padding 支持运行时整型标量)、`pl.matmul` / `pl.matmul_acc`、`pl.set_validshape`、`pl.min` / `pl.max` / `pl.range`、`pl.section_cube`、`pl.get_block_idx` / `pl.get_block_num` | | ||
| 11 | +| 分核数 | N 维网格:每核固定一个 c_out 分片(`chunk_idx = core_id // group_size`)+ 私有连续行区间;权重每核只预载 1 次;`c_out_chunks × group_size` 整除核数,零尾差 | | ||
| 12 | +| 实测环境 | Ascend950PR(davinci0 单卡),CANN 9.3.0 weekly、pypto 0.3.0(cann-pypto run 包随 CANN 伞目录安装)、PyTorch 2.x + torch_npu、Python 3.12 | | ||
| 13 | +| 测试标注 | pytest 用例(`tests/ops/experimental/conv/test_conv2d.py`,纳入全量收集);规格集取自性能场景集(ResNet-50 式 19 规格,编号 001-019),golden 用同设备 `torch.nn.functional.conv2d`,`atol/rtol = 0.01`;性能一律用 CANN profiler 的 kernel 设备耗时口径 | | ||
| 14 | +| 依赖 | pypto / pypto_pro、torch、torch_npu | | ||
| 15 | + | ||
| 16 | +## 功能说明 | ||
| 17 | + | ||
| 18 | +输入 `input_tensor` 为 `[B, C_in, H, W]`,权重 `weights` 为 `[C_out, C_in, KH, KW]`,输出 `output_tensor` 为 `[B, C_out, Ho, Wo]`,全部 NCHW 逻辑布局: | ||
| 19 | + | ||
| 20 | +```text | ||
| 21 | +out[b, co, ho, wo] = sum_(ci, kh, kw) input[b, ci, sh*ho - ph + dh*kh, sw*wo - pw + dw*kw] | ||
| 22 | + * weight[co, ci, kh, kw] (越界补 pad_value = 0) | ||
| 23 | +``` | ||
| 24 | + | ||
| 25 | +**支持域**:`groups == 1`;`C_out % BN == 0`(BN 由推导给出);`C_in` 任意(尾通道由 TLOAD 单帧补零,见约束表);`H/W` 任意(W 尾块由 `set_validshape` 收窄 + 运行时 padding 覆盖);`stride >= 1`、`dilation >= 1`、对称 padding;bf16 / fp16。 | ||
| 26 | + | ||
| 27 | +**数值契约**:FP32 累加器沿 `C_in/BK` 步乘加,最后一次 `matmul_acc` 收尾后经 FixPipe 一次舍入写出;与 torch conv2d 在 `atol/rtol=0.01` 门限内全元素通过。 | ||
| 28 | + | ||
| 29 | +## 函数原型 | ||
| 30 | + | ||
| 31 | +```python | ||
| 32 | +def make_conv2d_kernel(conv_params: ConvParams, *, double_buffer: bool = True, | ||
| 33 | + c_out_chunk: int | None = None, # c_out 分片大小(None=全部分片) | ||
| 34 | + weight_l0_resident: bool = False, # L0B 权重驻留(实测无收益,保留开关) | ||
| 35 | + l1_shape: int[2] | None = None, # [L1_M, L1_K] L1 级复用 | ||
| 36 | + l0_k: int | None = None) -> conv2d_pypto_pro # K_L0 步长(默认=BK*KH*KW) | ||
| 37 | +conv2d_pypto_pro[core_num](input_tensor, weights, output_tensor) | ||
| 38 | +``` | ||
| 39 | + | ||
| 40 | +`ConvParams` 字段:`batch_size / input_shape[2] / in_channels / out_channels / kernel_size[2] / stride[2] / padding[2] / dilation[2] / groups / dtype("bfloat16"|"float16") / tile_shape[3]=[BM,BK,BN] / core_num`。`double_buffer=False` 退化为单缓冲(对照基线)。各旋钮的语义与实现见 [DESIGN.md](DESIGN.md)。 | ||
| 41 | + | ||
| 42 | +## 约束说明 | ||
| 43 | + | ||
| 44 | +| 约束 | 来源 | | ||
| 45 | +| :--- | :--- | | ||
| 46 | +| `groups == 1` | kernel 断言,分组卷积未实现 | | ||
| 47 | +| `BM % 16 == 0`、`BK % 16 == 0`、`BN % 16 == 0` | fractal 几何(C0=16) | | ||
| 48 | +| L0/L1 双缓冲容量(见 DESIGN.md 地址表) | kernel 断言:L0A/L0B 各 `<= 64KiB`(双槽)、L0C `<= 256KiB`(双槽)、L1 总量 `<= 512KiB` | | ||
| 49 | +| `DKH < H` | H 窗口必须能 clamp 出合法加载起点;`W_win > W` 已由 min-window 覆盖(不再拒绝) | | ||
| 50 | + | ||
| 51 | +## 高性能指导 | ||
| 52 | + | ||
| 53 | +**优化主轴从工作分解与流量模型推出**。并行单元 = `B × ceil(C_out/BN) × Ho`,每单元 `ceil(Wo/BM)` 次 tile 迭代;每次迭代加载一次权重(`K_L0·BN·2` 字节)与一次 fmap 窗口(`DKH·W_win·BK·2` 字节)。权重总流量 `= C_out · Ho · w_blocks · K_L0 · 2`,**与 BN 无关、正比于 w_blocks**——各流水 profiling 显示 MTE2(GM→L1)是瓶颈通路,所以主轴是:**在容量约束内把 BM、BN 推到边界,用最少迭代次数覆盖输出**。 | ||
| 54 | + | ||
| 55 | +按规格推导(最终配置逐规格实测选优,见 RESULTS 全量结果表;推导要素如下): | ||
| 56 | + | ||
| 57 | +1. **`BK`:k1 规格 64/128、k3 规格 16 或 32**(1×1 卷积 K_L0=BK 不挤压 L0,可安全放大,实测 −32~70%;k3 放大须配合 `l0_k` 切分绕开 dst 限制与设备崩溃,`C_in % 16 == 0` 前提)。 | ||
| 58 | +2. **`BM`:≥ out_w 的最小 16 倍数(全行宽 tile)**。W 不切分使 w0 迭代归一(消除每 tile 的 img2col/cursor/发射开销,大 out_w 规格实测最高 −29%);`BM > W_in` 由 min-window 自动覆盖(窗口 clamp 到输入行宽)。BM 上限由 `BM·k_l0 ≤ 16384`(LOAD3D dst)与 L0A 容量约束。 | ||
| 59 | +3. **`BN`:{64, 32, 16, 128} 中能整除 C_out 且满足 L0B 容量的最大值**(双缓冲 `k_l0·BN·4 ≤ 64KiB`)。BN 大使 c_out_tiles 与写出次数减少。 | ||
| 60 | +4. **`l0_k`:BK>16 时启用**,把 K_L0 与 BK 解耦(如 BK64+l0k=288、BK32+l0k=144),解锁 BM 并绕开设备崩溃;`l0_k` 须整除 `BK·KH·KW`。 | ||
| 61 | +5. **`l1_shape=[L1_M, L1_K]`**:L1_K 分组使 fmap MTE2 流量 ÷L1_K(实测最高 −35%);L1_M 空间复用受 `l1_m×l1_k` 联用限制(见 RESULTS)。 | ||
| 62 | +6. **`c_out_chunk`:L1 预算内尽量大**(权重驻立 `C_in×chunk×K_L1·BN·2 ≤ 512KiB`),分片越大每核权重预载次数越少;N 维网格下分片数与核数整除配平。 | ||
| 63 | +7. **核数 `min(32, c_out_chunks × group_size)`**:N 维网格自动满载,零尾差。 | ||
| 64 | +8. **验证一律用 CANN profiler 的 kernel 设备耗时**(`torch_npu.profiler` Level1 + `PipeUtilization`,读 `op_summary*.csv` 的 `Task Duration` 与 `aic_*` 列);wall 口径含百微秒级 host 启动开销,不可用于小 shape 对比。设备测时抖动可达 10×,须取多轮中位/最小值。 | ||
| 65 | +9. **残差与边界**:19 规格性能比例(torch/本算子)0.30~1.27,两个规格已超越 torch、一个逼近;bound 分布 MTE2 主导、部分规格翻转为 CUBE;M 跨行展平需框架侧支持(详见 RESULTS)。 | ||
| 66 | + | ||
| 67 | +接口语义细节(`Img2ColConfig` 的编译期/运行时字段划分、`pos_m/pos_k` 语义)以 pto 仓 `python/pypto_pro/language/_api.py` 与 `python/pypto_pro/ir/op/block_ops.py` 的注释为准。 | ||
| 68 | + | ||
| 69 | +## 目录说明 | ||
| 70 | + | ||
| 71 | +``` | ||
| 72 | +conv/ | ||
| 73 | +├── README.md # 本文:功能、约束、高性能指导 | ||
| 74 | +├── DESIGN.md # tile 几何、地址表、双层循环边界推导 | ||
| 75 | +├── RESULTS.md # 19 个性能规格的功能与全量性能结果 | ||
| 76 | +├── op_kernel/ | ||
| 77 | +│ └── conv2d.py # N 维分核多核 kernel(l1/l0 旋钮)+ host 工具 | ||
| 78 | +``` | ||
| 79 | + | ||
| 80 | +用法: | ||
| 81 | + | ||
| 82 | +```bash | ||
| 83 | +source ~/pypto/env_setup.sh | ||
| 84 | +pytest tests/ops/experimental/conv/test_conv2d.py -v # 19 个性能规格(正确性,纳入全量测试收集) | ||
| 85 | +``` | ||
| @@ -0,0 +1,87 @@ | |||
| 1 | +# Conv2D(PyPTO-Pro)结果记录 | ||
| 2 | + | ||
| 3 | +对应实现:[op_kernel/conv2d.py](op_kernel/conv2d.py)。规格集与配置推导:[tests/test_conv2d.py](tests/test_conv2d.py)。接口与约束见 [README.md](README.md),tile、地址表与边界推导见 [DESIGN.md](DESIGN.md)。 | ||
| 4 | + | ||
| 5 | +本文全部数据都是本算子自身的实测值,最近一轮于 2026-11-28 在 `npu:0`(Ascend950PR,davinci0)按「性能结果」一节的协议采集,描述的是当前代码的行为。 | ||
| 6 | + | ||
| 7 | +| 数据类别 | 状态 | 出处 | | ||
| 8 | +| :--------------------------- | :---------------------- | :------------------------------------------- | | ||
| 9 | +| 功能与精度(19 个性能规格) | 已实测,全部通过 | `test_conv2d.py` | | ||
| 10 | +| 性能(19 个规格,kernel 设备耗时) | 已实测,中位差距见「性能结果」 | CANN profiler(采集脚本未随库提交) | | ||
| 11 | +| 各流水指标(MTE2/MAC/FixPipe/Scalar) | 已采集 | `本机 ~/prof_out/conv/(未入库)` | | ||
| 12 | + | ||
| 13 | +## 用例 | ||
| 14 | + | ||
| 15 | +19 个规格取自性能场景集(ResNet-50 式流水),只取规格(shape / stride / padding / dilation / dtype / groups)。实际启动配置(tile / chunk / l1_shape / l0_k)为逐规格实测选优,见「全量结果」表与 `tests/ops/experimental/conv/test_conv2d.py` 的 `TUNED_CONFIGS`。 | ||
| 16 | + | ||
| 17 | +| 规格 | fmap / weight | s / p / k | | ||
| 18 | +| :--- | :--- | :--- | | ||
| 19 | +| case_001 | `[6,32,352,640]` / `[64,32,3,3]` | 2/1/3×3 | | ||
| 20 | +| case_002 | `[6,64,176,320]` / `[64,64,3,3]` | 2/1/3×3 | | ||
| 21 | +| case_003 | `[6,64,88,160]` / `[64,64,3,3]` | 1/1/3×3 | | ||
| 22 | +| case_004 | `[6,64,176,320]` / `[64,64,1,1]` | 2/0/1×1 | | ||
| 23 | +| case_005 | `[6,64,88,160]` / `[128,64,3,3]` | 1/1/3×3 | | ||
| 24 | +| case_006 | `[6,128,88,160]` / `[128,128,3,3]` | 1/1/3×3 | | ||
| 25 | +| case_007 | `[6,64,88,160]` / `[128,64,1,1]` | 1/0/1×1 | | ||
| 26 | +| case_008 | `[6,128,88,160]` / `[128,128,3,3]` | 2/1/3×3 | | ||
| 27 | +| case_009 | `[6,128,44,80]` / `[128,128,3,3]` | 1/1/3×3 | | ||
| 28 | +| case_010 | `[6,128,88,160]` / `[128,128,1,1]` | 2/0/1×1 | | ||
| 29 | +| case_011 | `[6,128,44,80]` / `[256,128,3,3]` | 1/1/3×3 | | ||
| 30 | +| case_012 | `[6,256,44,80]` / `[256,256,3,3]` | 1/1/3×3 | | ||
| 31 | +| case_013 | `[6,128,44,80]` / `[256,128,1,1]` | 1/0/1×1 | | ||
| 32 | +| case_014 | `[6,256,44,80]` / `[256,256,3,3]` | 2/1/3×3 | | ||
| 33 | +| case_015 | `[6,256,22,40]` / `[256,256,3,3]` | 1/1/3×3 | | ||
| 34 | +| case_016 | `[6,256,44,80]` / `[256,256,1,1]` | 2/0/1×1 | | ||
| 35 | +| case_017 | `[6,256,22,40]` / `[512,256,3,3]` | 1/1/3×3 | | ||
| 36 | +| case_018 | `[6,512,22,40]` / `[512,512,3,3]` | 1/1/3×3 | | ||
| 37 | +| case_019 | `[6,256,22,40]` / `[512,256,1,1]` | 1/0/1×1 | | ||
| 38 | + | ||
| 39 | +## 精度标准 | ||
| 40 | + | ||
| 41 | +golden 是**同设备 torch `F.conv2d`(aclnn 实现)**:与设备实现不共享任何代码路径,规格逐项相同。 | ||
| 42 | + | ||
| 43 | +判定门限(`tests/ops/experimental/conv/test_conv2d.py` 的 `torch.testing.assert_close`,任一元素超限即用例失败): | ||
| 44 | + | ||
| 45 | +| 判据 | 要求 | | ||
| 46 | +| :--- | :--- | | ||
| 47 | +| 逐元素误差 | `\|actual − golden\| ≤ atol + rtol × \|golden\|`,`atol = 0.01`、`rtol = 0.01` | | ||
| 48 | +| 超门限元素数 | **必须为 0**(不允许任何单个元素超门限) | | ||
| 49 | +| 有限性 | 输出与 golden 均无非有限值 | | ||
| 50 | +| 形状 | 与 golden 完全一致 | | ||
| 51 | + | ||
| 52 | +19 个规格(输出元素合计约 2.1 亿)在该门限下全部通过。输出为 BF16,大量级规格(C_in=512 时 `\|golden\|` 可达数百)由 rtol 项主导容差。 | ||
| 53 | + | ||
| 54 | +## 性能结果(2026-11-28,kernel 级 profiling 口径) | ||
| 55 | + | ||
| 56 | +**采集协议**:CANN `torch_npu.profiler`(msprof 后端),Level1 + `PipeUtilization`;5 轮 `Task Duration` 中位数(kernel 设备耗时,不含 host 启动开销);对照组为同规格同设备同口径的 torch `F.conv2d`(aclnn)。**性能比例 = torch 耗时 ÷ 本算子耗时**(1.0 为持平,越大越好)。原始 PROF 数据按用例归档在本机 `~/prof_out/conv/`(未入库)。 | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +### 全量结果(每规格实测选优配置,2026-11-28 全量复测) | ||
| 60 | + | ||
| 61 | +全部 19 规格按最终配置复测(5 轮 `Task Duration` 中位数 + 同轮 `aic_*_ratio` 中位数);torch 对照值沿用 2026-11-27 采集。 | ||
| 62 | + | ||
| 63 | +| 规格 | tile | chunk | l1_shape | 本算子 (µs) | torch aclnn (µs) | 性能比例 | MTE2 占比 | MAC 占比 | bound | | ||
| 64 | +| :--- | :--- | ---: | :--- | ---: | ---: | ---: | ---: | ---: | :--- | | ||
| 65 | +| case_001 | `[320,16,64]` | 1 | [1,1] l0k=48 | 63.7 | 40.6 | 0.64 | 0.762 | 0.599 | MTE2 | | ||
| 66 | +| case_002 | `[160,16,64]` | 1 | [1,1] l0k=48 | 38.4 | 30.3 | 0.79 | 0.564 | 0.584 | CUBE | | ||
| 67 | +| case_003 | `[112,16,64]` | 1 | [1,1] | 32.9 | 20.9 | 0.64 | 0.768 | 0.586 | MTE2 | | ||
| 68 | +| case_004 | `[192,64,64]` | 1 | [1,1] | 12.2 | 15.5 | 1.27 | 0.618 | 0.231 | MTE2 | | ||
| 69 | +| case_005 | `[112,16,64]` | 2 | [1,1] | 45.8 | 28.5 | 0.62 | 0.654 | 0.782 | CUBE | | ||
| 70 | +| case_006 | `[112,16,64]` | 2 | [1, 4] | 84.9 | 46.3 | 0.55 | 0.472 | 0.812 | CUBE | | ||
| 71 | +| case_007 | `[192,16,64]` | 2 | [1, 4] | 20.6 | 15.6 | 0.76 | 0.394 | 0.407 | CUBE | | ||
| 72 | +| case_008 | `[112,32,64]` | 2 | [1,1] l0k=144 | 31.6 | 27.2 | 0.86 | 0.610 | 0.568 | MTE2 | | ||
| 73 | +| case_009 | `[112,16,64]` | 2 | [1,1] | 28.2 | 23.3 | 0.83 | 0.703 | 0.574 | MTE2 | | ||
| 74 | +| case_010 | `[80,64,64]` | 2 | [1,1] | 10.6 | 13.0 | 1.23 | 0.789 | 0.297 | MTE2 | | ||
| 75 | +| case_011 | `[112,32,64]` | 2 | [1, 2] l0k=144 | 45.4 | 31.6 | 0.70 | 0.424 | 0.723 | CUBE | | ||
| 76 | +| case_012 | `[112,32,64]` | 1 | [1, 2] l0k=144 | 99.9 | 46.0 | 0.46 | 0.496 | 0.729 | CUBE | | ||
| 77 | +| case_013 | `[80,64,64]` | 2 | [1,1] | 14.6 | 11.3 | 0.77 | 0.738 | 0.375 | MTE2 | | ||
| 78 | +| case_014 | `[64,16,64]` | 1 | [1, 2] | 53.8 | 34.2 | 0.64 | 0.672 | 0.599 | MTE2 | | ||
| 79 | +| case_015 | `[64,16,64]` | 1 | [1,1] | 46.9 | 36.5 | 0.78 | 0.848 | 0.548 | MTE2 | | ||
| 80 | +| case_016 | `[112,128,64]` | 2 | [1,1] | 13.3 | 10.4 | 0.78 | 0.846 | 0.265 | MTE2 | | ||
| 81 | +| case_017 | `[64,16,64]` | 1 | [1, 2] | 82.7 | 41.4 | 0.50 | 0.634 | 0.607 | MTE2 | | ||
| 82 | +| case_018 | `[48,64,32]` | 1 | [1, 2] l0k=288 | 173.7 | 52.6 | 0.30 | 0.611 | 0.716 | CUBE | | ||
| 83 | +| case_019 | `[112,128,64]` | 4 | [1,1] | 21.3 | 11.5 | 0.54 | 0.831 | 0.286 | MTE2 | | ||
| 84 | + | ||
| 85 | +## 环境 | ||
| 86 | + | ||
| 87 | +Ascend950PR(davinci0),CANN 9.3.0 weekly(`~/Ascend/cann-9.3.0/cann-9.3.0`),pypto 0.3.0(cann-pypto run 包,`--install-path` 伞目录安装),Python 3.12(miniconda py312),`TILE_FWK_DEVICE_ID=0`。 | ||
| @@ -0,0 +1,440 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | + | ||
| 12 | +"""Conv2D (PyPTO-Pro) — padding-runtime kernels and host helpers. | ||
| 13 | + | ||
| 14 | +Two kernel builders: | ||
| 15 | + | ||
| 16 | +* ``make_conv2d_kernel`` — chunked weight-resident multi-core kernel | ||
| 17 | + (v3, default). Loop order: c_out_chunk -> preload -> b -> | ||
| 18 | + o(grid-stride) -> w0 -> c_in -> c_out_tile-in-chunk. ``c_out_chunk`` | ||
| 19 | + weight c_out tiles stay resident in L1 per pass (slots laid out | ||
| 20 | + [c_in][c_out-in-chunk]); the fmap window is loaded once per | ||
| 21 | + (b, o, w0, c_in) and reused across the chunk, so the fmap re-read | ||
| 22 | + factor drops from c_out_tiles to ceil(c_out_tiles / c_out_chunk). | ||
| 23 | + l0c keeps one FP32 accumulator per resident c_out tile; store runs on | ||
| 24 | + the last c_in step with the slot's own handle so all group cursors | ||
| 25 | + realign exactly once per cycle. fmap/l0B stay depth-2 ping-pong. | ||
| 26 | + | ||
| 27 | +The padding of ``pl.Img2ColConfig`` accepts runtime integer scalars, so | ||
| 28 | +one generic double loop serves every output position: per output row the | ||
| 29 | +kernel computes the clamped load origin, the four runtime pads and the | ||
| 30 | +im2col row offset at run time; kernel/stride/dilation/pad_value stay | ||
| 31 | +compile-time constants. | ||
| 32 | + | ||
| 33 | +Known limitation: BK == 16 or C_in % 16 == 0 (cross-frame C_in tail | ||
| 34 | +zero-padding missing). | ||
| 35 | +""" | ||
| 36 | + | ||
| 37 | +from __future__ import annotations | ||
| 38 | + | ||
| 39 | +from dataclasses import dataclass | ||
| 40 | + | ||
| 41 | +import torch | ||
| 42 | +import torch_npu | ||
| 43 | +import pypto_pro.language as pl | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +@dataclass | ||
| 47 | +class ConvParams: | ||
| 48 | + batch_size: int | ||
| 49 | + input_shape: int[2] | ||
| 50 | + in_channels: int | ||
| 51 | + out_channels: int | ||
| 52 | + kernel_size: int[2] | ||
| 53 | + stride: int[2] | ||
| 54 | + padding: int[2] | ||
| 55 | + dilation: int[2] | ||
| 56 | + groups: int | ||
| 57 | + dtype: str | ||
| 58 | + tile_shape: int[3] # [bm, bk, bn] | ||
| 59 | + core_num: int | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +def output_hw(conv_params: ConvParams): | ||
| 63 | + h, w = conv_params.input_shape | ||
| 64 | + f_h, f_w = conv_params.kernel_size | ||
| 65 | + s_h, s_w = conv_params.stride | ||
| 66 | + p_h, p_w = conv_params.padding | ||
| 67 | + d_h, d_w = conv_params.dilation | ||
| 68 | + out_h = (h + 2 * p_h - (d_h * (f_h - 1) + 1)) // s_h + 1 | ||
| 69 | + out_w = (w + 2 * p_w - (d_w * (f_w - 1) + 1)) // s_w + 1 | ||
| 70 | + return out_h, out_w | ||
| 71 | + | ||
| 72 | + | ||
| 73 | +def make_conv2d_kernel(conv_params: ConvParams, *, double_buffer: bool = True, | ||
| 74 | + c_out_chunk: int | None = None, | ||
| 75 | + weight_l0_resident: bool = False, | ||
| 76 | + l1_shape: int[2] | None = None, | ||
| 77 | + l0_k: int | None = None): | ||
| 78 | + """Chunked weight-resident multi-core kernel with L1-level reuse knobs. | ||
| 79 | + | ||
| 80 | + ``l1_shape=[L1_M, L1_K]`` extends the tiling onto the L1 level: | ||
| 81 | + | ||
| 82 | + * ``L1_K`` — BK channel groups per fmap L1 load. One GM->L1 load | ||
| 83 | + brings ``L1_K`` channel groups of the window; group ``gi`` is | ||
| 84 | + expanded by ``pl.img2col(pos_k=gi*k_l1_full)``, so one MTE2 load | ||
| 85 | + feeds ``L1_K`` L1->L0A transfers (fmap MTE2 traffic / L1_K). | ||
| 86 | + * ``L1_M`` — BM output blocks per fmap L1 load. The L1 window is | ||
| 87 | + loaded wide enough to cover ``L1_M`` consecutive output blocks | ||
| 88 | + (width ``(L1_M*BM-1)*SW + DKW``); block ``j`` is expanded by | ||
| 89 | + ``pl.img2col(pos_m=pos_m_base + j*BM)``, so one MTE2 load feeds | ||
| 90 | + ``L1_M`` further L1->L0A transfers (spatial reuse). | ||
| 91 | + * min-window — when the ideal window exceeds the input width | ||
| 92 | + (``w_win > w_in``), the L1 load is clamped to one full input row | ||
| 93 | + (``w_win_eff = min(w_win, w_in)``) and the right shortfall is | ||
| 94 | + folded into the runtime ``pad_right``, so a ``BM > out_w`` tile | ||
| 95 | + loads each input row exactly once per (b, o, c_in) step. | ||
| 96 | + * ``l0_k`` — K extent per L0A/L0B step, decoupled from BK. K_L1 per | ||
| 97 | + channel group stays ``BK*KH*KW`` (GM->L1 granularity), but the | ||
| 98 | + L0 level iterates ``k_slices = BK*KH*KW / l0_k`` img2col+move+matmul | ||
| 99 | + steps with ``pos_k``/move-offset advancing through the K domain. | ||
| 100 | + This frees BM from the LOAD3D dst limit ``BM*K_L0 <= 16384`` even | ||
| 101 | + for large BK (the L0 K extent stays small), mirroring aclnn | ||
| 102 | + Conv2DV2's ``kAL1=288 / kL0=48`` strategy. | ||
| 103 | + | ||
| 104 | + With ``l1_shape=[1,1]`` the kernel reduces to the plain per-tile | ||
| 105 | + flow. l0c keeps ``chunk * L1_M`` FP32 accumulators (one per | ||
| 106 | + (c_out-tile-in-chunk, M-block)); every cursor realigns exactly once | ||
| 107 | + per cycle. ``weight_l0_resident=True``: when the per-core weight | ||
| 108 | + slice fits the 64KiB L0B, the weight is moved L1 -> L0B once per | ||
| 109 | + c_out tile and the main loop does no weight move (pairs with | ||
| 110 | + ``c_out_chunk=1``). None = auto-detect from the capacity rule. | ||
| 111 | + """ | ||
| 112 | + bm, bk, bn = conv_params.tile_shape | ||
| 113 | + l1_m, l1_k = (1, 1) if l1_shape is None else (l1_shape[0], l1_shape[1]) | ||
| 114 | + batch_size = conv_params.batch_size | ||
| 115 | + in_channels = conv_params.in_channels | ||
| 116 | + out_channels = conv_params.out_channels | ||
| 117 | + h_in, w_in = conv_params.input_shape | ||
| 118 | + kh, kw = conv_params.kernel_size | ||
| 119 | + sh, sw = conv_params.stride | ||
| 120 | + ph, pw = conv_params.padding | ||
| 121 | + dh, dw = conv_params.dilation | ||
| 122 | + dtype = pl.DT_BF16 if conv_params.dtype == "bfloat16" else pl.DT_FP16 | ||
| 123 | + dtype_size = 2 | ||
| 124 | + | ||
| 125 | + kernel_dim = kh * kw | ||
| 126 | + out_h, out_w = output_hw(conv_params) | ||
| 127 | + | ||
| 128 | + cin0 = 16 | ||
| 129 | + cout0 = 16 | ||
| 130 | + if conv_params.groups != 1: | ||
| 131 | + raise ValueError("groups != 1 not supported yet") | ||
| 132 | + if bm % 16 != 0 or bk % cin0 != 0 or bn % cout0 != 0: | ||
| 133 | + raise ValueError("BM/BK/BN must be 16-aligned (C0=16)") | ||
| 134 | + if l1_m < 1 or l1_k < 1: | ||
| 135 | + raise ValueError("l1_m/l1_k must be >= 1") | ||
| 136 | + if bk > cin0 and in_channels % cin0 != 0: | ||
| 137 | + raise AssertionError( | ||
| 138 | + "BK > 16 requires C_in % 16 == 0 (cross-frame C_in tail zero-padding missing)") | ||
| 139 | + | ||
| 140 | + c_in_tiles = (in_channels + bk - 1) // bk | ||
| 141 | + c_out_tiles = out_channels // bn | ||
| 142 | + if c_in_tiles % l1_k != 0: | ||
| 143 | + raise ValueError("l1_k must divide c_in_tiles") | ||
| 144 | + if bm * l1_m > out_w + ((bm - 1) * sw + (kw - 1) * dw + 1) // sw: | ||
| 145 | + raise ValueError("l1_m*BM coverage exceeds output width") | ||
| 146 | + | ||
| 147 | + dilated_k_h = (kh - 1) * dh + 1 | ||
| 148 | + dilated_k_w = (kw - 1) * dw + 1 | ||
| 149 | + w_win = (l1_m * bm - 1) * sw + dilated_k_w # ideal L1 window covers l1_m blocks | ||
| 150 | + w_win_eff = min(w_win, w_in) # min-window: clamp to the input width | ||
| 151 | + short_win = max(0, w_win - w_win_eff) # right shortfall folded into pad_right | ||
| 152 | + k_l1_full = bk * kernel_dim # K extent per L1 channel group (GM->L1) | ||
| 153 | + k_l0 = k_l1_full if l0_k is None else l0_k # K extent per L0A/L0B step | ||
| 154 | + if k_l1_full % k_l0 != 0: | ||
| 155 | + raise ValueError("l0_k must divide BK*KH*KW") | ||
| 156 | + if bm * k_l0 > 16384: | ||
| 157 | + raise ValueError("LOAD3D dst limit: BM*K_L0 <= 16384") | ||
| 158 | + k_slices = k_l1_full // k_l0 | ||
| 159 | + | ||
| 160 | + h_clamp_max = h_in - dilated_k_h | ||
| 161 | + w_clamp_max = w_in - w_win_eff | ||
| 162 | + | ||
| 163 | + fmap_l1_size = dilated_k_h * w_win_eff * bk * l1_k * dtype_size | ||
| 164 | + weight_l1_size = k_l1_full * bn * dtype_size | ||
| 165 | + # offset moves are range-checked by auto_mutex as [slot+off, slot+off+slot_size), | ||
| 166 | + # so pad the per-slot stride so the largest-offset move stays inside its slot | ||
| 167 | + weight_l1_stride = weight_l1_size + (k_slices - 1) * k_l0 * bn * dtype_size | ||
| 168 | + fmap_l0_size = bm * k_l0 * dtype_size | ||
| 169 | + weight_l0_size = k_l0 * bn * dtype_size | ||
| 170 | + l0c_size = bm * bn * 4 | ||
| 171 | + | ||
| 172 | + l0_addr = 0x0000 | ||
| 173 | + fmap_l1_base = 0x00000 | ||
| 174 | + fmap_align = 32 | ||
| 175 | + weight_l1_base = (fmap_l1_base + fmap_l1_size * 2 + fmap_align - 1) // fmap_align * fmap_align | ||
| 176 | + | ||
| 177 | + db = 2 if double_buffer else 1 | ||
| 178 | + chunk = c_out_tiles if c_out_chunk is None else max(1, min(c_out_chunk, c_out_tiles)) | ||
| 179 | + l0_resident = weight_l0_resident | ||
| 180 | + if l0_resident: | ||
| 181 | + chunk = 1 # L0B holds exactly one c_out tile's full c_in weights | ||
| 182 | + if l0_resident and l0_k is not None: | ||
| 183 | + raise ValueError("l0_k split is incompatible with weight_l0_resident (whole-slot move)") | ||
| 184 | + weight_slots = c_in_tiles * chunk | ||
| 185 | + weight_l0_slots = c_in_tiles if l0_resident else db | ||
| 186 | + # N-dim grid geometry (compile-time): cores map to c_out chunks in groups | ||
| 187 | + # of group_size; rows of a chunk split contiguously across its group | ||
| 188 | + c_out_chunks_ct = (c_out_tiles + chunk - 1) // chunk | ||
| 189 | + group_size = max(1, conv_params.core_num // c_out_chunks_ct) | ||
| 190 | + rows_per_core = (batch_size * out_h + group_size - 1) // group_size | ||
| 191 | + l0c_slots = chunk * l1_m | ||
| 192 | + | ||
| 193 | + if dilated_k_h >= h_in: | ||
| 194 | + raise ValueError("H window larger than input") | ||
| 195 | + if fmap_l1_size * db > weight_l1_base - fmap_l1_base: | ||
| 196 | + raise ValueError("L1 fmap region overflow") | ||
| 197 | + if weight_l1_base + weight_l1_stride * (weight_slots - 1) + weight_l1_size > 524288: | ||
| 198 | + raise ValueError("L1 overflow: fmap slots + resident weight slots exceed 512KiB") | ||
| 199 | + if fmap_l0_size * db > 65536: | ||
| 200 | + raise ValueError("L0A overflow") | ||
| 201 | + if weight_l0_size * weight_l0_slots > 65536: | ||
| 202 | + raise ValueError("L0B overflow") | ||
| 203 | + if l0c_size * l0c_slots > 262144: | ||
| 204 | + raise ValueError("L0C overflow (chunk*l1_m accumulators)") | ||
| 205 | + | ||
| 206 | + @pl.jit(auto_mutex=True) | ||
| 207 | + def conv2d_pypto_pro( | ||
| 208 | + input_tensor: pl.Tensor[[batch_size, in_channels, h_in, w_in], dtype], | ||
| 209 | + weights: pl.Tensor[[out_channels, in_channels, kh, kw], dtype], | ||
| 210 | + output_tensor: pl.Tensor[[batch_size, out_channels, out_h, out_w], | ||
| 211 | + dtype, pl.Layout.NCHW], | ||
| 212 | + ): | ||
| 213 | + fmap_l1_type = pl.TileType(shape=[1, bk * l1_k // cin0, dilated_k_h, w_win_eff, cin0], | ||
| 214 | + dtype=dtype, | ||
| 215 | + target_memory=pl.MemorySpace.Mat, | ||
| 216 | + layout=pl.NC1HWC0) | ||
| 217 | + weight_l1_type = pl.TileType(shape=[bk // cin0 * kernel_dim, bn // cout0, cout0, cin0], | ||
| 218 | + dtype=dtype, | ||
| 219 | + target_memory=pl.MemorySpace.Mat, | ||
| 220 | + layout=pl.FRACTAL_Z) | ||
| 221 | + fmap_l0_type = pl.TileType(shape=[bm, k_l0], | ||
| 222 | + dtype=dtype, | ||
| 223 | + target_memory=pl.MemorySpace.Left, | ||
| 224 | + layout=pl.NZ) | ||
| 225 | + weight_l0_type = pl.TileType(shape=[k_l0, bn], | ||
| 226 | + dtype=dtype, | ||
| 227 | + target_memory=pl.MemorySpace.Right, | ||
| 228 | + layout=pl.ZN) | ||
| 229 | + l0c_type = pl.TileType(shape=[bm, bn], dtype=pl.DT_FP32, | ||
| 230 | + target_memory=pl.MemorySpace.Acc, layout=pl.NZ) | ||
| 231 | + | ||
| 232 | + fmap_l1_buffer = pl.make_tile_group( | ||
| 233 | + type=fmap_l1_type, | ||
| 234 | + addrs=[fmap_l1_base + i * fmap_l1_size for i in range(db)], | ||
| 235 | + mutex_ids='auto', depth=db) | ||
| 236 | + # resident weight slots, laid out [c_in][c_out-in-chunk]; the cursor | ||
| 237 | + # order matches the (c_in outer, c_out inner) loop pair and realigns | ||
| 238 | + # exactly once per (o, w0) tile | ||
| 239 | + weight_l1_buffer = pl.make_tile_group( | ||
| 240 | + type=weight_l1_type, | ||
| 241 | + addrs=[weight_l1_base + i * weight_l1_stride for i in range(weight_slots)], | ||
| 242 | + mutex_ids='auto', depth=weight_slots) | ||
| 243 | + fmap_l0_buffer = pl.make_tile_group( | ||
| 244 | + type=fmap_l0_type, | ||
| 245 | + addrs=[l0_addr + i * fmap_l0_size for i in range(db)], | ||
| 246 | + mutex_ids='auto', depth=db) | ||
| 247 | + weight_l0_buffer = pl.make_tile_group( | ||
| 248 | + type=weight_l0_type, | ||
| 249 | + addrs=[l0_addr + i * weight_l0_size for i in range(weight_l0_slots)], | ||
| 250 | + mutex_ids='auto', depth=weight_l0_slots) | ||
| 251 | + # one accumulator per (M-block, c_out-tile-in-chunk); the cursor | ||
| 252 | + # consumes l0c_slots per c_in step, realigning every step | ||
| 253 | + l0c_buffer = pl.make_tile_group( | ||
| 254 | + type=l0c_type, | ||
| 255 | + addrs=[l0_addr + i * l0c_size for i in range(l0c_slots)], | ||
| 256 | + mutex_ids='auto', depth=l0c_slots) | ||
| 257 | + | ||
| 258 | + core_id = pl.get_block_idx() | ||
| 259 | + num_cores = pl.get_block_num() | ||
| 260 | + c_out_chunks = (c_out_tiles + chunk - 1) // chunk | ||
| 261 | + c_in_groups = c_in_tiles // l1_k | ||
| 262 | + | ||
| 263 | + with pl.section_cube(): | ||
| 264 | + # N-dim grid: each core owns ONE c_out chunk and a private row | ||
| 265 | + # range; the chunk's weight slots are preloaded once and reused | ||
| 266 | + # across every row the core processes (weight MTE2 traffic drops | ||
| 267 | + # from c_out_chunks preloads per core to exactly one). Cores map | ||
| 268 | + # to chunks in groups of group_size; rows of a chunk split across | ||
| 269 | + # its group contiguously. Idle cores (chunk_idx >= c_out_chunks | ||
| 270 | + # or empty row ranges) fall through with zero-iteration loops. | ||
| 271 | + total_row_units = batch_size * out_h | ||
| 272 | + chunk_idx = core_id // group_size | ||
| 273 | + co_base = chunk_idx * chunk | ||
| 274 | + row_begin = (core_id % group_size) * rows_per_core | ||
| 275 | + row_end = pl.min(row_begin + rows_per_core, total_row_units) | ||
| 276 | + | ||
| 277 | + # preload this core's (c_in, c_out) weight slots once; weights | ||
| 278 | + # are batch- and row-independent. After the loop the cursor is | ||
| 279 | + # back at slot 0, and the row loop below consumes exactly | ||
| 280 | + # c_in_tiles*chunk slots per row (realigns every row). | ||
| 281 | + for ci in pl.range(c_in_tiles): | ||
| 282 | + for co in pl.range(chunk): | ||
| 283 | + w_slot = weight_l1_buffer.next() # cursor advances unconditionally | ||
| 284 | + if (co_base + co) < c_out_tiles: # tail chunk: skip OOB slots | ||
| 285 | + pl.load(w_slot, weights, [(co_base + co) * bn, ci * bk, 0, 0]) | ||
| 286 | + if l0_resident: | ||
| 287 | + # adjacent L1->L0B move: RAW pattern proven in the | ||
| 288 | + # non-resident path (auto_mutex tracks slot deps) | ||
| 289 | + pl.move(weight_l0_buffer.next(), w_slot, [0, 0]) | ||
| 290 | + | ||
| 291 | + for work in pl.range(row_begin, row_end): | ||
| 292 | + b_idx = work // out_h | ||
| 293 | + o = work % out_h | ||
| 294 | + # H direction: runtime load origin + top/bottom pads | ||
| 295 | + hs = o * sh - ph | ||
| 296 | + h_load = pl.min(pl.max(hs, 0), h_clamp_max) | ||
| 297 | + d_h = hs - h_load | ||
| 298 | + d_h_bot = pl.max(d_h, 0) | ||
| 299 | + align_h = (sh - d_h_bot % sh) % sh | ||
| 300 | + pad_top = pl.max(-d_h, 0) + align_h | ||
| 301 | + pad_bottom = d_h_bot | ||
| 302 | + pos_row = (d_h_bot + align_h) // sh | ||
| 303 | + | ||
| 304 | + for w0 in pl.range(0, out_w, bm * l1_m): | ||
| 305 | + # W direction at L1-M super-block granularity; with | ||
| 306 | + # min-window the load is clamped to the input width | ||
| 307 | + # (one full row per MTE2 load) and the right | ||
| 308 | + # shortfall (short_win) is folded into pad_right so | ||
| 309 | + # wo_gen still covers the whole super-block. | ||
| 310 | + ws = w0 * sw - pw | ||
| 311 | + w_load = pl.min(pl.max(ws, 0), w_clamp_max) | ||
| 312 | + d_w = ws - w_load | ||
| 313 | + d_w_bot = pl.max(d_w, 0) | ||
| 314 | + align_w = (sw - d_w_bot % sw) % sw | ||
| 315 | + pad_left = pl.max(-d_w, 0) + align_w | ||
| 316 | + pad_right = d_w_bot + short_win | ||
| 317 | + pos_col = (d_w_bot + align_w) // sw | ||
| 318 | + wo_gen = (w_win_eff + pad_left + pad_right - dilated_k_w) // sw + 1 | ||
| 319 | + pos_m_base = pos_row * wo_gen + pos_col | ||
| 320 | + | ||
| 321 | + for cg in pl.range(c_in_groups): | ||
| 322 | + # one MTE2 load: l1_k channel groups of the wide window | ||
| 323 | + fmap_l1 = fmap_l1_buffer.next() | ||
| 324 | + pl.load(fmap_l1, input_tensor, | ||
| 325 | + [b_idx, cg * l1_k * bk, h_load, w_load]) | ||
| 326 | + for gi in pl.range(l1_k): | ||
| 327 | + group_k_base = gi * k_l1_full | ||
| 328 | + step = cg * l1_k + gi | ||
| 329 | + for ks in pl.range(k_slices): | ||
| 330 | + # K_L0 split: slice the group's K domain into | ||
| 331 | + # k_l0-sized L0A/L0B steps (pos_k / move-offset | ||
| 332 | + # advance through the K domain) | ||
| 333 | + pos_k = group_k_base + ks * k_l0 | ||
| 334 | + for j in pl.range(l1_m): | ||
| 335 | + # spatial reuse: same L1 data, M-block j | ||
| 336 | + pos_m = pos_m_base + j * bm | ||
| 337 | + mc_j = pl.min(bm, out_w - (w0 + j * bm)) | ||
| 338 | + fmap_l0 = fmap_l0_buffer.next() | ||
| 339 | + pl.set_validshape(fmap_l0, [mc_j, k_l0]) | ||
| 340 | + pl.img2col(fmap_l0, fmap_l1, | ||
| 341 | + config=pl.Img2ColConfig( | ||
| 342 | + kernel=[kh, kw], stride=[sh, sw], | ||
| 343 | + dilation=[dh, dw], | ||
| 344 | + padding=[pad_top, pad_bottom, | ||
| 345 | + pad_left, pad_right]), | ||
| 346 | + pos_m=pos_m, pos_k=pos_k) | ||
| 347 | + for c_out_idx in pl.range(chunk): | ||
| 348 | + # resident cursors advance unconditionally so | ||
| 349 | + # every (o, w0) tile consumes exactly one full | ||
| 350 | + # cycle; the tail chunk skips OOB slots only. | ||
| 351 | + # the same (c_in, c_out) slot spans all K | ||
| 352 | + # slices: address it BY INDEX so every ks | ||
| 353 | + # re-reads the right slot (a linear cursor | ||
| 354 | + # would mis-address co>0 slots at ks>0). | ||
| 355 | + w_l1 = weight_l1_buffer[step * chunk + c_out_idx] \ | ||
| 356 | + if not l0_resident else weight_l1_buffer.current() | ||
| 357 | + l0c = l0c_buffer.next() | ||
| 358 | + if (co_base + c_out_idx) < c_out_tiles: | ||
| 359 | + if mc_j > 0: | ||
| 360 | + weight_l0 = weight_l0_buffer.next() \ | ||
| 361 | + if not l0_resident else weight_l0_buffer.current() | ||
| 362 | + if not l0_resident: | ||
| 363 | + pl.move(weight_l0, w_l1, [ks * k_l0, 0]) | ||
| 364 | + pl.set_validshape(l0c, [mc_j, bn]) | ||
| 365 | + if step == 0 and ks == 0: | ||
| 366 | + pl.matmul(l0c, fmap_l0, weight_l0) | ||
| 367 | + else: | ||
| 368 | + pl.matmul_acc(l0c, l0c, fmap_l0, weight_l0) | ||
| 369 | + if step == c_in_tiles - 1 \ | ||
| 370 | + and ks == k_slices - 1: | ||
| 371 | + # accumulator complete on the last | ||
| 372 | + # c_in step / K slice; store with | ||
| 373 | + # this handle | ||
| 374 | + pl.store(output_tensor, l0c, | ||
| 375 | + [b_idx, (co_base + c_out_idx) * bn, | ||
| 376 | + o, w0 + j * bm]) | ||
| 377 | + | ||
| 378 | + return conv2d_pypto_pro | ||
| 379 | + | ||
| 380 | + | ||
| 381 | + | ||
| 382 | + | ||
| 383 | +def torch_dtype(conv_params: ConvParams): | ||
| 384 | + dtype_map = { | ||
| 385 | + "bfloat16": torch.bfloat16, | ||
| 386 | + "float16": torch.float16, | ||
| 387 | + } | ||
| 388 | + dt = dtype_map.get(conv_params.dtype) | ||
| 389 | + if dt is None: | ||
| 390 | + raise ValueError(f"unsupported dtype: {conv_params.dtype}") | ||
| 391 | + return dt | ||
| 392 | + | ||
| 393 | + | ||
| 394 | +def generate_inputs(conv_params: ConvParams): | ||
| 395 | + h, w = conv_params.input_shape | ||
| 396 | + f_h, f_w = conv_params.kernel_size | ||
| 397 | + out_h, out_w = output_hw(conv_params) | ||
| 398 | + torch_dt = torch_dtype(conv_params) | ||
| 399 | + input_tensor = torch.randn(conv_params.batch_size, conv_params.in_channels, h, w, | ||
| 400 | + dtype=torch_dt, device="npu") | ||
| 401 | + weights = torch.randn(conv_params.out_channels, conv_params.in_channels, f_h, f_w, | ||
| 402 | + dtype=torch_dt, device="npu") | ||
| 403 | + output_tensor = torch.empty(conv_params.batch_size, conv_params.out_channels, out_h, out_w, | ||
| 404 | + dtype=torch_dt, device="npu") | ||
| 405 | + return input_tensor, weights, output_tensor | ||
| 406 | + | ||
| 407 | + | ||
| 408 | +def generate_golden(input_tensor, weights, conv_params: ConvParams): | ||
| 409 | + return torch.nn.functional.conv2d( | ||
| 410 | + input_tensor, weights, | ||
| 411 | + stride=tuple(conv_params.stride), padding=tuple(conv_params.padding), | ||
| 412 | + dilation=tuple(conv_params.dilation), groups=conv_params.groups) | ||
| 413 | + | ||
| 414 | + | ||
| 415 | +def run_case(device_id, case_json, kernel_builder=make_conv2d_kernel, **builder_kwargs): | ||
| 416 | + torch_npu.npu.set_device(device_id) | ||
| 417 | + conv_params = ConvParams( | ||
| 418 | + batch_size=case_json["batch_size"], | ||
| 419 | + input_shape=case_json["input_shape"], | ||
| 420 | + in_channels=case_json["in_channels"], | ||
| 421 | + out_channels=case_json["out_channels"], | ||
| 422 | + kernel_size=case_json["kernel_size"], | ||
| 423 | + stride=case_json["stride"], | ||
| 424 | + padding=case_json["padding"], | ||
| 425 | + dilation=case_json["dilation"], | ||
| 426 | + groups=case_json["groups"], | ||
| 427 | + dtype=case_json["dtype"], | ||
| 428 | + tile_shape=case_json["tile_shape"], | ||
| 429 | + core_num=case_json["core_num"], | ||
| 430 | + ) | ||
| 431 | + input_tensor, weights, output_tensor = generate_inputs(conv_params) | ||
| 432 | + golden = generate_golden(input_tensor, weights, conv_params) | ||
| 433 | + torch.npu.synchronize() | ||
| 434 | + | ||
| 435 | + conv2d_pypto_pro = kernel_builder(conv_params, **builder_kwargs) | ||
| 436 | + conv2d_pypto_pro[conv_params.core_num](input_tensor, weights, output_tensor) | ||
| 437 | + torch.npu.synchronize() | ||
| 438 | + | ||
| 439 | + torch.testing.assert_close(output_tensor.cpu(), golden.cpu(), atol=0.01, rtol=0.01) | ||
| 440 | + return True | ||
| @@ -0,0 +1,114 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | + | ||
| 12 | +"""Conv2D (PyPTO-Pro) performance-scenario suite — 19 convolution specs | ||
| 13 | +(shape / stride / padding / dilation / dtype / groups) with analytically | ||
| 14 | +derived, per-spec measured launch configs. Kernel lives in | ||
| 15 | +ops/pro/experimental/conv/op_kernel/conv2d.py (padding-runtime, | ||
| 16 | +multi-core grid-stride, double-buffered, chunked weight residency). | ||
| 17 | + | ||
| 18 | +Each case runs in a fresh interpreter via subprocess: torch_npu refuses | ||
| 19 | +NPU re-initialization in a forked child once the runtime was initialized | ||
| 20 | +in the parent (conftest queries the SoC version there), so exec is the | ||
| 21 | +safe pattern — same approach as the xrunfk runner. | ||
| 22 | +""" | ||
| 23 | + | ||
| 24 | +import json | ||
| 25 | +import os | ||
| 26 | +import subprocess | ||
| 27 | +import sys | ||
| 28 | +from pathlib import Path | ||
| 29 | + | ||
| 30 | +import pytest | ||
| 31 | + | ||
| 32 | +_CONV = Path(__file__).resolve().parents[4] / "ops" / "pro" / "experimental" / "conv" | ||
| 33 | +_KERNEL = _CONV / "op_kernel" | ||
| 34 | + | ||
| 35 | +SPECS = [ | ||
| 36 | + ("ConvPerf_001", [6, 32, 352, 640], [64, 32, 3, 3], [2, 2], [1, 1, 1, 1], [1, 1]), | ||
| 37 | + ("ConvPerf_002", [6, 64, 176, 320], [64, 64, 3, 3], [2, 2], [1, 1, 1, 1], [1, 1]), | ||
| 38 | + ("ConvPerf_003", [6, 64, 88, 160], [64, 64, 3, 3], [1, 1], [1, 1, 1, 1], [1, 1]), | ||
| 39 | + ("ConvPerf_004", [6, 64, 176, 320], [64, 64, 1, 1], [2, 2], [0, 0, 0, 0], [1, 1]), | ||
| 40 | + ("ConvPerf_005", [6, 64, 88, 160], [128, 64, 3, 3], [1, 1], [1, 1, 1, 1], [1, 1]), | ||
| 41 | + ("ConvPerf_006", [6, 128, 88, 160], [128, 128, 3, 3], [1, 1], [1, 1, 1, 1], [1, 1]), | ||
| 42 | + ("ConvPerf_007", [6, 64, 88, 160], [128, 64, 1, 1], [1, 1], [0, 0, 0, 0], [1, 1]), | ||
| 43 | + ("ConvPerf_008", [6, 128, 88, 160], [128, 128, 3, 3], [2, 2], [1, 1, 1, 1], [1, 1]), | ||
| 44 | + ("ConvPerf_009", [6, 128, 44, 80], [128, 128, 3, 3], [1, 1], [1, 1, 1, 1], [1, 1]), | ||
| 45 | + ("ConvPerf_010", [6, 128, 88, 160], [128, 128, 1, 1], [2, 2], [0, 0, 0, 0], [1, 1]), | ||
| 46 | + ("ConvPerf_011", [6, 128, 44, 80], [256, 128, 3, 3], [1, 1], [1, 1, 1, 1], [1, 1]), | ||
| 47 | + ("ConvPerf_012", [6, 256, 44, 80], [256, 256, 3, 3], [1, 1], [1, 1, 1, 1], [1, 1]), | ||
| 48 | + ("ConvPerf_013", [6, 128, 44, 80], [256, 128, 1, 1], [1, 1], [0, 0, 0, 0], [1, 1]), | ||
| 49 | + ("ConvPerf_014", [6, 256, 44, 80], [256, 256, 3, 3], [2, 2], [1, 1, 1, 1], [1, 1]), | ||
| 50 | + ("ConvPerf_015", [6, 256, 22, 40], [256, 256, 3, 3], [1, 1], [1, 1, 1, 1], [1, 1]), | ||
| 51 | + ("ConvPerf_016", [6, 256, 44, 80], [256, 256, 1, 1], [2, 2], [0, 0, 0, 0], [1, 1]), | ||
| 52 | + ("ConvPerf_017", [6, 256, 22, 40], [512, 256, 3, 3], [1, 1], [1, 1, 1, 1], [1, 1]), | ||
| 53 | + ("ConvPerf_018", [6, 512, 22, 40], [512, 512, 3, 3], [1, 1], [1, 1, 1, 1], [1, 1]), | ||
| 54 | + ("ConvPerf_019", [6, 256, 22, 40], [512, 256, 1, 1], [1, 1], [0, 0, 0, 0], [1, 1]), | ||
| 55 | +] | ||
| 56 | + | ||
| 57 | +# Measured per-spec winner (structure A = weight-resident c_out-outer, | ||
| 58 | +# structure B = fmap-hoisted chunked residency), profiled with the CANN | ||
| 59 | +# profiler; see ops/pro/experimental/conv/RESULTS.md. | ||
| 60 | +TUNED_CONFIGS = { | ||
| 61 | + 'ConvPerf_001': {'tile': '[320, 16, 64]', 'chunk': 1, 'l1': None, 'resident': False, 'l0k': 48}, | ||
| 62 | + 'ConvPerf_002': {'tile': '[160, 16, 64]', 'chunk': 1, 'l1': None, 'resident': False, 'l0k': 48}, | ||
| 63 | + 'ConvPerf_003': {'tile': '[112, 16, 64]', 'chunk': 1, 'l1': None, 'resident': False}, | ||
| 64 | + 'ConvPerf_004': {'tile': '[192, 64, 64]', 'chunk': 1, 'l1': None, 'resident': False}, | ||
| 65 | + 'ConvPerf_005': {'tile': '[112, 16, 64]', 'chunk': 2, 'l1': None, 'resident': False}, | ||
| 66 | + 'ConvPerf_006': {'tile': '[160, 16, 64]', 'chunk': 2, 'l1': None, 'resident': False, 'l0k': 48}, | ||
| 67 | + 'ConvPerf_007': {'tile': '[192, 16, 64]', 'chunk': 2, 'l1': [1, 4], 'resident': False}, | ||
| 68 | + 'ConvPerf_008': {'tile': '[112, 32, 64]', 'chunk': 2, 'l1': None, 'resident': False, 'l0k': 144}, | ||
| 69 | + 'ConvPerf_009': {'tile': '[112, 16, 64]', 'chunk': 2, 'l1': None, 'resident': False}, | ||
| 70 | + 'ConvPerf_010': {'tile': '[80, 64, 64]', 'chunk': 2, 'l1': None, 'resident': False}, | ||
| 71 | + 'ConvPerf_011': {'tile': '[112, 32, 64]', 'chunk': 2, 'l1': [1, 2], 'resident': False, 'l0k': 144}, | ||
| 72 | + 'ConvPerf_012': {'tile': '[112, 32, 64]', 'chunk': 1, 'l1': [1, 2], 'resident': False, 'l0k': 144}, | ||
| 73 | + 'ConvPerf_013': {'tile': '[80, 64, 64]', 'chunk': 2, 'l1': None, 'resident': False}, | ||
| 74 | + 'ConvPerf_014': {'tile': '[64, 16, 64]', 'chunk': 1, 'l1': [1, 2], 'resident': False}, | ||
| 75 | + 'ConvPerf_015': {'tile': '[64, 16, 64]', 'chunk': 1, 'l1': None, 'resident': False}, | ||
| 76 | + 'ConvPerf_016': {'tile': '[112, 128, 64]', 'chunk': 2, 'l1': None, 'resident': False}, | ||
| 77 | + 'ConvPerf_017': {'tile': '[64, 16, 64]', 'chunk': 1, 'l1': [1, 2], 'resident': False}, | ||
| 78 | + 'ConvPerf_018': {'tile': '[48, 64, 32]', 'chunk': 1, 'l1': [1, 2], 'resident': False, 'l0k': 288}, | ||
| 79 | + 'ConvPerf_019': {'tile': '[112, 128, 64]', 'chunk': 4, 'l1': None, 'resident': False}, | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +pytestmark = pytest.mark.soc("950") | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +def _run_case(spec): | ||
| 86 | + name, fmap, weight, stride, padding, dilation = spec | ||
| 87 | + tuned = TUNED_CONFIGS[name] | ||
| 88 | + tile = tuned["tile"] | ||
| 89 | + if isinstance(tile, str): | ||
| 90 | + tile = json.loads(tile) | ||
| 91 | + case = { | ||
| 92 | + "case_index": name, | ||
| 93 | + "batch_size": fmap[0], "input_shape": fmap[2:], "in_channels": fmap[1], | ||
| 94 | + "out_channels": weight[0], "kernel_size": weight[2:], "stride": stride, | ||
| 95 | + "padding": padding[:2], "dilation": dilation, "groups": 1, | ||
| 96 | + "dtype": "bfloat16", "tile_shape": tile, "core_num": 32, | ||
| 97 | + } | ||
| 98 | + cmd = [sys.executable, "-c", | ||
| 99 | + "import sys, json; sys.path.insert(0, {op_kernel!r}); " | ||
| 100 | + "from conv2d import run_case; " | ||
| 101 | + "run_case(0, json.loads(sys.argv[1]), c_out_chunk={chunk}, " | ||
| 102 | + "weight_l0_resident={resident}, l1_shape={l1}, l0_k={l0k})".format( | ||
| 103 | + op_kernel=str(_KERNEL), chunk=tuned["chunk"], | ||
| 104 | + resident=tuned["resident"], l1=tuned["l1"], l0k=tuned.get("l0k")), | ||
| 105 | + json.dumps(case)] | ||
| 106 | + env = dict(os.environ) | ||
| 107 | + env.setdefault("TILE_FWK_DEVICE_ID", "0") | ||
| 108 | + r = subprocess.run(cmd, env=env, cwd=str(_CONV)) | ||
| 109 | + assert r.returncode == 0, f"{name} failed, see output above" | ||
| 110 | + | ||
| 111 | + | ||
| 112 | +@pytest.mark.parametrize("spec", SPECS, ids=[s[0] for s in SPECS]) | ||
| 113 | +def test_conv2d_perf_spec(spec): | ||
| 114 | + _run_case(spec) | ||