Merged
add allgathermm decode(ubmem) experimental #15418
王亮培Add on 23 days ago
add allgathermm decode(ubmem) experimental #15418
Merged
Total: 21 files changed+4577-292
| @@ -0,0 +1,21 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 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 | + | ||
| 11 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 12 | +if(NOT ENABLE_TEST) | ||
| 13 | + list(REMOVE_ITEM CURRENT_DIRS tests) | ||
| 14 | +endif() | ||
| 15 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 16 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 17 | + add_subdirectory(${SUB_DIR}) | ||
| 18 | + endif() | ||
| 19 | +endforeach() | ||
| 20 | + | ||
| 21 | +set(MC2_COMPILE ${SUB_MC2_COMPILE} PARENT_SCOPE) | ||
| @@ -0,0 +1,379 @@ | |||
| 1 | +# AllGatherMatmulV3(ubmem融合方案) | ||
| 2 | + | ||
| 3 | +本文档介绍 `experimental/mc2/all_gather_matmul_v3` 中基于 HCCL **ubmem 窗口(MTE window)** 的 | ||
| 4 | +AllGather + MX 量化矩阵乘融合方案,包括接口说明、支持范围、详细设计、编译部署与测试方法。 | ||
| 5 | + | ||
| 6 | +> 同目录族的 mc2 URMA 方案(`mc2/all_gather_matmul_v3`)通过 URMA all-gather 收集左矩阵后再做 | ||
| 7 | +> MX 量化矩阵乘;本方案改用ubmem 窗口完成 gather,AIV 通过读模式,直接把远端数据按照K方向切分的方式分批搬进本卡窗口、AIC 从窗口读取参与 MMAD,从而把通信与计算融合在同一个 kernel。 | ||
| 8 | + | ||
| 9 | +--- | ||
| 10 | + | ||
| 11 | +## 1. 方案概览 | ||
| 12 | + | ||
| 13 | +- **融合语义**:各卡持有自己的左矩阵 `x1[M, K]` 与 MX scale,AllGather 后得到 | ||
| 14 | + `A_all[rankSize * M, K]`,再与本卡右矩阵 `x2` 做 MX 量化矩阵乘,输出 `y[rankSize * M, N]`。 | ||
| 15 | + | ||
| 16 | + $$ | ||
| 17 | + y = \sum_{g=0}^{\lceil K/32 \rceil}\left( AllGather(x1) @ x2 \right) \cdot | ||
| 18 | + \left( AllGather(x1\_scale) \cdot x2\_scale \right) | ||
| 19 | + $$ | ||
| 20 | + | ||
| 21 | + scale 按 K 轴每 32 个元素一组(group size = 32),每组 2 个 e8m0 scale 值。 | ||
| 22 | + | ||
| 23 | +- **算子语义如图**: | ||
| 24 | + | ||
| 25 | + 1. Host 侧创建 ubmem 通信上下文; | ||
| 26 | + 2. AIV:把本卡 `x1`/`x1_scale` 拷入本卡窗口对应槽位,并把其余 rank 的 `x1`/`x1_scale` | ||
| 27 | + 拉入本卡窗口;按 K 方向分批次写入,每轮写完后通知AIC启动matmul计算; | ||
| 28 | + 3. AIC:从窗口读取 `A_all` 与 scale(首轮allgather结束即可开始 MMAD),与本地 `x2` 完成矩阵乘, | ||
| 29 | + 最后K方向全部算完后结果经 fixpipe 直接写 `y`。 | ||
| 30 | + | ||
| 31 | +- **主要收益**: | ||
| 32 | + - AIC 按 K 方向多轮次计算(而非等全部 AllGather 完成),首轮切K数据就绪即开始计算,掩盖通信时延,适用于decode小M场景; | ||
| 33 | + | ||
| 34 | +--- | ||
| 35 | + | ||
| 36 | +## 2. 支持范围 | ||
| 37 | + | ||
| 38 | +### 2.1 产品 | ||
| 39 | + | ||
| 40 | +| 产品 | 支持 | | ||
| 41 | +| --- | --- | | ||
| 42 | +| Ascend 950PR / 950DT 系列 | 支持 | | ||
| 43 | +| Atlas A3 / A2 / 推理系列 / 训练系列 | 不支持 | | ||
| 44 | + | ||
| 45 | +### 2.2 dtype 组合 | ||
| 46 | + | ||
| 47 | +| x1 | x2 | y | 说明 | | ||
| 48 | +| --- | --- | --- | --- | | ||
| 49 | +| e4m3 | e4m3 | bf16 / fp16 | 同 dtype | | ||
| 50 | +| e5m2 | e5m2 | bf16 / fp16 | 同 dtype | | ||
| 51 | +| e4m3 | e5m2 | bf16 / fp16 | fp8 异构 | | ||
| 52 | +| e5m2 | e4m3 | bf16 / fp16 | fp8 异构 | | ||
| 53 | +| fp4(e2m1, uint8 打包) | fp4 | bf16 / fp16 | 仅 ND,x1/x2 必须同为 fp4 | | ||
| 54 | + | ||
| 55 | +- fp8 场景 x1/x2 可任意混用; | ||
| 56 | +- fp4 以 uint8 打包(2 元素/字节),实际传入末维为 `K/2`,需传 `x1_dtype=x2_dtype=296`。 | ||
| 57 | + | ||
| 58 | +### 2.3 右矩阵布局 | ||
| 59 | + | ||
| 60 | +| 布局 | 存储形态 | kernel LayoutB | | ||
| 61 | +| --- | --- | --- | | ||
| 62 | +| ND + 转置 B | `[N, K]`(对外可传 `.t()` 视图) | `dn_ext_layout_ptn` | | ||
| 63 | +| ND + 非转置 B | 连续 `[K, N]` | `nd_ext_layout_ptn` | | ||
| 64 | +| NZ + 转置 B | `(ceil(K/32), ceil(N/16), 16, 32)` | `zn_layout_ptn` | | ||
| 65 | +| NZ + 非转置 B | `(ceil(N/32), ceil(K/16), 16, 32)` | `nz_layout_ptn` | | ||
| 66 | + | ||
| 67 | +- scale 布局随方向切换:转置 B 为 `[N, ceil(K/64), 2]`,非转置 B 为 `[ceil(K/64), N, 2]`; | ||
| 68 | +- fp4 仅支持 ND。 | ||
| 69 | + | ||
| 70 | +### 2.4 其他限制 | ||
| 71 | + | ||
| 72 | +- `rank_size ∈ {2, 4, 8}`; | ||
| 73 | +- `K ∈ [256, 65535)`;`fp4` 场景 K 须为偶数; | ||
| 74 | +- `bias` 暂不支持(必须传 `None`); | ||
| 75 | +- `gather_out` / `amax_out` 为预留输出,当前返回 `(0,)` 空占位 tensor。 | ||
| 76 | + | ||
| 77 | +--- | ||
| 78 | + | ||
| 79 | +## 3. 接口说明 | ||
| 80 | + | ||
| 81 | +### 3.1 函数原型 | ||
| 82 | + | ||
| 83 | +```python | ||
| 84 | +cann_ops_transformer.all_gather_quant_matmul( | ||
| 85 | + x1, | ||
| 86 | + x2, | ||
| 87 | + group, | ||
| 88 | + *, | ||
| 89 | + bias=None, | ||
| 90 | + x1_scale=None, | ||
| 91 | + x2_scale=None, | ||
| 92 | + group_sizes=None, | ||
| 93 | + x1_dtype=None, | ||
| 94 | + x2_dtype=None, | ||
| 95 | + x1_scale_dtype=None, | ||
| 96 | + x2_scale_dtype=None, | ||
| 97 | + y_dtype=None, | ||
| 98 | + comm_mode=None, | ||
| 99 | +) -> (Tensor, Tensor, Tensor) | ||
| 100 | +``` | ||
| 101 | + | ||
| 102 | +ubmem 路径必须使用 `comm_mode="ubmem"`(默认值即 `"ubmem"`)。MX 量化路径必须传 | ||
| 103 | +`x1_scale`/`x2_scale`;传 `None` 会在 meta / torch extension / aclnn 任一层直接报错。 | ||
| 104 | + | ||
| 105 | +### 3.2 参数说明 | ||
| 106 | + | ||
| 107 | +| 参数 | 类型 | 必选 | 说明 | dtype | 格式 / shape | | ||
| 108 | +| --- | --- | --- | --- | --- | --- | | ||
| 109 | +| `x1` | Tensor | 是 | 各卡本地左矩阵。fp4 场景 uint8 打包,末维为 `K/2`,配合 `x1_dtype=296` | fp8_e4m3fn / fp8_e5m2 / uint8(fp4) | ND,`(M, K)`(fp4 为 `(M, K/2)`) | | ||
| 110 | +| `x2` | Tensor | 是 | 右矩阵,支持转置/非转置两种方向 | fp8_e4m3fn / fp8_e5m2 / uint8(fp4) | ND:`[N,K]` 的 `.t()` 视图或连续 `[K,N]`;NZ:2D 逻辑 shape 或 4D storage | | ||
| 111 | +| `group` | ProcessGroup | 是 | HCCL 通信域 | - | - | | ||
| 112 | +| `bias` | Tensor | 否 | **ubmem 路径不支持,必须为 None** | - | - | | ||
| 113 | +| `x1_scale` | Tensor | 是 | x1 的 MX scale | e8m0(uint8 存储时配 `x1_scale_dtype=293`) | `(M, ceil(K/64), 2)` | | ||
| 114 | +| `x2_scale` | Tensor | 是 | x2 的 MX scale,布局随右矩阵方向 | e8m0(同上) | 转置:`(N, ceil(K/64), 2)`;非转置:`(ceil(K/64), N, 2)` | | ||
| 115 | +| `group_sizes` | List[int] | 否 | MX 仅支持 `[1, 1, 32]`,None 时自动推导 | int | - | | ||
| 116 | +| `x1_dtype` | int | 否 | None=按 tensor dtype;fp4 传 `296` | int | - | | ||
| 117 | +| `x2_dtype` | int | 否 | None=按 tensor dtype;fp4 传 `296` | int | - | | ||
| 118 | +| `x1_scale_dtype` | int | 否 | None=按 tensor dtype;uint8 存储 e8m0 传 `293` | int | - | | ||
| 119 | +| `x2_scale_dtype` | int | 否 | 同上 | int | - | | ||
| 120 | +| `y_dtype` | int | 否 | 输出 dtype:`15`(BF16,默认) / `5`(FP16); | int | - | | ||
| 121 | +| `comm_mode` | str | 否 | ubmem 路径必须为 `"ubmem"` | str | - | | ||
| 122 | + | ||
| 123 | +### 3.3 返回值 | ||
| 124 | + | ||
| 125 | +| 参数 | 说明 | dtype | shape | | ||
| 126 | +| --- | --- | --- | --- | | ||
| 127 | +| `y` | 融合计算结果 | 由 `y_dtype` 指定(BF16/FP16) | `(M * rankSize, N)` | | ||
| 128 | +| `gather_out` | 预留,未实现 | 同 `x1` | `(0,)` | | ||
| 129 | +| `amax_out` | 预留,未实现 | float32 | `(0,)` | | ||
| 130 | + | ||
| 131 | +### 3.4 调用示例(4 卡,ND 转置 B) | ||
| 132 | + | ||
| 133 | +以下示例假设已完成第 5 节的算子包与 torch extension 安装,并已 `source` CANN 的 `set_env.sh`。 | ||
| 134 | + | ||
| 135 | +```python | ||
| 136 | +import math | ||
| 137 | + | ||
| 138 | +# 默认使用 CANN 的 HCCL 内置 buffer;若运行时提示窗口超限,再按提示设置 | ||
| 139 | +# os.environ["HCCL_BUFFSIZE"] = "2000" # 单位 MB | ||
| 140 | +import torch | ||
| 141 | +import torch_npu | ||
| 142 | +import torch.distributed as dist | ||
| 143 | +import cann_ops_transformer | ||
| 144 | + | ||
| 145 | + | ||
| 146 | +def run(rank, world_size, m, k, n): | ||
| 147 | + torch_npu.npu.set_device(rank % 4) | ||
| 148 | + dist.init_process_group("hccl", rank=rank, world_size=world_size, | ||
| 149 | + init_method="tcp://127.0.0.1:29500") | ||
| 150 | + group = dist.new_group(ranks=list(range(world_size))) | ||
| 151 | + | ||
| 152 | + x1 = torch.randn(m, k).to(torch.float8_e4m3fn).npu() | ||
| 153 | + x2 = torch.randn(n, k).to(torch.float8_e4m3fn).npu() # 物理 [N, K] | ||
| 154 | + x1_scale = torch.randint(0, 256, (m, math.ceil(k / 64), 2), dtype=torch.uint8).npu() | ||
| 155 | + x2_scale = torch.randint(0, 256, (n, math.ceil(k / 64), 2), dtype=torch.uint8).npu() | ||
| 156 | + | ||
| 157 | + y, _, _ = cann_ops_transformer.all_gather_quant_matmul( | ||
| 158 | + x1, | ||
| 159 | + x2.t(), # ND 转置 B:传 [N,K] 的 .t() 视图 | ||
| 160 | + group, | ||
| 161 | + x1_scale=x1_scale, | ||
| 162 | + x2_scale=x2_scale, | ||
| 163 | + group_sizes=[1, 1, 32], | ||
| 164 | + x1_scale_dtype=293, | ||
| 165 | + x2_scale_dtype=293, | ||
| 166 | + y_dtype=15, # BF16 | ||
| 167 | + comm_mode="ubmem", | ||
| 168 | + ) | ||
| 169 | + torch.npu.synchronize() | ||
| 170 | + print(f"[rank {rank}] y={tuple(y.shape)} {y.dtype}") | ||
| 171 | + dist.barrier() | ||
| 172 | + dist.destroy_process_group() | ||
| 173 | +``` | ||
| 174 | + | ||
| 175 | +其他布局的构造方式: | ||
| 176 | + | ||
| 177 | +```python | ||
| 178 | +# ND 非转置 B:物理 [K, N],直接传连续 tensor;x2_scale 为 [ceil(K/64), N, 2] | ||
| 179 | +x2_kn = torch.randn(k, n).to(torch.float8_e4m3fn).npu() | ||
| 180 | + | ||
| 181 | +# NZ 转置 B:对物理 [N, K] 做 format_cast(29);x2_scale 为 [N, ceil(K/64), 2] | ||
| 182 | +x2_nz = torch_npu.npu_format_cast(x2, 29) | ||
| 183 | + | ||
| 184 | +# NZ 非转置 B:对物理 [K, N] 做 format_cast(29);x2_scale 为 [ceil(K/64), N, 2] | ||
| 185 | +x2_kn_nz = torch_npu.npu_format_cast(x2_kn, 29) | ||
| 186 | +``` | ||
| 187 | + | ||
| 188 | +fp4 场景:`x1/x2` 用 uint8 打包,调用时传 | ||
| 189 | +`x1_dtype=296, x2_dtype=296`,且仅支持 ND。 | ||
| 190 | + | ||
| 191 | +--- | ||
| 192 | + | ||
| 193 | +## 4. 详细方案设计 | ||
| 194 | + | ||
| 195 | +整体流程(状态同步 → AIV gather → AIC matmul)如下图: | ||
| 196 | + | ||
| 197 | + | ||
| 198 | + | ||
| 199 | +### 4.1 状态区逻辑 | ||
| 200 | + | ||
| 201 | +每个 rank 的通信窗口 = HCCL 内置 buffer,前 4KB 为状态区,其后依次是 data 区 | ||
| 202 | +(`rankSize` 个 x1 槽位)与 scale 区(`rankSize` 个 scale 槽位)。状态区按 | ||
| 203 | +`srcRank × coreIdx` 划槽(每槽 32B,实际写 1 个 float)。 | ||
| 204 | + | ||
| 205 | +- **本地就绪**:`CopyLocalData` 完成后,每个非 leftover 核向本组负责的 peer 写 1 个 | ||
| 206 | + `flag=1.0`,槽位为 `(myRank, myCoreIdx)`; | ||
| 207 | +- **配对等待**:每个核只轮询本卡窗口里 `(remoteRank, myCoreIdx)` 的槽位,读到 | ||
| 208 | + `1.0 ± 0.5` 即认为配对的远端分片已就绪,随后清零; | ||
| 209 | +- **1:1 握手**:不做全局 Sum、不要求所有 rank 到齐;leftover 核不参与; | ||
| 210 | +- 作用:先确认"本地数据已写好、远端对应分片已就绪",再做远端搬运,避免读写竞争。 | ||
| 211 | + | ||
| 212 | +### 4.2 allgather 阶段 | ||
| 213 | + | ||
| 214 | +**本地填槽**(`CopyLocalData`): | ||
| 215 | + | ||
| 216 | +- 除最后 1 个 V 核外,其余核按 M 行均分,把本 rank 的 x1 从 GM 搬到本卡窗口的 self 槽位; | ||
| 217 | +- 最后 1 个 V 核单独搬运本 rank 的 scale; | ||
| 218 | +- 完成后 `SyncAll`,保证本地槽位对所有核可见。 | ||
| 219 | + | ||
| 220 | +**远端分组**(只对 `rankSize-1` 个远端 rank 分组): | ||
| 221 | + | ||
| 222 | +``` | ||
| 223 | +groupSize = V核数 / (rankSize - 1) | ||
| 224 | +groupIdx = aivId / groupSize | ||
| 225 | +peer = (curRankId + 1 + groupIdx) % rankSize # 组间轮转 | ||
| 226 | +leftover = groupIdx >= rankSize - 1 # 多余核,不参与远端搬运 | ||
| 227 | +kDim = min(ceil(K/512), groupSize, 2) # K 方向最多 2 个核 | ||
| 228 | +mDim = min(groupSize / kDim, M) # M 方向均分 | ||
| 229 | +``` | ||
| 230 | + | ||
| 231 | +- 组内 `kDim` 个核按奇偶 512 元素切片覆盖 K,`mDim` 个核按行切分 M; | ||
| 232 | +- 每组最后 1 个核兼搬该远端 rank 的 scale; | ||
| 233 | +- 示例:V核 = 24、rankSize = 4 → 8 核/组,kDim = 2、mDim = 4; | ||
| 234 | +- leftover 核不搬远端数据(本 rank 数据由本地拷贝完成),但仍参与轮间 `SyncAll` 与 flag 计数。 | ||
| 235 | + | ||
| 236 | +**逐轮搬运**: | ||
| 237 | + | ||
| 238 | +- 粒度:512 个 K 元素为一切片,一轮 = 1024 个 K(kDim=2 时两个切片交替); | ||
| 239 | +- 单轮:远端 GM → UB(ping/pong)→ 本卡窗口 GM; | ||
| 240 | +- 每轮结束:`SyncAll` 轮间屏障 → `CrossCoreSetFlag` 通知 AIC 本轮数据可读。 | ||
| 241 | + | ||
| 242 | +### 4.3 matmul 阶段 | ||
| 243 | + | ||
| 244 | +- **MX 量化矩阵乘**:A/B 以 fp8/fp4 原值参与计算;e8m0 block scale(每 32 个 K 一组) | ||
| 245 | + 由 mad_mx 指令在乘加过程中直接应用(等价于 A、B 各乘自己的 scale 后立即相乘累加); | ||
| 246 | +- **按轮等待**:AIC 读第 `iter` 段 `kL1` 前,累计等待 `ceil((iter+1)*kL1/1024)` 次 flag, | ||
| 247 | + 保证该段所有列已 gather 完成; | ||
| 248 | +- **装载顺序**:B/bias 不依赖 gather,先发 GM→L1;再 `CrossCoreWaitFlag`;随后装载 | ||
| 249 | + A、scaleA(scaleB 随 B 一起);L1→L0 → MMAD; | ||
| 250 | +- **输出**:整个 K 方向在 L0C 累加完成后,fixpipe 一次写 `y`(bf16/fp16)。 | ||
| 251 | + | ||
| 252 | +### 4.4 优化手段 | ||
| 253 | + | ||
| 254 | +- **K 轮流水**:AIC 不等完整 AllGather,首轮就绪即开算,通信与计算按轮重叠; | ||
| 255 | +- **B/bias 预取**:把不依赖 gather 的装载提前到等待 flag 之前,隐藏部分等待时间; | ||
| 256 | +- **小行数远端预读**: | ||
| 257 | + - 一轮的搬运量(payload)= 本核行数 × 每切片字节数;该数据能一次装进一个 UB | ||
| 258 | + buffer 时称为"单 chunk"(`行数 ≤ xBufSize_ / 每切片字节数`),否则要按 buffer | ||
| 259 | + 容量分多次 GM→UB 拷贝,称为"多 chunk"; | ||
| 260 | + - 仅当"单 chunk"且单核行数 ≤ 14 时才启用预读:下一轮的远端读(MTE2)提前到 | ||
| 261 | + 本轮写(MTE3)和轮间屏障之前发出,与之重叠;轮间 `SyncAll` 只等 MTE3 | ||
| 262 | + (`{PIPE_MTE3, PIPE_MTE3}`); | ||
| 263 | + - "多 chunk"或大 payload 不启用预读,避免抢当前轮带宽; | ||
| 264 | + | ||
| 265 | +--- | ||
| 266 | + | ||
| 267 | +## 5. 编译、部署与运行 | ||
| 268 | + | ||
| 269 | +### 5.1 环境要求 | ||
| 270 | + | ||
| 271 | +- 硬件:Ascend 950PR / 950DT,至少 `world_size` 张卡(示例 4 卡); | ||
| 272 | +- 软件:CANN toolkit、Python 3.10、torch / torch_npu、numpy、ml_dtypes; | ||
| 273 | +- 编译依赖:gcc/g++(torch extension 首次调用时需要 JIT 编译)、Python `build` 包 | ||
| 274 | + (`pip install build`,用于打 whl;缺失时 `build.sh` 会跳过 whl 构建且不报错); | ||
| 275 | +- 环境变量: | ||
| 276 | + | ||
| 277 | +```bash | ||
| 278 | +source $CANN_HOME/set_env.sh # 例如 /home/xxx/Ascend/cann-9.3.0/set_env.sh | ||
| 279 | +export ASCEND_RT_VISIBLE_DEVICES=0,1,2,3 # 数量须与 --world-size 一致 | ||
| 280 | +``` | ||
| 281 | + | ||
| 282 | +- 默认不要设置 `HCCL_BUFFSIZE`:ubmem 窗口直接使用 HCCL 内置 buffer;若运行时报窗口超限, | ||
| 283 | + 再按提示适当增大 `HCCL_BUFFSIZE`(单位 MB)。 | ||
| 284 | + | ||
| 285 | +### 5.2 编译并安装自定义算子包 | ||
| 286 | + | ||
| 287 | +```bash | ||
| 288 | +cd ops-transformer | ||
| 289 | +source $CANN_HOME/set_env.sh | ||
| 290 | +bash build.sh --pkg --experimental --soc=ascend950 --ops=all_gather_matmul_v3 -j16 | ||
| 291 | +./build_out/cann-ops-transformer-custom_linux-x86_64.run --quiet | ||
| 292 | +``` | ||
| 293 | + | ||
| 294 | +- `--pkg` 产出 `build_out/cann-ops-transformer-custom_linux-x86_64.run`,安装到 | ||
| 295 | + `$ASCEND_OPP_PATH/vendors/custom_transformer`; | ||
| 296 | +- 安装后确认:`ls $ASCEND_OPP_PATH/vendors/custom_transformer`; | ||
| 297 | +- 安装脚本会提示把 `op_api/lib` 加入动态库路径;直接写 Python 调用时必须设置(`run_test.sh` | ||
| 298 | + 已内置): | ||
| 299 | + `export LD_LIBRARY_PATH=$ASCEND_OPP_PATH/vendors/custom_transformer/op_api/lib/:$LD_LIBRARY_PATH`; | ||
| 300 | +- 只改 `torch_extension/` 或 `test/` 时不需要重编算子包。 | ||
| 301 | + | ||
| 302 | +### 5.3 安装 torch extension | ||
| 303 | + | ||
| 304 | +```bash | ||
| 305 | +# 构建 whl(带 --ops 的 --pkg 流程不会自动构建 whl,需单独执行本命令) | ||
| 306 | +bash build.sh --torch_extension --experimental | ||
| 307 | +pip install --force-reinstall --no-deps build_out/cann_ops_transformer-*.whl | ||
| 308 | +``` | ||
| 309 | + | ||
| 310 | +- 这里**不要带 `--ops`**:带 `--ops` 会生成 `cann_ops_transformer_<vendor>` 包,导入名不再是 | ||
| 311 | + `cann_ops_transformer`,与测试脚本/示例不一致;不带 `--ops` + `--experimental` 生成全量实验 | ||
| 312 | + 算子包,导入名为 `cann_ops_transformer`; | ||
| 313 | +- whl 是纯 Python 包(op 定义 + `csrc` 源码),**不预编译 .so**:首次调用算子时, | ||
| 314 | + `OpBuilder` 通过 `torch.utils.cpp_extension.load` 按源码 JIT 编译,缓存到 | ||
| 315 | + `~/.cache/torch_extensions`; | ||
| 316 | +- JIT 依赖 gcc/g++、torch/torch_npu 头文件以及 `ASCEND_HOME_PATH` 指向的 CANN include; | ||
| 317 | +- 首次调用会多花几十秒到几分钟编译,之后复用缓存;修改 `torch_extension/csrc` 后会自动重编 | ||
| 318 | + (按源码指纹判断)。安装后可在 `bash test/run_test.sh --list-cases` 的 | ||
| 319 | + `[ENV] cann_ops_transformer=` 行确认实际使用的包路径(run_test.sh 会把用户 site-packages | ||
| 320 | + 放到 PYTHONPATH 最前)。 | ||
| 321 | + | ||
| 322 | +### 5.4 运行 | ||
| 323 | + | ||
| 324 | +```bash | ||
| 325 | +cd experimental/mc2/all_gather_matmul_v3 | ||
| 326 | + | ||
| 327 | +# 精度:单 case(4 卡) | ||
| 328 | +bash test/run_test.sh --mode precision --cases m48 --world-size 4 \ | ||
| 329 | + --x1-dtype e4m3 --x2-dtype e4m3 --y-dtype bf16 --x2-format ND --x2-orient trans | ||
| 330 | + | ||
| 331 | +# 默认 18 个 shape / 12 个非对齐 M shape | ||
| 332 | +bash test/run_test.sh --mode precision --cases all --world-size 4 \ | ||
| 333 | + --x1-dtype e4m3 --x2-dtype e4m3 --y-dtype bf16 --x2-format ND --x2-orient trans | ||
| 334 | +bash test/run_test.sh --mode precision --cases odd --world-size 4 \ | ||
| 335 | + --x1-dtype e4m3 --x2-dtype e4m3 --y-dtype bf16 --x2-format ND --x2-orient trans | ||
| 336 | + | ||
| 337 | +# 自定义 shape(per-rank M=144, K=7168, N=4400) | ||
| 338 | +bash test/run_test.sh --mode precision --m 144 --k 7168 --n 4400 --world-size 4 \ | ||
| 339 | + --x1-dtype e4m3 --x2-dtype e4m3 --y-dtype bf16 --x2-format ND --x2-orient trans | ||
| 340 | +``` | ||
| 341 | + | ||
| 342 | +- 完整参数、性能模式与 CSV 说明见第 6 节; | ||
| 343 | +- 也可以不使用测试脚本,直接 `import cann_ops_transformer` 调用 | ||
| 344 | + `all_gather_quant_matmul`(见 3.4 示例)。 | ||
| 345 | + | ||
| 346 | +--- | ||
| 347 | + | ||
| 348 | +## 6. 测试与验证 | ||
| 349 | + | ||
| 350 | +测试脚本位于 `test/`,内置 18 个默认 shape(`m4` ~ `m96`,K=3072,N=2560): | ||
| 351 | + | ||
| 352 | +```bash | ||
| 353 | +# 精度(CPU golden 反量化 matmul 比对) | ||
| 354 | +bash test/run_test.sh --mode precision --cases all --world-size 4 \ | ||
| 355 | + --x1-dtype e4m3 --x2-dtype e5m2 --y-dtype fp16 --x2-format NZ --x2-orient trans | ||
| 356 | + | ||
| 357 | +# 性能 + 掩盖率(仅 e4m3 x e4m3 -> bf16) | ||
| 358 | +bash test/run_test.sh --mode perf --cases m48,m96 --world-size 4 | ||
| 359 | +``` | ||
| 360 | + | ||
| 361 | +- 精度模式支持全部 10 种 dtype 组合与 4 种布局,参考值为 CPU golden(fp32 反量化 matmul); | ||
| 362 | +- 性能模式按 profiler 解析各 rank 的 `op_summary`,跨 rank 取最大、后 5/10 次迭代平均, | ||
| 363 | + 由 rank0 汇总写 CSV; | ||
| 364 | +- 非对齐 M 组(`m5` ~ `m93`)用 `--cases odd` 运行;`--cases all,odd` 可一次跑完 30 个 shape; | ||
| 365 | + | ||
| 366 | +--- | ||
| 367 | + | ||
| 368 | +## 7. 已知限制与注意事项 | ||
| 369 | + | ||
| 370 | +1. **bias 不支持**:ubmem 路径必须传 `None`; | ||
| 371 | +2. **gather_out / amax_out 未实现**:返回 `(0,)` 占位; | ||
| 372 | +3. **fp4 仅 ND**:fp4 + NZ 直接拦截;且 x1/x2 必须同为 fp4; | ||
| 373 | +4. **NZ 仅 fp8**;NZ 4D 分形存储按 N 的 16/32 对齐分块(转置 16、非转置 32),y 的 N 仍为逻辑 N(由 `x2_scale` 决定); | ||
| 374 | +5. **K == N 歧义**:2D 输入无法仅从形状区分方向,按 `x2_scale` 布局消歧 | ||
| 375 | + (`[N,kd,2]` 视为转置、`[kd,N,2]` 视为非转置);scale 也方形时直接报错; | ||
| 376 | +6. **窗口容量**:窗口必须落在 HCCL 内置 buffer 内,超出时报错并提示增大 `HCCL_BUFFSIZE`; | ||
| 377 | +7. **确定性**:默认支持确定性计算。 | ||
| 378 | + | ||
| 379 | +--- | ||
| @@ -0,0 +1,3 @@ | |||
| 1 | +version https://git-lfs.github.com/spec/v1 | ||
| 2 | +oid sha256:19924ebd41bd9c973db58395b4035c09d167d0491a4497c97686f6300bfbecb0 | ||
| 3 | +size 239955 | ||
| @@ -0,0 +1,3 @@ | |||
| 1 | +version https://git-lfs.github.com/spec/v1 | ||
| 2 | +oid sha256:65c5cb1dce3a480fcee4d673933a26b28c3b13067b0c1c48dd18e2c06813f4ae | ||
| 3 | +size 3027294 | ||
| @@ -0,0 +1,508 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 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 | + | ||
| 11 | +/*! | ||
| 12 | + * \file aclnn_all_gather_matmul_v3.cpp | ||
| 13 | + */ | ||
| 14 | + | ||
| 15 | +#include "aclnnInner_all_gather_matmul_v3.h" | ||
| 16 | + | ||
| 17 | +#include <cstring> | ||
| 18 | +#include <initializer_list> | ||
| 19 | + | ||
| 20 | +#include "acl/acl.h" | ||
| 21 | +#include "aclnn/aclnn_base.h" | ||
| 22 | +#include "aclnn_kernels/common/op_error_check.h" | ||
| 23 | +#include "common/op_api/mc2_aclnn_util.h" | ||
| 24 | +#include "common/op_host/op_api/mc2_3rd_matmul_util.h" | ||
| 25 | +#include "mc2_log_compat.h" | ||
| 26 | +#include "graph/types.h" | ||
| 27 | +#include "opdev/op_log.h" | ||
| 28 | +#include "opdev/platform.h" | ||
| 29 | +#include "opdev/op_executor.h" | ||
| 30 | + | ||
| 31 | +using namespace op; | ||
| 32 | + | ||
| 33 | +namespace { | ||
| 34 | + | ||
| 35 | +enum class NnopbaseHcclServerType : uint32_t { | ||
| 36 | + NNOPBASE_HCCL_SERVER_TYPE_AICPU = 0, | ||
| 37 | + NNOPBASE_HCCL_SERVER_TYPE_MTE, | ||
| 38 | + NNOPBASE_HCCL_SERVER_TYPE_CCU, | ||
| 39 | + NNOPBASE_HCCL_SERVER_TYPE_END | ||
| 40 | +}; | ||
| 41 | + | ||
| 42 | +constexpr int64_t TWO_DIMS = 2; | ||
| 43 | +constexpr int64_t FOUR_DIMS = 4; | ||
| 44 | +constexpr int64_t SCALE_DIMS = 3; | ||
| 45 | +constexpr int64_t MX_SCALE_BLOCK = 64; | ||
| 46 | +constexpr int64_t NZ_FRACTAL_ROW = 16; | ||
| 47 | +constexpr int64_t NZ_FRACTAL_COL = 32; | ||
| 48 | +constexpr int64_t SCALE_LAST_DIM = 2; | ||
| 49 | +constexpr size_t HCCL_GROUP_NAME_LENGTH_MAX = 128U; // HCCL group 名长度上限 | ||
| 50 | + | ||
| 51 | +const std::initializer_list<op::DataType> X_DTYPE_SUPPORT_LIST = { | ||
| 52 | + op::DataType::DT_FLOAT8_E4M3FN, op::DataType::DT_FLOAT8_E5M2, op::DataType::DT_FLOAT4_E2M1}; | ||
| 53 | +const std::initializer_list<op::DataType> SCALE_DTYPE_SUPPORT_LIST = {op::DataType::DT_FLOAT8_E8M0}; | ||
| 54 | +const std::initializer_list<op::DataType> OUT_DTYPE_SUPPORT_LIST = {op::DataType::DT_BF16, op::DataType::DT_FLOAT16}; | ||
| 55 | +const std::initializer_list<op::DataType> BIAS_DTYPE_SUPPORT_LIST = {op::DataType::DT_FLOAT}; | ||
| 56 | + | ||
| 57 | +// 用户传 [N,K].t() (viewShape [K,N]) → 翻回 [N,K] 连续视图,保留原始物理存储 | ||
| 58 | +static const aclTensor* TransX2Tensor(const aclTensor* x2) | ||
| 59 | +{ | ||
| 60 | + uint64_t storageDimsNum = x2->GetStorageShape().GetDimNum(); | ||
| 61 | + std::vector<int64_t> storageDims(storageDimsNum); | ||
| 62 | + for (uint64_t i = 0; i < storageDimsNum; i++) { | ||
| 63 | + storageDims[i] = x2->GetStorageShape().GetDim(i); | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + uint64_t viewDimsNum = x2->GetViewShape().GetDimNum(); | ||
| 67 | + std::vector<int64_t> viewDims; | ||
| 68 | + viewDims.resize(viewDimsNum); | ||
| 69 | + for (uint64_t i = 0; i < viewDimsNum; i++) { | ||
| 70 | + viewDims[i] = x2->GetViewShape().GetDim(i); | ||
| 71 | + } | ||
| 72 | + // transpose the viewshape last two dimensions | ||
| 73 | + viewDims[0] = x2->GetViewShape().GetDim(1); | ||
| 74 | + viewDims[1] = x2->GetViewShape().GetDim(0); | ||
| 75 | + | ||
| 76 | + aclDataType dataType = aclDataType::ACL_DT_UNDEFINED; | ||
| 77 | + aclGetDataType(x2, &dataType); | ||
| 78 | + std::vector<int64_t> stride(viewDimsNum); | ||
| 79 | + auto transStride = x2->GetViewStrides(); | ||
| 80 | + stride = std::vector<int64_t>(transStride.begin(), transStride.end()); | ||
| 81 | + // transpose the two dimensions | ||
| 82 | + stride[0] = transStride[1]; | ||
| 83 | + stride[1] = transStride[0]; | ||
| 84 | + auto offset = x2->GetViewOffset(); | ||
| 85 | + aclFormat format = aclFormat::ACL_FORMAT_ND; | ||
| 86 | + | ||
| 87 | + return aclCreateTensor(viewDims.data(), viewDimsNum, dataType, stride.data(), offset, format, storageDims.data(), | ||
| 88 | + storageDimsNum, x2->GetTensor()->GetAddr()); | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +// CheckNullParams: 校验 REQUIRED 输入/输出非空(MX 量化必须传 x1_scale/x2_scale; | ||
| 92 | +// 本次交付不使能 gather_out/amax_out,不做校验) | ||
| 93 | +static bool CheckNullParams(const aclTensor* context, const aclTensor* x1, const aclTensor* x2, | ||
| 94 | + const aclTensor* x1Scale, const aclTensor* x2Scale, const aclTensor* output, | ||
| 95 | + uint64_t* workspaceSize, aclOpExecutor** executor) | ||
| 96 | +{ | ||
| 97 | + if (context == nullptr || x1 == nullptr || x2 == nullptr || x1Scale == nullptr || x2Scale == nullptr || | ||
| 98 | + output == nullptr || workspaceSize == nullptr || executor == nullptr) { | ||
| 99 | + if (context == nullptr) | ||
| 100 | + OP_LOGE_WITH_INVALID_INPUT("aclnnAllGatherQuantMatmulV3", "context"); | ||
| @@ -0,0 +1,50 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 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 | + | ||
| 11 | +if (BUILD_OPEN_PROJECT) | ||
| 12 | + # Core OpDef registration | ||
| 13 | + target_sources(op_host_aclnnInner PRIVATE | ||
| 14 | + all_gather_matmul_v3_def.cpp | ||
| 15 | + ) | ||
| 16 | + | ||
| 17 | + add_modules_sources_with_soc( | ||
| 18 | + OP_API_INDEPENDENT ON | ||
| 19 | + OP_API_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../op_api | ||
| 20 | + OP_MC2_ENABLE ON | ||
| 21 | + OPTYPE all_gather_matmul_v3 all_gather_matmul_v3 ACLNNTYPE aclnn aclnn_inner) | ||
| 22 | + set(SUB_MC2_COMPILE TRUE PARENT_SCOPE) | ||
| 23 | + set(MC2_OPT ON PARENT_SCOPE) | ||
| 24 | + # experimental 模式下 depends 会被改写到 experimental/ 前缀, mc2/3rd 无对应目录会导致 | ||
| 25 | + # kernel src-copy 阶段失败; mc2/3rd 的 host 编译(MC2_OPT)与安装(无条件路径)不依赖此声明。 | ||
| 26 | + set(all_gather_matmul_v3_depends mc2/common PARENT_SCOPE) | ||
| 27 | + set(all_gather_matmul_v3_apt_depends mc2/common PARENT_SCOPE) | ||
| 28 | + file(MAKE_DIRECTORY ${CMAKE_SOURCE_DIR}/third_party/ops-tensor/include/tensor_api/impl/c_api | ||
| 29 | + ${CMAKE_SOURCE_DIR}/third_party/ops-tensor/include/tensor_api/include/c_api) | ||
| 30 | + | ||
| 31 | + set(CONDITION_UNIT ${ASCEND_COMPUTE_UNIT}) | ||
| 32 | + if("${CONDITION_UNIT}" STREQUAL "ascend950") | ||
| 33 | + add_ops_compile_options( | ||
| 34 | + OP_NAME AllGatherMatmulV3 | ||
| 35 | + COMPUTE_UNIT Ascend950PR_9599 | ||
| 36 | + OPTIONS --cce-auto-sync=off | ||
| 37 | + -mllvm | ||
| 38 | + -cce-aicore-dcci-before-kernel-end=false | ||
| 39 | + -I${CMAKE_SOURCE_DIR}/mc2/common/op_kernel | ||
| 40 | + -I${CMAKE_SOURCE_DIR}/mc2/common/op_kernel/apace/tests/st/.third_party/ops-tensor/include | ||
| 41 | + ) | ||
| 42 | + endif() | ||
| 43 | + target_include_directories(op_host_aclnnInner PRIVATE | ||
| 44 | + ${CMAKE_SOURCE_DIR}/mc2/common/op_kernel | ||
| 45 | + ${CMAKE_SOURCE_DIR}/mc2 | ||
| 46 | + ) | ||
| 47 | +else() | ||
| 48 | + add_mc2_modules_sources(OPTYPE all_gather_matmul_v3 all_gather_matmul_v3 ACLNNTYPE aclnn aclnn_inner) | ||
| 49 | + set(SUB_MC2_COMPILE TRUE PARENT_SCOPE) | ||
| 50 | +endif() | ||
| @@ -0,0 +1,119 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 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 | + | ||
| 11 | +/*! | ||
| 12 | + * \file all_gather_matmul_v3_def.cpp | ||
| 13 | + * \brief OpDef definition for AllGatherMatmulV3 (ubmem/MTE window path only, MX-quant FP8/FP4) | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include <register/op_def_registry.h> | ||
| 17 | + | ||
| 18 | +namespace ops { | ||
| 19 | +class AllGatherMatmulV3 : public OpDef { | ||
| 20 | +public: | ||
| 21 | + explicit AllGatherMatmulV3(const char *name) | ||
| 22 | + : OpDef(name) | ||
| 23 | + { | ||
| 24 | + this->Input("context") | ||
| 25 | + .ParamType(REQUIRED) | ||
| 26 | + .DataTypeList({ge::DT_INT32}) | ||
| 27 | + .FormatList({ge::FORMAT_ND}) | ||
| 28 | + .AutoContiguous(); | ||
| 29 | + this->Input("x1") | ||
| 30 | + .ParamType(REQUIRED) | ||
| 31 | + .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E5M2, | ||
| 32 | + ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E5M2, | ||
| 33 | + ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E5M2, | ||
| 34 | + ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E5M2, | ||
| 35 | + ge::DT_FLOAT4_E2M1, ge::DT_FLOAT4_E2M1}) | ||
| 36 | + .FormatList({ge::FORMAT_ND}) | ||
| 37 | + .AutoContiguous(); | ||
| 38 | + this->Input("x2") | ||
| 39 | + .ParamType(REQUIRED) | ||
| 40 | + .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E5M2, | ||
| 41 | + ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, | ||
| 42 | + ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E5M2, | ||
| 43 | + ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, | ||
| 44 | + ge::DT_FLOAT4_E2M1, ge::DT_FLOAT4_E2M1}) | ||
| 45 | + .Format({ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_ND, | ||
| 46 | + ge::FORMAT_ND, ge::FORMAT_ND, ge::FORMAT_FRACTAL_NZ, ge::FORMAT_FRACTAL_NZ, | ||
| 47 | + ge::FORMAT_FRACTAL_NZ, ge::FORMAT_FRACTAL_NZ, ge::FORMAT_FRACTAL_NZ, ge::FORMAT_FRACTAL_NZ, | ||
| 48 | + ge::FORMAT_FRACTAL_NZ, ge::FORMAT_FRACTAL_NZ, ge::FORMAT_ND, ge::FORMAT_ND}) | ||
| 49 | + .IgnoreContiguous(); | ||
| 50 | + this->Input("bias") | ||
| 51 | + .ParamType(OPTIONAL) | ||
| 52 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, | ||
| 53 | + ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, | ||
| 54 | + ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT}) | ||
| 55 | + .FormatList({ge::FORMAT_ND}) | ||
| 56 | + .AutoContiguous(); | ||
| 57 | + this->Input("x1_scale") | ||
| 58 | + .ParamType(OPTIONAL) | ||
| 59 | + .DataType({ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, | ||
| 60 | + ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, | ||
| 61 | + ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, | ||
| 62 | + ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, | ||
| 63 | + ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0}) | ||
| 64 | + .FormatList({ge::FORMAT_ND}) | ||
| 65 | + .AutoContiguous(); | ||
| 66 | + this->Input("x2_scale") | ||
| 67 | + .ParamType(OPTIONAL) | ||
| 68 | + .DataType({ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, | ||
| 69 | + ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, | ||
| 70 | + ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, | ||
| 71 | + ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0, | ||
| 72 | + ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0}) | ||
| 73 | + .FormatList({ge::FORMAT_ND}); | ||
| 74 | + this->Output("y") | ||
| 75 | + .ParamType(REQUIRED) | ||
| 76 | + .DataType({ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, | ||
| 77 | + ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, | ||
| 78 | + ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16, ge::DT_BF16, ge::DT_FLOAT16}) | ||
| 79 | + .FormatList({ge::FORMAT_ND}); | ||
| 80 | + this->Output("gather_out") | ||
| 81 | + .ParamType(REQUIRED) | ||
| 82 | + .DataType({ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E5M2, | ||
| 83 | + ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E5M2, | ||
| 84 | + ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E5M2, | ||
| 85 | + ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E4M3FN, ge::DT_FLOAT8_E5M2, ge::DT_FLOAT8_E5M2, | ||
| 86 | + ge::DT_FLOAT4_E2M1, ge::DT_FLOAT4_E2M1}) | ||
| 87 | + .FormatList({ge::FORMAT_ND}); | ||
| 88 | + this->Output("amax_out") | ||
| 89 | + .ParamType(OPTIONAL) | ||
| 90 | + .DataType({ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, | ||
| 91 | + ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, | ||
| 92 | + ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT, ge::DT_FLOAT}) | ||
| 93 | + .FormatList({ge::FORMAT_ND}); | ||
| 94 | + this->Attr("group").AttrType(REQUIRED).String(); | ||
| 95 | + this->Attr("hccl_buffer_size").AttrType(REQUIRED).Int(); | ||
| 96 | + this->Attr("is_trans_a").AttrType(OPTIONAL).Bool(false); | ||
| 97 | + this->Attr("is_trans_b").AttrType(OPTIONAL).Bool(false); | ||
| 98 | + this->Attr("rank_size").AttrType(OPTIONAL).Int(0); | ||
| 99 | + this->Attr("group_size").AttrType(OPTIONAL).Int(0); | ||
| 100 | + this->Attr("y_dtype").AttrType(OPTIONAL).Int(static_cast<int64_t>(ge::DT_UNDEFINED)); | ||
| 101 | + this->Attr("comm_mode").AttrType(OPTIONAL).String("ubmem"); | ||
| 102 | + | ||
| 103 | + OpAICoreConfig aicoreConfig_a5; | ||
| 104 | + aicoreConfig_a5.DynamicCompileStaticFlag(true) | ||
| 105 | + .DynamicFormatFlag(true) | ||
| 106 | + .DynamicRankSupportFlag(true) | ||
| 107 | + .DynamicShapeSupportFlag(true) | ||
| 108 | + .NeedCheckSupportFlag(false) | ||
| 109 | + .PrecisionReduceFlag(true) | ||
| 110 | + .ExtendCfgInfo("aclnnSupport.value", "support_aclnn") | ||
| 111 | + .ExtendCfgInfo("jitCompile.flag", "static_false") // 动态shape,复用二进制,后续图支持后修改 | ||
| 112 | + .ExtendCfgInfo("multiKernelSupportDynamicGraph.value", "multi_kernel") | ||
| 113 | + .ExtendCfgInfo("opFile.value", "all_gather_matmul_v3_apt"); | ||
| 114 | + this->AICore().AddConfig("ascend950", aicoreConfig_a5); | ||
| 115 | + } | ||
| 116 | +}; | ||
| 117 | + | ||
| 118 | +OP_ADD(AllGatherMatmulV3); | ||
| 119 | +} // namespace ops | ||
| @@ -0,0 +1,314 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 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 | + | ||
| 11 | +/*! | ||
| 12 | + * \file all_gather_matmul_v3_infershape.cpp | ||
| 13 | + * \brief InferShape for AllGatherMatmulV3 | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include <register/op_impl_registry.h> | ||
| 17 | + | ||
| 18 | +#include "common/utils/op_mc2.h" | ||
| 19 | +#include "mc2_log.h" | ||
| 20 | +#include "op_host/mc2_common_infershape.h" | ||
| 21 | +#include "util/math_util.h" | ||
| 22 | + | ||
| 23 | +namespace ops { | ||
| 24 | + | ||
| 25 | +using Ops::Base::CeilDiv; | ||
| 26 | + | ||
| 27 | +namespace { | ||
| 28 | + | ||
| 29 | +constexpr size_t INDEX_IN_X1 = 1; | ||
| 30 | +constexpr size_t INDEX_IN_X2 = 2; | ||
| 31 | +constexpr size_t INDEX_IN_X1_SCALE = 4; | ||
| 32 | +constexpr size_t INDEX_IN_X2_SCALE = 5; | ||
| 33 | +constexpr size_t INDEX_OUT_Y = 0; | ||
| 34 | +constexpr size_t INDEX_OUT_GATHER_OUT = 1; | ||
| 35 | +constexpr size_t INDEX_ATTR_IS_TRANS_B = 3; | ||
| 36 | +constexpr size_t INDEX_ATTR_RANK_SIZE = 4; | ||
| 37 | +constexpr size_t INDEX_ATTR_Y_DTYPE = 6; | ||
| 38 | + | ||
| 39 | +constexpr int64_t MX_SCALE_BLOCK_SIZE = 64; | ||
| 40 | +constexpr int64_t SCALE_LAST_DIM = 2; | ||
| 41 | +constexpr int64_t DIM_MINUS_ONE = -1; | ||
| 42 | +constexpr int64_t K_MIN_VAL = 256; | ||
| 43 | +constexpr int64_t K_MAX_VAL = 65535; | ||
| 44 | +constexpr size_t MATRIX_DIM_NUM = 2; | ||
| 45 | +constexpr int64_t NZ_FRACTAL_ROW = 16; | ||
| 46 | +constexpr int64_t NZ_FRACTAL_COL = 32; | ||
| 47 | + | ||
| 48 | +// scale 各维度可能为动态未知(-1),仅对已知维度做等值校验 | ||
| 49 | +bool IsDimMismatch(uint64_t actual, int64_t expected) | ||
| 50 | +{ | ||
| 51 | + return actual != static_cast<uint64_t>(DIM_MINUS_ONE) && actual != static_cast<uint64_t>(expected); | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +// rank_size 未设置(<=0)时拦截 | ||
| 55 | +ge::graphStatus ResolveRankSize(const gert::InferShapeContext* context, int64_t& rankSize) | ||
| 56 | +{ | ||
| 57 | + const auto nodeName = context->GetNodeName(); | ||
| 58 | + const auto attrs = context->GetAttrs(); | ||
| 59 | + const int64_t* rankSizeAttr = attrs->GetAttrPointer<int64_t>(INDEX_ATTR_RANK_SIZE); | ||
| 60 | + OPS_CHECK(rankSizeAttr == nullptr, OP_LOGE_WITH_INVALID_INPUT(nodeName, "rank_size"), return ge::GRAPH_FAILED); | ||
| 61 | + rankSize = *rankSizeAttr; | ||
| 62 | + OPS_CHECK(rankSize <= 0, OP_LOGE(nodeName, "rank_size attr must be set, got %ld", rankSize), | ||
| 63 | + return ge::GRAPH_FAILED); | ||
| 64 | + return ge::GRAPH_SUCCESS; | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +bool IsX2NzFormat(const gert::InferShapeContext* context) | ||
| 68 | +{ | ||
| 69 | + auto x2Desc = context->GetInputDesc(INDEX_IN_X2); | ||
| 70 | + return x2Desc != nullptr && | ||
| 71 | + static_cast<ge::Format>(ge::GetPrimaryFormat(x2Desc->GetStorageFormat())) == ge::FORMAT_FRACTAL_NZ; | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +ge::graphStatus CheckMatrixInputShapes(const gert::InferShapeContext* context) | ||
| 75 | +{ | ||
| 76 | + const auto x1Shape = context->GetInputShape(INDEX_IN_X1); | ||
| 77 | + const auto x2Shape = context->GetInputShape(INDEX_IN_X2); | ||
| 78 | + OPS_CHECK_NULL_WITH_CONTEXT(context, x1Shape); | ||
| 79 | + OPS_CHECK_NULL_WITH_CONTEXT(context, x2Shape); | ||
| 80 | + if (x1Shape->GetDimNum() != MATRIX_DIM_NUM) { | ||
| 81 | + OP_LOGE_FOR_INVALID_SHAPEDIM(context->GetNodeName(), "x1", (std::to_string(x1Shape->GetDimNum()) + "D").c_str(), | ||
| 82 | + "2D"); | ||
| 83 | + return ge::GRAPH_FAILED; | ||
| 84 | + } | ||
| 85 | + const bool x2Nz = IsX2NzFormat(context); | ||
| 86 | + const size_t x2DimNum = x2Shape->GetDimNum(); | ||
| 87 | + if ((!x2Nz && x2DimNum != MATRIX_DIM_NUM) || (x2Nz && x2DimNum != MATRIX_DIM_NUM && x2DimNum != 4U)) { | ||
| 88 | + OP_LOGE_FOR_INVALID_SHAPEDIM(context->GetNodeName(), "x2", (std::to_string(x2DimNum) + "D").c_str(), | ||
| 89 | + "2D (ND) or 2D/4D (FRACTAL_NZ)"); | ||
| 90 | + return ge::GRAPH_FAILED; | ||
| 91 | + } | ||
| 92 | + return ge::GRAPH_SUCCESS; | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +ge::graphStatus CheckMatrixDtypes(const gert::InferShapeContext* context) | ||
| 96 | +{ | ||
| 97 | + const auto nodeName = context->GetNodeName(); | ||
| 98 | + auto x1Dtype = context->GetInputDesc(INDEX_IN_X1)->GetDataType(); | ||
| 99 | + auto x2Dtype = context->GetInputDesc(INDEX_IN_X2)->GetDataType(); | ||
| 100 | + if ((x1Dtype != ge::DT_FLOAT8_E4M3FN && x1Dtype != ge::DT_FLOAT8_E5M2 && x1Dtype != ge::DT_FLOAT4_E2M1) || | ||
| 101 | + (x2Dtype != ge::DT_FLOAT8_E4M3FN && x2Dtype != ge::DT_FLOAT8_E5M2 && x2Dtype != ge::DT_FLOAT4_E2M1)) { | ||
| 102 | + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( | ||
| 103 | + nodeName, "x1, x2", | ||
| 104 | + (std::to_string(static_cast<int>(x1Dtype)) + ", " + std::to_string(static_cast<int>(x2Dtype))).c_str(), | ||
| 105 | + "only FP8_E4M3FN/FP8_E5M2/FP4_E2M1 supported"); | ||
| 106 | + return ge::GRAPH_FAILED; | ||
| 107 | + } | ||
| 108 | + if ((x1Dtype == ge::DT_FLOAT4_E2M1) != (x2Dtype == ge::DT_FLOAT4_E2M1)) { | ||
| 109 | + OP_LOGE_FOR_INVALID_DTYPES_WITH_REASON( | ||
| 110 | + nodeName, "x1, x2", | ||
| 111 | + (std::to_string(static_cast<int>(x1Dtype)) + ", " + std::to_string(static_cast<int>(x2Dtype))).c_str(), | ||
| 112 | + "FP4 requires both x1 and x2 to be FP4_E2M1"); | ||
| 113 | + return ge::GRAPH_FAILED; | ||
| 114 | + } | ||
| 115 | + return ge::GRAPH_SUCCESS; | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +ge::graphStatus CheckKDimMatch(const gert::InferShapeContext* context, int64_t kX1, int64_t kX2) | ||
| 119 | +{ | ||
| 120 | + OPS_CHECK(kX1 != kX2, | ||
| 121 | + OP_LOGE_FOR_INVALID_VALUES_WITH_REASON(context->GetNodeName(), "x1.K, x2.K", | ||
| 122 | + (std::to_string(kX1) + ", " + std::to_string(kX2)).c_str(), | ||
| 123 | + "The values of x1.K and x2.K must be the same"), | ||
| 124 | + return ge::GRAPH_FAILED); | ||
| 125 | + return ge::GRAPH_SUCCESS; | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +ge::graphStatus CheckKConstraints(const gert::InferShapeContext* context, int64_t k) | ||
| 129 | +{ | ||
| 130 | + const auto nodeName = context->GetNodeName(); | ||
| 131 | + OPS_CHECK( | ||
| 132 | + k < K_MIN_VAL || k >= K_MAX_VAL, | ||
| 133 | + OP_LOGE_FOR_INVALID_VALUE( | ||
| 134 | + nodeName, "K", std::to_string(k).c_str(), | ||
| 135 | + (std::string("in range [") + std::to_string(K_MIN_VAL) + ", " + std::to_string(K_MAX_VAL) + ")").c_str()), | ||
| 136 | + return ge::GRAPH_FAILED); | ||
| 137 | + | ||
| 138 | + // fp4 按 4bit 打包,K 必须为偶数 | ||
| 139 | + if (context->GetInputDesc(INDEX_IN_X1)->GetDataType() == ge::DT_FLOAT4_E2M1) { | ||
| 140 | + OPS_CHECK(k % 2 != 0, | ||
| 141 | + OP_LOGE_FOR_INVALID_VALUE(nodeName, "K", std::to_string(k).c_str(), "must be even in mxfp4 scene"), | ||
| 142 | + return ge::GRAPH_FAILED); | ||
| 143 | + } | ||
| 144 | + return ge::GRAPH_SUCCESS; | ||
| 145 | +} | ||
| 146 | + | ||
| 147 | +ge::graphStatus CheckOneScaleShape(const gert::InferShapeContext* context, const gert::Shape* scaleShape, | ||
| 148 | + const char* paramName, int64_t dim0, int64_t expectedScaleK) | ||
| 149 | +{ | ||
| 150 | + const auto nodeName = context->GetNodeName(); | ||
| 151 | + OPS_CHECK(IsDimMismatch(scaleShape->GetDim(0U), dim0) || IsDimMismatch(scaleShape->GetDim(1U), expectedScaleK) || | ||
【一般】这版把 scale dimNum==3 的校验删了,但下面还是直接 GetDim(0U)/GetDim(1U)/GetDim(2U),图模式下用户传个 2D scale 进来就是越界访问,报错信息也跟着乱。转置前版本这里是有 SHAPEDIM 校验的,建议补回来。 ![]() ![]() | |||
| 152 | + IsDimMismatch(scaleShape->GetDim(2U), SCALE_LAST_DIM), | ||
| 153 | + OP_LOGE_FOR_INVALID_SHAPE( | ||
| 154 | + nodeName, paramName, | ||
| 155 | + (std::string("[") + std::to_string(scaleShape->GetDim(0U)) + "," + | ||
| 156 | + std::to_string(scaleShape->GetDim(1U)) + "," + std::to_string(scaleShape->GetDim(2U)) + "]") | ||
| 157 | + .c_str(), | ||
| 158 | + (std::string("[") + std::to_string(dim0) + "," + std::to_string(expectedScaleK) + "," + | ||
| 159 | + std::to_string(SCALE_LAST_DIM) + "]") | ||
| 160 | + .c_str()), | ||
| 161 | + return ge::GRAPH_FAILED); | ||
| 162 | + return ge::GRAPH_SUCCESS; | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +// x1_scale: [M, Ceil(K/64), 2]; | ||
| 166 | +// x2_scale: 转置 B 为 [N, Ceil(K/64), 2]; 非转置 B 为 [Ceil(K/64), N, 2] | ||
| 167 | +ge::graphStatus CheckScaleShapes(const gert::InferShapeContext* context, int64_t m, int64_t n, int64_t k, bool transX2) | ||
| 168 | +{ | ||
| 169 | + auto x1ScaleShape = context->GetOptionalInputShape(INDEX_IN_X1_SCALE); | ||
| 170 | + auto x2ScaleShape = context->GetOptionalInputShape(INDEX_IN_X2_SCALE); | ||
| 171 | + if (x1ScaleShape == nullptr || x2ScaleShape == nullptr) { | ||
| 172 | + return ge::GRAPH_SUCCESS; | ||
| 173 | + } | ||
| 174 | + int64_t expectedScaleK = CeilDiv(k, MX_SCALE_BLOCK_SIZE); | ||
| 175 | + if (CheckOneScaleShape(context, x1ScaleShape, "x1_scale", m, expectedScaleK) != ge::GRAPH_SUCCESS) { | ||
| 176 | + return ge::GRAPH_FAILED; | ||
| 177 | + } | ||
| 178 | + const int64_t x2ScaleDim0 = transX2 ? n : expectedScaleK; | ||
| 179 | + const int64_t x2ScaleDim1 = transX2 ? expectedScaleK : n; | ||
| 180 | + if (CheckOneScaleShape(context, x2ScaleShape, "x2_scale", x2ScaleDim0, x2ScaleDim1) != ge::GRAPH_SUCCESS) { | ||
| 181 | + return ge::GRAPH_FAILED; | ||
| 182 | + } | ||
| 183 | + return ge::GRAPH_SUCCESS; | ||
| 184 | +} | ||
| 185 | + | ||
| 186 | +ge::graphStatus DeriveOutputShapes(gert::InferShapeContext* context, int64_t m, int64_t k, int64_t n, int64_t worldSize) | ||
| 187 | +{ | ||
| 188 | + // y = [world_size * M_per_rank, N] | ||
| 189 | + auto outShape = context->GetOutputShape(INDEX_OUT_Y); | ||
| 190 | + OPS_CHECK_NULL_WITH_CONTEXT(context, outShape); | ||
| 191 | + outShape->SetDimNum(MATRIX_DIM_NUM); | ||
| 192 | + if (m != DIM_MINUS_ONE && n != DIM_MINUS_ONE) { | ||
| 193 | + outShape->SetDim(0U, m * worldSize); | ||
| 194 | + outShape->SetDim(1U, n); | ||
| 195 | + } else { | ||
| 196 | + outShape->SetDim(0U, DIM_MINUS_ONE); | ||
| 197 | + outShape->SetDim(1U, DIM_MINUS_ONE); | ||
| 198 | + } | ||
| 199 | + | ||
| 200 | + // gather_out = [world_size * M_per_rank, K] (REQUIRED) | ||
| 201 | + auto gatherOutShape = context->GetOutputShape(INDEX_OUT_GATHER_OUT); | ||
| 202 | + OPS_CHECK_NULL_WITH_CONTEXT(context, gatherOutShape); | ||
| 203 | + gatherOutShape->SetDimNum(MATRIX_DIM_NUM); | ||
| 204 | + if (m != DIM_MINUS_ONE && k != DIM_MINUS_ONE) { | ||
| 205 | + gatherOutShape->SetDim(0U, m * worldSize); | ||
| 206 | + gatherOutShape->SetDim(1U, k); | ||
| 207 | + } else { | ||
| 208 | + gatherOutShape->SetDim(0U, DIM_MINUS_ONE); | ||
| 209 | + gatherOutShape->SetDim(1U, DIM_MINUS_ONE); | ||
| 210 | + } | ||
| 211 | + return ge::GRAPH_SUCCESS; | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +} // namespace | ||
| 215 | + | ||
| 216 | +ge::graphStatus AllGatherMatmulV3InferShape(gert::InferShapeContext* context) | ||
| 217 | +{ | ||
| 218 | + const auto nodeName = context->GetNodeName(); | ||
| 219 | + OP_LOGD(nodeName, "InferShape start"); | ||
| 220 | + | ||
| 221 | + OP_LOGE_IF(CheckMatrixInputShapes(context) != ge::GRAPH_SUCCESS, ge::GRAPH_FAILED, nodeName, | ||
| 222 | + "check matrix input shapes failed."); | ||
| 223 | + OP_LOGE_IF(CheckMatrixDtypes(context) != ge::GRAPH_SUCCESS, ge::GRAPH_FAILED, nodeName, | ||
| 224 | + "check matrix dtypes failed."); | ||
| 225 | + | ||
| 226 | + // 提取维度:x1 [M, K];x2 ND 在 is_trans_b=true 时为 [N, K]; | ||
| 227 | + // x2 NZ 为 [N, K] 的 FRACTAL_NZ 分块存储(2D 逻辑或 4D storage) | ||
| 228 | + const auto x1Shape = context->GetInputShape(INDEX_IN_X1); | ||
| 229 | + const auto x2Shape = context->GetInputShape(INDEX_IN_X2); | ||
| 230 | + int64_t m = x1Shape->GetDim(0U); | ||
| 231 | + int64_t k = x1Shape->GetDim(1U); | ||
| 232 | + const bool* isTransX2 = context->GetAttrs()->GetAttrPointer<bool>(INDEX_ATTR_IS_TRANS_B); | ||
| 233 | + const bool transX2 = ((isTransX2 != nullptr) && (*isTransX2)); | ||
| 234 | + const bool x2Nz = IsX2NzFormat(context); | ||
| 235 | + int64_t n = 0; | ||
| 236 | + int64_t kX2 = k; | ||
| 237 | + if (x2Nz) { | ||
| 238 | + if (x2Shape->GetDimNum() == MATRIX_DIM_NUM) { | ||
| 239 | + // 2D 逻辑形态: 转置 [N,K] / 非转置 [K,N] | ||
| 240 | + n = transX2 ? x2Shape->GetDim(0U) : x2Shape->GetDim(1U); | ||
| 241 | + kX2 = transX2 ? x2Shape->GetDim(1U) : x2Shape->GetDim(0U); | ||
| 242 | + } else { | ||
| 243 | + OPS_CHECK(x2Shape->GetDim(2U) != NZ_FRACTAL_ROW || x2Shape->GetDim(3U) != NZ_FRACTAL_COL, | ||
| 244 | + OP_LOGE_FOR_INVALID_SHAPE( | ||
| 245 | + context->GetNodeName(), "x2", | ||
| 246 | + (std::string("[") + std::to_string(x2Shape->GetDim(0U)) + "," + | ||
| 247 | + std::to_string(x2Shape->GetDim(1U)) + "," + std::to_string(x2Shape->GetDim(2U)) + "," + | ||
| 248 | + std::to_string(x2Shape->GetDim(3U)) + "]") | ||
| 249 | + .c_str(), | ||
| 250 | + "[*, *, 16, 32] (FRACTAL_NZ storage)"), | ||
| 251 | + return ge::GRAPH_FAILED); | ||
| 252 | + // 4D storage 只反映分块数, N 优先取调用方给定的输出 y dim1; | ||
| 253 | + // 兜底: 转置 [N,K] -> ceil(N/16)*16; 非转置 [K,N] -> ceil(N/32)*32 | ||
| 254 | + auto yShape = context->GetOutputShape(INDEX_OUT_Y); | ||
| 255 | + int64_t nFromOut = | ||
| 256 | + (yShape != nullptr && yShape->GetDimNum() >= MATRIX_DIM_NUM) ? yShape->GetDim(1U) : DIM_MINUS_ONE; | ||
| 257 | + n = (nFromOut > 0) ? | ||
| 258 | + nFromOut : | ||
| 259 | + (transX2 ? x2Shape->GetDim(1U) * NZ_FRACTAL_ROW : x2Shape->GetDim(0U) * NZ_FRACTAL_COL); | ||
| 260 | + } | ||
| 261 | + } else { | ||
| 262 | + n = transX2 ? x2Shape->GetDim(0U) : x2Shape->GetDim(1U); | ||
| 263 | + kX2 = transX2 ? x2Shape->GetDim(1U) : x2Shape->GetDim(0U); | ||
| 264 | + } | ||
| 265 | + | ||
| 266 | + // rank_size: 必须由外界显式传入(<=0 时 ResolveRankSize 拦截报错) | ||
| 267 | + int64_t worldSize = 0; | ||
| 268 | + OP_LOGE_IF(ResolveRankSize(context, worldSize) != ge::GRAPH_SUCCESS, ge::GRAPH_FAILED, nodeName, | ||
| 269 | + "resolve rank_size failed."); | ||
| 270 | + | ||
| 271 | + OP_LOGD(nodeName, "InferShape: x1[%ld,%ld] x2 K=%ld N=%ld rankSize=%ld", m, k, kX2, n, worldSize); | ||
| 272 | + | ||
| 273 | + // NZ 4D storage 的 K 维是分块数, 不做等值校验(K 以 x1 为准) | ||
| 274 | + if (!x2Nz || x2Shape->GetDimNum() == MATRIX_DIM_NUM) { | ||
| 275 | + OP_LOGE_IF(CheckKDimMatch(context, k, kX2) != ge::GRAPH_SUCCESS, ge::GRAPH_FAILED, nodeName, | ||
| 276 | + "check K dim match failed."); | ||
| 277 | + } | ||
| 278 | + // 静态 shape 才做取值约束,动态 shape(-1) 留待 tiling 校验 | ||
| 279 | + if (m != DIM_MINUS_ONE && k != DIM_MINUS_ONE && n != DIM_MINUS_ONE) { | ||
| 280 | + OP_LOGE_IF(CheckKConstraints(context, k) != ge::GRAPH_SUCCESS, ge::GRAPH_FAILED, nodeName, | ||
| 281 | + "check K constraints failed."); | ||
| 282 | + OP_LOGE_IF(CheckScaleShapes(context, m, n, k, transX2) != ge::GRAPH_SUCCESS, ge::GRAPH_FAILED, nodeName, | ||
| 283 | + "check scale shapes failed."); | ||
| 284 | + } | ||
| 285 | + | ||
| 286 | + OP_LOGE_IF(DeriveOutputShapes(context, m, k, n, worldSize) != ge::GRAPH_SUCCESS, ge::GRAPH_FAILED, nodeName, | ||
| 287 | + "derive output shapes failed."); | ||
| 288 | + | ||
| 289 | + OP_LOGD(nodeName, "InferShape success: M_per_rank=%ld K=%ld N=%ld world_size=%ld", m, k, n, worldSize); | ||
| 290 | + return ge::GRAPH_SUCCESS; | ||
| 291 | +} | ||
| 292 | + | ||
| 293 | +// y dtype 由 y_dtype attr 决定(BF16/FP16),gather_out 与 x1 同 dtype | ||
| 294 | +ge::graphStatus AllGatherMatmulV3InferDataType(gert::InferDataTypeContext* context) | ||
| 295 | +{ | ||
| 296 | + const auto nodeName = context->GetNodeName(); | ||
| 297 | + | ||
| 298 | + auto yDtypePtr = context->GetAttrs()->GetAttrPointer<int64_t>(INDEX_ATTR_Y_DTYPE); | ||
| 299 | + ge::DataType yDtype = (yDtypePtr != nullptr) ? static_cast<ge::DataType>(*yDtypePtr) : ge::DT_UNDEFINED; | ||
| 300 | + OPS_CHECK( | ||
| 301 | + yDtype != ge::DT_BF16 && yDtype != ge::DT_FLOAT16, | ||
| 302 | + OP_LOGE_FOR_INVALID_DTYPE(nodeName, "y_dtype", std::to_string(static_cast<int>(yDtype)).c_str(), "BF16/FP16"), | ||
| 303 | + return ge::GRAPH_FAILED); | ||
| 304 | + | ||
| 305 | + context->SetOutputDataType(INDEX_OUT_Y, yDtype); | ||
| 306 | + context->SetOutputDataType(INDEX_OUT_GATHER_OUT, context->GetInputDataType(INDEX_IN_X1)); | ||
| 307 | + return ge::GRAPH_SUCCESS; | ||
| 308 | +} | ||
| 309 | + | ||
| 310 | +IMPL_OP_INFERSHAPE(AllGatherMatmulV3) | ||
| 311 | + .InferShape(AllGatherMatmulV3InferShape) | ||
| 312 | + .InferDataType(AllGatherMatmulV3InferDataType); | ||
| 313 | + | ||
| 314 | +} // namespace ops | ||
Aexperimental/mc2/all_gather_matmul_v3/op_host/op_tiling/arch35/all_gather_matmul_v3_tiling.cpp+904-0
| @@ -0,0 +1,106 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 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. | ||
| 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 the License for the specific language governing permissions and limitations under the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file all_gather_matmul_v3_apt.cpp | ||
| 13 | + * \brief Kernel entry for AllGatherMatmulV3 (ubmem/MTE window path only, MX-quant FP8/FP4) | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include <kernel_operator.h> | ||
| 17 | +#include "all_gather_matmul_v3_tiling_key.h" | ||
| 18 | +#include "apace/tiling/matmul_tiling/quant_matmul_tiling_data.h" | ||
| 19 | +#include "blaze/gemm/policy/dispatch_policy.h" | ||
| 20 | +#include "blaze/gemm/block/block_scheduler_qbmm.h" | ||
| 21 | +#include "blaze/gemm/block/block_mmad.h" | ||
| 22 | +#include "blaze/gemm/kernel/kernel_universal.h" | ||
| 23 | +#include "blaze/gemm/kernel/kernel_qbmm_mx.h" | ||
| 24 | +#include "blaze/epilogue/block/block_epilogue_empty.h" | ||
| 25 | +#include "apace/kernel/fusions/all_gather_quant_matmul/all_gather_quant_matmul_ubmem_impl.h" | ||
| 26 | +#include "apace/block/mmad/qmm_mx_block_mmad_tile_k_wait_flag.h" | ||
| 27 | + | ||
| 28 | +using namespace AscendC; | ||
| 29 | +using namespace Apace; | ||
| 30 | + | ||
| 31 | +template <bool TRANS_B> | ||
| 32 | +__global__ __aicore__ void all_gather_matmul_v3(GM_ADDR context, GM_ADDR x1, GM_ADDR x2, GM_ADDR bias, GM_ADDR x1_scale, | ||
| 33 | + GM_ADDR x2_scale, GM_ADDR y, GM_ADDR gather_out, GM_ADDR amax_out, | ||
| 34 | + GM_ADDR workspaceGM, GM_ADDR tilingGM) | ||
| 35 | +{ | ||
| 36 | + (void)gather_out; | ||
| 37 | + (void)amax_out; | ||
| 38 | + (void)bias; | ||
| 39 | + (void)workspaceGM; | ||
| 40 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_1); | ||
| 41 | + | ||
| 42 | + REGISTER_TILING_DEFAULT(QuantMatmulTilingData); | ||
| 43 | + | ||
| 44 | + GET_TILING_DATA_WITH_STRUCT(QuantMatmulTilingData, tilingData, tilingGM); | ||
| 45 | + | ||
| 46 | + using TypeA = DTYPE_X1; | ||
| 47 | + using TypeB = DTYPE_X2; | ||
| 48 | + using TypeC = DTYPE_Y; | ||
| 49 | + using LayoutA = asc::te::nd_ext_layout_ptn; | ||
| 50 | + // 右矩阵布局: ND/NZ x 转置([N,K])/非转置([K,N]) 四种组合 | ||
| 51 | + constexpr bool isX2Nz = (FORMAT_X2 == FORMAT_FRACTAL_NZ); | ||
| 52 | + using LayoutB = AscendC::Std::conditional_t< | ||
| 53 | + isX2Nz, AscendC::Std::conditional_t<TRANS_B, asc::te::zn_layout_ptn, asc::te::nz_layout_ptn>, | ||
| 54 | + AscendC::Std::conditional_t<TRANS_B, asc::te::dn_ext_layout_ptn, asc::te::nd_ext_layout_ptn>>; | ||
| 55 | + using LayoutC = asc::te::nd_ext_layout_ptn; | ||
| 56 | + using ProblemShape = asc::te::shape<int64_t, int64_t, int64_t, int64_t>; | ||
| 57 | + // apace路径下切k mmad模板(独立类, 每 AG_SYNC_INTERVAL 个 K 做一次跨核等待) | ||
| 58 | + using BlockMmad = Blaze::Gemm::Block::QmmMxBlockMmadTileKWaitFlag<0, false, TypeA, LayoutA, TypeB, LayoutB, TypeC, | ||
| 59 | + LayoutC, float, LayoutC>; | ||
| 60 | + using BlockScheduler = | ||
| 61 | + Blaze::Gemm::Block::BlockSchedulerQuantBatchMatmulV3<ProblemShape, 0, LayoutA, LayoutB, TypeA>; | ||
| 62 | + using BlockEpilogue = Blaze::Gemm::Block::BlockEpilogueEmpty; | ||
| 63 | + using Impl = Apace::AllGatherQuantMatmulUbmemImpl<ProblemShape, BlockMmad, BlockEpilogue, BlockScheduler>; | ||
| 64 | + | ||
| 65 | + using KernelImpl = typename Impl::KernelImpl; | ||
| 66 | + | ||
| 67 | + typename Impl::Params params; | ||
| 68 | + params.matmulKernelParams.problemShape = ProblemShape{ | ||
| 69 | + static_cast<int64_t>(tilingData.m), static_cast<int64_t>(tilingData.n), static_cast<int64_t>(tilingData.k), 1L}; | ||
| 70 | + params.matmulKernelParams.mmadParams = typename BlockMmad::Params{nullptr, x2, y, nullptr, nullptr, x2_scale}; | ||
| 71 | + params.matmulKernelParams.l1Params = typename BlockMmad::L1Params{ | ||
| 72 | + static_cast<uint64_t>(tilingData.stepK) * tilingData.baseK, tilingData.scaleKL1, 2}; | ||
| 73 | + params.matmulKernelParams.schParams = typename BlockScheduler::Params{tilingData.baseM, | ||
| 74 | + tilingData.baseN, | ||
| 75 | + tilingData.mTailTile, | ||
| 76 | + tilingData.nTailTile, | ||
| 77 | + tilingData.mBaseTailSplitCnt, | ||
| 78 | + tilingData.nBaseTailSplitCnt, | ||
| 79 | + tilingData.mTailMain, | ||
| 80 | + tilingData.nTailMain}; | ||
| 81 | + params.matmulKernelParams.qbmmParams = typename KernelImpl::QBMMTiling{1, | ||
| 82 | + 1, | ||
| 83 | + 1, | ||
| 84 | + 1, | ||
| 85 | + 1, | ||
| 86 | + 1, | ||
| 87 | + 1, | ||
| 88 | + 1, | ||
| 89 | + 1, | ||
| 90 | + 1, | ||
| 91 | + 1, | ||
| 92 | + 1, | ||
| 93 | + 0, | ||
| 94 | + tilingData.baseM, | ||
| 95 | + tilingData.baseN, | ||
| 96 | + tilingData.baseK, | ||
| 97 | + 0, | ||
| 98 | + tilingData.dbL0c}; | ||
| 99 | + params.hcclContext = context; | ||
| 100 | + params.tilingData = &tilingData; | ||
| 101 | + params.x1Addr = x1; | ||
| 102 | + params.x1ScaleAddr = x1_scale; | ||
| 103 | + | ||
| 104 | + Impl impl; | ||
| 105 | + impl(params); | ||
| 106 | +} | ||
| @@ -0,0 +1,20 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 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 | + | ||
| 11 | +#ifndef ALL_GATHER_MATMUL_APACE_TILING_KEY_H | ||
| 12 | +#define ALL_GATHER_MATMUL_APACE_TILING_KEY_H | ||
| 13 | + | ||
| 14 | +#include <ascendc/host_api/tiling/template_argument.h> | ||
| 15 | + | ||
| 16 | +ASCENDC_TPL_ARGS_DECL(AllGatherMatmulV3, ASCENDC_TPL_BOOL_DECL(TRANS_B, 0, 1), ); | ||
| 17 | + | ||
| 18 | +ASCENDC_TPL_SEL(ASCENDC_TPL_ARGS_SEL(ASCENDC_TPL_BOOL_SEL(TRANS_B, 0, 1))); | ||
| 19 | + | ||
| 20 | +#endif | ||
| @@ -0,0 +1,8 @@ | |||
| 1 | +# 运行产物(精度/性能结果 CSV 与 profiler 导出目录)不入库 | ||
| 2 | +Profiling_Result_*/ | ||
| 3 | +PROF_*/ | ||
| 4 | +all_gather_matmul_v3_precision_result.csv | ||
| 5 | +all_gather_matmul_v3_performance_result.csv | ||
| 6 | +logs/ | ||
| 7 | +extra-info/ | ||
| 8 | +__pycache__/ | ||
| @@ -0,0 +1,57 @@ | |||
| 1 | +#!/bin/bash | ||
| 2 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 3 | +# all_gather_matmul_v3 (ubmem) 测试运行包装 —— 交付版,环境无关,无需修改本文件。 | ||
| 4 | +# | ||
| 5 | +# 前置(调用前自行完成): | ||
| 6 | +# 1) conda activate <装了 cann_ops_transformer wheel 的环境> (python3/torch/torch_npu 就绪) | ||
| 7 | +# 2) source <CANN_HOME>/set_env.sh (已安装 custom_transformer 算子包) | ||
| 8 | +# | ||
| 9 | +# 用法: | ||
| 10 | +# bash run_test.sh --mode precision --cases all --world-size 4 # 精度(18 个默认形状) | ||
| 11 | +# bash run_test.sh --mode perf --cases all --world-size 4 # 性能+掩盖率 | ||
| 12 | +# bash run_test.sh --mode precision --m 48 --k 3584 --n 2816 # 自定义形状 | ||
| 13 | +# bash run_test.sh --list-cases # 查看内置用例 | ||
| 14 | +# 可选环境变量: ASCEND_RT_VISIBLE_DEVICES(默认 0,1,2,3, 须覆盖 world-size 个设备) | ||
| 15 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 16 | +set -o pipefail | ||
| 17 | + | ||
| 18 | +if [ -z "${ASCEND_HOME_PATH:-}" ]; then | ||
| 19 | + echo "[ERROR] 未检测到 ASCEND_HOME_PATH, 请先 source CANN 的 set_env.sh" | ||
| 20 | + exit 1 | ||
| 21 | +fi | ||
| 22 | + | ||
| 23 | +USER_SITE=$(python3 -c "import site; print(site.getusersitepackages())" 2>/dev/null) | ||
| 24 | +SITE_PKG=$(python3 -c "import sysconfig; print(sysconfig.get_paths()['purelib'])" 2>/dev/null) | ||
| 25 | +PREPEND="" | ||
| 26 | +if [ -n "${USER_SITE:-}" ] && [ -d "$USER_SITE" ]; then | ||
| 27 | + PREPEND="$USER_SITE" | ||
| 28 | +fi | ||
| 29 | +if [ -n "$SITE_PKG" ]; then | ||
| 30 | + if [ -n "$PREPEND" ]; then PREPEND="$PREPEND:$SITE_PKG"; else PREPEND="$SITE_PKG"; fi | ||
| 31 | +fi | ||
| 32 | +if [ -n "$PREPEND" ]; then | ||
| 33 | + if [ -n "${PYTHONPATH:-}" ]; then | ||
| 34 | + export PYTHONPATH="$PREPEND:$PYTHONPATH" | ||
| 35 | + else | ||
| 36 | + export PYTHONPATH="$PREPEND" | ||
| 37 | + fi | ||
| 38 | +fi | ||
| 39 | +export LD_LIBRARY_PATH="${ASCEND_HOME_PATH}/opp/vendors/custom_transformer/op_api/lib/:${LD_LIBRARY_PATH}" | ||
| 40 | + | ||
| 41 | +export ASCEND_RT_VISIBLE_DEVICES=${ASCEND_RT_VISIBLE_DEVICES:-0,1,2,3} | ||
| 42 | + | ||
| 43 | +# 精度模式不设该变量; 性能模式 golden 小算子走 CCU 编排(对融合算子无影响) | ||
| 44 | +if [[ "$*" == *"--mode perf"* ]]; then | ||
| 45 | + export HCCL_OP_EXPANSION_MODE=CCU_SCHED | ||
| 46 | +else | ||
| 47 | + unset HCCL_OP_EXPANSION_MODE | ||
| 48 | +fi | ||
| 49 | +unset HCCL_BUFFSIZE | ||
| 50 | + | ||
| 51 | +cd "$(dirname "$0")" | ||
| 52 | +echo "[ENV] python=$(which python3)" | ||
| 53 | +echo "[ENV] cann_ops_transformer=$(python3 -c 'import cann_ops_transformer as c; print(c.__file__)' 2>&1 | tail -1)" | ||
| 54 | +echo "[ENV] ASCEND_HOME_PATH=${ASCEND_HOME_PATH}" | ||
| 55 | +mkdir -p logs | ||
| 56 | +python3 all_gather_matmul_v3_test.py "$@" 2>&1 | tee "logs/run_$(date +%Y%m%d_%H%M%S).log" | ||
| 57 | +exit "${PIPESTATUS[0]}" | ||
| @@ -0,0 +1,12 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 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 | +__all__ = ["all_gather_quant_matmul"] | ||
| 11 | + | ||
| 12 | +from .all_gather_quant_matmul import all_gather_quant_matmul | ||
| @@ -0,0 +1,518 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 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 | +import logging | ||
| 11 | +import os | ||
| 12 | +from typing import List, Optional, Tuple | ||
| 13 | + | ||
| 14 | +import torch | ||
| 15 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library | ||
| 16 | +from torch.library import impl | ||
| 17 | +from torch_npu.utils._error_code import ErrCode, ops_error | ||
| 18 | + | ||
| 19 | +_UBMEM_CTX_CACHE = {} | ||
| 20 | + | ||
| 21 | +UBMEM_CONTEXT_TAG = "all_gather_quant_matmul_ubmem" | ||
| 22 | + | ||
| 23 | +_logger = logging.getLogger(__name__) | ||
| 24 | + | ||
| 25 | +# dtype 枚举: <256 为 torch ScalarType 枚举, >=256 为 ACL 枚举 + 256 | ||
| 26 | +_DTYPE_ENUM_FP16 = 5 | ||
| 27 | +_DTYPE_ENUM_BF16 = 15 | ||
| 28 | +_DTYPE_ENUM_FP8_E5M2 = 23 | ||
| 29 | +_DTYPE_ENUM_FP8_E4M3FN = 24 | ||
| 30 | +_DTYPE_ENUM_FP4_E2M1 = 296 # ACL_FLOAT4_E2M1, 以 uint8 打包存储(2 元素/字节) | ||
| 31 | + | ||
| 32 | +_ACL_DTYPE_TO_TORCH_DTYPE = { | ||
| 33 | + _DTYPE_ENUM_FP16: torch.float16, | ||
| 34 | + _DTYPE_ENUM_BF16: torch.bfloat16, | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +# 不包含算子逻辑,只声明需要哪个.cpp,加哪些include路径,注册什么op签名,然后父类OpBuilder框架才知道怎么编译,底层 | ||
| 39 | +# 走torch的cpp_extension JIT机制:调gcc、缓存.so等 | ||
| 40 | +class _AllGatherQuantMatmulOpBuilder( | ||
| 41 | + OpBuilder | ||
| 42 | +): # 继承 cann_ops_transformer的OpBuilder框架 | ||
| 43 | + def __init__(self): | ||
| 44 | + super(_AllGatherQuantMatmulOpBuilder, self).__init__( | ||
| 45 | + "npu_all_gather_quant_matmul", category="mc2" | ||
| 46 | + ) | ||
| 47 | + | ||
| 48 | + def sources(self): # 编译的源文件 | ||
| 49 | + return ["csrc/mc2/all_gather_quant_matmul.cpp"] | ||
| 50 | + | ||
| 51 | + # 已装CANN的kernel头 | ||
| 52 | + def include_paths(self): | ||
| 53 | + paths = super().include_paths() | ||
| 54 | + candidate_paths = [ | ||
| 55 | + os.path.join( | ||
| 56 | + self._cann_path, | ||
| 57 | + "opp/vendors/custom_transformer/op_impl/ai_core/tbe/custom_transformer_impl/ascendc/common/op_kernel", | ||
| 58 | + ), | ||
| 59 | + os.path.join( | ||
| 60 | + self._cann_path, | ||
| 61 | + "opp/vendors/custom_transformer/op_impl/ai_core/tbe/custom_transformer_impl/ascendc/common", | ||
| 62 | + ), | ||
| 63 | + os.path.join( | ||
| 64 | + self._cann_path, | ||
| 65 | + "vendors/custom_transformer/op_impl/ai_core/tbe/custom_transformer_impl/ascendc/common", | ||
| 66 | + ), | ||
| 67 | + os.path.join( | ||
| 68 | + self._cann_path, | ||
| 69 | + "opp/built-in/op_impl/ai_core/tbe/impl/ops_transformer/ascendc/common", | ||
| 70 | + ), | ||
| 71 | + os.path.join( | ||
| 72 | + self._cann_path, | ||
| 73 | + "opp/built-in/op_impl/ai_core/tbe/impl/ops_transformer/ascendc/common/op_kernel", | ||
| 74 | + ), | ||
| 75 | + ] | ||
| 76 | + for path in candidate_paths: | ||
| 77 | + if os.path.isdir(path): | ||
| 78 | + paths.append(path) | ||
| 79 | + return paths | ||
| 80 | + | ||
| 81 | + # torch.library的op签名 | ||
| 82 | + def schema(self) -> str: | ||
| 83 | + return ( | ||
| 84 | + "npu_all_gather_quant_matmul(Tensor context, Tensor x1, Tensor x2, " | ||
| 85 | + "int hccl_buffer_size, str group_name, int rank_size, *, " | ||
| 86 | + "Tensor? bias=None, Tensor? x1_scale=None, Tensor? x2_scale=None, " | ||
| 87 | + "int[] group_sizes=[], " | ||
| 88 | + "int? x1_dtype=None, int? x2_dtype=None, " | ||
| 89 | + "int? x1_scale_dtype=None, int? x2_scale_dtype=None, " | ||
| 90 | + "int? y_dtype=None, str comm_mode=None" | ||
| 91 | + ") -> (Tensor, Tensor, Tensor)" | ||
| 92 | + ) | ||
| 93 | + | ||
| 94 | + # FakeTensorMode的shape推演 | ||
| 95 | + def register_meta(self): | ||
| 96 | + @impl(get_as_library(), self.name, "Meta") | ||
| 97 | + def npu_all_gather_quant_matmul_meta( | ||
| 98 | + context, | ||
| 99 | + x1, | ||
| 100 | + x2, | ||
| @@ -0,0 +1,248 @@ | |||
| 1 | +// ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +// Copyright (c) 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 | + | ||
| 11 | +#include <set> | ||
| 12 | +#include <torch/extension.h> | ||
| 13 | +#include <cstdint> | ||
| 14 | +#include <cstring> | ||
| 15 | +#include <string> | ||
| 16 | +#include "acl/acl.h" | ||
| 17 | +#include "acl/acl_rt.h" | ||
| 18 | +#include "aclnn_common.h" | ||
| 19 | +#include "hccl_common.h" | ||
| 20 | +#include "apace/core/aiv_comm/collective_comm_context.h" | ||
| 21 | +#include "apace/utils/comm_channel_builder.h" | ||
| 22 | + | ||
| 23 | +namespace op_api { | ||
| 24 | +using npu_utils = at_npu::native::NpuUtils; | ||
| 25 | +const int DIM_TWO = 2; | ||
| 26 | +const int DIM_THREE = 3; | ||
| 27 | +const int DIM_FOUR = 4; | ||
| 28 | +const int ACL_FORMAT_NZ_VALUE = 29; // ACL_FORMAT_FRACTAL_NZ | ||
| 29 | +static const int64_t GROUP_MAX = 65535; | ||
| 30 | +static const size_t GROUP_DIM = 3; | ||
| 31 | +static const size_t OFFSET_32_BITS = 32; | ||
| 32 | +static const size_t OFFSET_16_BITS = 16; | ||
| 33 | +const std::set<int> SUPPORT_RANK_SIZE_LIST{2, 4, 8}; | ||
【一般】这里把 16 从 rank_size 支持列表里去掉了,但 tiling 的 CheckRankSizeAttr 和 README 2.4 节都还是 {2, 4, 8, 16},torch 层先把 16 卡死就跟下游口径对不上了。如果是 ubmem 路径故意不支持 16,README 和 tiling 校验要一起收掉;不是的话把 16 加回来。 ![]() ![]() | |||
| 34 | + | ||
| 35 | +int64_t CheckAndGetGroupSizeAg(at::IntArrayRef groupSizeList) | ||
| 36 | +{ | ||
| 37 | + int64_t groups = 0; | ||
| 38 | + if (groupSizeList.empty()) { | ||
| 39 | + return groups; | ||
| 40 | + } | ||
| 41 | + size_t groupDim = groupSizeList.size(); | ||
| 42 | + TORCH_CHECK(groupDim == GROUP_DIM, "group_sizes only support input with three elements, but got ", groupDim); | ||
| 43 | + | ||
| 44 | + int64_t groupM = static_cast<int64_t>(groupSizeList[0]); | ||
| 45 | + int64_t groupN = static_cast<int64_t>(groupSizeList[1]); | ||
| 46 | + int64_t groupK = static_cast<int64_t>(groupSizeList[2]); | ||
| 47 | + | ||
| 48 | + bool invalid_group_param = ((groupM <= GROUP_MAX && groupM >= 0) && (groupN <= GROUP_MAX && groupN >= 0) && | ||
| 49 | + (groupK <= GROUP_MAX && groupK >= 0)); | ||
| 50 | + TORCH_CHECK(invalid_group_param, "group param value must conform to range [0, 65535]"); | ||
| 51 | + | ||
| 52 | + groups = static_cast<int64_t>((static_cast<uint64_t>(groupM) << OFFSET_32_BITS) + | ||
| 53 | + (static_cast<uint64_t>(groupN) << OFFSET_16_BITS) + static_cast<uint64_t>(groupK)); | ||
| 54 | + return groups; | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +std::tuple<at::Tensor, at::Tensor, at::Tensor> NpuAllGatherQuantMatmul( | ||
| 58 | + const at::Tensor& context, const at::Tensor& x1, const at::Tensor& x2, int64_t hcclBufferSize, std::string group, | ||
| 59 | + int64_t rankSize, const c10::optional<at::Tensor>& biasOptional, const c10::optional<at::Tensor>& x1ScaleOptional, | ||
| 60 | + const c10::optional<at::Tensor>& x2ScaleOptional, c10::IntArrayRef groupSizes, c10::optional<int64_t> x1Dtype, | ||
| 61 | + c10::optional<int64_t> x2Dtype, c10::optional<int64_t> x1ScaleDtype, c10::optional<int64_t> x2ScaleDtype, | ||
| 62 | + c10::optional<int64_t> yDtype, std::string commMode) | ||
| 63 | +{ | ||
| 64 | + TORCH_CHECK(x1.dim() == DIM_TWO, | ||
| 65 | + "The x1 input of allgatherquantmatmul is required to be 2D, but the actual x1 input is ", x1.dim(), | ||
| 66 | + "D."); | ||
| 67 | + TORCH_CHECK(x2.dim() == DIM_TWO || x2.dim() == DIM_FOUR, | ||
| 68 | + "The x2 input of allgatherquantmatmul is required to be 2D (ND/NZ logical) or 4D " | ||
| 69 | + "(FRACTAL_NZ storage), but the actual x2 input is ", | ||
| 70 | + x2.dim(), "D."); | ||
| 71 | + TORCH_CHECK(SUPPORT_RANK_SIZE_LIST.find(rankSize) != SUPPORT_RANK_SIZE_LIST.end(), | ||
| 72 | + "The rank_size should be in [2, 4, 8], but the actual value is ", rankSize, "."); | ||
| 73 | + TORCH_CHECK(x1ScaleOptional.has_value() && x1ScaleOptional->dim() == DIM_THREE, | ||
| 74 | + "x1_scale is required for MX quant and must be 3D [M, ceil(K/64), 2]."); | ||
| 75 | + TORCH_CHECK(x2ScaleOptional.has_value() && x2ScaleOptional->dim() == DIM_THREE, | ||
| 76 | + "x2_scale is required for MX quant and must be 3D " | ||
| 77 | + "([N, ceil(K/64), 2] for transposed B, [ceil(K/64), N, 2] for non-transposed B)."); | ||
| 78 | + | ||
| 79 | + auto x1Size = x1.sizes(); | ||
| 80 | + auto x2Size = x2.sizes(); | ||
| 81 | + int64_t mPerRank = x1Size[0]; | ||
| 82 | + const bool x2Nz = (at_npu::native::get_npu_format(x2) == ACL_FORMAT_NZ_VALUE); | ||
| 83 | + const bool x2IsFp4 = x2Dtype.has_value() && GetAclDataType(x2Dtype.value()) == ACL_FLOAT4_E2M1; | ||
| 84 | + // fp4 打包存储(2 元素/字节)时 x1 末维为 K/2, 方向判断用逻辑 K | ||
| 85 | + const int64_t k = x2IsFp4 ? x1Size[1] * 2 : x1Size[1]; | ||
| 86 | + const int64_t kd = (k + 63) / 64; | ||
| 87 | + const int64_t sD0 = x2ScaleOptional->size(0); | ||
| 88 | + const int64_t sD1 = x2ScaleOptional->size(1); | ||
| 89 | + int64_t n = 0; | ||
| 90 | + if (sD0 == kd && sD1 != kd) { | ||
| 91 | + n = sD1; // 非转置 B: scale=[kd,n,2], N=scale.dim1 | ||
| 92 | + } else if (sD1 == kd && sD0 != kd) { | ||
| 93 | + n = sD0; // 转置 B: scale=[n,kd,2], N=scale.dim0 | ||
| 94 | + } else { | ||
| 95 | + n = (sD0 == kd) ? sD1 : sD0; | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + at::ScalarType outScalarType = at::kBFloat16; | ||
| 99 | + if (yDtype.has_value()) { | ||
| 100 | + aclDataType outAclDtype = GetAclDataType(yDtype.value()); | ||
| 101 | + TORCH_CHECK(outAclDtype == ACL_BF16 || outAclDtype == ACL_FLOAT16, | ||
| 102 | + "y_dtype only supports bf16(15) or fp16(5) in the ubmem path, but got invalid enum value ", | ||
| 103 | + yDtype.value(), "."); | ||
| 104 | + outScalarType = (outAclDtype == ACL_FLOAT16) ? at::kHalf : at::kBFloat16; | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + at::Tensor y = at::empty({mPerRank * rankSize, n}, x1.options().dtype(outScalarType)); | ||
| 108 | + | ||
| 109 | + std::string commModeStr = std::string(commMode); | ||
| 110 | + char* commModePtr = const_cast<char*>(commModeStr.c_str()); | ||
| 111 | + | ||
| 112 | + std::string groupStr = std::string(group); | ||
| 113 | + char* groupPtr = const_cast<char*>(groupStr.c_str()); | ||
| 114 | + | ||
| 115 | + // x1/x2 支持原生 fp8(e4m3/e5m2) 或 fp4(打包 uint8 + dtype 枚举 296), | ||
| 116 | + auto isFp4Storage = [](const at::Tensor& t) { return t.scalar_type() == at::kByte; }; | ||
| 117 | + for (const auto* item : {&x1, &x2}) { | ||
| 118 | + const auto st = item->scalar_type(); | ||
| 119 | + TORCH_CHECK(st == at::ScalarType::Float8_e4m3fn || st == at::ScalarType::Float8_e5m2 || st == at::kByte, | ||
| 120 | + "x1/x2 only support torch.float8_e4m3fn, torch.float8_e5m2 or uint8 " | ||
| 121 | + "(packed fp4, pass x1_dtype/x2_dtype=296), but got tensor dtype ", | ||
| 122 | + st, "."); | ||
| 123 | + } | ||
| 124 | + aclDataType x1AclDtype = | ||
| 125 | + x1Dtype.has_value() ? GetAclDataType(x1Dtype.value()) : ConvertToAclDataType(x1.scalar_type()); | ||
| 126 | + aclDataType x2AclDtype = | ||
| 127 | + x2Dtype.has_value() ? GetAclDataType(x2Dtype.value()) : ConvertToAclDataType(x2.scalar_type()); | ||
| 128 | + auto isSupportedX = [](aclDataType dt) { | ||
| 129 | + return dt == ACL_FLOAT8_E4M3FN || dt == ACL_FLOAT8_E5M2 || dt == ACL_FLOAT4_E2M1; | ||
| 130 | + }; | ||
| 131 | + TORCH_CHECK(isSupportedX(x1AclDtype), "x1 dtype enum is not supported, got ", static_cast<int>(x1AclDtype), | ||
| 132 | + " (expected 24 e4m3 / 23 e5m2 / 296 fp4)."); | ||
| 133 | + TORCH_CHECK(isSupportedX(x2AclDtype), "x2 dtype enum is not supported, got ", static_cast<int>(x2AclDtype), | ||
| 134 | + " (expected 24 e4m3 / 23 e5m2 / 296 fp4)."); | ||
| 135 | + // fp4 必须用 uint8 打包存储; fp8 枚举允许原生 fp8 存储或 uint8 bitcast | ||
| 136 | + // (例如 e5m2 无法直接 npu_format_cast, 以 uint8 存储 + dtype 枚举传入) | ||
| 137 | + TORCH_CHECK((x1AclDtype != ACL_FLOAT4_E2M1) || isFp4Storage(x1), | ||
| 138 | + "x1 dtype enum 296 (fp4) requires uint8 packed storage."); | ||
| 139 | + TORCH_CHECK((x2AclDtype != ACL_FLOAT4_E2M1) || isFp4Storage(x2), | ||
| 140 | + "x2 dtype enum 296 (fp4) requires uint8 packed storage."); | ||
| 141 | + TORCH_CHECK((x1AclDtype == ACL_FLOAT4_E2M1) == (x2AclDtype == ACL_FLOAT4_E2M1), | ||
| 142 | + "FP4 requires both x1 and x2 to be FP4 (x1_dtype=x2_dtype=296)."); | ||
| 143 | + if (x2.dim() == DIM_FOUR || at_npu::native::get_npu_format(x2) == ACL_FORMAT_NZ_VALUE) { | ||
| 144 | + TORCH_CHECK(x1AclDtype != ACL_FLOAT4_E2M1, "FP4 does not support FRACTAL_NZ x2."); | ||
| 145 | + } | ||
| 146 | + | ||
| 147 | + // gather_out / amax_out 当前不使能, | ||
| 148 | + // torch 侧传 {0} 空占位 tensor 经 aclnn 透传 inner(aclnn/tiling/kernel 均不处理),并原样返回给 torch。 | ||
| 149 | + at::Tensor gatherOut = at::empty({0}, x1.options().dtype(x1.scalar_type())); | ||
| 150 | + at::Tensor amaxOut = at::empty({0}, x1.options().dtype(at::kFloat)); | ||
| 151 | + | ||
| 152 | + const at::Tensor& x1ScaleReal = x1ScaleOptional.value_or(at::Tensor()); | ||
| 153 | + const at::Tensor& x2ScaleReal = x2ScaleOptional.value_or(at::Tensor()); | ||
| 154 | + | ||
| 155 | + // scale 原始 dtype 校验:仅支持 uint8(packed, 搭配 e8m0 枚举) 或原生 float8_e8m0fnu。 | ||
| 156 | + if (x1ScaleReal.defined()) { | ||
| 157 | + auto scaleSt = x1ScaleReal.scalar_type(); | ||
| 158 | + TORCH_CHECK(scaleSt == at::kByte || scaleSt == at::ScalarType::Float8_e8m0fnu, | ||
| 159 | + "x1_scale only supports torch.uint8 (packed, pass x1_scale_dtype=293) or " | ||
| 160 | + "torch.float8_e8m0fnu, but got tensor dtype ", | ||
| 161 | + scaleSt, ". Dtype enum cannot override an unsupported storage dtype."); | ||
| 162 | + } | ||
| 163 | + if (x2ScaleReal.defined()) { | ||
| 164 | + auto scaleSt = x2ScaleReal.scalar_type(); | ||
| 165 | + TORCH_CHECK(scaleSt == at::kByte || scaleSt == at::ScalarType::Float8_e8m0fnu, | ||
| 166 | + "x2_scale only supports torch.uint8 (packed, pass x2_scale_dtype=293) or " | ||
| 167 | + "torch.float8_e8m0fnu, but got tensor dtype ", | ||
| 168 | + scaleSt, ". Dtype enum cannot override an unsupported storage dtype."); | ||
| 169 | + } | ||
| 170 | + | ||
| 171 | + aclDataType x1ScaleAclDtype = | ||
| 172 | + x1ScaleDtype.has_value() ? | ||
| 173 | + GetAclDataType(x1ScaleDtype.value()) : | ||
| 174 | + (x1ScaleReal.defined() ? ConvertToAclDataType(x1ScaleReal.scalar_type()) : ACL_DT_UNDEFINED); | ||
| 175 | + aclDataType x2ScaleAclDtype = | ||
| 176 | + x2ScaleDtype.has_value() ? | ||
| 177 | + GetAclDataType(x2ScaleDtype.value()) : | ||
| 178 | + (x2ScaleReal.defined() ? ConvertToAclDataType(x2ScaleReal.scalar_type()) : ACL_DT_UNDEFINED); | ||
| 179 | + | ||
| 180 | + TensorWrapper x1Wrapper = {x1, x1AclDtype}; | ||
| 181 | + TensorWrapper x2Wrapper = {x2, x2AclDtype}; | ||
| 182 | + TensorWrapper x1ScaleWrapper = {x1ScaleReal, x1ScaleAclDtype}; | ||
| 183 | + TensorWrapper x2ScaleWrapper = {x2ScaleReal, x2ScaleAclDtype}; | ||
| 184 | + TensorWrapper gatherOutWrapper = {gatherOut, x1AclDtype}; | ||
| 185 | + | ||
| 186 | + int64_t groupSize = CheckAndGetGroupSizeAg(groupSizes); | ||
| 187 | + | ||
| 188 | + ACLNN_CMD(aclnnAllGatherQuantMatmulV3, context, x1Wrapper, x2Wrapper, biasOptional, x1ScaleWrapper, x2ScaleWrapper, | ||
| 189 | + groupPtr, rankSize, hcclBufferSize, groupSize, commModePtr, y, gatherOutWrapper); | ||
| 190 | + | ||
| 191 | + return std::make_tuple(y, gatherOut, amaxOut); | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +using ApaceCommUbmemContext = Apace::AivComm::CommUbmemContext; | ||
| 195 | +using UbmemCommChannelBuilder = CommChannelBuilder<ChannelMode::UBMEM>; // apace内comm_channel_builder.h | ||
| 196 | + | ||
| 197 | +/*! | ||
| 198 | + * \brief 创建 UBMEM 模式 device context 并包装为 at::Tensor 返回 | ||
| 199 | + * | ||
| 200 | + * 内部流程: | ||
| 201 | + * 1. 动态加载 HCCL 函数指针,从 group name 获取 HcclComm handle | ||
| 202 | + * 2. CommChannelBuilder<UBMEM>::CreateDeviceContext:engine ctx 按 tag 幂等复用,新建时 | ||
| 203 | + * 清零内置 buffer、建链并填充 rankId/rankSize/commBufferAddrs[] | ||
| 204 | + */ | ||
| 205 | +at::Tensor CreateUbmemContext(std::string group, std::string ctxTag) | ||
| 206 | +{ | ||
| 207 | + InitHcclEngineCtxFunctions(); | ||
| 208 | + | ||
| 209 | + HcclComm comm = nullptr; | ||
| 210 | + auto hcclRet = HcomGetCommHandleByGroupFunc(group.c_str(), &comm); // group名-> HCCL comm句柄 | ||
| 211 | + TORCH_CHECK(hcclRet == HCCL_SUCCESS, "Get HCCL handle failed, group: ", group, ", ret: ", hcclRet); | ||
| 212 | + | ||
| 213 | + UbmemCommChannelBuilder builder(comm); | ||
| 214 | + ApaceCommUbmemContext hostCtx = {}; | ||
| 215 | + void* devCtx = builder.CreateDeviceContext(&hostCtx, sizeof(ApaceCommUbmemContext), ctxTag.c_str(), &hostCtx); | ||
| 216 | + TORCH_CHECK(devCtx != nullptr, "CreateDeviceContext failed, ctxTag: ", ctxTag); | ||
| 217 | + | ||
| 218 | + at::Tensor context = | ||
| 219 | + at::from_blob(devCtx, {static_cast<int64_t>(sizeof(ApaceCommUbmemContext) / sizeof(int32_t))}, at::kInt); | ||
| 220 | + return context; | ||
| 221 | +} | ||
| 222 | + | ||
| 223 | +/*! | ||
| 224 | + * \brief 获取 group 对应 HCCL 内置 buffer 大小(供 host 侧窗口容量预检) | ||
| 225 | + */ | ||
| 226 | +int64_t GetHcclBufferSizeByGroup(std::string group) | ||
| 227 | +{ | ||
| 228 | + InitHcclEngineCtxFunctions(); | ||
| 229 | + | ||
| 230 | + HcclComm comm = nullptr; | ||
| 231 | + auto hcclRet = HcomGetCommHandleByGroupFunc(group.c_str(), &comm); | ||
| 232 | + TORCH_CHECK(hcclRet == HCCL_SUCCESS, "Get HCCL handle failed, group: ", group, ", ret: ", hcclRet); | ||
| 233 | + | ||
| 234 | + void* buf = nullptr; | ||
| 235 | + uint64_t bufSize = 0; | ||
| 236 | + hcclRet = HcclGetHcclBufferFunc(comm, &buf, &bufSize); | ||
| 237 | + TORCH_CHECK(hcclRet == HCCL_SUCCESS && buf != nullptr, "HcclGetHcclBuffer failed, ret: ", hcclRet); | ||
| 238 | + return static_cast<int64_t>(bufSize); | ||
| 239 | +} | ||
| 240 | + | ||
| 241 | +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) | ||
| 242 | +{ | ||
| 243 | + m.def("npu_all_gather_quant_matmul", &NpuAllGatherQuantMatmul, "npu_all_gather_quant_matmul"); | ||
| 244 | + m.def("create_ubmem_context", &CreateUbmemContext, "create_ubmem_context", py::arg("group"), py::arg("ctx_tag")); | ||
| 245 | + m.def("get_hccl_buffer_size", &GetHcclBufferSizeByGroup, "get_hccl_buffer_size", py::arg("group")); | ||
| 246 | +} | ||
| 247 | + | ||
| 248 | +} // namespace op_api | ||
| @@ -10,7 +10,7 @@ | |||
| 10 | 10 | ||
| 11 | /*! | 11 | /*! |
| 12 | * \file qmm_mx_block_mmad_tile_k_wait_flag.h | 12 | * \file qmm_mx_block_mmad_tile_k_wait_flag.h |
| 13 | - * \brief BlockMmad specialization for MatmulWithScaleMx with split-K hard sync support. | 13 | + * \brief Standalone BlockMmad class for MatmulWithScaleMx with split-K hard sync support. |
| 14 | * | 14 | * |
| 15 | * Based on Blaze's block_mmad_qbmm_mx.h, extended with: | 15 | * Based on Blaze's block_mmad_qbmm_mx.h, extended with: |
| 16 | * - split-K hard sync: CrossCoreWaitFlag(9) every AG_SYNC_INTERVAL/kL1 K-iterations | 16 | * - split-K hard sync: CrossCoreWaitFlag(9) every AG_SYNC_INTERVAL/kL1 K-iterations |
| @@ -39,11 +39,12 @@ namespace Block { | |||
| 39 | 39 | ||
| 40 | static constexpr uint64_t AG_SYNC_INTERVAL = 1024UL; | 40 | static constexpr uint64_t AG_SYNC_INTERVAL = 1024UL; |
| 41 | static constexpr uint16_t CROSS_CORE_FLAG_NUM_NINE = 9; | 41 | static constexpr uint16_t CROSS_CORE_FLAG_NUM_NINE = 9; |
| 42 | +static constexpr uint8_t CROSS_CORE_INNER_CUBE_VEC_SYNC = 0x2U; | ||
| 42 | 43 | ||
| 43 | -template <uint64_t A_FULL_LOAD_MODE, bool ATOMIC_ADD, class ScheduleType_, class AType_, class LayoutA_, class BType_, | 44 | +// 独立 BlockMmad 类(与 QmmMxBlockMmadFragment 组织方式一致), 不依赖 BlockMmad 偏特化派发 |
| 44 | - class LayoutB_, class CType_, class LayoutC_, class BiasType_, class LayoutBias_> | 45 | +template <uint64_t A_FULL_LOAD_MODE, bool ATOMIC_ADD, class AType_, class LayoutA_, class BType_, class LayoutB_, |
| 45 | -class BlockMmad<MatmulWithScaleMx<A_FULL_LOAD_MODE, ATOMIC_ADD, ScheduleType_>, AType_, LayoutA_, BType_, LayoutB_, | 46 | + class CType_, class LayoutC_, class BiasType_, class LayoutBias_> |
| 46 | - CType_, LayoutC_, BiasType_, LayoutBias_> { | 47 | +class QmmMxBlockMmadTileKWaitFlag { |
| 47 | public: | 48 | public: |
| 48 | using AType = AType_; | 49 | using AType = AType_; |
| 49 | using BType = BType_; | 50 | using BType = BType_; |
| @@ -52,12 +53,14 @@ public: | |||
| 52 | using LayoutB = LayoutB_; | 53 | using LayoutB = LayoutB_; |
| 53 | using LayoutC = LayoutC_; | 54 | using LayoutC = LayoutC_; |
| 54 | using BiasType = BiasType_; | 55 | using BiasType = BiasType_; |
| 55 | - using DispatchPolicy = MatmulWithScaleMx<A_FULL_LOAD_MODE, ATOMIC_ADD, ScheduleType_>; | 56 | + using DispatchPolicy = MatmulWithScaleMx<A_FULL_LOAD_MODE, ATOMIC_ADD>; |
| 56 | using ProblemShape = asc::te::shape<int64_t, int64_t, int64_t, int64_t>; | 57 | using ProblemShape = asc::te::shape<int64_t, int64_t, int64_t, int64_t>; |
| 57 | using BlockShape = asc::te::shape<int64_t, int64_t, int64_t, int64_t>; | 58 | using BlockShape = asc::te::shape<int64_t, int64_t, int64_t, int64_t>; |
| 58 | static constexpr bool weightNz = IsWeightNz<LayoutB>::value; | 59 | static constexpr bool weightNz = IsWeightNz<LayoutB>::value; |
| 59 | static constexpr bool transA = IsTrans<LayoutA>::value; | 60 | static constexpr bool transA = IsTrans<LayoutA>::value; |
| 60 | static constexpr bool transB = IsTrans<LayoutB>::value; | 61 | static constexpr bool transB = IsTrans<LayoutB>::value; |
| 62 | + using LayoutScaleB = | ||
| 63 | + AscendC::Std::conditional_t<transB, asc::te::scaleb_dn_layout_ptn, asc::te::scaleb_nd_layout_ptn>; | ||
| 61 | 64 | ||
| 62 | struct Params { | 65 | struct Params { |
| 63 | GM_ADDR aGmAddr{nullptr}; | 66 | GM_ADDR aGmAddr{nullptr}; |
| @@ -74,7 +77,7 @@ public: | |||
| 74 | uint64_t l1BufNum; | 77 | uint64_t l1BufNum; |
| 75 | }; | 78 | }; |
| 76 | 79 | ||
| 77 | - __aicore__ inline BlockMmad() | 80 | + __aicore__ inline QmmMxBlockMmadTileKWaitFlag() |
| 78 | { | 81 | { |
| 79 | AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(INPUT_BUFFER_FLAG_0); | 82 | AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(INPUT_BUFFER_FLAG_0); |
| 80 | AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(INPUT_BUFFER_FLAG_1); | 83 | AscendC::SetFlag<AscendC::HardEvent::MTE1_MTE2>(INPUT_BUFFER_FLAG_1); |
| @@ -87,7 +90,7 @@ public: | |||
| 87 | AscendC::SetMMLayoutTransform(true); // true means column first when fixpipe_l0c2out | 90 | AscendC::SetMMLayoutTransform(true); // true means column first when fixpipe_l0c2out |
| 88 | } | 91 | } |
| 89 | 92 | ||
| 90 | - __aicore__ inline ~BlockMmad() | 93 | + __aicore__ inline ~QmmMxBlockMmadTileKWaitFlag() |
| 91 | { | 94 | { |
| 92 | AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(INPUT_BUFFER_FLAG_0); | 95 | AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(INPUT_BUFFER_FLAG_0); |
| 93 | AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(INPUT_BUFFER_FLAG_1); | 96 | AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(INPUT_BUFFER_FLAG_1); |
| @@ -148,22 +151,13 @@ public: | |||
| 148 | // split-K hard sync: AIV 每就绪 AG_SYNC_INTERVAL(1024) 元素 set(9) 一次,每核共 ceil(k/1024) 次。 | 151 | // split-K hard sync: AIV 每就绪 AG_SYNC_INTERVAL(1024) 元素 set(9) 一次,每核共 ceil(k/1024) 次。 |
| 149 | // AIC 读第 iter0 段 K [iter0*kL1,(iter0+1)*kL1) 前,需累计等到 ceil((iter0+1)*kL1/1024) 次, | 152 | // AIC 读第 iter0 段 K [iter0*kL1,(iter0+1)*kL1) 前,需累计等到 ceil((iter0+1)*kL1/1024) 次, |
| 150 | // 保证该段所有列已 gather 完成。循环末尾 drain 补齐,确保 wait 次数恒等于 AIV set 次数。 | 153 | // 保证该段所有列已 gather 完成。循环末尾 drain 补齐,确保 wait 次数恒等于 AIV set 次数。 |
| 151 | - const uint64_t agTotalSets = CeilDiv(k_, AG_SYNC_INTERVAL); | 154 | + const uint64_t totalSets = CeilDiv(k_, AG_SYNC_INTERVAL); |
| 152 | - uint64_t agWaited = 0; | 155 | + uint64_t waited = 0; |
| 153 | for (uint64_t iter0 = 0; iter0 < kL1Iter_; ++iter0) { | 156 | for (uint64_t iter0 = 0; iter0 < kL1Iter_; ++iter0) { |
| 154 | - if (firstRound) { | 157 | + // gather 等待下沉到 ProcessL1Iteration 内(B/bias 装载之后),见该函数注释。 |
| 155 | - uint64_t waitTarget = CeilDiv((iter0 + 1) * kL1_, AG_SYNC_INTERVAL); | ||
| 156 | - if (waitTarget > agTotalSets) { | ||
| 157 | - waitTarget = agTotalSets; | ||
| 158 | - } | ||
| 159 | - while (agWaited < waitTarget) { | ||
| 160 | - AscendC::CrossCoreWaitFlag(CROSS_CORE_FLAG_NUM_NINE); | ||
| 161 | - agWaited++; | ||
| 162 | - } | ||
| 163 | - } | ||
| 164 | - | ||
| 165 | ProcessL1Iteration(gmA, gmB, gmScaleA, gmScaleB, gmBias, tensorL0C, tileL1L0Param, iter0, | 158 | ProcessL1Iteration(gmA, gmB, gmScaleA, gmScaleB, gmBias, tensorL0C, tileL1L0Param, iter0, |
| 166 | - scaleKOffsetStride, scaleKIter, scaleKIterIdx, isFirstSplitK, isLastSplitK); | 159 | + scaleKOffsetStride, scaleKIter, scaleKIterIdx, isFirstSplitK, isLastSplitK, totalSets, |
| 160 | + waited); | ||
| 167 | } | 161 | } |
| 168 | if (isLastSplitK) { | 162 | if (isLastSplitK) { |
| 169 | if constexpr (AscendC::Std::is_same_v<asc::te::get_mem_location<TensorC>, asc::te::location::ub>) { | 163 | if constexpr (AscendC::Std::is_same_v<asc::te::get_mem_location<TensorC>, asc::te::location::ub>) { |
| @@ -184,9 +178,9 @@ public: | |||
| 184 | if (firstRound) { | 178 | if (firstRound) { |
| 185 | // drain 剩余 set(9),确保 AIC wait 次数恒等于 AIV set 次数(ceil(k/AG_SYNC_INTERVAL)), | 179 | // drain 剩余 set(9),确保 AIC wait 次数恒等于 AIV set 次数(ceil(k/AG_SYNC_INTERVAL)), |
| 186 | // 避免残留计数影响后续(虽然只有 firstRound wait,但计数须收支平衡)。 | 180 | // 避免残留计数影响后续(虽然只有 firstRound wait,但计数须收支平衡)。 |
| 187 | - while (agWaited < agTotalSets) { | 181 | + while (waited < totalSets) { |
| 188 | - AscendC::CrossCoreWaitFlag(CROSS_CORE_FLAG_NUM_NINE); | 182 | + AscendC::CrossCoreWaitFlag<CROSS_CORE_INNER_CUBE_VEC_SYNC, PIPE_MTE2>(CROSS_CORE_FLAG_NUM_NINE); |
| 189 | - agWaited++; | 183 | + waited++; |
| 190 | } | 184 | } |
| 191 | } | 185 | } |
| 192 | firstRound = false; | 186 | firstRound = false; |
| @@ -496,32 +490,45 @@ private: | |||
| 496 | TensorScaleB const& gmScaleB, TensorBias const& gmBias, | 490 | TensorScaleB const& gmScaleB, TensorBias const& gmBias, |
| 497 | TensorL0C& tensorL0C, TileL1L0Param& tileL1L0Param, uint64_t iter0, | 491 | TensorL0C& tensorL0C, TileL1L0Param& tileL1L0Param, uint64_t iter0, |
| 498 | uint64_t scaleKOffsetStride, uint64_t scaleKIter, uint64_t& scaleKIterIdx, | 492 | uint64_t scaleKOffsetStride, uint64_t scaleKIter, uint64_t& scaleKIterIdx, |
| 499 | - bool isFirstSplitK, bool isLastSplitK) | 493 | + bool isFirstSplitK, bool isLastSplitK, uint64_t totalSets, |
| 494 | + uint64_t& waited) | ||
| 500 | { | 495 | { |
| 501 | const uint64_t l1BufId = abL1LoopCnt_ & (l1BufNum_ - 1); | 496 | const uint64_t l1BufId = abL1LoopCnt_ & (l1BufNum_ - 1); |
| 502 | const uint64_t scaleL1BufId = scaleLoopCnt_ & 1; | 497 | const uint64_t scaleL1BufId = scaleLoopCnt_ & 1; |
| 503 | const uint64_t kL1Offset = iter0 * kL1_; | 498 | const uint64_t kL1Offset = iter0 * kL1_; |
| 504 | const uint64_t scaleGmOffset = iter0 * scaleKOffsetStride; | 499 | const uint64_t scaleGmOffset = iter0 * scaleKOffsetStride; |
| 505 | 500 | ||
| 506 | - // scaleA, scaleB GM->L1 | ||
| 507 | - auto scalePair = CopyScalesInL1(gmScaleA, gmScaleB, tileL1L0Param, scaleL1BufId, kL1Offset, scaleGmOffset, | ||
| 508 | - scaleKIterIdx == 0); | ||
| 509 | - auto& tensorScaleAL1 = scalePair.scaleA; | ||
| 510 | - auto& tensorScaleBL1 = scalePair.scaleB; | ||
| 511 | - | ||
| 512 | AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(l1BufId); | 501 | AscendC::WaitFlag<AscendC::HardEvent::MTE1_MTE2>(l1BufId); |
| 513 | tileL1L0Param.curGmKL1 = (iter0 + 1 == kL1Iter_) ? (k_ - kL1Offset) : kL1_; | 502 | tileL1L0Param.curGmKL1 = (iter0 + 1 == kL1Iter_) ? (k_ - kL1Offset) : kL1_; |
| 514 | tileL1L0Param.curPadKL1 = Align64(tileL1L0Param.curGmKL1); | 503 | tileL1L0Param.curPadKL1 = Align64(tileL1L0Param.curGmKL1); |
| 515 | 504 | ||
| 516 | - // A GM->L1 | 505 | + // B/bias 不依赖 gather:先发 GM->L1,再等 gather。 |
| 517 | - auto tensorAL1 = CopyAInL1(gmA, tileL1L0Param, l1BufId, kL1Offset); | ||
| 518 | - | ||
| 519 | // bias GM->L1 | 506 | // bias GM->L1 |
| 520 | auto tensorBiasL1 = CopyBiasInL1(gmBias, tileL1L0Param, scaleL1BufId, iter0, isFirstSplitK); | 507 | auto tensorBiasL1 = CopyBiasInL1(gmBias, tileL1L0Param, scaleL1BufId, iter0, isFirstSplitK); |
| 521 | 508 | ||
| 522 | // B GM->L1; slice first, then copy. | 509 | // B GM->L1; slice first, then copy. |
| 523 | auto tensorBL1 = CopyBInL1(gmB, tileL1L0Param, l1BufId, kL1Offset); | 510 | auto tensorBL1 = CopyBInL1(gmB, tileL1L0Param, l1BufId, kL1Offset); |
| 524 | 511 | ||
| 512 | + if (firstRound) { | ||
| 513 | + uint64_t waitTarget = CeilDiv((iter0 + 1) * kL1_, AG_SYNC_INTERVAL); | ||
| 514 | + if (waitTarget > totalSets) { | ||
| 515 | + waitTarget = totalSets; | ||
| 516 | + } | ||
| 517 | + while (waited < waitTarget) { | ||
| 518 | + AscendC::CrossCoreWaitFlag<CROSS_CORE_INNER_CUBE_VEC_SYNC, PIPE_MTE2>(CROSS_CORE_FLAG_NUM_NINE); | ||
| 519 | + waited++; | ||
| 520 | + } | ||
| 521 | + } | ||
| 522 | + | ||
| 523 | + // scaleA, scaleB GM->L1(scaleA 依赖 gather) | ||
| 524 | + auto scalePair = CopyScalesInL1(gmScaleA, gmScaleB, tileL1L0Param, scaleL1BufId, kL1Offset, scaleGmOffset, | ||
| 525 | + scaleKIterIdx == 0); | ||
| 526 | + auto& tensorScaleAL1 = scalePair.scaleA; | ||
| 527 | + auto& tensorScaleBL1 = scalePair.scaleB; | ||
| 528 | + | ||
| 529 | + // A GM->L1(依赖 gather) | ||
| 530 | + auto tensorAL1 = CopyAInL1(gmA, tileL1L0Param, l1BufId, kL1Offset); | ||
| 531 | + | ||
| 525 | AscendC::SetFlag<AscendC::HardEvent::MTE2_MTE1>(l1BufId); | 532 | AscendC::SetFlag<AscendC::HardEvent::MTE2_MTE1>(l1BufId); |
| 526 | AscendC::WaitFlag<AscendC::HardEvent::MTE2_MTE1>(l1BufId); | 533 | AscendC::WaitFlag<AscendC::HardEvent::MTE2_MTE1>(l1BufId); |
| 527 | 534 | ||
Mmc2/common/op_kernel/apace/tests/st/all_gather_quant_matmul/ubmem/src/apace_agm_kernel_launcher.h+4-4
| @@ -46,9 +46,8 @@ __aicore__ inline void AllGatherQuantMatmulUbmemKernelImpl(GM_ADDR hcclContext, | |||
| 46 | using LayoutB = typename AscendC::Std::conditional_t<!isX2Nz, asc::te::dn_ext_layout_ptn, asc::te::nz_layout_ptn>; | 46 | using LayoutB = typename AscendC::Std::conditional_t<!isX2Nz, asc::te::dn_ext_layout_ptn, asc::te::nz_layout_ptn>; |
| 47 | using LayoutC = asc::te::nd_ext_layout_ptn; | 47 | using LayoutC = asc::te::nd_ext_layout_ptn; |
| 48 | 48 | ||
| 49 | - using DispatchPolicy = MatmulWithScaleMx<0, false>; | ||
| 50 | using BlockMmad = | 49 | using BlockMmad = |
| 51 | - Block::BlockMmad<DispatchPolicy, TypeA, LayoutA, TypeB, LayoutB, TypeC, LayoutC, BiasType, LayoutC>; | 50 | + Block::QmmMxBlockMmadTileKWaitFlag<0, false, TypeA, LayoutA, TypeB, LayoutB, TypeC, LayoutC, BiasType, LayoutC>; |
| 52 | using BlockScheduler = Block::BlockSchedulerQuantBatchMatmulV3<asc::te::shape<int64_t, int64_t, int64_t, int64_t>, | 51 | using BlockScheduler = Block::BlockSchedulerQuantBatchMatmulV3<asc::te::shape<int64_t, int64_t, int64_t, int64_t>, |
| 53 | 0, LayoutA, LayoutB, TypeA>; | 52 | 0, LayoutA, LayoutB, TypeA>; |
| 54 | using BlockEpilogue = Block::BlockEpilogueEmpty; | 53 | using BlockEpilogue = Block::BlockEpilogueEmpty; |
| @@ -92,12 +91,13 @@ __aicore__ inline void AllGatherQuantMatmulUbmemKernelImpl(GM_ADDR hcclContext, | |||
| 92 | tilingData->baseK, | 91 | tilingData->baseK, |
| 93 | 0, | 92 | 0, |
| 94 | tilingData->dbL0c}; | 93 | tilingData->dbL0c}; |
| 94 | + (void)allGatherDataOut; | ||
| 95 | + (void)allGatherScalesOut; | ||
| 96 | + | ||
| 95 | params.hcclContext = hcclContext; | 97 | params.hcclContext = hcclContext; |
| 96 | params.tilingGM = tilingGM; | 98 | params.tilingGM = tilingGM; |
| 97 | params.x1Addr = x1; | 99 | params.x1Addr = x1; |
| 98 | params.x1ScaleAddr = x1Scale; | 100 | params.x1ScaleAddr = x1Scale; |
| 99 | - params.allGatherDataOutAddr = allGatherDataOut; | ||
| 100 | - params.allGatherScalesOutAddr = allGatherScalesOut; | ||
| 101 | 101 | ||
| 102 | Impl impl; | 102 | Impl impl; |
| 103 | impl(params); | 103 | impl(params); |
| @@ -31,6 +31,8 @@ | |||
| 31 | #include "hccl/hccl.h" | 31 | #include "hccl/hccl.h" |
| 32 | #include "apace_st_utils.h" | 32 | #include "apace_st_utils.h" |
| 33 | #include "apace/utils/apace_constant.h" | 33 | #include "apace/utils/apace_constant.h" |
| 34 | +#include "apace/core/aiv_comm/collective_comm_context.h" | ||
| 35 | +#include "apace/utils/comm_channel_builder.h" | ||
| 34 | #include "apace/tiling/matmul_tiling/quant_matmul_tiling.h" | 36 | #include "apace/tiling/matmul_tiling/quant_matmul_tiling.h" |
| 35 | #include "apace/tiling/matmul_tiling/quant_matmul_tiling_data.h" | 37 | #include "apace/tiling/matmul_tiling/quant_matmul_tiling_data.h" |
| 36 | #include "tiling/hccl/hccl_tiling.h" | 38 | #include "tiling/hccl/hccl_tiling.h" |
| @@ -40,7 +42,6 @@ extern "C" HcclResult HcclCommInitAll(uint32_t commNum, int32_t* devIds, HcclCom | |||
| 40 | extern "C" HcclResult HcclCommDestroy(HcclComm comm); | 42 | extern "C" HcclResult HcclCommDestroy(HcclComm comm); |
| 41 | extern "C" HcclResult HcclGetCommName(HcclComm comm, char* commName); | 43 | extern "C" HcclResult HcclGetCommName(HcclComm comm, char* commName); |
| 42 | extern "C" HcclResult HcomGetCommHandleByGroup(const char* groupName, void** commHandle); | 44 | extern "C" HcclResult HcomGetCommHandleByGroup(const char* groupName, void** commHandle); |
| 43 | -extern "C" HcclResult HcclAllocComResourceByTiling(HcclComm comm, void* stream, void* mc2Tiling, void** commContext); | ||
| 44 | 45 | ||
| 45 | static constexpr int32_t BENCHMARK_ITERATIONS = 20; | 46 | static constexpr int32_t BENCHMARK_ITERATIONS = 20; |
| 46 | static constexpr int64_t MAX_RANK_NUM = 64; | 47 | static constexpr int64_t MAX_RANK_NUM = 64; |
| @@ -114,21 +115,10 @@ void ParseArgs(int argc, char* argv[], int* m, int* k, int* n, int* rankNum, std | |||
| 114 | } | 115 | } |
| 115 | } | 116 | } |
| 116 | 117 | ||
| 117 | -struct UbmemHostTilingData { | 118 | +int CreateTilingDataAndContext(const char* hcomName, int m, int k, int n, int rankNum, bool isNz, |
| 118 | - Mc2InitTiling mc2InitTiling; | ||
| 119 | - Mc2CcTiling mc2CcTiling; | ||
| 120 | - QuantMatmulTilingData mmTile; | ||
| 121 | -}; | ||
| 122 | - | ||
| 123 | -int CreateTilingDataAndContext(const char* hcomName, aclrtStream stream, int m, int k, int n, int rankNum, bool isNz, | ||
| 124 | void** deviceTilingAddr, void** deviceContextAddr, uint32_t* usedCoreNum) | 119 | void** deviceTilingAddr, void** deviceContextAddr, uint32_t* usedCoreNum) |
| 125 | { | 120 | { |
| 126 | - UbmemHostTilingData* tilingData = new UbmemHostTilingData(); | 121 | + QuantMatmulTilingData mmTile = {}; |
| 127 | - if (tilingData == nullptr) { | ||
| 128 | - ERROR_LOG("tilingData alloc failed"); | ||
| 129 | - return -1; | ||
| 130 | - } | ||
| 131 | - *tilingData = {}; | ||
| 132 | 122 | ||
| 133 | uint64_t totalM = static_cast<uint64_t>(m) * static_cast<uint64_t>(rankNum); | 123 | uint64_t totalM = static_cast<uint64_t>(m) * static_cast<uint64_t>(rankNum); |
| 134 | QuantMatmulTilingSwat<mm::DataType::DT_FLOAT8_E4M3FN, mm::DataType::DT_FLOAT8_E4M3FN, mm::BiasDataType::DT_FLOAT> | 124 | QuantMatmulTilingSwat<mm::DataType::DT_FLOAT8_E4M3FN, mm::DataType::DT_FLOAT8_E4M3FN, mm::BiasDataType::DT_FLOAT> |
| @@ -136,49 +126,32 @@ int CreateTilingDataAndContext(const char* hcomName, aclrtStream stream, int m, | |||
| 136 | tilingEngine.SetOptimizeEnable(false); | 126 | tilingEngine.SetOptimizeEnable(false); |
| 137 | tilingEngine.SetMTailAlignEnable(true); | 127 | tilingEngine.SetMTailAlignEnable(true); |
| 138 | bool transB = !isNz; | 128 | bool transB = !isNz; |
| 139 | - tilingEngine.GetTilingData(totalM, static_cast<uint64_t>(n), static_cast<uint64_t>(k), false, transB, | 129 | + tilingEngine.GetTilingData(totalM, static_cast<uint64_t>(n), static_cast<uint64_t>(k), false, transB, mmTile); |
| 140 | - tilingData->mmTile); | ||
| 141 | 130 | ||
| 142 | - *usedCoreNum = tilingData->mmTile.usedCoreNum; | 131 | + *usedCoreNum = mmTile.usedCoreNum; |
| 143 | INFO_LOG("Tiling: M=%d, K=%d, N=%d, rankNum=%d, isNz=%d, transB=%d, usedCoreNum=%u", m, k, n, rankNum, isNz, transB, | 132 | INFO_LOG("Tiling: M=%d, K=%d, N=%d, rankNum=%d, isNz=%d, transB=%d, usedCoreNum=%u", m, k, n, rankNum, isNz, transB, |
| 144 | *usedCoreNum); | 133 | *usedCoreNum); |
| 145 | 134 | ||
| 146 | - AscendC::Mc2CcTilingConfig mc2CcTilingConfig(hcomName, 6, "AlltoAll=level0:fullmesh;level1:pairwise"); | 135 | + HcclComm commHandle; |
| 147 | - mc2CcTilingConfig.SetCommEngine(3); | 136 | + int ret = HcomGetCommHandleByGroup(hcomName, reinterpret_cast<void**>(&commHandle)); |
| 148 | - int ret = mc2CcTilingConfig.GetTiling(tilingData->mc2InitTiling); | 137 | + CHECK_RET(ret == ACL_SUCCESS, ERROR_LOG("HcomGetCommHandleByGroup failed. ret = %d", ret); return ret); |
| 149 | - CHECK_RET(ret == ACL_SUCCESS, ERROR_LOG("GetTiling mc2InitTiling failed. ret = %d", ret); delete tilingData; | 138 | + |
| 150 | - return ret); | 139 | + // 与 torch-ext 一致:CommChannelBuilder<UBMEM>::CreateDeviceContext 按 tag 幂等复用 engine ctx, |
| 151 | - ret = mc2CcTilingConfig.GetTiling(tilingData->mc2CcTiling); | 140 | + // 建链时清零内置 buffer 并填充 rankId/rankSize/commBufferAddrs[] |
| 152 | - CHECK_RET(ret == ACL_SUCCESS, ERROR_LOG("GetTiling mc2CcTiling failed. ret = %d", ret); delete tilingData; | 141 | + CommChannelBuilder<ChannelMode::UBMEM> builder(commHandle); |
| 153 | - return ret); | 142 | + Apace::AivComm::CommUbmemContext hostContext = {}; |
| 143 | + void* ubmemContext = | ||
| 144 | + builder.CreateDeviceContext(&hostContext, sizeof(hostContext), "apace_agm_ubmem", &hostContext); | ||
| 145 | + CHECK_RET(ubmemContext != nullptr, ERROR_LOG("CreateDeviceContext failed"); return -1); | ||
| 154 | 146 | ||
| 155 | int mmTileSize = sizeof(QuantMatmulTilingData); | 147 | int mmTileSize = sizeof(QuantMatmulTilingData); |
| 156 | ret = aclrtMalloc(deviceTilingAddr, mmTileSize, ACL_MEM_MALLOC_HUGE_FIRST); | 148 | ret = aclrtMalloc(deviceTilingAddr, mmTileSize, ACL_MEM_MALLOC_HUGE_FIRST); |
| 157 | - CHECK_RET(ret == ACL_SUCCESS, ERROR_LOG("aclrtMalloc TilingData failed. ret = %d", ret); delete tilingData; | 149 | + CHECK_RET(ret == ACL_SUCCESS, ERROR_LOG("aclrtMalloc TilingData failed. ret = %d", ret); return ret); |
| 158 | - return ret); | 150 | + ret = aclrtMemcpy(*deviceTilingAddr, mmTileSize, &mmTile, mmTileSize, ACL_MEMCPY_HOST_TO_DEVICE); |
| 159 | - ret = aclrtMemcpy(*deviceTilingAddr, mmTileSize, &tilingData->mmTile, mmTileSize, ACL_MEMCPY_HOST_TO_DEVICE); | ||
| 160 | CHECK_RET(ret == ACL_SUCCESS, ERROR_LOG("aclrtMemcpy TilingData failed. ret = %d", ret); | 151 | CHECK_RET(ret == ACL_SUCCESS, ERROR_LOG("aclrtMemcpy TilingData failed. ret = %d", ret); |
| 161 | - aclrtFree(*deviceTilingAddr); *deviceTilingAddr = nullptr; delete tilingData; return ret); | 152 | + aclrtFree(*deviceTilingAddr); *deviceTilingAddr = nullptr; return ret); |
| 162 | 153 | ||
| 163 | - HcclComm commHandle; | 154 | + *deviceContextAddr = ubmemContext; |
| 164 | - ret = HcomGetCommHandleByGroup(hcomName, reinterpret_cast<void**>(&commHandle)); | ||
| 165 | - CHECK_RET(ret == ACL_SUCCESS, ERROR_LOG("HcomGetCommHandleByGroup failed. ret = %d", ret); | ||
| 166 | - aclrtFree(*deviceTilingAddr); *deviceTilingAddr = nullptr; delete tilingData; return ret); | ||
| 167 | - | ||
| 168 | - void* mc2Context = nullptr; | ||
| 169 | - ret = HcclAllocComResourceByTiling(commHandle, stream, tilingData, &mc2Context); | ||
| 170 | - CHECK_RET(ret == ACL_SUCCESS, ERROR_LOG("HcclAllocComResourceByTiling failed. ret = %d", ret); | ||
| 171 | - aclrtFree(*deviceTilingAddr); *deviceTilingAddr = nullptr; delete tilingData; return ret); | ||
| 172 | - if (mc2Context == nullptr) { | ||
| 173 | - ERROR_LOG("mc2Context is nullptr"); | ||
| 174 | - aclrtFree(*deviceTilingAddr); | ||
| 175 | - *deviceTilingAddr = nullptr; | ||
| 176 | - delete tilingData; | ||
| 177 | - return -1; | ||
| 178 | - } | ||
| 179 | - *deviceContextAddr = mc2Context; | ||
| 180 | - | ||
| 181 | - delete tilingData; | ||
| 182 | return ACL_SUCCESS; | 155 | return ACL_SUCCESS; |
| 183 | } | 156 | } |
| 184 | 157 | ||
| @@ -208,8 +181,8 @@ int LaunchOneThread(Args& args) | |||
| 208 | void* tilingAddr = nullptr; | 181 | void* tilingAddr = nullptr; |
| 209 | void* mc2ContextAddr = nullptr; | 182 | void* mc2ContextAddr = nullptr; |
| 210 | uint32_t usedCoreNum = 0; | 183 | uint32_t usedCoreNum = 0; |
| 211 | - ret = CreateTilingDataAndContext(hcomName, args.stream, args.m, args.k, args.n, args.rankDim, args.isNz, | 184 | + ret = CreateTilingDataAndContext(hcomName, args.m, args.k, args.n, args.rankDim, args.isNz, &tilingAddr, |
| 212 | - &tilingAddr, &mc2ContextAddr, &usedCoreNum); | 185 | + &mc2ContextAddr, &usedCoreNum); |
| 213 | CHECK_RET(ret == ACL_SUCCESS, ERROR_LOG("CreateTilingDataAndContext failed. ret = %d", ret); return ret); | 186 | CHECK_RET(ret == ACL_SUCCESS, ERROR_LOG("CreateTilingDataAndContext failed. ret = %d", ret); return ret); |
| 214 | 187 | ||
| 215 | uint64_t m = args.m, k = args.k, n = args.n, rankNum = args.rankDim; | 188 | uint64_t m = args.m, k = args.k, n = args.n, rankNum = args.rankDim; |


【一般】experimental 这套 op_host/op_tiling 相对 mc2 版本改了不少逻辑(NZ 4D 尺寸推导、非转置 B 的 scale 布局、comm_mode=ubmem 拦截),但整个目录没带 tests/ut,mc2 版本是有 infershape/tiling/aclnn 一整套 UT 的。新增的 NZ 分块校验、非转置 scale 布局这些分支建议把对应用例补齐再合。