Merged
wqbmm A16W8 切blaze #353
renzetaoAdd on Sep 10
wqbmm A16W8 切blaze #353
Merged
Total: 33 files changed+3349-2
| @@ -19,6 +19,7 @@ | |||
| 19 | | [block_mmad_qbmm_mx_l0c_pingpong](./block_mmad_qbmm_mx_l0c_pingpong.md) | MX 量化矩阵乘 L0C PingPong Block,支持 N 方向拆分、Scale 复用和 SplitK 写回控制 | | 19 | | [block_mmad_qbmm_mx_l0c_pingpong](./block_mmad_qbmm_mx_l0c_pingpong.md) | MX 量化矩阵乘 L0C PingPong Block,支持 N 方向拆分、Scale 复用和 SplitK 写回控制 | |
| 20 | | [block_mmad_matmul_streamk](./block_mmad_matmul_streamk.md) | StreamK 矩阵乘 Block,支持 workspace 输出、K 轴切分 | | 20 | | [block_mmad_matmul_streamk](./block_mmad_matmul_streamk.md) | StreamK 矩阵乘 Block,支持 workspace 输出、K 轴切分 | |
| 21 | | [block_mmad_weight_prologue_mx](./block_mmad_weight_prologue_mx.md) | AIV 已写入 B/Bias L1 后的 MX AIC BlockMmad | | 21 | | [block_mmad_weight_prologue_mx](./block_mmad_weight_prologue_mx.md) | AIV 已写入 B/Bias L1 后的 MX AIC BlockMmad | |
| 22 | +| [block_mmad_wqmm_mix_weight_prologue](./block_mmad_wqmm_mix_weight_prologue.md) | 权重反量化矩阵乘的 AIC 计算、L1 空间划分及缓冲同步 | | ||
| 22 | 23 | ||
| 23 | ### BlockScheduler(任务调度) | 24 | ### BlockScheduler(任务调度) |
| 24 | | 组件名 | 描述 | | 25 | | 组件名 | 描述 | |
| @@ -26,6 +27,7 @@ | |||
| 26 | | [block_scheduler](./block_scheduler.md) | 公共框架:tile 切分、Z 型扫描、尾块处理 | | 27 | | [block_scheduler](./block_scheduler.md) | 公共框架:tile 切分、Z 型扫描、尾块处理 | |
| 27 | | [block_scheduler_matmul_basic](./block_scheduler_matmul_basic.md) | Basic 调度器:尾块切分、SplitK 切分、L2Cache 配置 | | 28 | | [block_scheduler_matmul_basic](./block_scheduler_matmul_basic.md) | Basic 调度器:尾块切分、SplitK 切分、L2Cache 配置 | |
| 28 | | [block_scheduler_matmul_streamk](./block_scheduler_matmul_streamk.md) | StreamK 调度器:DP+SK 混合策略、K 轴切分 | | 29 | | [block_scheduler_matmul_streamk](./block_scheduler_matmul_streamk.md) | StreamK 调度器:DP+SK 混合策略、K 轴切分 | |
| 30 | +| [block_scheduler_wqmm](./block_scheduler_wqmm.md) | WQMM 的 M/N 分核与三段 N 区间调度,提供分块坐标和有效长度 | | ||
| 29 | | [block_scheduler_qbmm_mx](./block_scheduler_qbmm_mx.md) | QBMM 调度器:Batch 维度切分、量化对齐 | | 31 | | [block_scheduler_qbmm_mx](./block_scheduler_qbmm_mx.md) | QBMM 调度器:Batch 维度切分、量化对齐 | |
| 30 | | [block_scheduler_gmm_swat_with_tail_split](./block_scheduler_gmm_swat_with_tail_split.md) | QGMM 调度器:group 间连续分核、SWAT 扫描、末组 tail split | | 32 | | [block_scheduler_gmm_swat_with_tail_split](./block_scheduler_gmm_swat_with_tail_split.md) | QGMM 调度器:group 间连续分核、SWAT 扫描、末组 tail split | |
| 31 | | [block_scheduler_matmul_swat_with_tail_split](./block_scheduler_matmul_swat_with_tail_split.md) | 通用 M/N SWAT 扫描、尾块合并和 compact tail split | | 33 | | [block_scheduler_matmul_swat_with_tail_split](./block_scheduler_matmul_swat_with_tail_split.md) | 通用 M/N SWAT 扫描、尾块合并和 compact tail split | |
| @@ -0,0 +1,208 @@ | |||
| 1 | +# Block Mmad WQMM Mix Weight Prologue | ||
| 2 | + | ||
| 3 | +> [代码位置](../../../../include/blaze/gemm/block/block_mmad_wqmm_mix_weight_prologue.h) | ||
| 4 | + | ||
| 5 | +## 功能说明 | ||
| 6 | + | ||
| 7 | +该组件是 `BlockMmad<MatmulWithWeightAntiquant<...>, ...>` 的偏特化,负责 AIC 侧的权重反量化矩阵乘。 | ||
| 8 | +AIV Prologue 将量化权重 `weight` 转换为输入 `x` 的类型并写入共享 L1;BlockMmad 装载 `x` 和可选的 | ||
| 9 | +`bias`,执行矩阵乘并通过 Fixpipe 将输出 `y` 写回 GM。 | ||
| 10 | + | ||
| 11 | +每次调用处理一个 M/N 分块,内部完成完整 K 轴的 FP32 累加。计算接口不接收 weight Tensor, | ||
| 12 | +而是等待 Prologue 提供对应的 L1 权重分块,并在读取完成后通知 AIV 可以复用缓冲区。 | ||
| 13 | + | ||
| 14 | +## 使用限制 | ||
| 15 | + | ||
| 16 | +- 面向 Ascend 950 / DAV_3510,仅支持 `MatmulWithWeightAntiquant` 调度策略。 | ||
| 17 | +- 矩阵乘计算由 AIC 执行;AIV 可初始化组件并查询共享权重缓冲区地址。 | ||
| 18 | +- 输入 `x` 和输出 `y` 的类型支持 FP16、BF16;量化权重支持 INT8、FP8 E4M3、HiFloat8。 | ||
| 19 | + 反量化参数类型必须与 `x` 相同。配套 Kernel 的类型组合及布局限制见 | ||
| 20 | + [Kernel 支持范围](../kernel/kernel_wqmm_mix_antiquant.md#支持范围)。 | ||
| 21 | +- 必须配合 AIV Prologue 使用,双方按相同的 M/N 分块顺序及 K 分块配置处理数据。 | ||
| 22 | + 缺少对应的权重就绪信号时,AIC 无法完成计算。 | ||
| 23 | +- 输出写回 GM。分块配置须满足 L1、L0 和偏置缓冲区的容量及对齐要求;尾块计算使用真实有效长度。 | ||
| 24 | + | ||
| 25 | +数学上的权重为 `(K,N)`,而模板参数 `LayoutB` 的坐标约定为 `(N,K)`。 | ||
| 26 | +`nd_ext_layout_ptn` 对应 GM `(N,K)` 存储及 L1 ZN 布局; | ||
| 27 | +`dn_ext_layout_ptn` 对应 GM `(K,N)` 存储及 L1 NZ 布局。L1 布局均按 `(K,N)` 描述。 | ||
| 28 | + | ||
| 29 | +## 外部接口 | ||
| 30 | + | ||
| 31 | +### Params | ||
| 32 | + | ||
| 33 | +```cpp | ||
| 34 | +using L1TileShape = asc::te::shape<int64_t, int64_t, int64_t, int64_t>; | ||
| 35 | +using L0TileShape = asc::te::shape<int64_t, int64_t, int64_t>; | ||
| 36 | + | ||
| 37 | +struct Params { | ||
| 38 | + GM_ADDR aGmAddr{nullptr}; | ||
| 39 | + GM_ADDR cGmAddr{nullptr}; | ||
| 40 | + GM_ADDR biasGmAddr{nullptr}; | ||
| 41 | + L1TileShape l1TileShape; | ||
| 42 | + L0TileShape l0TileShape; | ||
| 43 | + bool hasBias{false}; | ||
| 44 | + uint64_t kSize{0}; | ||
| 45 | +}; | ||
| 46 | +``` | ||
| 47 | + | ||
| 48 | +| 成员 | 含义 | | ||
| 49 | +| --- | --- | | ||
| 50 | +| `aGmAddr` | 输入 `x` 的 GM 起始地址,由配套 Kernel 用于构造 `(M,K)` Tensor | | ||
| 51 | +| `cGmAddr` | 输出 `y` 的 GM 起始地址,由配套 Kernel 用于构造 `(M,N)` Tensor | | ||
| 52 | +| `biasGmAddr` | 可选 `bias` 的 GM 起始地址,由配套 Kernel 用于构造 `(1,N)` Tensor;未启用时可为 `nullptr` | | ||
| 53 | +| `l1TileShape` | `(baseM,baseN,KaL1,KbL1)`,后两项分别为输入和权重的 L1 K 分块配置,单位为元素 | | ||
| 54 | +| `l0TileShape` | `(baseM,baseN,baseK)`,L0 分块配置,单位为元素 | | ||
| 55 | +| `hasBias` | 是否读取并叠加 `bias`,默认 `false` | | ||
| 56 | +| `kSize` | 完整 K 轴长度,单位为元素;调用前须设置为实际长度 | | ||
| 57 | + | ||
| 58 | +BlockMmad 本身不读取上述三个 GM 地址字段,实际搬运地址来自 `operator()` 传入的 Tensor。 | ||
| 59 | +通过配套 Kernel 调用时,由 Kernel 读取这些字段并构造、切分 Tensor。 | ||
| 60 | +`KaL1` 与 `KbL1` 的大小关系决定输入装载方式,见[输入装载方式](#输入装载方式)。 | ||
| 61 | + | ||
| 62 | +### 构造函数和析构函数 | ||
| 63 | + | ||
| 64 | +```cpp | ||
| 65 | +__aicore__ inline BlockMmad(); | ||
| 66 | +__aicore__ inline ~BlockMmad(); | ||
| 67 | +``` | ||
| 68 | + | ||
| 69 | +默认构造后,由 Kernel 调用 `Init` 完成初始化;析构函数在 AIC 上关闭矩阵布局转换。 | ||
| 70 | + | ||
| 71 | +### Init | ||
| 72 | + | ||
| 73 | +```cpp | ||
| 74 | +__aicore__ inline void Init(const Params& params); | ||
| 75 | +``` | ||
| 76 | + | ||
| 77 | +根据 `params` 配置片上缓冲区,在 AIC 上启用矩阵布局转换。 | ||
| 78 | +Kernel 在 AIC/AIV 分支之前调用一次,完成后才能调用 `GetShareMemPtr` 或 `operator()`。 | ||
| 79 | + | ||
| 80 | +### GetShareMemPtr | ||
| 81 | + | ||
| 82 | +```cpp | ||
| 83 | +template <typename MemoryLocation, typename DType> | ||
| 84 | +__aicore__ inline auto GetShareMemPtr(uint32_t bufferId) const; | ||
| 85 | +``` | ||
| 86 | + | ||
| 87 | +返回指定共享权重缓冲区的类型化内存指针,供 AIV Prologue 构造 L1 Tensor。 | ||
| 88 | + | ||
| 89 | +| 参数 | 约束 | | ||
| 90 | +| --- | --- | | ||
| 91 | +| `MemoryLocation` | 必须为 `asc::te::location::l1` | | ||
| 92 | +| `DType` | 必须与输入 `x` 的类型 `AType` 一致,即反量化后的权重类型 | | ||
| 93 | +| `bufferId` | 取 0 或 1,指定两份共享权重缓冲区之一 | | ||
| 94 | + | ||
| 95 | +该接口只提供地址,不执行搬运或核间同步。调用方通过配套 Prologue 管理权重写入及缓冲区复用。 | ||
| 96 | + | ||
| 97 | +### operator() | ||
| 98 | + | ||
| 99 | +```cpp | ||
| 100 | +template <class TensorA, class TensorBias, class TensorC, class Shape> | ||
| 101 | +__aicore__ inline void operator()( | ||
| 102 | + const TensorA& tensorA, | ||
| 103 | + const TensorBias& tensorBias, | ||
| 104 | + TensorC& tensorC, | ||
| 105 | + const Shape& actualShape); | ||
| 106 | +``` | ||
| 107 | + | ||
| 108 | +在 AIC 上执行当前 M/N 分块的矩阵乘,遍历完整 K 轴后写回输出。 | ||
| 109 | + | ||
| 110 | +| 参数 | 含义 | | ||
| 111 | +| --- | --- | | ||
| 112 | +| `tensorA` | 当前输入 `x` 的 GM 切片,形状为 `(tileM,K)`,包含完整 K 轴 | | ||
| 113 | +| `tensorBias` | 当前 N 分块的 `bias` GM 切片,形状为 `(1,tileN)`;`hasBias=false` 时不读取 | | ||
| 114 | +| `tensorC` | 当前输出 `y` 的 GM 切片,形状为 `(tileM,tileN)` | | ||
| 115 | +| `actualShape` | `(tileM,tileN)`,表示当前分块的真实有效长度,单位为元素 | | ||
| 116 | + | ||
| 117 | +Tensor 的切片范围必须与 `actualShape` 和初始化参数中的 `kSize` 一致。 | ||
| 118 | +未启用偏置时仍需传入符合接口类型要求的 `tensorBias`。 | ||
| 119 | + | ||
| 120 | +## 调用流程 | ||
| 121 | + | ||
| 122 | +1. 配置 `Params`,在 AIC/AIV 分支之前默认构造 BlockMmad 并调用 `Init`。 | ||
| 123 | +2. AIV 通过 `GetShareMemPtr` 获取共享 L1 地址,由 Prologue 搬运并反量化当前分块的权重。 | ||
| 124 | +3. AIC 根据 Scheduler 的结果准备 `x`、`bias`、`y` 的 GM 切片,调用 `operator()`。 | ||
| 125 | +4. BlockMmad 装载输入和偏置,逐个 K 分块等待权重就绪,将数据搬入 L0 并执行 MMAD。 | ||
| 126 | + 对应权重读取完成后,通知 AIV 可以复用缓冲区。 | ||
| 127 | +5. 完成当前 M/N 分块的 K 轴累加后,通过 Fixpipe 写回 `y`。 | ||
| 128 | + | ||
| 129 | +AIC 和 AIV 并行执行,通过核间信号协调上述数据读写。输入预取由 Kernel 负责。 | ||
| 130 | +以下为 Kernel 内的调用片段,`params`、GM Tensor 和分块坐标均由 Kernel 准备。 | ||
| 131 | + | ||
| 132 | +初始化组件并构造共享地址提供者: | ||
| 133 | + | ||
| 134 | +```cpp | ||
| 135 | +BlockMmad blockMmad; | ||
| 136 | +blockMmad.Init(params.mmadParams); | ||
| 137 | +auto getSharedWeightMem = [&blockMmad](uint32_t bufferId) __aicore__ { | ||
| 138 | + return blockMmad.template GetShareMemPtr<asc::te::location::l1, AType>(bufferId); | ||
| 139 | +}; | ||
| 140 | +``` | ||
| 141 | + | ||
| 142 | +Kernel 将 `getSharedWeightMem` 传给 AIV Prologue。在 AIC 侧,每个 M/N 分块执行: | ||
| 143 | + | ||
| 144 | +```cpp | ||
| 145 | +auto blockX = gmX.slice( | ||
| 146 | + asc::te::make_coord(coordM, 0UL), asc::te::make_shape(tileM, kSize)); | ||
| 147 | +auto blockBias = gmBias.slice( | ||
| 148 | + asc::te::make_coord(0UL, params.mmadParams.hasBias ? coordN : 0UL), | ||
| 149 | + asc::te::make_shape(1UL, tileN)); | ||
| 150 | +auto blockY = gmY.slice( | ||
| 151 | + asc::te::make_coord(coordM, coordN), asc::te::make_shape(tileM, tileN)); | ||
| 152 | +blockMmad(blockX, blockBias, blockY, asc::te::make_shape(tileM, tileN)); | ||
| 153 | +``` | ||
| 154 | + | ||
| 155 | +以上片段依赖配套 AIV Prologue,完整组件组装和参数准备见 | ||
| 156 | +[Kernel 调用示例](../kernel/kernel_wqmm_mix_antiquant.md#调用示例)。 | ||
| 157 | + | ||
| 158 | +## L1 空间划分 | ||
| 159 | + | ||
| 160 | +缓冲区是为分块数据预留的片上空间。以下地址和容量均以**字节**计: | ||
| 161 | + | ||
| 162 | +- `l1Bytes`:L1 总容量。 | ||
| 163 | +- `weightBytes = baseN*KbL1*sizeof(AType)`:每份反量化权重容量,`AType` 为输入 `x` 的类型。 | ||
| 164 | +- `biasBytes = hasBias ? 4096 : 0`:每份 `bias` 预留容量。 | ||
| 165 | + | ||
| 166 | +| 区域 | 地址范围,左闭右开 | | ||
| 167 | +| --- | --- | | ||
| 168 | +| 权重缓冲区 0 | `[0, weightBytes)` | | ||
| 169 | +| `bias` 缓冲区 0 | `[weightBytes, weightBytes+biasBytes)` | | ||
| 170 | +| 输入 `x` 缓冲区 0 | `[weightBytes+biasBytes, l1Bytes/2)` | | ||
| 171 | +| 输入 `x` 缓冲区 1 | `[l1Bytes/2, l1Bytes-weightBytes-biasBytes)` | | ||
| 172 | +| `bias` 缓冲区 1 | `[l1Bytes-weightBytes-biasBytes, l1Bytes-weightBytes)` | | ||
| 173 | +| 权重缓冲区 1 | `[l1Bytes-weightBytes, l1Bytes)` | | ||
| 174 | + | ||
| 175 | +每份 `x` 缓冲区容量为 `xHalfBytes = l1Bytes/2-weightBytes-biasBytes`, | ||
| 176 | +两份相邻缓冲区的总容量为 `2*xHalfBytes`。调用方须保证容量为正且足以容纳所选布局。 | ||
| 177 | +未启用 `bias` 时,其预留区域为空;启用时实际搬入 `tileN*sizeof(BiasType)` 字节,不能超过 4096 字节。 | ||
| 178 | + | ||
| 179 | +权重缓冲区基址由配置的 `baseN` 和 `KbL1` 决定,尾块不能改变其基址。 | ||
| 180 | +布局填充指为满足对齐而占用的额外元素;检查容量时需包含这些元素,不能只比较逻辑有效长度。 | ||
| 181 | + | ||
| 182 | +## 输入装载方式 | ||
| 183 | + | ||
| 184 | +| 方式 | 选择条件与存储内容 | | ||
| 185 | +| --- | --- | | ||
| 186 | +| 普通双缓冲 | `KaL1 <= KbL1`。逐 K 分块装载 `x`,交替使用两份缓冲区。 | | ||
| 187 | +| 奇偶分散全载 | `KaL1 > KbL1`,输入不转置,`K % KbL1 == 0`,且较多的一半 K 分块能放入一份 `x` 缓冲区。当前 M 分块的全部输入按 K 分块交替存入两份缓冲区。 | | ||
| 188 | +| 连续全载 | `KaL1 > KbL1` 且不满足奇偶分散条件。将完整 `(tileM,K)` 输入以 NZ 布局存入相邻的两份 `x` 缓冲区,再按 K 切片读取。 | | ||
| 189 | + | ||
| 190 | +奇偶分散方式的容量条件为 | ||
| 191 | +`ceil((K/KbL1)/2)*KbL1*AlignUp(tileM,16)*sizeof(AType) <= xHalfBytes`。 | ||
| 192 | + | ||
| 193 | +连续全载要求完整 NZ 布局的物理大小不超过 `2*xHalfBytes`。 | ||
| 194 | +每次处理 M/N 分块时按真实 `tileM` 构造布局;尾块的搬运包含对齐填充,MMAD 使用真实有效 K 长度。 | ||
| 195 | + | ||
| 196 | +## 缓冲与同步 | ||
| 197 | + | ||
| 198 | +`BufferSlot` 管理片上缓冲区地址及本地流水同步。普通双缓冲按 K 分块保护输入的读写; | ||
| 199 | +全载方式同时保护两份输入缓冲区,直到当前 M/N 分块的全部 L0 读取结束。 | ||
| 200 | +L0、偏置转换缓冲区和累加缓冲区使用各自的同步作用域。 | ||
| 201 | + | ||
| 202 | +AIC/AIV 通过 `MatmulWithWeightAntiquant::SyncProtocol` 协调共享权重缓冲区: | ||
| 203 | + | ||
| 204 | +1. 两份权重缓冲区初始空闲,AIV 写入后发送就绪信号。 | ||
| 205 | +2. AIC 等待对应信号,将权重搬入 L0 后通知 AIV 该缓冲区可以复用。 | ||
| 206 | +3. AIV 复用缓冲区前等待空闲信号,结束时等待最后写入的权重被读取。 | ||
| 207 | + | ||
| 208 | +两个 AIV 使用各自的核间同步标志。输入 `x` 的装载方式不改变每个 K 分块所需的权重同步次数。 | ||
| @@ -0,0 +1,73 @@ | |||
| 1 | +# BlockSchedulerWqmmTailResplit | ||
| 2 | + | ||
| 3 | +> [代码位置](../../../../include/blaze/gemm/block/block_scheduler_wqmm.h) | ||
| 4 | + | ||
| 5 | +## 功能说明 | ||
| 6 | + | ||
| 7 | +该调度器将矩阵乘的 M/N 区域分配给 AIC 及其对应的两个 AIV。 | ||
| 8 | +Host 提供 N 轴主块和两段尾块的数量、长度,调度器据此计算各核的分块坐标和有效长度。 | ||
| 9 | +分块指一次处理的矩阵子区域;尾块是轴末端不足主块大小的区域,可进一步分为两段以分配给不同核。 | ||
| 10 | +K 轴遍历由 Kernel 和 BlockMmad 负责。 | ||
| 11 | + | ||
| 12 | +## 模板与参数 | ||
| 13 | + | ||
| 14 | +模板参数 `ProblemShape_` 表达 `(M,N,K)`,分别对应输入 `x` 的行数、权重 `weight` 的输出通道数及归约长度。 | ||
| 15 | + | ||
| 16 | +| `Params` 成员 | 类型 | 含义 | | ||
| 17 | +| --- | --- | --- | | ||
| 18 | +| `mL1Tile` | `int64_t` | 每次处理的最大 M 长度,单位为元素 | | ||
| 19 | +| `mainBlockCount`、`mainBlockSize` | `uint64_t` | N0 主块数量、每块 N 长度 | | ||
| 20 | +| `firstTailBlockCount`、`firstTailBlockSize` | `uint64_t` | N1 尾块数量、每块 N 长度 | | ||
| 21 | +| `secondTailBlockCount`、`secondTailBlockSize` | `uint64_t` | N2 尾块数量、每块 N 长度 | | ||
| 22 | +| `cubeNumBlocksM`、`cubeNumBlocksN` | `uint64_t` | M/N 方向的 AIC 分核数 | | ||
| 23 | + | ||
| 24 | +各 N 长度以元素计。调用方须保证 M/N、`mL1Tile` 和分核数为正, | ||
| 25 | +三个 N 区间的 `count*size` 之和等于 N,非空区间的分块长度为正。 | ||
| 26 | +主块和尾块的配置均须满足所用 Kernel 的片上缓冲区容量要求。 | ||
| 27 | +`Params` 成员默认值均为 0,使用前需要设置合法的分块配置。 | ||
| 28 | + | ||
| 29 | +## 公开接口 | ||
| 30 | + | ||
| 31 | +| 方法 | 含义及返回值 | | ||
| 32 | +| --- | --- | | ||
| 33 | +| 构造函数 `(const ProblemShape_& problemShape, const Params& params)` | 根据当前核号初始化负责的区间 | | ||
| 34 | +| `GetCoreNums()` | AIC 数量,即 `cubeNumBlocksM*cubeNumBlocksN` | | ||
| 35 | +| `GetBlockNums()` | 当前核的 `(M,N0,N1,N2)` 分块数量;可用 `auto` 接收 | | ||
| 36 | +| `GetBlockCoordM(mIdx)` | M 起始坐标,类型为 `uint64_t` | | ||
| 37 | +| `GetBlockShapeM(coordM)` | M 有效长度,类型为 `uint64_t` | | ||
| 38 | +| `GetBlockCoordN<N_RANGE>(nIdx)` | N 起始坐标,类型为 `uint64_t` | | ||
| 39 | +| `GetBlockShapeN<N_RANGE>(coordN)` | N 有效长度,类型为 `uint64_t` | | ||
| 40 | + | ||
| 41 | +坐标和长度均以元素计。`N_RANGE=0/1/2` 分别表示 N0、N1、N2。 | ||
| 42 | +坐标接口接收当前核内的分块序号;长度接口接收该轴的标量坐标,返回值裁剪到对应区间的边界。 | ||
| 43 | +Kernel 根据这些标量构造 Tensor 切片所需的 Shape/Coord。 | ||
| 44 | + | ||
| 45 | +## 分配规则 | ||
| 46 | + | ||
| 47 | +M 轴先按 `ceil(M/cubeNumBlocksM)` 划分核间区间,每个核再以 `mL1Tile` 为步长遍历自己的区间。 | ||
| 48 | +N0、N1、N2 在 N 轴上顺次相接:N0 起点为 0,后一区间起点为前一区间终点。 | ||
| 49 | + | ||
| 50 | +N0 和 N1 都从 N 方向的第 0 个核开始轮转分配;N2 从 N1 最后分配位置的下一核接续。 | ||
| 51 | +设当前 N 方向核号为 `nDimIdx`,其第一个 N2 分块序号为: | ||
| 52 | + | ||
| 53 | +```text | ||
| 54 | +(nDimIdx + cubeNumBlocksN - firstTailBlockCount % cubeNumBlocksN) % cubeNumBlocksN | ||
| 55 | +``` | ||
| 56 | + | ||
| 57 | +AIV 将自身核号除以子核数量,得到对应 AIC 的逻辑核号。 | ||
| 58 | +AIC 与 AIV 按 M → N0 → N1 → N2 的相同顺序遍历;每个 M 分块均遍历其负责的全部 N 区间。 | ||
| 59 | + | ||
| 60 | +## 分配示例 | ||
| 61 | + | ||
| 62 | +取 `M=65`、`N=159`,`cubeNumBlocksM=1`、`cubeNumBlocksN=2`、`mL1Tile=32`, | ||
| 63 | +N0 为 2 块、每块 64;N1 为 1 块、长度 15;N2 为 1 块、长度 16。 | ||
| 64 | +两个核的 N 分配如下,区间左闭右开: | ||
| 65 | + | ||
| 66 | +| 区间 | N 方向核 0 | N 方向核 1 | | ||
| 67 | +| --- | --- | --- | | ||
| 68 | +| N0 `[0,128)` | `[0,64)` | `[64,128)` | | ||
| 69 | +| N1 `[128,143)` | `[128,143)` | 无 | | ||
| 70 | +| N2 `[143,159)` | 无 | `[143,159)` | | ||
| 71 | + | ||
| 72 | +两个核都处理 M 起点 0、32、64,对应有效长度 32、32、1。 | ||
| 73 | +每个 M 分块内,核 0 依次处理 N0 和 N1,核 1 依次处理 N0 和 N2。 | ||
| @@ -26,6 +26,7 @@ | |||
| 26 | | [kernel_qbmm_pertensor_streamk](./kernel_qbmm_pertensor_streamk.md) | QBMM per-tensor StreamK Kernel,AIC 输出分块累加结果,AIV 统一归约并反量化 | | 26 | | [kernel_qbmm_pertensor_streamk](./kernel_qbmm_pertensor_streamk.md) | QBMM per-tensor StreamK Kernel,AIC 输出分块累加结果,AIV 统一归约并反量化 | |
| 27 | | [kernel_matmul_mix_weight_prologue](./kernel_matmul_mix_weight_prologue.md) | AIV 权重前处理 + AIC MX MMAD 的 Mix Kernel | | 27 | | [kernel_matmul_mix_weight_prologue](./kernel_matmul_mix_weight_prologue.md) | AIV 权重前处理 + AIC MX MMAD 的 Mix Kernel | |
| 28 | | [kernel_wqgmm_mix_weight_prologue](./kernel_wqgmm_mix_weight_prologue.md) | Grouped MX A8W4 Mix Kernel,支持 E2M1/E1M2、FP16/BF16 输出、可选 Bias 和单/多 Weight | | 28 | | [kernel_wqgmm_mix_weight_prologue](./kernel_wqgmm_mix_weight_prologue.md) | Grouped MX A8W4 Mix Kernel,支持 E2M1/E1M2、FP16/BF16 输出、可选 Bias 和单/多 Weight | |
| 29 | +| [kernel_wqmm_mix_antiquant](./kernel_wqmm_mix_antiquant.md) | 8 位权重反量化矩阵乘:AIV 前处理与 AIC 计算的 `GemmUniversal` 偏特化 | | ||
| 29 | | [kernel_matmul_with_scale_add](./kernel_matmul_with_scale_add.md) | FusedMatMul scale_add Kernel,AIC 矩阵乘 + AIV 缩放相加后处理 | | 30 | | [kernel_matmul_with_scale_add](./kernel_matmul_with_scale_add.md) | FusedMatMul scale_add Kernel,AIC 矩阵乘 + AIV 缩放相加后处理 | |
| 30 | 31 | ||
| 31 | ## 公共框架 | 32 | ## 公共框架 |
| @@ -0,0 +1,162 @@ | |||
| 1 | +# Kernel WQMM Mix Antiquant | ||
| 2 | + | ||
| 3 | +> [代码位置](../../../../include/blaze/gemm/kernel/kernel_wqmm_mix_antiquant.h) | ||
| 4 | + | ||
| 5 | +## 功能说明 | ||
| 6 | + | ||
| 7 | +该组件将量化权重 `weight` 反量化为输入 `x` 的类型,再执行矩阵乘并写回输出 `y`。 | ||
| 8 | +AIV 负责权重搬运和反量化,AIC 负责矩阵乘、可选的 `bias` 加法及输出写回。 | ||
| 9 | + | ||
| 10 | +逻辑矩阵维度为 `x: (M,K)`、`weight: (K,N)`、`y: (M,N)`。 | ||
| 11 | + | ||
| 12 | +计算过程为: | ||
| 13 | + | ||
| 14 | +$$ | ||
| 15 | +\begin{aligned} | ||
| 16 | +\mathrm{weightDequant} | ||
| 17 | +&= \left(\operatorname{cast}_{x}(\mathrm{weight}) | ||
| 18 | + + \mathrm{antiquantOffset}\right)\odot\mathrm{antiquantScale}, \\ | ||
| 19 | +y &= x\,\mathrm{weightDequant} + \mathrm{bias}. | ||
| 20 | +\end{aligned} | ||
| 21 | +$$ | ||
| 22 | + | ||
| 23 | +其中,$\operatorname{cast}_{x}$ 表示转换为 `x` 的类型,$\odot$ 表示逐元素乘法, | ||
| 24 | +反量化参数按下述量化模式广播;`bias` 为可选的 N 元素向量,沿 M 轴广播。 | ||
| 25 | +未启用 `antiquantOffset` 或 `bias` 时省略对应加法。转换、反量化加法和乘法分别按 `x` 的类型舍入, | ||
| 26 | +矩阵乘使用 FP32 累加,结果转换为 `y` 的类型。 | ||
| 27 | + | ||
| 28 | +### per-tensor 量化模式 | ||
| 29 | + | ||
| 30 | +`antiquantScale` 和可选的 `antiquantOffset` 各包含一个元素,整张权重矩阵共用同一组反量化参数。 | ||
| 31 | + | ||
| 32 | +### per-channel 量化模式 | ||
| 33 | + | ||
| 34 | +`antiquantScale` 和可选的 `antiquantOffset` 各包含 N 个元素,每个输出通道使用一组反量化参数, | ||
| 35 | +同一通道的参数沿 K 轴广播。 | ||
| 36 | + | ||
| 37 | +## 支持范围 | ||
| 38 | + | ||
| 39 | +| 项目 | 支持范围 | | ||
| 40 | +| --- | --- | | ||
| 41 | +| 架构 | Ascend 950 / DAV_3510 | | ||
| 42 | +| 输入 `x`、输出 `y` | FP16 或 BF16,类型相同 | | ||
| 43 | +| 权重 `weight` | INT8、FP8 E4M3、HiFloat8 | | ||
| 44 | +| GM 权重存储 | 连续的 `(N,K)` 或 `(K,N)` 数组,见下表 | | ||
| 45 | +| `antiquantScale`、`antiquantOffset` | 类型与 `x` 相同;per-tensor 或 per-channel;偏移可选 | | ||
| 46 | +| `bias` | 形状 `(N,)`,类型为 `x` 类型或 FP32,可选 | | ||
| 47 | +| AIV 配置 | 每个 AIC 对应两个 AIV,输入缓冲区数量为 2 或 4 | | ||
| 48 | + | ||
| 49 | +该特化不支持输入 `x` 转置、INT4、FP4、MX 量化和 GM WeightNZ 格式。 | ||
| 50 | +`ProblemShape` 只描述 `(M,N,K)`,不包含 batch 维度。 | ||
| 51 | + | ||
| 52 | +### 权重的布局方向 | ||
| 53 | + | ||
| 54 | +数学计算中的 `weight` 始终为 `(K,N)`。代码接口 `LayoutB` 以 `(N,K)` 为坐标描述权重, | ||
| 55 | +其布局名称需要与 GM 实际存储顺序区分: | ||
| 56 | + | ||
| 57 | +| `LayoutB` | GM 存储顺序 | 内部 `TRANS_B` | 反量化后的 UB/L1 布局,按 `(K,N)` 描述 | | ||
| 58 | +| --- | --- | --- | --- | | ||
| 59 | +| `nd_ext_layout_ptn` | `(N,K)`,K 连续 | `true` | ZN | | ||
| 60 | +| `dn_ext_layout_ptn` | `(K,N)`,N 连续 | `false` | NZ | | ||
| 61 | + | ||
| 62 | +Kernel 通过 `!IsTrans<LayoutB>::value` 推导方向。N 轴分块起点为 `coordN` 时, | ||
| 63 | +权重地址偏移分别为 `coordN*K` 和 `coordN` 个权重元素;per-channel 的反量化参数偏移为 | ||
| 64 | +`coordN` 个参数元素,per-tensor 参数不随 N 分块偏移。 | ||
| 65 | + | ||
| 66 | +## 模板与参数 | ||
| 67 | + | ||
| 68 | +### Kernel 组装 | ||
| 69 | + | ||
| 70 | +`GemmUniversal<ProblemShape_, BlockMmad_, BlockEpilogue_, BlockScheduler_>` 的该偏特化要求 | ||
| 71 | +`BlockEpilogue_ = void`,且 `BlockMmad_::DispatchPolicy::ScheduleType` 为 | ||
| 72 | +`KernelMmadAPrefetchBAntiquant`。 | ||
| 73 | + | ||
| 74 | +| 模板参数 | 含义 | | ||
| 75 | +| --- | --- | | ||
| 76 | +| `ProblemShape_` | `(M,N,K)` 的 Shape 类型,通常为 `asc::te::shape<int64_t, int64_t, int64_t>` | | ||
| 77 | +| `BlockMmad_` | [WQMM BlockMmad](../block/block_mmad_wqmm_mix_weight_prologue.md),负责 AIC 计算 | | ||
| 78 | +| `BlockEpilogue_` | `void`;输出写回由 BlockMmad 完成 | | ||
| 79 | +| `BlockScheduler_` | [WQMM Scheduler](../block/block_scheduler_wqmm.md),提供 M/N 分块 | | ||
| 80 | + | ||
| 81 | +调度策略为 `MatmulWithWeightAntiquant<AivNum_, UbMte2InnerSize_, UbMte2BufNum_, AntiquantType_, HasAntiquantOffset_>`: | ||
| 82 | + | ||
| 83 | +| 参数 | 含义及取值 | | ||
| 84 | +| --- | --- | | ||
| 85 | +| `AivNum_` | 每个 AIC 对应的 AIV 数量,取 2 | | ||
| 86 | +| `UbMte2InnerSize_` | 权重输入 UB 行距,单位为字节;默认 512 | | ||
| 87 | +| `UbMte2BufNum_` | 输入缓冲区数量,取 2 或 4,默认 2 | | ||
| 88 | +| `AntiquantType_` | `QuantMode::PERCHANNEL_MODE` 或 `QuantMode::PERTENSOR_MODE` | | ||
| 89 | +| `HasAntiquantOffset_` | 是否使用 `antiquantOffset`,默认 `false` | | ||
| 90 | + | ||
| 91 | +### Kernel Params | ||
| 92 | + | ||
| 93 | +公开调用接口为 `__aicore__ inline void operator()(const Params& params) const`。 | ||
| 94 | + | ||
| 95 | +| `Params` 成员 | 类型 | 含义 | | ||
| 96 | +| --- | --- | --- | | ||
| 97 | +| `problemShape` | `ProblemShape` | `(M,N,K)`,各轴长度以元素计 | | ||
| 98 | +| `mmadParams` | `BlockMmadParams` | `x`、`y`、`bias` 地址和 L1/L0 分块配置,详见 BlockMmad 文档 | | ||
| 99 | +| `aPreloadSize` | `uint64_t` | 每核预取的 `x` 元素数,0 表示关闭 | | ||
| 100 | +| `aElementCount` | `uint64_t` | `x` 的总元素数,用于限制预取范围 | | ||
| 101 | +| `prologueParams` | `PrologueParams` | 权重及反量化参数地址,见下表 | | ||
| 102 | +| `schedulerParams` | `BlockSchedulerParams` | M/N 分核及三段 N 区间配置 | | ||
| 103 | + | ||
| 104 | +公开结构 `PrologueParams`: | ||
| 105 | + | ||
| 106 | +| 成员 | 类型 | 含义 | | ||
| 107 | +| --- | --- | --- | | ||
| 108 | +| `bGmAddr` | `GM_ADDR` | 量化权重起始地址,共 `K*N` 个 1 字节元素 | | ||
| 109 | +| `scaleGmAddr` | `GM_ADDR` | `antiquantScale`;per-tensor 为 1 个元素,per-channel 为 N 个元素 | | ||
| 110 | +| `offsetGmAddr` | `GM_ADDR` | 可选 `antiquantOffset`,形状及类型与 `antiquantScale` 相同;未启用时可为 `nullptr` | | ||
| 111 | +| `weightL2Cacheable` | `uint32_t` | 非零使用 `NORMAL_FIRST_VICTIM`,0 使用 `NOTALLOC_KEEP` 缓存模式 | | ||
| 112 | + | ||
| 113 | +### AIV Prologue | ||
| 114 | + | ||
| 115 | +`KernelWqmmMixAntiquantPrologue` 封装权重前处理。其模板参数指定输入与权重类型、UB 行距与缓冲区数量、 | ||
| 116 | +权重方向、反量化模式、同步协议和共享 L1 地址提供者。`AntiquantScaleType_` 必须与 `XType_` 相同。 | ||
| 117 | + | ||
| 118 | +其 `Params` 为公开结构: | ||
| 119 | + | ||
| 120 | +| 成员 | 类型 | 含义 | | ||
| 121 | +| --- | --- | --- | | ||
| 122 | +| `kbL1Size` | `uint64_t` | L1 权重分块的 K 长度,单位为元素 | | ||
| 123 | +| `weightStride` | `uint64_t` | GM 权重物理行距,单位为权重元素;两种方向分别为 K 或 N | | ||
| 124 | +| `weightCacheMode` | `asc_load_l2_cache_mode` | GM 权重读取的缓存模式 | | ||
| 125 | +| `scaleValue` | `XType_` | per-tensor 的 `antiquantScale` 标量 | | ||
| 126 | +| `offsetValue` | `XType_` | per-tensor 且启用偏移时使用的 `antiquantOffset` 标量 | | ||
| 127 | + | ||
| 128 | +```cpp | ||
| 129 | +__aicore__ inline explicit KernelWqmmMixAntiquantPrologue( | ||
| 130 | + const Params& params, const SharedMemProvider_& sharedMemProvider); | ||
| 131 | + | ||
| 132 | +__aicore__ inline void operator()( | ||
| 133 | + __gm__ WeightType_* blockB, | ||
| 134 | + __gm__ AntiquantScaleType_* blockScale, | ||
| 135 | + __gm__ AntiquantScaleType_* blockOffset, | ||
| 136 | + uint64_t tileN, uint64_t kSize); | ||
| 137 | +``` | ||
| 138 | + | ||
| 139 | +`blockB` 指向当前 N 分块的量化权重,`blockScale` 和 `blockOffset` 指向对应通道参数。 | ||
| 140 | +per-tensor 使用构造参数中的标量;未启用偏移时不读取 `blockOffset`。 | ||
| 141 | +`tileN`、`kSize` 分别是当前权重分块的有效 N 长度和完整 K 长度,以元素计。 | ||
| 142 | +共享地址提供者返回两份 L1 权重缓冲区的地址。VF 函数和内部容量常量为私有实现。 | ||
| 143 | + | ||
| 144 | +## 调用示例 | ||
| 145 | + | ||
| 146 | +以下示例组装 INT8 权重、FP16 输入、GM `(N,K)` 权重存储、per-channel 且无偏移的 Kernel 类型: | ||
| 147 | + | ||
| 148 | +```cpp | ||
| 149 | +using Policy = Blaze::Gemm::MatmulWithWeightAntiquant< | ||
| 150 | + 2, 512, 2, Blaze::Gemm::QuantMode::PERCHANNEL_MODE, false>; | ||
| 151 | +using Layout = asc::te::nd_ext_layout_ptn; | ||
| 152 | +using Shape = asc::te::shape<int64_t, int64_t, int64_t>; | ||
| 153 | +using Block = Blaze::Gemm::Block::BlockMmad< | ||
| 154 | + Policy, half, Layout, AscendC::Std::tuple<int8_t, half>, | ||
| 155 | + AscendC::Std::tuple<Layout, Layout>, half, Layout, half, Layout>; | ||
| 156 | +using Scheduler = Blaze::Gemm::Block::BlockSchedulerWqmmTailResplit<Shape>; | ||
| 157 | +using Kernel = Blaze::Gemm::Kernel::GemmUniversal<Shape, Block, void, Scheduler>; | ||
| 158 | +``` | ||
| 159 | + | ||
| 160 | +填充 `Kernel::Params` 后在混合核入口调用 `Kernel{}(params)`。 | ||
| 161 | +完整的参数组装和运行方式见 | ||
| 162 | +[权重反量化样例](../../../../examples/weight_quant_batch_matmul/weight_quant_batch_matmul_antiquant/README.md)。 | ||
| @@ -8,6 +8,7 @@ | |||
| 8 | | [tile_mmad_mx](./tile_mmad_mx.md) | MX Mmad Trait 定义,用于量化矩阵乘计算 | | 8 | | [tile_mmad_mx](./tile_mmad_mx.md) | MX Mmad Trait 定义,用于量化矩阵乘计算 | |
| 9 | | [pad_mx_k_l1](./pad_mx_kl1.md) | MX K 轴 Padding,用于 L1 数据对齐补零 | | 9 | | [pad_mx_k_l1](./pad_mx_kl1.md) | MX K 轴 Padding,用于 L1 数据对齐补零 | |
| 10 | | [copy_gm_to_l1](./copy_gm_to_l1.md) | A 矩阵 ND slice 非连续场景的 GM->L1 搬运 | | 10 | | [copy_gm_to_l1](./copy_gm_to_l1.md) | A 矩阵 ND slice 非连续场景的 GM->L1 搬运 | |
| 11 | +| [copy_ub_to_l1](./copy_ub_to_l1.md) | FP16/BF16 权重 padding 布局的 UB→L1 搬运 | | ||
| 11 | | [tile_weight_quant_mx_preprocess](./tile_weight_quant_mx_preprocess.md) | packed FP4 ND/NZ 转换、bias 预缩放和 UB/L1 布局契约 | | 12 | | [tile_weight_quant_mx_preprocess](./tile_weight_quant_mx_preprocess.md) | packed FP4 ND/NZ 转换、bias 预缩放和 UB/L1 布局契约 | |
| 12 | 13 | ||
| 13 | ## 聚合头 | 14 | ## 聚合头 |
| @@ -15,7 +16,7 @@ | |||
| 15 | Tile 层原语按功能聚合为两个 public 入口头,均按架构宏分发到 `arch35/` 实现: | 16 | Tile 层原语按功能聚合为两个 public 入口头,均按架构宏分发到 `arch35/` 实现: |
| 16 | 17 | ||
| 17 | - **`blaze/gemm/tile/datamove.h`**:数据搬运原语,聚合 | 18 | - **`blaze/gemm/tile/datamove.h`**:数据搬运原语,聚合 |
| 18 | - `copy_gm_to_l1` / `copy_gm_to_ub` / `copy_mx_scale` / `copy_weight_ub_to_l1` | 19 | + `copy_gm_to_l1` / `copy_gm_to_ub` / `copy_mx_scale` / `copy_weight_ub_to_l1` / `copy_ub_to_l1` |
| 19 | - **`blaze/gemm/tile/compute.h`**:计算与变换原语,聚合 | 20 | - **`blaze/gemm/tile/compute.h`**:计算与变换原语,聚合 |
| 20 | `fill_ub` / `pad_mx_kl1` / `scale_mx_bias` / `shift_w4_to_w8` | 21 | `fill_ub` / `pad_mx_kl1` / `scale_mx_bias` / `shift_w4_to_w8` |
| 21 | 22 | ||
| @@ -0,0 +1,88 @@ | |||
| 1 | +# Copy UB To L1 | ||
| 2 | + | ||
| 3 | +> [代码位置](../../../../include/blaze/gemm/tile/arch35/copy_ub_to_l1.h) | ||
| 4 | + | ||
| 5 | +## 功能说明 | ||
| 6 | + | ||
| 7 | +该组件将带分组填充的 FP16/BF16 权重从 UB 搬运到 L1,供 WQMM 权重反量化使用。 | ||
| 8 | +调用方通过 `asc::te::make_copy(Blaze::Gemm::Tile::CopyPaddedUBToL1{})` 创建 Copy atom, | ||
| 9 | +再使用 `asc::te::copy(copyUB2L1, dstTensor, srcTensor)` 执行搬运。 | ||
| 10 | +`CopyPaddedUBToL1` 根据源布局 pattern 选择对应的搬运分支。 | ||
| 11 | +该实现直接从源、目标的层次化布局提取搬运参数,调用 `asc_copy_ub2l1` 完成数据搬运。 | ||
| 12 | + | ||
| 13 | +## 使用限制 | ||
| 14 | + | ||
| 15 | +- 仅在 `__NPU_ARCH__ == 3510` 时由聚合头 `blaze/gemm/tile/datamove.h` 引入。 | ||
| 16 | +- 源 Tensor 位于 UB,目标 Tensor 位于 L1;两端元素类型相同,支持 FP16 或 BF16。 | ||
| 17 | +- 源布局 pattern 为 `Blaze::Gemm::zn_row_padding_layout_ptn` 或 | ||
| 18 | + `Blaze::Gemm::nz_col_padding_layout_ptn`。 | ||
| 19 | +- 源 pattern 决定搬运分支;目标布局提供对应分组轴的实际 L1 行距。两端完整 shape 可以不同, | ||
| 20 | + 但每个分组内的数据排列必须兼容。 | ||
| 21 | +- 调用方保证范围非空、地址及连续段长度和行距按 32 字节对齐、段间空隙非负, | ||
| 22 | + 搬运参数可由指令字段表示,且缓冲区容量覆盖包含填充的物理范围。 | ||
| 23 | + | ||
| 24 | +## 布局构造接口 | ||
| 25 | + | ||
| 26 | +源布局由 [layout_struct.h](../../../../include/blaze/gemm/utils/layout_struct.h) 中的两个辅助类构造: | ||
| 27 | + | ||
| 28 | +```cpp | ||
| 29 | +template <typename T> | ||
| 30 | +struct ZnRowPaddingUBLayout { | ||
| 31 | + __aicore__ inline auto operator()(int64_t kSize, int64_t nSize, int64_t groupPitch) const; | ||
| 32 | +}; | ||
| 33 | + | ||
| 34 | +template <typename T> | ||
| 35 | +struct NzColPaddingUBLayout { | ||
| 36 | + __aicore__ inline auto operator()(int64_t kSize, int64_t nSize, int64_t groupPitch) const; | ||
| 37 | +}; | ||
| 38 | +``` | ||
| 39 | + | ||
| 40 | +两个类均位于 `Blaze::Gemm` 命名空间,`T` 为 FP16 或 BF16。 | ||
| 41 | +`kSize`、`nSize` 是权重逻辑坐标 `(K,N)` 下的有效长度;`groupPitch` 为包含填充的实际 UB 分组行距, | ||
| 42 | +三者均以元素计。令 `C0=32/sizeof(T)=16`,构造结果如下: | ||
| 43 | + | ||
| 44 | +| 构造类 | 源 pattern | shape | stride,单位为元素 | | ||
| 45 | +| --- | --- | --- | --- | | ||
| 46 | +| `ZnRowPaddingUBLayout<T>` | `zn_row_padding_layout_ptn` | `((16,ceil(kSize/16)),(1,nSize))` | `((1,groupPitch),(16,16))` | | ||
| 47 | +| `NzColPaddingUBLayout<T>` | `nz_col_padding_layout_ptn` | `((1,kSize),(16,ceil(nSize/16)))` | `((16,16),(1,groupPitch))` | | ||
| 48 | + | ||
| 49 | +ZN 保留有效 N 长度并对齐 K,NZ 保留有效 K 长度并对齐 N。 | ||
| 50 | +WQMM VF 的 UB 分组行距为 `65*16` 个元素,尾块也使用该行距,不能根据有效 shape 缩小间距。 | ||
| 51 | + | ||
| 52 | +## 搬运参数 | ||
| 53 | + | ||
| 54 | +对于源 shape `((k0,k1),(n0,n1))`,按源 pattern 提取以下参数。 | ||
| 55 | +行距分别从源、目标 layout 的对应 stride 中读取,单位为元素。 | ||
| 56 | + | ||
| 57 | +| 源 pattern | 连续段数量 | 每段元素数 | 分组行距 | | ||
| 58 | +| --- | --- | --- | --- | | ||
| 59 | +| `zn_row_padding_layout_ptn` | `k1` | `k0*n0*n1` | `stride[0][1]` | | ||
| 60 | +| `nz_col_padding_layout_ptn` | `n1` | `k0*k1*n0` | `stride[1][1]` | | ||
| 61 | + | ||
| 62 | +设每段元素数为 `segmentElements`,两端行距为 `srcPitch`、`dstPitch`。 | ||
| 63 | +指令的 `block_len`、`src_gap` 和 `dst_gap` 以 32 字节为单位: | ||
| 64 | + | ||
| 65 | +```text | ||
| 66 | +block_len = segmentElements * sizeof(T) / 32 | ||
| 67 | +src_gap = (srcPitch - segmentElements) * sizeof(T) / 32 | ||
| 68 | +dst_gap = (dstPitch - segmentElements) * sizeof(T) / 32 | ||
| 69 | +``` | ||
| 70 | + | ||
| 71 | +## 使用方式 | ||
| 72 | + | ||
| 73 | +调用方包含 `blaze/gemm/tile/datamove.h`,使用上述辅助类构造源布局,并为目标提供兼容的 L1 布局。 | ||
| 74 | +以下展示 ZN 分组的调用片段,`ubWeight` 和 `l1Weight` 为已分配的类型化指针, | ||
| 75 | +`l1Layout` 描述目标 L1 的实际分组排列和行距。 | ||
| 76 | + | ||
| 77 | +```cpp | ||
| 78 | +auto ubLayout = Blaze::Gemm::ZnRowPaddingUBLayout<T>{}(kSize, nSize, groupPitch); | ||
| 79 | +auto srcTensor = asc::te::make_tensor( | ||
| 80 | + asc::te::make_mem_ptr<asc::te::location::ub>(ubWeight), ubLayout); | ||
| 81 | +auto dstTensor = asc::te::make_tensor( | ||
| 82 | + asc::te::make_mem_ptr<asc::te::location::l1>(l1Weight), l1Layout); | ||
| 83 | +auto copyUB2L1 = asc::te::make_copy(Blaze::Gemm::Tile::CopyPaddedUBToL1{}); | ||
| 84 | +asc::te::copy(copyUB2L1, dstTensor, srcTensor); | ||
| 85 | +``` | ||
| 86 | + | ||
| 87 | +NZ 分组使用 `NzColPaddingUBLayout<T>` 构造源布局,并提供对应的 L1 NZ 布局。 | ||
| 88 | +`CopyPaddedUBToL1` 通过 `copy_traits` 注册,默认使用 Tensor API 的 `ub_to_l1_trait_default`。 | ||
| @@ -111,6 +111,7 @@ add_subdirectory(block_attn_res_prepare) | |||
| 111 | add_subdirectory(transpose_batch_mat_mul) | 111 | add_subdirectory(transpose_batch_mat_mul) |
| 112 | add_subdirectory(quant_batch_matmul) | 112 | add_subdirectory(quant_batch_matmul) |
| 113 | add_subdirectory(weight_quant_batch_matmul_mx) | 113 | add_subdirectory(weight_quant_batch_matmul_mx) |
| 114 | +add_subdirectory(weight_quant_batch_matmul) | ||
| 114 | add_subdirectory(grouped_matmul) | 115 | add_subdirectory(grouped_matmul) |
| 115 | add_subdirectory(quant_matmul_activation_quant) | 116 | add_subdirectory(quant_matmul_activation_quant) |
| 116 | add_subdirectory(transpose_quant_batch_matmul) | 117 | add_subdirectory(transpose_quant_batch_matmul) |
| @@ -111,6 +111,7 @@ examples/ | |||
| 111 | | `quant_batch_matmul/` | quant_batch_matmul_cube, quant_batch_matmul_mix, quant_batch_matmul_mx | 量化批量矩阵乘法样例 | | 111 | | `quant_batch_matmul/` | quant_batch_matmul_cube, quant_batch_matmul_mix, quant_batch_matmul_mx | 量化批量矩阵乘法样例 | |
| 112 | | `block_attn_res_prepare/` | block_attn_res_prepare | Attention residual prepare 样例 | | 112 | | `block_attn_res_prepare/` | block_attn_res_prepare | Attention residual prepare 样例 | |
| 113 | | `weight_quant_batch_matmul_mx/` | weight_quant_batch_matmul_mx_swat | 权重量化批量矩阵乘法样例 | | 113 | | `weight_quant_batch_matmul_mx/` | weight_quant_batch_matmul_mx_swat | 权重量化批量矩阵乘法样例 | |
| 114 | +| `weight_quant_batch_matmul/` | [weight_quant_batch_matmul_antiquant](weight_quant_batch_matmul/weight_quant_batch_matmul_antiquant/README.md) | INT8 权重反量化矩阵乘,FP16/BF16 输入、两种权重存储方向及尾块 | | ||
建议改为weight_quant_matmul目录,子目录将weight_quant_matmul_a8w4_mx、weight_quant_matmul_a8w4_pergroup、weight_quant_matmul_a16w4放在一起 ![]() ![]() | |||
| 114 | | `grouped_matmul/` | quant_grouped_matmul_mx, [quant_grouped_matmul_cubeonly](grouped_matmul/quant_grouped_matmul_cubeonly/README.md), [grouped_matmul_mx_a8w4](grouped_matmul/grouped_matmul_mx_a8w4/README.md) | Grouped MatMul 与量化 Cube/MX A8W4 样例 | | 115 | | `grouped_matmul/` | quant_grouped_matmul_mx, [quant_grouped_matmul_cubeonly](grouped_matmul/quant_grouped_matmul_cubeonly/README.md), [grouped_matmul_mx_a8w4](grouped_matmul/grouped_matmul_mx_a8w4/README.md) | Grouped MatMul 与量化 Cube/MX A8W4 样例 | |
| 115 | | `quant_matmul_activation_quant/` | quant_matmul_activation_quant | 量化矩阵乘激活融合样例 | | 116 | | `quant_matmul_activation_quant/` | quant_matmul_activation_quant | 量化矩阵乘激活融合样例 | |
| 116 | | `transpose_quant_batch_matmul/` | tqbmm_mx | 转置量化批量矩阵乘法样例 | | 117 | | `transpose_quant_batch_matmul/` | tqbmm_mx | 转置量化批量矩阵乘法样例 | |
| @@ -0,0 +1,10 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +ops_example_add_executable(weight_quant_batch_matmul_antiquant | ||
| 10 | + weight_quant_batch_matmul_antiquant/weight_quant_batch_matmul_antiquant.cpp) | ||
| @@ -0,0 +1,62 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 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 | +"""Generate deterministic A16W8 inputs and golden with staged antiquant rounding.""" | ||
| 11 | + | ||
| 12 | +import argparse | ||
| 13 | +from pathlib import Path | ||
| 14 | + | ||
| 15 | +import ml_dtypes | ||
| 16 | +import numpy as np | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def main(): | ||
| 20 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 21 | + for axis in ("m", "k", "n"): | ||
| 22 | + parser.add_argument(f"--{axis}", type=int, required=True) | ||
| 23 | + parser.add_argument("--dtype", choices=("fp16", "bf16"), required=True) | ||
| 24 | + for flag in ("trans-b", "per-tensor", "offset", "bias"): | ||
| 25 | + parser.add_argument(f"--{flag}", type=int, choices=(0, 1), required=True) | ||
| 26 | + parser.add_argument("--output-dir", type=Path, required=True) | ||
| 27 | + args = parser.parse_args() | ||
| 28 | + if min(args.m, args.k, args.n) <= 0: | ||
| 29 | + parser.error("M, K and N must be positive") | ||
| 30 | + dtype = np.float16 if args.dtype == "fp16" else ml_dtypes.bfloat16 | ||
| 31 | + rng = np.random.default_rng(20260918) | ||
| 32 | + a = (rng.integers(-8, 9, (args.m, args.k)).astype(np.float32) / 8).astype(dtype) | ||
| 33 | + b = rng.integers(-8, 9, (args.k, args.n), dtype=np.int8) | ||
| 34 | + count = 1 if args.per_tensor else args.n | ||
| 35 | + scale = (rng.integers(1, 5, count).astype(np.float32) / 16).astype(dtype) | ||
| 36 | + offset = (rng.integers(-2, 3, count).astype(np.float32) / 4).astype(dtype) | ||
| 37 | + bias = (rng.integers(-4, 5, args.n).astype(np.float32) / 8).astype(dtype) | ||
| 38 | + # Cast, add offset and multiply scale round separately in the VF output dtype. | ||
| 39 | + converted = b.astype(dtype) | ||
| 40 | + if args.offset: | ||
| 41 | + converted = (converted.astype(np.float32) + offset.astype(np.float32)).astype( | ||
| 42 | + dtype | ||
| 43 | + ) | ||
| 44 | + converted = (converted.astype(np.float32) * scale.astype(np.float32)).astype(dtype) | ||
| 45 | + golden = a.astype(np.float32) @ converted.astype(np.float32) | ||
| 46 | + if args.bias: | ||
| 47 | + golden += bias.astype(np.float32) | ||
| 48 | + args.output_dir.mkdir(parents=True, exist_ok=True) | ||
| 49 | + arrays = { | ||
| 50 | + "a": a, | ||
| 51 | + "b": b.T.copy() if args.trans_b else b, | ||
| 52 | + "scale": scale, | ||
| 53 | + "offset": offset, | ||
| 54 | + "bias": bias, | ||
| 55 | + "golden_c": golden.astype(dtype), | ||
| 56 | + } | ||
| 57 | + for name, values in arrays.items(): | ||
| 58 | + values.tofile(args.output_dir / f"{name}.bin") | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +if __name__ == "__main__": | ||
| 62 | + main() | ||
| @@ -0,0 +1,65 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 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 | +"""Compare every output element; reject empty, truncated or non-finite outputs.""" | ||
| 11 | + | ||
| 12 | +import argparse | ||
| 13 | +from pathlib import Path | ||
| 14 | +import sys | ||
| 15 | + | ||
| 16 | +import ml_dtypes | ||
| 17 | +import numpy as np | ||
| 18 | + | ||
| 19 | +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "common")) | ||
| 20 | +from metrics import write_metrics_json | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def main(): | ||
| 24 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 25 | + parser.add_argument("golden", type=Path) | ||
| 26 | + parser.add_argument("actual", type=Path) | ||
| 27 | + parser.add_argument("--dtype", choices=("fp16", "bf16"), required=True) | ||
| 28 | + args = parser.parse_args() | ||
| 29 | + dtype = np.float16 if args.dtype == "fp16" else ml_dtypes.bfloat16 | ||
| 30 | + if ( | ||
| 31 | + args.golden.stat().st_size == 0 | ||
| 32 | + or args.golden.stat().st_size != args.actual.stat().st_size | ||
| 33 | + ): | ||
| 34 | + raise ValueError("Empty output or mismatched binary sizes") | ||
| 35 | + if args.actual.stat().st_size % np.dtype(dtype).itemsize: | ||
| 36 | + raise ValueError("Output contains an incomplete element") | ||
| 37 | + golden = np.fromfile(args.golden, dtype=dtype).astype(np.float32) | ||
| 38 | + actual = np.fromfile(args.actual, dtype=dtype).astype(np.float32) | ||
| 39 | + rtol, atol = (0.001, 0.001) if args.dtype == "fp16" else (0.008, 0.008) | ||
| 40 | + finite = np.isfinite(golden) & np.isfinite(actual) | ||
| 41 | + diff = np.abs(actual - golden) | ||
| 42 | + good = finite & (diff <= atol + rtol * np.abs(golden)) | ||
| 43 | + passed = bool(np.all(good)) | ||
| 44 | + maximum = float(diff.max()) if np.all(finite) else float("inf") | ||
| 45 | + status = "pass" if passed else "fail" | ||
| 46 | + write_metrics_json( | ||
| 47 | + [ | ||
| 48 | + { | ||
| 49 | + "name": "output", | ||
| 50 | + "max_abs_diff": maximum, | ||
| 51 | + "error_ratio": float(np.mean(~good)), | ||
| 52 | + "status": status, | ||
| 53 | + } | ||
| 54 | + ], | ||
| 55 | + status, | ||
| 56 | + str(args.actual.parent), | ||
| 57 | + ) | ||
| 58 | + print( | ||
| 59 | + f"[{status.upper()}] elements={golden.size}, max_abs_diff={maximum}, mismatches={np.count_nonzero(~good)}" | ||
| 60 | + ) | ||
| 61 | + return 0 if passed else 1 | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +if __name__ == "__main__": | ||
| 65 | + raise SystemExit(main()) | ||
| @@ -0,0 +1,105 @@ | |||
| 1 | +# 权重反量化矩阵乘样例 | ||
| 2 | + | ||
| 3 | +## 概述 | ||
| 4 | + | ||
| 5 | +本样例使用 WQMM `GemmUniversal`,由 AIV 对 INT8 权重 `weight` 反量化, | ||
| 6 | +再由 AIC 计算输入 `x` 与反量化权重的矩阵乘,写回输出 `y`。 | ||
| 7 | +可选参数包括反量化偏移 `antiquantOffset` 和输出偏置 `bias`。 | ||
| 8 | + | ||
| 9 | +```text | ||
| 10 | +weightDequant = (cast(weight) + antiquantOffset) * antiquantScale | ||
| 11 | + y = x @ weightDequant + bias | ||
| 12 | +``` | ||
| 13 | + | ||
| 14 | +`x`、`weight`、`y` 的逻辑形状分别为 `(M,K)`、`(K,N)`、`(M,N)`。 | ||
| 15 | +未启用偏移或偏置时省略对应加法。转换、反量化加法和乘法分别按 FP16/BF16 舍入, | ||
| 16 | +矩阵乘使用 FP32 累加,输出转换为输入类型。 | ||
| 17 | + | ||
| 18 | +## 支持架构 | ||
| 19 | + | ||
| 20 | +Ascend 950 / DAV_3510,使用设备 0。 | ||
| 21 | + | ||
| 22 | +## 使用约束 | ||
| 23 | + | ||
| 24 | +- 输入 `x` 和输出 `y` 为相同的 FP16 或 BF16 类型;权重固定为 INT8。 | ||
| 25 | + `antiquantScale`、`antiquantOffset` 和 `bias` 与输入类型相同。 | ||
| 26 | +- M、K、N 均为正,样例限制 `M <= 256`、`K <= 4096`、`N <= 1024`。 | ||
| 27 | + 这些是样例的配置范围,组件的类型与容量约束见 [Kernel 文档](../../../docs/API/gemm/kernel/kernel_wqmm_mix_antiquant.md)。 | ||
| 28 | +- 样例采用固定分块:M/N/K 基本块为 32/64/64,输入和权重的 L1 K 分块长度均为 128, | ||
| 29 | + UB 输入行距为 512 字节,配置两份输入缓冲区和两个 AIC。分块是每次处理的子区域, | ||
| 30 | + 缓冲区是其片上存储空间,行距是相邻物理行起点间的距离。 | ||
| 31 | +- 完整 N 轮次分配给两个 AIC,剩余 N 拆成两段尾块。M 超过 32 时分多轮处理, | ||
| 32 | + K 超过 128 时交替使用两份 L1 权重缓冲区。样例关闭输入预取,采用普通双缓冲装载输入。 | ||
| 33 | +- 尾块搬运包含对齐所需的填充空间,矩阵乘使用真实有效长度。 | ||
| 34 | + | ||
| 35 | +组件还支持 FP8 E4M3、HiFloat8 权重及 FP32 `bias`,这些类型不属于本样例的验证范围。 | ||
| 36 | + | ||
| 37 | +## 执行命令 | ||
| 38 | + | ||
| 39 | +在仓库根目录执行,先配置 CANN 环境,并安装 [examples 依赖](../../requirements.txt): | ||
| 40 | + | ||
| 41 | +```bash | ||
| 42 | +source /path/to/cann/set_env.sh | ||
| 43 | +bash build.sh --examples --ops=weight_quant_batch_matmul | ||
| 44 | +``` | ||
| 45 | + | ||
| 46 | +也可使用公共样例入口,仅运行指定样例: | ||
| 47 | + | ||
| 48 | +```bash | ||
| 49 | +bash examples/common/run.sh --ops=weight_quant_batch_matmul --target=weight_quant_batch_matmul_antiquant | ||
| 50 | +``` | ||
| 51 | + | ||
| 52 | +仅编译时添加 `--build-only`;使用已编译的可执行文件时添加 `--skip-build`。 | ||
| 53 | +公共入口按 CSV 逐条生成输入、运行 Kernel 并验证输出。 | ||
| 54 | + | ||
| 55 | +## CSV 参数 | ||
| 56 | + | ||
| 57 | +用例配置见 [weight_quant_batch_matmul_antiquant.csv](./weight_quant_batch_matmul_antiquant.csv)。 | ||
| 58 | + | ||
| 59 | +| 字段 | 含义与取值 | | ||
| 60 | +| --- | --- | | ||
| 61 | +| `casename` | 用例名称 | | ||
| 62 | +| `m,k,n` | M、K、N 逻辑长度,均以元素计 | | ||
| 63 | +| `x_dtype` | `fp16` 或 `bf16` | | ||
| 64 | +| `transpose_weight` | 1:GM 权重按 `(N,K)` 存储;0:按 `(K,N)` 存储 | | ||
| 65 | +| `antiquant_per_tensor` | 1:整张权重使用一个反量化缩放值和可选偏移值;0:每个 N 通道各使用一组参数 | | ||
| 66 | +| `has_antiquant_offset` | 1:启用 `antiquantOffset`;0:关闭 | | ||
| 67 | +| `has_bias` | 1:启用 `bias`;0:关闭 | | ||
| 68 | + | ||
| 69 | +[weight_quant_batch_matmul_antiquant.conf](./weight_quant_batch_matmul_antiquant.conf) | ||
| 70 | +为公共运行入口提供参数映射:`[gen_data]` 将 CSV 字段映射为数据生成脚本的命名参数, | ||
| 71 | +`[kernel]` 指定可执行文件的位置参数顺序,`[verify]` 指定预期结果、设备结果及数据类型。 | ||
| 72 | +`$OUTPUT_DIR` 由运行入口提供,作为当前用例的数据目录。 | ||
| 73 | + | ||
| 74 | +## 输入输出文件 | ||
| 75 | + | ||
| 76 | +以下二进制文件存放在当前用例的数据目录中。表中的形状表示元素排列,无额外文件头。 | ||
| 77 | + | ||
| 78 | +| 文件 | 内容与形状 | | ||
| 79 | +| --- | --- | | ||
| 80 | +| `a.bin` | 输入 `x`,`(M,K)` | | ||
| 81 | +| `b.bin` | INT8 权重 `weight`,按 `transpose_weight` 选择 `(N,K)` 或 `(K,N)` 存储 | | ||
| 82 | +| `scale.bin` | `antiquantScale`,per-tensor 为 1 个元素,per-channel 为 N 个元素 | | ||
| 83 | +| `offset.bin` | `antiquantOffset`,形状与 `antiquantScale` 相同;启用偏移时读取 | | ||
| 84 | +| `bias.bin` | `bias`,N 个元素;启用偏置时读取 | | ||
| 85 | +| `golden_c.bin` | CPU 生成的预期输出 `y`,`(M,N)` | | ||
| 86 | +| `npu_out.bin` | 设备计算的输出 `y`,`(M,N)` | | ||
| 87 | + | ||
| 88 | +数据生成脚本固定随机种子为 20260918,并生成可选参数文件;Kernel 仅在对应开关启用时读取。 | ||
| 89 | +验证脚本在数据目录写入 `verify_metrics.json`,公共入口汇总生成 | ||
| 90 | +`weight_quant_batch_matmul_antiquant_result.csv`。临时数据目录的保留方式由公共入口管理。 | ||
| 91 | + | ||
| 92 | +## 验证标准 | ||
| 93 | + | ||
| 94 | +CSV 中的 8 个用例覆盖 FP16/BF16、两种权重存储方向、per-channel/per-tensor、 | ||
| 95 | +偏移和偏置开关,以及 M/N/K 尾块和多轮分块。 | ||
| 96 | +CPU 预期结果逐步模拟反量化舍入,再执行 FP32 矩阵乘及输出类型转换。 | ||
| 97 | + | ||
| 98 | +每个输出元素均须满足: | ||
| 99 | + | ||
| 100 | +```text | ||
| 101 | +abs(actual - golden) <= atol + rtol * abs(golden) | ||
| 102 | +``` | ||
| 103 | + | ||
| 104 | +FP16 的 `atol`、`rtol` 均为 0.001;BF16 均为 0.008。 | ||
| 105 | +非有限值、空输出或长度错误均判定为失败。本样例验证数值结果,不采集性能数据。 | ||
| @@ -0,0 +1,8 @@ | |||
| 1 | +[gen_data] | ||
| 2 | +params=--m:m,--k:k,--n:n,--dtype:x_dtype,--trans-b:transpose_weight,--per-tensor:antiquant_per_tensor,--offset:has_antiquant_offset,--bias:has_bias,--output-dir:$OUTPUT_DIR | ||
| 3 | + | ||
| 4 | +[kernel] | ||
| 5 | +params=m,k,n,x_dtype,transpose_weight,antiquant_per_tensor,has_antiquant_offset,has_bias,$OUTPUT_DIR | ||
| 6 | + | ||
| 7 | +[verify] | ||
| 8 | +params=$OUTPUT_DIR/golden_c.bin,$OUTPUT_DIR/npu_out.bin,--dtype:x_dtype | ||
| @@ -0,0 +1,198 @@ | |||
| 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 <cstdint> | ||
| 12 | +#include <cstdlib> | ||
| 13 | +#include <stdexcept> | ||
| 14 | +#include <string> | ||
| 15 | +#include <vector> | ||
| 16 | +#include "data_utils.h" | ||
| 17 | +#include "blaze/gemm/kernel/kernel_wqmm_mix_antiquant.h" | ||
| 18 | +#include "blaze/gemm/block/block_scheduler_wqmm.h" | ||
| 19 | + | ||
| 20 | +namespace { | ||
| 21 | +constexpr int64_t BASE_M = 32; | ||
| 22 | +constexpr int64_t BASE_N = 64; | ||
| 23 | +constexpr int64_t BASE_K = 64; | ||
| 24 | +constexpr int64_t L1_K = 128; | ||
| 25 | +constexpr uint32_t BLOCK_NUM = 2; | ||
| 26 | + | ||
| 27 | +struct Config { | ||
| 28 | + int64_t m, k, n; | ||
| 29 | + bool bf16, transB, perTensor, offset, bias; | ||
| 30 | + std::string directory; | ||
| 31 | +}; | ||
| 32 | + | ||
| 33 | +class DeviceBuffer { | ||
| 34 | +public: | ||
| 35 | + explicit DeviceBuffer(size_t bytes) : bytes_(bytes) | ||
| 36 | + { | ||
| 37 | + ACL_CHECK(aclrtMalloc(reinterpret_cast<void**>(&data_), bytes_, ACL_MEM_MALLOC_HUGE_FIRST)); | ||
| 38 | + ACL_CHECK(aclrtMemset(data_, bytes_, 0, bytes_)); | ||
| 39 | + } | ||
| 40 | + ~DeviceBuffer() { aclrtFree(data_); } | ||
| 41 | + DeviceBuffer(const DeviceBuffer&) = delete; | ||
| 42 | + DeviceBuffer& operator=(const DeviceBuffer&) = delete; | ||
| 43 | + uint8_t* Get() const { return data_; } | ||
| 44 | + void Load(const std::string& path) | ||
| 45 | + { | ||
| 46 | + std::vector<uint8_t> host(bytes_); | ||
| 47 | + if (!ReadFile(path, host.data(), bytes_)) { | ||
| 48 | + throw std::runtime_error("Failed to read input: " + path); | ||
| 49 | + } | ||
| 50 | + ACL_CHECK(aclrtMemcpy(data_, bytes_, host.data(), bytes_, ACL_MEMCPY_HOST_TO_DEVICE)); | ||
| 51 | + } | ||
| 52 | + void Save(const std::string& path) const | ||
| 53 | + { | ||
| 54 | + std::vector<uint8_t> host(bytes_); | ||
| 55 | + ACL_CHECK(aclrtMemcpy(host.data(), bytes_, data_, bytes_, ACL_MEMCPY_DEVICE_TO_HOST)); | ||
| 56 | + if (!WriteFile(path, host.data(), bytes_)) { | ||
| 57 | + throw std::runtime_error("Failed to write output: " + path); | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + | ||
| 61 | +private: | ||
| 62 | + uint8_t* data_{nullptr}; | ||
| 63 | + size_t bytes_; | ||
| 64 | +}; | ||
| 65 | + | ||
| 66 | +template <typename T, bool TransB, bool PerTensor, bool HasOffset> | ||
| 67 | +__global__ __aicore__ void WqmmAntiquantKernel(GM_ADDR a, GM_ADDR b, GM_ADDR scale, GM_ADDR offset, GM_ADDR bias, | ||
| 68 | + GM_ADDR c, int64_t m, int64_t k, int64_t n, bool hasBias) | ||
| 69 | +{ | ||
| 70 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); | ||
| 71 | + AscendC::InitSocState(); | ||
| 72 | + | ||
| 73 | + using Policy = Blaze::Gemm::MatmulWithWeightAntiquant< | ||
| 74 | + 2, 512, 2, PerTensor ? Blaze::Gemm::QuantMode::PERTENSOR_MODE : Blaze::Gemm::QuantMode::PERCHANNEL_MODE, | ||
| 75 | + HasOffset>; | ||
| 76 | + using Layout = asc::te::nd_ext_layout_ptn; | ||
| 77 | + using BLayout = AscendC::Std::conditional_t<TransB, Layout, asc::te::dn_ext_layout_ptn>; | ||
| 78 | + using Shape = asc::te::shape<int64_t, int64_t, int64_t>; | ||
| 79 | + using Block = Blaze::Gemm::Block::BlockMmad<Policy, T, Layout, AscendC::Std::tuple<int8_t, T>, | ||
| 80 | + AscendC::Std::tuple<BLayout, Layout>, T, Layout, T, Layout>; | ||
| 81 | + using Scheduler = Blaze::Gemm::Block::BlockSchedulerWqmmTailResplit<Shape>; | ||
| 82 | + using Kernel = Blaze::Gemm::Kernel::GemmUniversal<Shape, Block, void, Scheduler>; | ||
| 83 | + typename Kernel::Params params{}; | ||
| 84 | + params.problemShape = asc::te::make_shape(m, n, k); | ||
| 85 | + params.mmadParams.aGmAddr = a; | ||
| 86 | + params.mmadParams.cGmAddr = c; | ||
| 87 | + params.mmadParams.biasGmAddr = bias; | ||
| 88 | + params.mmadParams.l1TileShape = asc::te::make_shape(BASE_M, BASE_N, L1_K, L1_K); | ||
| 89 | + params.mmadParams.l0TileShape = asc::te::make_shape(BASE_M, BASE_N, BASE_K); | ||
| 90 | + params.mmadParams.hasBias = hasBias; | ||
| 91 | + params.mmadParams.kSize = k; | ||
| 92 | + params.prologueParams = {b, scale, offset, 1U}; | ||
| 93 | + // Full N rounds use both AICs. Split the remainder between two tail ranges. | ||
| 94 | + const uint64_t mainCount = static_cast<uint64_t>(n / (BASE_N * BLOCK_NUM)) * BLOCK_NUM; | ||
| 95 | + const uint64_t remainder = static_cast<uint64_t>(n) - mainCount * BASE_N; | ||
| 96 | + const uint64_t first = remainder / BLOCK_NUM; | ||
| 97 | + const uint64_t second = remainder - first; | ||
| 98 | + params.schedulerParams = {BASE_M, mainCount, first != 0 ? 1UL : 0UL, second != 0 ? 1UL : 0UL, BASE_N, first, second, | ||
| 99 | + 1UL, BLOCK_NUM}; | ||
| 100 | + Kernel{}(params); | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +template <typename T, bool TransB, bool PerTensor, bool HasOffset> | ||
| 104 | +void Run(const Config& config, aclrtStream stream) | ||
| 105 | +{ | ||
| 106 | + const size_t quantCount = PerTensor ? 1 : config.n; | ||
| 107 | + DeviceBuffer a(config.m * config.k * sizeof(T)); | ||
| 108 | + DeviceBuffer b(config.k * config.n); | ||
| 109 | + DeviceBuffer scale(quantCount * sizeof(T)); | ||
| 110 | + DeviceBuffer offset(quantCount * sizeof(T)); | ||
| 111 | + DeviceBuffer bias(config.n * sizeof(T)); | ||
| 112 | + DeviceBuffer c(config.m * config.n * sizeof(T)); | ||
| 113 | + a.Load(config.directory + "/a.bin"); | ||
| 114 | + b.Load(config.directory + "/b.bin"); | ||
| 115 | + scale.Load(config.directory + "/scale.bin"); | ||
| 116 | + if constexpr (HasOffset) { | ||
| 117 | + offset.Load(config.directory + "/offset.bin"); | ||
| 118 | + } | ||
| 119 | + if (config.bias) { | ||
| 120 | + bias.Load(config.directory + "/bias.bin"); | ||
| 121 | + } | ||
| 122 | + WqmmAntiquantKernel<T, TransB, PerTensor, HasOffset><<<BLOCK_NUM, 0, stream>>>( | ||
| 123 | + a.Get(), b.Get(), scale.Get(), HasOffset ? offset.Get() : nullptr, config.bias ? bias.Get() : nullptr, c.Get(), | ||
| 124 | + config.m, config.k, config.n, config.bias); | ||
| 125 | + ACL_CHECK(aclrtSynchronizeStream(stream)); | ||
| 126 | + c.Save(config.directory + "/npu_out.bin"); | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +template <typename T, bool TransB, bool PerTensor> | ||
| 130 | +void SelectOffset(const Config& config, aclrtStream stream) | ||
| 131 | +{ | ||
| 132 | + if (config.offset) { | ||
| 133 | + Run<T, TransB, PerTensor, true>(config, stream); | ||
| 134 | + } else { | ||
| 135 | + Run<T, TransB, PerTensor, false>(config, stream); | ||
| 136 | + } | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +template <typename T, bool TransB> | ||
| 140 | +void SelectQuant(const Config& config, aclrtStream stream) | ||
| 141 | +{ | ||
| 142 | + if (config.perTensor) { | ||
| 143 | + SelectOffset<T, TransB, true>(config, stream); | ||
| 144 | + } else { | ||
| 145 | + SelectOffset<T, TransB, false>(config, stream); | ||
| 146 | + } | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +template <typename T> | ||
| 150 | +void SelectLayout(const Config& config, aclrtStream stream) | ||
| 151 | +{ | ||
| 152 | + if (config.transB) { | ||
| 153 | + SelectQuant<T, true>(config, stream); | ||
| 154 | + } else { | ||
| 155 | + SelectQuant<T, false>(config, stream); | ||
| 156 | + } | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +bool ParseBool(const char* arg) | ||
| 160 | +{ | ||
| 161 | + const std::string value(arg); | ||
| 162 | + if (value != "0" && value != "1") { | ||
| 163 | + throw std::invalid_argument("Boolean arguments must be 0 or 1"); | ||
| 164 | + } | ||
| 165 | + return value == "1"; | ||
| 166 | +} | ||
| 167 | +} // namespace | ||
| 168 | + | ||
| 169 | +int main(int argc, const char** argv) | ||
| 170 | +{ | ||
| 171 | + try { | ||
| 172 | + if (argc != 10) { | ||
| 173 | + throw std::invalid_argument( | ||
| 174 | + "Usage: <m> <k> <n> <fp16|bf16> <trans_b> <per_tensor> <offset> <bias> <data_dir>"); | ||
| 175 | + } | ||
| 176 | + const std::string dtype(argv[4]); | ||
| 177 | + if (dtype != "fp16" && dtype != "bf16") { | ||
| 178 | + throw std::invalid_argument("dtype must be fp16 or bf16"); | ||
| 179 | + } | ||
| 180 | + Config config{std::stoll(argv[1]), std::stoll(argv[2]), std::stoll(argv[3]), | ||
| 181 | + dtype == "bf16", ParseBool(argv[5]), ParseBool(argv[6]), | ||
| 182 | + ParseBool(argv[7]), ParseBool(argv[8]), argv[9]}; | ||
| 183 | + if (config.m <= 0 || config.m > 256 || config.k <= 0 || config.k > 4096 || config.n <= 0 || config.n > 1024) { | ||
| 184 | + throw std::invalid_argument("Example supports 1<=M<=256, 1<=K<=4096, 1<=N<=1024"); | ||
| 185 | + } | ||
| 186 | + aclrtStream stream{nullptr}; | ||
| 187 | + ACLDeviceGuard guard(stream); | ||
| 188 | + if (config.bf16) { | ||
| 189 | + SelectLayout<bfloat16_t>(config, stream); | ||
| 190 | + } else { | ||
| 191 | + SelectLayout<half>(config, stream); | ||
| 192 | + } | ||
| 193 | + return 0; | ||
| 194 | + } catch (const std::exception& error) { | ||
| 195 | + std::cerr << error.what() << std::endl; | ||
| 196 | + return 1; | ||
| 197 | + } | ||
| 198 | +} | ||
| @@ -0,0 +1,9 @@ | |||
| 1 | +casename,m,k,n,x_dtype,transpose_weight,antiquant_per_tensor,has_antiquant_offset,has_bias | ||
| 2 | +fp16_nk_channel_tail,3,255,257,fp16,1,0,0,0 | ||
| 3 | +fp16_kn_channel_offset_multim,65,513,159,fp16,0,0,1,1 | ||
| 4 | +fp16_nk_tensor_offset,32,129,64,fp16,1,1,1,0 | ||
| 5 | +fp16_kn_tensor,17,256,128,fp16,0,1,0,1 | ||
| 6 | +bf16_nk_channel_offset,33,255,31,bf16,1,0,1,1 | ||
| 7 | +bf16_kn_channel,7,129,257,bf16,0,0,0,0 | ||
| 8 | +bf16_nk_tensor,64,513,159,bf16,1,1,0,0 | ||
| 9 | +bf16_kn_tensor_offset,3,65,17,bf16,0,1,1,1 | ||
| @@ -237,10 +237,11 @@ private: | |||
| 237 | 237 | ||
| 238 | __aicore__ inline void Init(const Params& params) | 238 | __aicore__ inline void Init(const Params& params) |
| 239 | { | 239 | { |
| 240 | + constexpr uint32_t SCALE_K_INDEX = 3; | ||
| 240 | uint64_t l1BaseM = static_cast<uint64_t>(asc::te::get<MNK_M>(params.l1TileShape)); | 241 | uint64_t l1BaseM = static_cast<uint64_t>(asc::te::get<MNK_M>(params.l1TileShape)); |
| 241 | uint64_t l1BaseN = static_cast<uint64_t>(asc::te::get<MNK_N>(params.l1TileShape)); | 242 | uint64_t l1BaseN = static_cast<uint64_t>(asc::te::get<MNK_N>(params.l1TileShape)); |
| 242 | kL1Size_ = static_cast<uint64_t>(asc::te::get<MNK_K>(params.l1TileShape)); | 243 | kL1Size_ = static_cast<uint64_t>(asc::te::get<MNK_K>(params.l1TileShape)); |
| 243 | - scaleKL1Size_ = static_cast<uint64_t>(asc::te::get<3>(params.l1TileShape)); | 244 | + scaleKL1Size_ = static_cast<uint64_t>(asc::te::get<SCALE_K_INDEX>(params.l1TileShape)); |
| 244 | kL0Size_ = static_cast<uint64_t>(asc::te::get<MNK_K>(params.l0TileShape)); | 245 | kL0Size_ = static_cast<uint64_t>(asc::te::get<MNK_K>(params.l0TileShape)); |
| 245 | l1BufferNum_ = params.l1BufferNum; | 246 | l1BufferNum_ = params.l1BufferNum; |
| 246 | l1BufferMask_ = l1BufferNum_ - 1U; | 247 | l1BufferMask_ = l1BufferNum_ - 1U; |
| @@ -0,0 +1,418 @@ | |||
| 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 block_mmad_wqmm_mix_weight_prologue.h | ||
| 13 | + * \brief AIC-side BlockMmad specialization for multiplication with dequantized 8-bit weights. | ||
| 14 | + * | ||
| 15 | + * The AIV prologue dequantizes weight into shared L1 buffers. This block loads x and optional bias, | ||
| 16 | + * copies inputs from L1 to L0, computes MMAD, and writes y through Fixpipe. Cross-core flags coordinate | ||
| 17 | + * weight buffer reuse; BufferSlot entries manage local buffer addresses and pipeline synchronization. | ||
| 18 | + */ | ||
| 19 | +#pragma once | ||
| 20 | + | ||
| 21 | +#if ASC_DEVKIT_MAJOR >= 9 | ||
| 22 | +#include "kernel_basic_intf.h" | ||
| 23 | +#else | ||
| 24 | +#include "kernel_operator.h" | ||
| 25 | +#include "kernel_operator_intf.h" | ||
| 26 | +#endif | ||
| 27 | + | ||
| 28 | +#include "tensor_api/tensor.h" | ||
| 29 | +#include "blaze/gemm/block/block_mmad.h" | ||
| 30 | +#include "blaze/gemm/policy/dispatch_policy.h" | ||
| 31 | +#include "blaze/gemm/tile/copy_gm_to_l1.h" | ||
| 32 | +#include "blaze/gemm/utils/buffer_manager.h" | ||
| 33 | +#include "blaze/gemm/utils/common_utils.h" | ||
| 34 | +#include "blaze/gemm/utils/layout_utils.h" | ||
| 35 | + | ||
| 36 | +namespace Blaze::Gemm::Block { | ||
| 37 | + | ||
| 38 | +template <uint64_t AivNum_, uint32_t UbMte2InnerSize_, uint32_t UbMte2BufNum_, QuantMode AntiquantType_, | ||
| 39 | + bool HasAntiquantOffset_, class AType_, class LayoutA_, class BTypeTuple_, class LayoutBTuple_, class CType_, | ||
| 40 | + class LayoutC_, class BiasType_, class LayoutBias_> | ||
| 41 | +class BlockMmad< | ||
| 42 | + MatmulWithWeightAntiquant<AivNum_, UbMte2InnerSize_, UbMte2BufNum_, AntiquantType_, HasAntiquantOffset_>, AType_, | ||
| 43 | + LayoutA_, BTypeTuple_, LayoutBTuple_, CType_, LayoutC_, BiasType_, LayoutBias_> { | ||
| 44 | +public: | ||
| 45 | + static_assert(AscendC::Std::tuple_size_v<BTypeTuple_> == 2, "B type tuple must contain weight and scale"); | ||
| 46 | + static_assert(AscendC::Std::tuple_size_v<LayoutBTuple_> == 2, "B layout tuple must contain weight and scale"); | ||
| 47 | + using DispatchPolicy = MatmulWithWeightAntiquant<AivNum_, UbMte2InnerSize_, UbMte2BufNum_, AntiquantType_, | ||
| 48 | + HasAntiquantOffset_>; | ||
| 49 | + using AType = AType_; | ||
| 50 | + using BType = typename AscendC::Std::tuple_element<0, BTypeTuple_>::type; | ||
| 51 | + using ScaleType = typename AscendC::Std::tuple_element<1, BTypeTuple_>::type; | ||
| 52 | + using CType = CType_; | ||
| 53 | + using BiasType = BiasType_; | ||
| 54 | + using LayoutA = LayoutA_; | ||
| 55 | + using LayoutB = typename AscendC::Std::tuple_element<0, LayoutBTuple_>::type; | ||
| 56 | + using LayoutScale = typename AscendC::Std::tuple_element<1, LayoutBTuple_>::type; | ||
| 57 | + using LayoutC = LayoutC_; | ||
| 58 | + using LayoutBias = LayoutBias_; | ||
| 59 | + using L1TileShape = asc::te::shape<int64_t, int64_t, int64_t, int64_t>; | ||
| 60 | + using L0TileShape = asc::te::shape<int64_t, int64_t, int64_t>; | ||
| 61 | + | ||
| 62 | + static_assert(AscendC::Std::is_same_v<AType, half> || AscendC::Std::is_same_v<AType, bfloat16_t>, | ||
| 63 | + "WQMM Blaze requires FP16/BF16 A"); | ||
| 64 | + static_assert(AscendC::Std::is_same_v<CType, half> || AscendC::Std::is_same_v<CType, bfloat16_t>, | ||
| 65 | + "WQMM Blaze requires FP16/BF16 C"); | ||
| 66 | + static_assert(AscendC::Std::is_same_v<BType, int8_t> || AscendC::Std::is_same_v<BType, float8_e4m3_t> || | ||
| 67 | + AscendC::Std::is_same_v<BType, hifloat8_t>, | ||
| 68 | + "WQMM Blaze requires int8/FP8 E4M3/HiFloat8 B"); | ||
| 69 | + static_assert(AscendC::Std::is_same_v<ScaleType, AType>, | ||
| 70 | + "WQMM Blaze requires antiquant scale/offset type to match A"); | ||
| 71 | + | ||
| 72 | + struct Params { | ||
| 73 | + GM_ADDR aGmAddr{nullptr}; | ||
| 74 | + GM_ADDR cGmAddr{nullptr}; | ||
| 75 | + GM_ADDR biasGmAddr{nullptr}; | ||
| 76 | + L1TileShape l1TileShape; | ||
| 77 | + L0TileShape l0TileShape; | ||
| 78 | + bool hasBias{false}; | ||
| 79 | + uint64_t kSize{0}; | ||
| 80 | + }; | ||
| 81 | + | ||
| 82 | + __aicore__ inline BlockMmad() = default; | ||
| 83 | + | ||
| 84 | + __aicore__ inline ~BlockMmad() | ||
| 85 | + { | ||
| 86 | + if ASCEND_IS_AIC { | ||
| 87 | + AscendC::SetMMLayoutTransform(false); | ||
| 88 | + } | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + __aicore__ inline void Init(const Params& params) | ||
| 92 | + { | ||
| 93 | + kSize_ = params.kSize; | ||
| 94 | + hasBias_ = params.hasBias; | ||
| 95 | + nBase_ = static_cast<uint64_t>(asc::te::get<MNK_N>(params.l1TileShape)); | ||
| 96 | + kL1Size_ = static_cast<uint64_t>(asc::te::get<3>(params.l1TileShape)); | ||
| 97 | + kL0Size_ = static_cast<uint64_t>(asc::te::get<MNK_K>(params.l0TileShape)); | ||
| 98 | + nL0Size_ = static_cast<uint64_t>(asc::te::get<MNK_N>(params.l0TileShape)); | ||
| 99 | + kTileCount_ = CeilDiv(kSize_, kL1Size_); | ||
| 100 | + aTilesPerBank_ = CeilDiv(kTileCount_, DOUBLE_BUFFER_COUNT); | ||
| 101 | + // Load the complete x tile when KaL1 exceeds KbL1, including K tails. | ||
| 102 | + aFullLoad_ = static_cast<uint64_t>(asc::te::get<2>(params.l1TileShape)) > kL1Size_; | ||
| 103 | + InitBufferSlots(); | ||
| 104 | + | ||
| 105 | + if ASCEND_IS_AIV { | ||
| 106 | + return; | ||
| 107 | + } | ||
| 108 | + AscendC::SetMMLayoutTransform(true); | ||
这个函数可以放到构造函数,和析构函数对应上 ![]() ![]() | |||
| 109 | + } | ||
| 110 | + | ||
| 111 | + template <typename MemoryLocation, typename DType> | ||
| 112 | + __aicore__ inline auto GetShareMemPtr(uint32_t bufferId) const | ||
| 113 | + { | ||
| 114 | + static_assert(AscendC::Std::is_same_v<MemoryLocation, asc::te::location::l1>, | ||
| 115 | + "WQMM shared weight memory must be in L1"); | ||
| 116 | + static_assert(AscendC::Std::is_same_v<DType, AType>, | ||
| 117 | + "WQMM shared weight type must match the antiquant output type"); | ||
| 118 | + return asc::te::make_mem_ptr<MemoryLocation, DType>(bL1Slots_[bufferId].Addr()); | ||
| 119 | + } | ||
| 120 | + | ||
| 121 | + template <class TensorA, class TensorBias, class TensorC, class Shape> | ||
| 122 | + __aicore__ inline void operator()(const TensorA& tensorA, const TensorBias& tensorBias, TensorC& tensorC, | ||
| 123 | + const Shape& actualShape) | ||
| 124 | + { | ||
| 125 | + mL1Size_ = static_cast<uint64_t>(asc::te::get<MNK_M>(actualShape)); | ||
| 126 | + nL1Size_ = static_cast<uint64_t>(asc::te::get<MNK_N>(actualShape)); | ||
| 127 | + if (aFullLoad_) { | ||
| 128 | + const bool interleaved = CanInterleaveFullA(); | ||
| 129 | + const auto& aSlot0 = aL1Slots_[0U]; | ||
| 130 | + const auto& aSlot1 = aL1Slots_[1U]; | ||
| 131 | + { | ||
| 132 | + auto aWrite0 = aSlot0.LockMte2(); | ||
| 133 | + auto aWrite1 = aSlot1.LockMte2(); | ||
| 134 | + CopyFullAToL1(tensorA, interleaved); | ||
| 135 | + CopyBiasToL1(tensorBias, cvLoopIdx_ & 1U); | ||
| 136 | + } | ||
| 137 | + { | ||
| 138 | + // Full x loading reserves both buffers until all K/L0 reads of this M/N tile finish. | ||
| 139 | + auto aRead0 = aSlot0.LockMte1(); | ||
| 140 | + auto aRead1 = aSlot1.LockMte1(); | ||
| 141 | + RunKLoop<true>(tensorA, tensorBias, interleaved); | ||
| 142 | + } | ||
| 143 | + } else { | ||
| 144 | + RunKLoop<false>(tensorA, tensorBias, false); | ||
| 145 | + } | ||
| 146 | + CopyCToGm(tensorC); | ||
| 147 | + } | ||
| 148 | + | ||
| 149 | +private: | ||
| 150 | + using SyncProtocol = typename DispatchPolicy::SyncProtocol; | ||
| 151 | + using MakeAL1Layout = asc::te::frame_layout_format<asc::te::nz_layout_ptn, asc::te::layout_trait_default<AType>>; | ||
| 152 | + // LayoutB uses (N,K) coordinates for weight: ND stores N x K, DN stores K x N. | ||
| 153 | + // The L1 layout describes the logical (K,N) matrix used by MMAD. | ||
| 154 | + using MakeBL1Layout = AscendC::Std::conditional_t< | ||
| 155 | + !IsTrans<LayoutB>::value, | ||
| 156 | + asc::te::frame_layout_format<asc::te::zn_layout_ptn, asc::te::layout_trait_default<AType>>, | ||
| 157 | + asc::te::frame_layout_format<asc::te::nz_layout_ptn, asc::te::layout_trait_default<AType>>>; | ||
| 158 | + | ||
| 159 | + __aicore__ inline void InitBufferSlots() | ||
| 160 | + { | ||
| 161 | + // Keep the L1 bias reservation consistent with Kernel::PreloadA. | ||
| 162 | + constexpr uint64_t BIAS_L1_BYTES = 4096UL; | ||
| 163 | + const uint64_t weightBytes = nBase_ * kL1Size_ * sizeof(AType); | ||
| 164 | + const uint64_t biasBytes = hasBias_ ? BIAS_L1_BYTES : 0UL; | ||
| 165 | + const uint64_t aL1Base = weightBytes + biasBytes; | ||
| 166 | + aHalfBytes_ = AscendC::TOTAL_L1_SIZE / DOUBLE_BUFFER_COUNT - aL1Base; | ||
| 167 | + // L1 regions: weight0 | bias0 | x0 | x1 | bias1 | weight1. All offsets are bytes. | ||
| 168 | + for (uint32_t i = 0; i < DOUBLE_BUFFER_COUNT; ++i) { | ||
| 169 | + uint8_t bufferId = BufferLayout::L1ADataBufferId(i); | ||
| 170 | + aL1Slots_[i] = {aL1Base + i * aHalfBytes_, bufferId}; | ||
| 171 | + bL1Slots_[i] = {i * (AscendC::TOTAL_L1_SIZE - weightBytes), bufferId}; | ||
| 172 | + if (hasBias_) { | ||
| 173 | + biasL1Slots_[i] = {i == 0 ? weightBytes : AscendC::TOTAL_L1_SIZE - weightBytes - biasBytes, bufferId}; | ||
| 174 | + } | ||
| 175 | + btSlots_[i] = {nL0Size_ * sizeof(float) * i, BufferLayout::BTBufferId(i)}; | ||
| 176 | + l0Slots_[i] = {(AscendC::TOTAL_L0A_SIZE / DOUBLE_BUFFER_COUNT) * i, BufferLayout::L0BufferId(i)}; | ||
| 177 | + } | ||
| 178 | + l0cSlot_ = {0UL, BufferLayout::L0CBufferId(0U)}; | ||
| 179 | + } | ||
| 180 | + | ||
| 181 | + __aicore__ inline bool CanInterleaveFullA() const | ||
| 182 | + { | ||
| 183 | + const uint64_t maxHalfBytes = aTilesPerBank_ * kL1Size_ * CeilAlign(mL1Size_, BLOCK_CUBE) * sizeof(AType); | ||
| 184 | + return !IsTrans<LayoutA>::value && kSize_ % kL1Size_ == 0 && maxHalfBytes <= aHalfBytes_; | ||
| 185 | + } | ||
| 186 | + | ||
| 187 | + template <typename TensorA> | ||
| 188 | + __aicore__ inline void CopyFullAToL1(const TensorA& tensorA, bool interleaved) | ||
| 189 | + { | ||
| 190 | + auto copyGM2L1 = asc::te::make_copy(asc::te::copy_gm_to_l1{}); | ||
| 191 | + if (!interleaved) { | ||
| 192 | + auto l1A = asc::te::make_tensor(asc::te::make_mem_ptr<asc::te::location::l1, AType>(aL1Slots_[0U].Addr()), | ||
| 193 | + MakeAL1Layout{}(mL1Size_, kSize_)); | ||
| 194 | + asc::te::copy(copyGM2L1, l1A, tensorA); | ||
| 195 | + return; | ||
| 196 | + } | ||
| 197 | + | ||
| 198 | + for (uint32_t parity = 0; parity < DOUBLE_BUFFER_COUNT; ++parity) { | ||
| 199 | + const uint64_t count = parity == 0 ? aTilesPerBank_ : kTileCount_ - aTilesPerBank_; | ||
| 200 | + if (count == 0) { | ||
| 201 | + continue; | ||
| 202 | + } | ||
| 203 | + auto gmTile = tensorA.slice(asc::te::make_coord(0UL, parity * kL1Size_), | ||
| 204 | + asc::te::make_shape(mL1Size_, kL1Size_)); | ||
| 205 | + auto gmLayout = gmTile.layout(); | ||
| 206 | + using GmPattern = asc::te::get_layout_pattern<typename TensorA::layout_type>; | ||
| 207 | + auto batchGmLayout = asc::te::make_pattern_layout<GmPattern, asc::te::layout_trait_default<AType>>( | ||
| 208 | + asc::te::make_shape(count, gmLayout.shape()), | ||
| 209 | + asc::te::make_stride(DOUBLE_BUFFER_COUNT * kL1Size_, gmLayout.stride())); | ||
| 210 | + auto gmBatch = asc::te::make_tensor(gmTile.data(), batchGmLayout); | ||
| 211 | + auto l1Layout = MakeAL1Layout{}(mL1Size_, kL1Size_); | ||
| 212 | + auto batchL1Layout = asc::te::make_pattern_layout<asc::te::nz_layout_ptn, | ||
| 213 | + asc::te::layout_trait_default<AType>>( | ||
| 214 | + asc::te::make_shape(count, l1Layout.shape()), | ||
| 215 | + asc::te::make_stride(CeilAlign(mL1Size_, BLOCK_CUBE) * kL1Size_, l1Layout.stride())); | ||
| 216 | + const uint64_t bank = (cvLoopIdx_ + parity) & 1U; | ||
| 217 | + auto l1Batch = asc::te::make_tensor( | ||
| 218 | + asc::te::make_mem_ptr<asc::te::location::l1, AType>(aL1Slots_[bank].Addr()), batchL1Layout); | ||
| 219 | + asc::te::copy(copyGM2L1, l1Batch, gmBatch); | ||
| 220 | + } | ||
| 221 | + } | ||
| 222 | + | ||
| 223 | + template <typename TensorBias> | ||
| 224 | + __aicore__ inline void CopyBiasToL1(const TensorBias& tensorBias, uint64_t bank) | ||
| 225 | + { | ||
| 226 | + if (hasBias_) { | ||
| 227 | + auto biasLayout = asc::te::make_frame_layout<asc::te::nd_ext_layout_ptn>(1UL, nL1Size_); | ||
| 228 | + auto l1Bias = asc::te::make_tensor( | ||
| 229 | + asc::te::make_mem_ptr<asc::te::location::l1, BiasType>(biasL1Slots_[bank].Addr()), biasLayout); | ||
| 230 | + asc::te::copy(asc::te::make_copy(asc::te::copy_gm_to_l1{}), l1Bias, tensorBias); | ||
| 231 | + } | ||
| 232 | + } | ||
| 233 | + | ||
| 234 | + template <bool FullLoad, typename TensorA, typename TensorBias> | ||
| 235 | + __aicore__ inline void RunKLoop(const TensorA& tensorA, const TensorBias& tensorBias, bool interleaved) | ||
| 236 | + { | ||
| 237 | + for (uint64_t kLoopIdx = 0; kLoopIdx < kTileCount_; ++kLoopIdx, ++cvLoopIdx_) { | ||
| 238 | + const uint64_t kOffset = kLoopIdx * kL1Size_; | ||
| 239 | + const uint64_t kL1Size = Min(kL1Size_, kSize_ - kOffset); | ||
| 240 | + if constexpr (!FullLoad) { | ||
| 241 | + auto tensorATile = tensorA.slice(asc::te::make_coord(0UL, kOffset), | ||
| 242 | + asc::te::make_shape(mL1Size_, kL1Size)); | ||
| 243 | + CopyAAndBiasToL1(tensorATile, tensorBias, kOffset, kL1Size, cvLoopIdx_); | ||
| 244 | + } | ||
| 245 | + WaitConvertedWeight(); | ||
| 246 | + if (FullLoad && !interleaved) { | ||
| 247 | + auto fullAL1 = asc::te::make_tensor( | ||
| 248 | + asc::te::make_mem_ptr<asc::te::location::l1, AType>(aL1Slots_[0U].Addr()), | ||
| 249 | + MakeAL1Layout{}(mL1Size_, kSize_)); | ||
| 250 | + auto tileAL1 = fullAL1.slice(asc::te::make_coord(0UL, kOffset), asc::te::make_shape(mL1Size_, kL1Size)); | ||
| 251 | + IterateMmad<FullLoad>(tileAL1, kOffset, kL1Size); | ||
| 252 | + } else { | ||
| 253 | + auto tileAL1 = asc::te::make_tensor( | ||
| 254 | + asc::te::make_mem_ptr<asc::te::location::l1, AType>(CurrentAOffset(kOffset, interleaved)), | ||
| 255 | + MakeAL1Layout{}(mL1Size_, kL1Size)); | ||
| 256 | + IterateMmad<FullLoad>(tileAL1, kOffset, kL1Size); | ||
| 257 | + } | ||
| 258 | + ReleaseConvertedWeight(); | ||
| 259 | + } | ||
| 260 | + } | ||
| 261 | + | ||
| 262 | + template <typename TensorA, typename TensorBias> | ||
| 263 | + __aicore__ inline void CopyAAndBiasToL1(const TensorA& tensorA, const TensorBias& tensorBias, uint64_t kOffset, | ||
| 264 | + uint64_t kL1Size, uint64_t loopIdx) | ||
| 265 | + { | ||
| 266 | + uint64_t bank = loopIdx & 1U; | ||
| 267 | + const auto& l1DataSlot = aL1Slots_[bank]; | ||
| 268 | + auto l1A = asc::te::make_tensor(asc::te::make_mem_ptr<asc::te::location::l1, AType>(l1DataSlot.Addr()), | ||
| 269 | + MakeAL1Layout{}(mL1Size_, kL1Size)); | ||
| 270 | + auto copyGM2L1 = asc::te::make_copy(asc::te::copy_gm_to_l1{}); | ||
| 271 | + auto l1DataLock = l1DataSlot.LockMte2(); | ||
| 272 | + asc::te::copy(copyGM2L1, l1A, tensorA); | ||
| 273 | + | ||
| 274 | + if (kOffset == 0) { | ||
| 275 | + CopyBiasToL1(tensorBias, bank); | ||
| 276 | + } | ||
| 277 | + } | ||
| 278 | + | ||
| 279 | + __aicore__ inline uint64_t CurrentAOffset(uint64_t kOffset, bool interleaved) const | ||
| 280 | + { | ||
| 281 | + uint64_t bank = cvLoopIdx_ & 1U; | ||
| 282 | + uint64_t offset = aL1Slots_[bank].Addr(); | ||
| 283 | + if (interleaved) { | ||
| 284 | + offset += (kOffset / (kL1Size_ * 2U)) * CeilAlign(mL1Size_, BLOCK_CUBE) * kL1Size_ * sizeof(AType); | ||
| 285 | + } | ||
| 286 | + return offset; | ||
| 287 | + } | ||
| 288 | + | ||
| 289 | + template <bool AL1AlreadyLocked, typename TensorAL1> | ||
| 290 | + __aicore__ inline void IterateMmad(const TensorAL1& tensorAL1, uint64_t kOffset, uint64_t kL1Size) | ||
| 291 | + { | ||
| 292 | + uint64_t bank = cvLoopIdx_ & 1U; | ||
| 293 | + auto tensorBL1 = asc::te::make_tensor( | ||
| 294 | + asc::te::make_mem_ptr<asc::te::location::l1, AType>(bL1Slots_[bank].Addr()), | ||
| 295 | + MakeBL1Layout{}(kL1Size, nL1Size_)); | ||
| 296 | + auto tensorL0C = asc::te::make_tensor( | ||
| 297 | + asc::te::make_mem_ptr<asc::te::location::l0c, float>(l0cSlot_.Addr()), | ||
| 298 | + asc::te::frame_layout_format<asc::te::nz_layout_ptn, asc::te::_16>{}(mL1Size_, nL1Size_)); | ||
| 299 | + | ||
| 300 | + uint64_t kL0Count = CeilDiv(kL1Size, kL0Size_); | ||
| 301 | + for (uint64_t kL0Idx = 0; kL0Idx < kL0Count; ++kL0Idx) { | ||
| 302 | + uint64_t kL0Offset = kL0Idx * kL0Size_; | ||
| 303 | + uint64_t kL0Size = Min(kL0Size_, kL1Size - kL0Offset); | ||
| 304 | + uint64_t l0Buffer = l0LoopIdx_ & 1U; | ||
| 305 | + const auto& l0Slot = l0Slots_[l0Buffer]; | ||
| 306 | + const auto& btSlot = btSlots_[l0Buffer]; | ||
| 307 | + uint64_t l0Offset = l0Slot.Addr(); | ||
| 308 | + auto tensorAL0 = asc::te::make_tensor( | ||
| 309 | + asc::te::make_mem_ptr<asc::te::location::l0a, AType>(l0Offset), | ||
| 310 | + asc::te::make_frame_layout<asc::te::nz_layout_ptn, asc::te::layout_trait_default<AType>>(mL1Size_, | ||
| 311 | + kL0Size)); | ||
| 312 | + auto tensorBL0 = asc::te::make_tensor( | ||
| 313 | + asc::te::make_mem_ptr<asc::te::location::l0b, AType>(l0Offset), | ||
| 314 | + asc::te::make_frame_layout<asc::te::zn_layout_ptn, asc::te::layout_trait_default<AType>>(kL0Size, | ||
| 315 | + nL1Size_)); | ||
| 316 | + auto aSlice = tensorAL1.slice(asc::te::make_coord(0UL, kL0Offset), asc::te::make_shape(mL1Size_, kL0Size)); | ||
| 317 | + auto bSlice = tensorBL1.slice(asc::te::make_coord(kL0Offset, 0UL), asc::te::make_shape(kL0Size, nL1Size_)); | ||
| 318 | + | ||
| 319 | + auto tensorBiasL0 = asc::te::make_tensor( | ||
| 320 | + asc::te::make_mem_ptr<asc::te::location::bias, float>(btSlot.Addr()), | ||
| 321 | + asc::te::make_frame_layout<asc::te::nd_ext_layout_ptn>(1UL, CeilAlign(nL1Size_, BLOCK_CUBE))); | ||
| 322 | + bool needBias = hasBias_ && kOffset == 0 && kL0Idx == 0; | ||
| 323 | + auto copyL1ToL0 = [&]() __aicore__ { | ||
| 324 | + auto l0Lock = l0Slot.LockMte1(); | ||
| 325 | + asc::te::copy(asc::te::make_copy(asc::te::copy_l1_to_l0a{}), tensorAL0, aSlice); | ||
| 326 | + asc::te::copy(asc::te::make_copy(asc::te::copy_l1_to_l0b{}), tensorBL0, bSlice); | ||
| 327 | + if (needBias) { | ||
| 328 | + auto tensorBiasL1 = asc::te::make_tensor( | ||
| 329 | + asc::te::make_mem_ptr<asc::te::location::l1, BiasType>(biasL1Slots_[bank].Addr()), | ||
| 330 | + asc::te::make_frame_layout<asc::te::nd_ext_layout_ptn>(1UL, nL1Size_)); | ||
| 331 | + auto btLock = btSlot.LockMte1(); | ||
| 332 | + asc::te::copy(asc::te::make_copy(asc::te::copy_l1_to_biastable{}), tensorBiasL0, tensorBiasL1); | ||
| 333 | + } | ||
| 334 | + }; | ||
| 335 | + if constexpr (AL1AlreadyLocked) { | ||
| 336 | + copyL1ToL0(); | ||
| 337 | + } else { | ||
| 338 | + auto l1DataLock = aL1Slots_[bank].LockMte1(); | ||
| 339 | + copyL1ToL0(); | ||
| 340 | + } | ||
| 341 | + | ||
| 342 | + uint8_t unitFlag = kOffset + kL0Offset + kL0Size == kSize_ ? FINAL_ACCUMULATION : NON_FINAL_ACCUMULATION; | ||
| 343 | + bool initC = kOffset == 0 && kL0Idx == 0 && !hasBias_; | ||
| 344 | + asc::te::mmad_params mmParams{static_cast<uint16_t>(mL1Size_), static_cast<uint16_t>(nL1Size_), | ||
| 345 | + static_cast<uint16_t>(kL0Size), | ||
| 346 | + static_cast<asc::te::unit_flag_mode>(unitFlag), initC}; | ||
| 347 | + constexpr auto mmAtom = asc::te::make_mmad(asc::te::mmad_operation{}, asc::te::mmad_trait_default{}); | ||
| 348 | + auto l0Lock = l0Slot.LockM(); | ||
| 349 | + auto l0cLock = l0cSlot_.LockM(); | ||
| 350 | + if (needBias) { | ||
| 351 | + auto btLock = btSlot.LockM(); | ||
| 352 | + asc::te::mmad(mmAtom.with(mmParams), tensorL0C, tensorAL0, tensorBL0, tensorBiasL0); | ||
| 353 | + } else { | ||
| 354 | + asc::te::mmad(mmAtom.with(mmParams), tensorL0C, tensorAL0, tensorBL0); | ||
| 355 | + } | ||
| 356 | + ++l0LoopIdx_; | ||
| 357 | + } | ||
| 358 | + } | ||
| 359 | + | ||
| 360 | + template <typename TensorC> | ||
| 361 | + __aicore__ inline void CopyCToGm(TensorC& tensorC) | ||
| 362 | + { | ||
| 363 | + auto l0cLock = l0cSlot_.LockFix(); | ||
| 364 | + auto tensorL0C = asc::te::make_tensor( | ||
| 365 | + asc::te::make_mem_ptr<asc::te::location::l0c, float>(l0cSlot_.Addr()), | ||
| 366 | + asc::te::frame_layout_format<asc::te::nz_layout_ptn, asc::te::_16>{}(mL1Size_, nL1Size_)); | ||
| 367 | + asc::te::l0c_to_gm_params fixParams{static_cast<asc::te::unit_flag_mode>(FINAL_ACCUMULATION)}; | ||
| 368 | + asc::te::copy(asc::te::make_copy(asc::te::copy_l0c_to_gm{}).with(fixParams), tensorC, tensorL0C); | ||
| 369 | + } | ||
| 370 | + | ||
| 371 | + __aicore__ inline void WaitConvertedWeight() { WaitWeightFlag<SyncProtocol::AIV_READY_FLAG>(); } | ||
| 372 | + | ||
| 373 | + __aicore__ inline void ReleaseConvertedWeight() { SetWeightFlag<SyncProtocol::AIC_FREE_FLAG>(); } | ||
| 374 | + | ||
| 375 | + template <uint16_t FLAG> | ||
| 376 | + __aicore__ inline void WaitWeightFlag() const | ||
| 377 | + { | ||
| 378 | + if constexpr (AivNum_ == 2) { | ||
| 379 | + AscendC::CrossCoreWaitFlag<SyncProtocol::MODE, PIPE_MTE1>(FLAG + SyncProtocol::FLAG_ID_MAX); | ||
| 380 | + } | ||
| 381 | + AscendC::CrossCoreWaitFlag<SyncProtocol::MODE, PIPE_MTE1>(FLAG); | ||
| 382 | + } | ||
| 383 | + | ||
| 384 | + template <uint16_t FLAG> | ||
| 385 | + __aicore__ inline void SetWeightFlag() const | ||
| 386 | + { | ||
| 387 | + if constexpr (AivNum_ == 2) { | ||
| 388 | + AscendC::CrossCoreSetFlag<SyncProtocol::MODE, PIPE_MTE1>(FLAG + SyncProtocol::FLAG_ID_MAX); | ||
| 389 | + } | ||
| 390 | + AscendC::CrossCoreSetFlag<SyncProtocol::MODE, PIPE_MTE1>(FLAG); | ||
| 391 | + } | ||
| 392 | + | ||
| 393 | + static constexpr uint64_t DOUBLE_BUFFER_COUNT = 2UL; | ||
| 394 | + using BufferLayout = BufferIdLayout<DOUBLE_BUFFER_COUNT, DOUBLE_BUFFER_COUNT, DOUBLE_BUFFER_COUNT>; | ||
| 395 | + | ||
| 396 | + uint64_t kSize_{0}; | ||
| 397 | + uint64_t nBase_{0}; | ||
| 398 | + uint64_t kL1Size_{0}; | ||
| 399 | + uint64_t kL0Size_{0}; | ||
| 400 | + uint64_t nL0Size_{0}; | ||
| 401 | + uint64_t kTileCount_{0}; | ||
| 402 | + uint64_t aTilesPerBank_{0}; | ||
| 403 | + uint64_t aHalfBytes_{0}; | ||
| 404 | + uint64_t mL1Size_{0}; | ||
| 405 | + uint64_t nL1Size_{0}; | ||
| 406 | + uint64_t l0LoopIdx_{0}; | ||
| 407 | + uint64_t cvLoopIdx_{0}; | ||
| 408 | + bool hasBias_{false}; | ||
| 409 | + bool aFullLoad_{false}; | ||
| 410 | + BufferSlot aL1Slots_[DOUBLE_BUFFER_COUNT]; | ||
| 411 | + BufferSlot bL1Slots_[DOUBLE_BUFFER_COUNT]; | ||
| 412 | + BufferSlot biasL1Slots_[DOUBLE_BUFFER_COUNT]; | ||
| 413 | + BufferSlot btSlots_[DOUBLE_BUFFER_COUNT]; | ||
| 414 | + BufferSlot l0Slots_[DOUBLE_BUFFER_COUNT]; // L0A/L0B share offsets and synchronization IDs. | ||
| 415 | + BufferSlot l0cSlot_; // Only one accumulator buffer is used. | ||
| 416 | +}; | ||
| 417 | + | ||
| 418 | +} // namespace Blaze::Gemm::Block | ||
| @@ -0,0 +1,172 @@ | |||
| 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 block_scheduler_wqmm.h | ||
| 13 | + * \brief 3-segment N-axis scheduler: mainBlock + firstTailBlock + secondTailBlock with tail resplit. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#pragma once | ||
| 17 | + | ||
| 18 | +#include "blaze/gemm/utils/common_utils.h" | ||
| 19 | + | ||
| 20 | +namespace Blaze { | ||
| 21 | +namespace Gemm { | ||
| 22 | +namespace Block { | ||
| 23 | + | ||
| 24 | +// Partition M across cores and distribute precomputed N main/first-tail/second-tail ranges. | ||
| 25 | +// Coordinates and valid lengths use elements; K traversal belongs to the kernel and BlockMmad. | ||
| 26 | +template <class ProblemShape_> | ||
| 27 | +class BlockSchedulerWqmmTailResplit { | ||
| 28 | +private: | ||
| 29 | + using BlockNums = asc::te::shape<uint64_t, uint64_t, uint64_t, uint64_t>; | ||
| 30 | + static constexpr uint32_t N_RANGE_MAIN = 0; // N0: main blocks. | ||
| 31 | + static constexpr uint32_t N_RANGE_FIRST_TAIL = 1; // N1: first tail blocks. | ||
| 32 | + static constexpr uint32_t N_RANGE_SECOND_TAIL = 2; // N2: second tail blocks after resplitting. | ||
| 33 | + | ||
| 34 | +public: | ||
| 35 | + struct Params { | ||
| 36 | + int64_t mL1Tile{0}; | ||
| 37 | + uint64_t mainBlockCount{0}; | ||
| 38 | + uint64_t firstTailBlockCount{0}; | ||
| 39 | + uint64_t secondTailBlockCount{0}; | ||
| 40 | + uint64_t mainBlockSize{0}; | ||
| 41 | + uint64_t firstTailBlockSize{0}; | ||
| 42 | + uint64_t secondTailBlockSize{0}; | ||
| 43 | + uint64_t cubeNumBlocksM{0}; | ||
| 44 | + uint64_t cubeNumBlocksN{0}; | ||
| 45 | + }; | ||
| 46 | + | ||
| 47 | + __aicore__ inline BlockSchedulerWqmmTailResplit(const ProblemShape_& problemShape, const Params& params) | ||
| 48 | + { | ||
| 49 | + uint64_t mSize = static_cast<uint64_t>(asc::te::get<0>(problemShape)); | ||
| 50 | + nSize_ = static_cast<uint64_t>(asc::te::get<1>(problemShape)); | ||
| 51 | + if ASCEND_IS_AIC { | ||
| 52 | + blockIdx_ = static_cast<uint64_t>(AscendC::GetBlockIdx()); | ||
| 53 | + } else { | ||
| 54 | + blockIdx_ = static_cast<uint64_t>(AscendC::GetBlockIdx()) / AscendC::GetSubBlockNum(); | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + auto singleCoreM = CeilDiv(mSize, params.cubeNumBlocksM); | ||
| 58 | + mStart_ = blockIdx_ / params.cubeNumBlocksN * singleCoreM; | ||
| 59 | + mTile_ = params.mL1Tile; | ||
| 60 | + mStop_ = Min(mStart_ + singleCoreM, mSize); | ||
| 61 | + coreNums_ = params.cubeNumBlocksM * params.cubeNumBlocksN; | ||
| 62 | + | ||
| 63 | + nDimIdx_ = blockIdx_ % params.cubeNumBlocksN; | ||
| 64 | + cubeNumBlocksN_ = params.cubeNumBlocksN; | ||
| 65 | + mainBlockCount_ = params.mainBlockCount; | ||
| 66 | + firstTailBlockCount_ = params.firstTailBlockCount; | ||
| 67 | + secondTailBlockCount_ = params.secondTailBlockCount; | ||
| 68 | + | ||
| 69 | + n0Tile_ = params.mainBlockSize; | ||
| 70 | + n0Stop_ = Min(mainBlockCount_ * n0Tile_, nSize_); | ||
| 71 | + | ||
| 72 | + n1Tile_ = params.firstTailBlockSize; | ||
| 73 | + n1Stop_ = Min(mainBlockCount_ * n0Tile_ + firstTailBlockCount_ * n1Tile_, nSize_); | ||
| 74 | + | ||
| 75 | + n2Tile_ = params.secondTailBlockSize; | ||
| 76 | + firstN2BlockIdx_ = (nDimIdx_ + cubeNumBlocksN_ - firstTailBlockCount_ % cubeNumBlocksN_) % cubeNumBlocksN_; | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + __aicore__ inline BlockNums GetBlockNums() const | ||
| 80 | + { | ||
| 81 | + uint64_t mBlockNum = mStart_ < mStop_ ? CeilDiv(mStop_ - mStart_, mTile_) : 0UL; | ||
| 82 | + uint64_t n0BlockNum = GetDistributedBlockNum(mainBlockCount_, nDimIdx_); | ||
| 83 | + uint64_t n1BlockNum = GetDistributedBlockNum(firstTailBlockCount_, nDimIdx_); | ||
| 84 | + uint64_t n2BlockNum = GetDistributedBlockNum(secondTailBlockCount_, firstN2BlockIdx_); | ||
| 85 | + return asc::te::make_shape(mBlockNum, n0BlockNum, n1BlockNum, n2BlockNum); | ||
| 86 | + } | ||
| 87 | + | ||
| 88 | + __aicore__ inline uint64_t GetCoreNums() const { return coreNums_; } | ||
| 89 | + | ||
| 90 | + // Return a scalar because only the M-axis coordinate is needed; no Coord tuple is necessary. | ||
| 91 | + __aicore__ inline uint64_t GetBlockCoordM(uint64_t mIdx) const { return mStart_ + mIdx * mTile_; } | ||
| 92 | + | ||
| 93 | + // Return a scalar because only the M-axis length is needed; no Shape tuple is necessary. | ||
| 94 | + __aicore__ inline uint64_t GetBlockShapeM(uint64_t coordM) const | ||
GetBlockShape是同样的问题,当前对外应该是统一的两个函数,GetBlockShape返回各个维度的大小,GetBlockCoord返回各个维度的坐标,请参考其他block Schedule的实现 ![]() ![]() | |||
| 95 | + { | ||
| 96 | + uint64_t tileM = coordM < mStop_ ? Min(mStop_ - coordM, mTile_) : 0UL; | ||
| 97 | + return tileM; | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + // Return a scalar because only the N-axis coordinate is needed; no Coord tuple is necessary. | ||
| 101 | + template <uint32_t N_RANGE> | ||
| 102 | + __aicore__ inline uint64_t GetBlockCoordN(uint64_t nIdx) const | ||
MN的BlockCoord不能合并吗?直接返回M/N方向的坐标 ![]() ![]() | |||
| 103 | + { | ||
| 104 | + static_assert(N_RANGE <= N_RANGE_SECOND_TAIL, "N range must be main, first tail or second tail"); | ||
| 105 | + uint64_t coordN; | ||
| 106 | + if constexpr (N_RANGE == N_RANGE_MAIN) { | ||
| 107 | + coordN = (nDimIdx_ + nIdx * cubeNumBlocksN_) * n0Tile_; | ||
| 108 | + } else if constexpr (N_RANGE == N_RANGE_FIRST_TAIL) { | ||
| 109 | + coordN = n0Stop_ + (nDimIdx_ + nIdx * cubeNumBlocksN_) * n1Tile_; | ||
| 110 | + } else { | ||
| 111 | + coordN = n1Stop_ + (firstN2BlockIdx_ + nIdx * cubeNumBlocksN_) * n2Tile_; | ||
| 112 | + } | ||
| 113 | + return coordN; | ||
| 114 | + } | ||
| 115 | + | ||
| 116 | + // Return a scalar because only the N-axis length is needed; no Shape tuple is necessary. | ||
| 117 | + template <uint32_t N_RANGE> | ||
| 118 | + __aicore__ inline uint64_t GetBlockShapeN(uint64_t coordN) const | ||
| 119 | + { | ||
| 120 | + static_assert(N_RANGE <= N_RANGE_SECOND_TAIL, "N range must be main, first tail or second tail"); | ||
| 121 | + uint64_t rangeStop; | ||
| 122 | + uint64_t rangeTile; | ||
| 123 | + if constexpr (N_RANGE == N_RANGE_MAIN) { | ||
| 124 | + rangeStop = n0Stop_; | ||
| 125 | + rangeTile = n0Tile_; | ||
| 126 | + } else if constexpr (N_RANGE == N_RANGE_FIRST_TAIL) { | ||
| 127 | + rangeStop = n1Stop_; | ||
| 128 | + rangeTile = n1Tile_; | ||
| 129 | + } else { | ||
| 130 | + rangeStop = nSize_; | ||
| 131 | + rangeTile = n2Tile_; | ||
| 132 | + } | ||
| 133 | + uint64_t tileN = coordN < rangeStop ? Min(rangeStop - coordN, rangeTile) : 0UL; | ||
| 134 | + return tileN; | ||
| 135 | + } | ||
| 136 | + | ||
| 137 | +private: | ||
| 138 | + __aicore__ inline uint64_t GetDistributedBlockNum(uint64_t totalBlockNum, uint64_t firstBlockIdx) const | ||
| 139 | + { | ||
| 140 | + if (firstBlockIdx >= totalBlockNum) { | ||
| 141 | + return 0UL; | ||
| 142 | + } | ||
| 143 | + return CeilDiv(totalBlockNum - firstBlockIdx, cubeNumBlocksN_); | ||
| 144 | + } | ||
| 145 | + | ||
| 146 | + uint64_t blockIdx_; | ||
| 147 | + uint64_t coreNums_; | ||
| 148 | + uint64_t nDimIdx_; | ||
| 149 | + uint64_t cubeNumBlocksN_; | ||
| 150 | + uint64_t nSize_; | ||
| 151 | + | ||
| 152 | + uint64_t mainBlockCount_; | ||
| 153 | + uint64_t firstTailBlockCount_; | ||
| 154 | + uint64_t secondTailBlockCount_; | ||
| 155 | + uint64_t firstN2BlockIdx_; | ||
| 156 | + | ||
| 157 | + uint64_t mStart_; | ||
| 158 | + uint64_t mStop_; | ||
| 159 | + uint64_t mTile_; | ||
| 160 | + | ||
| 161 | + uint64_t n0Stop_; | ||
| 162 | + uint64_t n0Tile_; | ||
| 163 | + | ||
| 164 | + uint64_t n1Stop_; | ||
| 165 | + uint64_t n1Tile_; | ||
| 166 | + | ||
| 167 | + uint64_t n2Tile_; | ||
| 168 | +}; | ||
| 169 | + | ||
| 170 | +} // namespace Block | ||
| 171 | +} // namespace Gemm | ||
| 172 | +} // namespace Blaze | ||
| @@ -49,6 +49,7 @@ struct KernelGmmSwiGluMixMx {}; // MIX AIC+AIV schedule for Grou | |||
| 49 | struct KernelMatmulEmuSplitWeight {}; // Double bf16 matmul to simulate fp32 (AIC+AIV) | 49 | struct KernelMatmulEmuSplitWeight {}; // Double bf16 matmul to simulate fp32 (AIC+AIV) |
| 50 | struct KernelMmadWithScaleMxMix {}; // Multi-block with Mx scale, epilogue after block mmad | 50 | struct KernelMmadWithScaleMxMix {}; // Multi-block with Mx scale, epilogue after block mmad |
| 51 | struct KernelGroupedMmadNoQuant {}; // Grouped multi-block without quantization | 51 | struct KernelGroupedMmadNoQuant {}; // Grouped multi-block without quantization |
| 52 | +struct KernelMmadAPrefetchBAntiquant {}; // AIV weight dequantization and AIC matrix multiplication | ||
| 52 | enum class MatmulOutputMode : std::uint8_t { OVERWRITE = 0, INPLACE_ADD = 1 }; | 53 | enum class MatmulOutputMode : std::uint8_t { OVERWRITE = 0, INPLACE_ADD = 1 }; |
| 53 | enum class MatMulL0C2Out : std::uint8_t { ON_THE_FLY = 0, ND_FIXPIPE_1_1 = 1, ND_FIXPIPE_1_2 = 2 }; | 54 | enum class MatMulL0C2Out : std::uint8_t { ON_THE_FLY = 0, ND_FIXPIPE_1_1 = 1, ND_FIXPIPE_1_2 = 2 }; |
| 54 | 55 | ||
| @@ -273,5 +274,38 @@ struct MatmulMultiBlockFixpipeOpti { | |||
| 273 | static constexpr uint64_t FUSED_OP_TYPE = FusedOpType_; | 274 | static constexpr uint64_t FUSED_OP_TYPE = FusedOpType_; |
| 274 | }; | 275 | }; |
| 275 | 276 | ||
| 277 | +/** | ||
| 278 | + * @struct MatmulWithWeightAntiquant | ||
| 279 | + * @brief Blaze dispatch policy for 8-bit weight dequantization followed by AIC matrix multiplication. | ||
| 280 | + * @param [in] AivNum_: number of AIV sub-blocks per AIC; must be 2 | ||
| 281 | + * @param [in] UbMte2InnerSize_: weight input UB row pitch in bytes | ||
| 282 | + * @param [in] UbMte2BufNum_: number of prologue input buffers; only 2 or 4 are supported | ||
| 283 | + * @param [in] AntiquantType_: per-tensor or per-channel antiquantization | ||
| 284 | + * @param [in] HasAntiquantOffset_: whether antiquantOffset is enabled | ||
| 285 | + */ | ||
| 286 | +template <uint64_t AivNum_ = 2, uint32_t UbMte2InnerSize_ = 512, uint32_t UbMte2BufNum_ = 2, | ||
| 287 | + QuantMode AntiquantType_ = QuantMode::PERCHANNEL_MODE, bool HasAntiquantOffset_ = false> | ||
| 288 | +struct MatmulWithWeightAntiquant { | ||
| 289 | + using ScheduleType = KernelMmadAPrefetchBAntiquant; | ||
| 290 | + struct SyncProtocol { | ||
| 291 | + static constexpr uint16_t MODE = 4; | ||
| 292 | + static constexpr uint16_t AIV_READY_FLAG = 9; | ||
| 293 | + static constexpr uint16_t AIC_FREE_FLAG = 8; | ||
| 294 | + static constexpr uint16_t FLAG_ID_MAX = 16; | ||
| 295 | + }; | ||
| 296 | + | ||
| 297 | + static constexpr uint64_t AIV_NUM = AivNum_; | ||
| 298 | + static constexpr uint32_t UB_MTE2_INNER_SIZE = UbMte2InnerSize_; | ||
| 299 | + static constexpr uint32_t UB_MTE2_BUFFER_NUM = UbMte2BufNum_; | ||
| 300 | + static constexpr QuantMode ANTIQUANT_TYPE = AntiquantType_; | ||
| 301 | + static constexpr bool HAS_ANTIQUANT_OFFSET = HasAntiquantOffset_; | ||
| 302 | + | ||
| 303 | + static_assert(AivNum_ == 2, "Weight antiquantization requires two AIV sub-blocks"); | ||
| 304 | + static_assert(UbMte2BufNum_ == 2 || UbMte2BufNum_ == 4, | ||
| 305 | + "Weight antiquantization supports only 2 or 4 UB input buffers"); | ||
| 306 | + static_assert(AntiquantType_ == QuantMode::PERTENSOR_MODE || AntiquantType_ == QuantMode::PERCHANNEL_MODE, | ||
| 307 | + "Weight antiquantization supports only per-tensor or per-channel quantization"); | ||
| 308 | +}; | ||
| 309 | + | ||
| 276 | } // namespace Gemm | 310 | } // namespace Gemm |
| 277 | } // namespace Blaze | 311 | } // namespace Blaze |
| @@ -0,0 +1,132 @@ | |||
| 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 copy_ub_to_l1.h | ||
| 13 | + * \brief FP16/BF16 UB-to-L1 copy for padded ZN and NZ source layouts. | ||
| 14 | + */ | ||
| 15 | +#pragma once | ||
| 16 | + | ||
| 17 | +#include "tensor_api/tensor.h" | ||
| 18 | +#include "blaze/gemm/utils/layout_struct.h" | ||
| 19 | + | ||
| 20 | +namespace Blaze::Gemm::Tile { | ||
| 21 | + | ||
| 22 | +// Each outer row group (ZN) or column group (NZ) must contain a contiguous span. | ||
| 23 | +// The source pattern selects the grouping; destination strides must describe | ||
| 24 | +// the same contiguous groups in L1. Only gaps may differ. Singleton | ||
| 25 | +// dimensions may have zero stride, and source/destination shapes need not match. | ||
| 26 | +// Callers provide nonempty, compatible layouts, 32-byte-aligned spans/pitches, | ||
| 27 | +// nonnegative gaps fitting the instruction fields, and sufficient buffer capacity. | ||
| 28 | +struct CopyPaddedUBToL1 { | ||
| 29 | + template <typename Traits, const Traits& traits, typename DstTensor, typename SrcTensor> | ||
| 30 | + __aicore__ inline static void Copy(const DstTensor& dst, const SrcTensor& src) | ||
| 31 | + { | ||
| 32 | + // Deduce unqualified scalars through address-space-qualified pointers; | ||
| 33 | + // Tensor element types themselves can retain CCE address-space qualifiers. | ||
| 34 | + using DstType = decltype(GetL1Scalar(dst.data().get())); | ||
| 35 | + using SrcType = decltype(GetUbScalar(src.data().get())); | ||
| 36 | + static_assert(AscendC::Std::is_same_v<DstType, SrcType>, | ||
| 37 | + "UB-to-L1 copy requires matching source and destination types"); | ||
| 38 | + static_assert(AscendC::Std::is_same_v<DstType, half> || AscendC::Std::is_same_v<DstType, bfloat16_t>, | ||
| 39 | + "UB-to-L1 copy supports only FP16/BF16 elements"); | ||
| 40 | + | ||
| 41 | + using SrcPattern = asc::te::get_layout_pattern<typename SrcTensor::layout_type>; | ||
| 42 | + constexpr bool IS_ZN_ROW_PADDING = AscendC::Std::is_same_v<SrcPattern, Blaze::Gemm::zn_row_padding_layout_ptn>; | ||
| 43 | + constexpr bool IS_NZ_COL_PADDING = AscendC::Std::is_same_v<SrcPattern, Blaze::Gemm::nz_col_padding_layout_ptn>; | ||
| 44 | + static_assert(IS_ZN_ROW_PADDING || IS_NZ_COL_PADDING, | ||
| 45 | + "UB-to-L1 copy requires a supported padding source layout"); | ||
| 46 | + | ||
| 47 | + if constexpr (IS_ZN_ROW_PADDING) { | ||
| 48 | + CopyZnRowPaddingToL1<DstType>(dst, src); | ||
| 49 | + } else if constexpr (IS_NZ_COL_PADDING) { | ||
| 50 | + CopyNzColPaddingToL1<DstType>(dst, src); | ||
| 51 | + } | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | +private: | ||
| 55 | + static constexpr int64_t BLOCK_BYTES = 32; | ||
| 56 | + | ||
| 57 | + template <typename Scalar> | ||
| 58 | + __aicore__ static Scalar GetL1Scalar(__cbuf__ Scalar*); | ||
| 59 | + | ||
| 60 | + template <typename Scalar> | ||
| 61 | + __aicore__ static Scalar GetUbScalar(__ubuf__ Scalar*); | ||
| 62 | + | ||
| 63 | + template <typename Scalar, typename DstTensor, typename SrcTensor> | ||
| 64 | + __aicore__ inline static void CopyZnRowPaddingToL1(const DstTensor& dst, const SrcTensor& src) | ||
| 65 | + { | ||
| 66 | + constexpr int64_t ELEMS_PER_BLOCK = BLOCK_BYTES / sizeof(Scalar); | ||
| 67 | + const auto srcShape = asc::te::get_shape(src.layout()); | ||
| 68 | + const auto srcStride = asc::te::get_stride(src.layout()); | ||
| 69 | + const auto dstStride = asc::te::get_stride(dst.layout()); | ||
| 70 | + | ||
| 71 | + // Each K group contains k0*n0*n1 contiguous weight elements; lengths and gaps use 32-byte units. | ||
| 72 | + const auto rowShape = AscendC::Std::get<0>(srcShape); | ||
| 73 | + const auto columnShape = AscendC::Std::get<1>(srcShape); | ||
| 74 | + const int64_t rowInnerSize = static_cast<int64_t>(AscendC::Std::get<0>(rowShape)); | ||
| 75 | + const int64_t columnInnerSize = static_cast<int64_t>(AscendC::Std::get<0>(columnShape)); | ||
| 76 | + const int64_t columnOuterSize = static_cast<int64_t>(AscendC::Std::get<1>(columnShape)); | ||
| 77 | + const int64_t blockCount = static_cast<int64_t>(AscendC::Std::get<1>(rowShape)); | ||
| 78 | + const int64_t blockLen = rowInnerSize * columnInnerSize * columnOuterSize / ELEMS_PER_BLOCK; | ||
| 79 | + const int64_t srcBlockSpan = static_cast<int64_t>(AscendC::Std::get<1>(AscendC::Std::get<0>(srcStride))) / | ||
| 80 | + ELEMS_PER_BLOCK; | ||
| 81 | + const int64_t dstBlockSpan = static_cast<int64_t>(AscendC::Std::get<1>(AscendC::Std::get<0>(dstStride))) / | ||
| 82 | + ELEMS_PER_BLOCK; | ||
| 83 | + const int64_t srcGap = srcBlockSpan - blockLen; | ||
| 84 | + const int64_t dstGap = dstBlockSpan - blockLen; | ||
| 85 | + | ||
| 86 | + asc_copy_ub2l1((__cbuf__ void*)dst.data().get(), (__ubuf__ void*)src.data().get(), | ||
| 87 | + static_cast<uint16_t>(blockCount), static_cast<uint16_t>(blockLen), | ||
| 88 | + static_cast<uint16_t>(srcGap), static_cast<uint16_t>(dstGap)); | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + template <typename Scalar, typename DstTensor, typename SrcTensor> | ||
| 92 | + __aicore__ inline static void CopyNzColPaddingToL1(const DstTensor& dst, const SrcTensor& src) | ||
| 93 | + { | ||
| 94 | + constexpr int64_t ELEMS_PER_BLOCK = BLOCK_BYTES / sizeof(Scalar); | ||
| 95 | + const auto srcShape = asc::te::get_shape(src.layout()); | ||
| 96 | + const auto srcStride = asc::te::get_stride(src.layout()); | ||
| 97 | + const auto dstStride = asc::te::get_stride(dst.layout()); | ||
| 98 | + | ||
| 99 | + // Each N group contains k0*k1*n0 contiguous weight elements; lengths and gaps use 32-byte units. | ||
| 100 | + const auto rowShape = AscendC::Std::get<0>(srcShape); | ||
| 101 | + const auto columnShape = AscendC::Std::get<1>(srcShape); | ||
| 102 | + const int64_t rowInnerSize = static_cast<int64_t>(AscendC::Std::get<0>(rowShape)); | ||
| 103 | + const int64_t rowOuterSize = static_cast<int64_t>(AscendC::Std::get<1>(rowShape)); | ||
| 104 | + const int64_t columnInnerSize = static_cast<int64_t>(AscendC::Std::get<0>(columnShape)); | ||
| 105 | + const int64_t blockCount = static_cast<int64_t>(AscendC::Std::get<1>(columnShape)); | ||
| 106 | + const int64_t blockLen = rowInnerSize * rowOuterSize * columnInnerSize / ELEMS_PER_BLOCK; | ||
| 107 | + const int64_t srcBlockSpan = static_cast<int64_t>(AscendC::Std::get<1>(AscendC::Std::get<1>(srcStride))) / | ||
| 108 | + ELEMS_PER_BLOCK; | ||
| 109 | + const int64_t dstBlockSpan = static_cast<int64_t>(AscendC::Std::get<1>(AscendC::Std::get<1>(dstStride))) / | ||
| 110 | + ELEMS_PER_BLOCK; | ||
| 111 | + const int64_t srcGap = srcBlockSpan - blockLen; | ||
| 112 | + const int64_t dstGap = dstBlockSpan - blockLen; | ||
| 113 | + | ||
| 114 | + asc_copy_ub2l1((__cbuf__ void*)dst.data().get(), (__ubuf__ void*)src.data().get(), | ||
| 115 | + static_cast<uint16_t>(blockCount), static_cast<uint16_t>(blockLen), | ||
| 116 | + static_cast<uint16_t>(srcGap), static_cast<uint16_t>(dstGap)); | ||
| 117 | + } | ||
| 118 | +}; | ||
| 119 | + | ||
| 120 | +} // namespace Blaze::Gemm::Tile | ||
| 121 | + | ||
| 122 | +namespace asc::te { | ||
| 123 | + | ||
| 124 | +template <typename Traits> | ||
| 125 | +struct copy_traits<Blaze::Gemm::Tile::CopyPaddedUBToL1, Traits> | ||
| 126 | + : public copy_traits<Blaze::Gemm::Tile::CopyPaddedUBToL1, Traits, Blaze::Gemm::Tile::CopyPaddedUBToL1, Traits> {}; | ||
| 127 | + | ||
| 128 | +template <> | ||
| 129 | +struct copy_traits<Blaze::Gemm::Tile::CopyPaddedUBToL1> | ||
| 130 | + : public copy_traits<Blaze::Gemm::Tile::CopyPaddedUBToL1, ub_to_l1_trait_default> {}; | ||
| 131 | + | ||
| 132 | +} // namespace asc::te | ||
| @@ -17,6 +17,7 @@ | |||
| 17 | #if (defined(__NPU_ARCH__) && __NPU_ARCH__ == 3510) | 17 | #if (defined(__NPU_ARCH__) && __NPU_ARCH__ == 3510) |
| 18 | #include "blaze/gemm/tile/arch35/copy_gm_to_l1.h" | 18 | #include "blaze/gemm/tile/arch35/copy_gm_to_l1.h" |
| 19 | #include "blaze/gemm/tile/arch35/copy_gm_to_ub.h" | 19 | #include "blaze/gemm/tile/arch35/copy_gm_to_ub.h" |
| 20 | +#include "blaze/gemm/tile/arch35/copy_ub_to_l1.h" | ||
| 20 | #include "blaze/gemm/tile/arch35/copy_mx_scale.h" | 21 | #include "blaze/gemm/tile/arch35/copy_mx_scale.h" |
| 21 | #include "blaze/gemm/tile/arch35/copy_weight_ub_to_l1.h" | 22 | #include "blaze/gemm/tile/arch35/copy_weight_ub_to_l1.h" |
| 22 | #endif | 23 | #endif |
| @@ -17,6 +17,54 @@ | |||
| 17 | namespace Blaze { | 17 | namespace Blaze { |
| 18 | namespace Gemm { | 18 | namespace Gemm { |
| 19 | 19 | ||
| 20 | +// FP16/BF16 weight UB layouts in logical (K,N) coordinates, shape ((k0,k1),(n0,n1)). | ||
| 21 | +// ZN: stride ((1,pitch),(k0,n0*k0)); NZ: stride ((n0,k0*n0),(1,pitch)). | ||
| 22 | +// A full tile adds one k0/n0 padding segment between groups. Tail tiles retain | ||
| 23 | +// the VF allocation pitch instead of recomputing it from the effective shape. | ||
| 24 | +struct zn_row_padding_layout_ptn {}; | ||
| 25 | +struct nz_col_padding_layout_ptn {}; | ||
| 26 | + | ||
| 27 | +// Construct the physical (K,N) region copied from FP16/BF16 UB storage. | ||
| 28 | +// groupPitch is in elements and describes the allocated VF group spacing, | ||
| 29 | +// including padding. It must not shrink when the effective tile is a tail. | ||
| 30 | +template <typename T> | ||
| 31 | +struct ZnRowPaddingUBLayout { | ||
| 32 | + static_assert(AscendC::Std::is_same_v<T, half> || AscendC::Std::is_same_v<T, bfloat16_t>, | ||
| 33 | + "ZnRowPaddingUBLayout expects FP16/BF16 elements"); | ||
| 34 | + | ||
| 35 | + __aicore__ inline auto operator()(int64_t kSize, int64_t nSize, int64_t groupPitch) const | ||
| 36 | + { | ||
| 37 | + constexpr int64_t C0 = asc::te::c0_element<T>; | ||
| 38 | + using Block = AscendC::Std::Int<C0>; | ||
| 39 | + using One = AscendC::Std::Int<1>; | ||
| 40 | + // Preserve the valid N length; align K to a 32-byte group (C0 = 16 elements). | ||
| 41 | + auto shape = asc::te::make_shape(asc::te::make_shape(Block{}, CeilDiv(kSize, C0)), | ||
| 42 | + asc::te::make_shape(One{}, nSize)); | ||
| 43 | + auto stride = asc::te::make_stride(asc::te::make_stride(One{}, groupPitch), | ||
| 44 | + asc::te::make_stride(Block{}, Block{})); | ||
| 45 | + return asc::te::make_pattern_layout<zn_row_padding_layout_ptn, asc::te::layout_trait_default<T>>(shape, stride); | ||
| 46 | + } | ||
| 47 | +}; | ||
| 48 | + | ||
| 49 | +template <typename T> | ||
| 50 | +struct NzColPaddingUBLayout { | ||
| 51 | + static_assert(AscendC::Std::is_same_v<T, half> || AscendC::Std::is_same_v<T, bfloat16_t>, | ||
| 52 | + "NzColPaddingUBLayout expects FP16/BF16 elements"); | ||
| 53 | + | ||
| 54 | + __aicore__ inline auto operator()(int64_t kSize, int64_t nSize, int64_t groupPitch) const | ||
| 55 | + { | ||
| 56 | + constexpr int64_t C0 = asc::te::c0_element<T>; | ||
| 57 | + using Block = AscendC::Std::Int<C0>; | ||
| 58 | + using One = AscendC::Std::Int<1>; | ||
| 59 | + // Preserve the valid K length; align N to a 32-byte group (C0 = 16 elements). | ||
| 60 | + auto shape = asc::te::make_shape(asc::te::make_shape(One{}, kSize), | ||
| 61 | + asc::te::make_shape(Block{}, CeilDiv(nSize, C0))); | ||
| 62 | + auto stride = asc::te::make_stride(asc::te::make_stride(Block{}, Block{}), | ||
| 63 | + asc::te::make_stride(One{}, groupPitch)); | ||
| 64 | + return asc::te::make_pattern_layout<nz_col_padding_layout_ptn, asc::te::layout_trait_default<T>>(shape, stride); | ||
| 65 | + } | ||
| 66 | +}; | ||
| 67 | + | ||
| 20 | // Layout for 8-bit weight tiles in Unified Buffer (ZN conversion path). | 68 | // Layout for 8-bit weight tiles in Unified Buffer (ZN conversion path). |
| 21 | // | 69 | // |
| 22 | // This is a specialized UB layout for 8-bit weight data. Unlike the standard | 70 | // This is a specialized UB layout for 8-bit weight data. Unlike the standard |
| @@ -0,0 +1,17 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +AddOpTestCase(weight_quant_batch_matmul "ascend950pr_9599" "") | ||
| 10 | + | ||
| 11 | +# Observe the instruction boundary without replacing Tensor API or the SDK | ||
| 12 | +# implementation. The wrapper forwards every call to the real CPU-debug stub. | ||
| 13 | +# The aggregate executable is created later. Scope this option to ascend950; | ||
| 14 | +# use a directory property to retain the framework's CMake 3.16 compatibility. | ||
| 15 | +get_filename_component(_wqmm_ut_parent "${CMAKE_CURRENT_SOURCE_DIR}/.." ABSOLUTE) | ||
| 16 | +set_property(DIRECTORY "${_wqmm_ut_parent}" APPEND PROPERTY LINK_OPTIONS | ||
| 17 | + "$<$<STREQUAL:$<TARGET_PROPERTY:NAME>,ops_tensor_kernel_ut_ascend950>:LINKER:--wrap=_Z17copy_ubuf_to_cbufPvS_htttt>") | ||
| @@ -0,0 +1,87 @@ | |||
| 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 test_weight_quant_batch_matmul.cpp | ||
| 13 | + * \brief Production template instantiation and public L1 bank address checks. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "gtest/gtest.h" | ||
| 17 | +#include "blaze_kernel_stub.h" | ||
| 18 | +#include "tikicpulib.h" | ||
| 19 | +#include "kernel_operator.h" | ||
| 20 | + | ||
| 21 | +#include "blaze/gemm/tile/datamove.h" | ||
| 22 | +#include "blaze/gemm/utils/layout_struct.h" | ||
| 23 | +#include "weight_quant_batch_matmul.h" | ||
| 24 | + | ||
| 25 | +namespace { | ||
| 26 | + | ||
| 27 | +using Blaze::Gemm::QuantMode; | ||
| 28 | +using namespace WeightQuantBatchMatmulUT; | ||
| 29 | + | ||
| 30 | +using Fp16Int8 = Components<half, int8_t, half, half, 512, 2, true, QuantMode::PERCHANNEL_MODE, false, false>; | ||
| 31 | +using Fp16Int8Offset = Components<half, int8_t, half, half, 256, 4, false, QuantMode::PERTENSOR_MODE, true, true>; | ||
| 32 | +using Bf16Int8 = Components<bfloat16_t, int8_t, bfloat16_t, bfloat16_t, 1024, 2, true, QuantMode::PERCHANNEL_MODE, true, | ||
| 33 | + false>; | ||
| 34 | +using Fp16Fp8 = Components<half, float8_e4m3_t, half, half, 512, 4, false, QuantMode::PERCHANNEL_MODE, false, false>; | ||
| 35 | +using Bf16Fp8 = Components<bfloat16_t, float8_e4m3_t, bfloat16_t, bfloat16_t, 512, 2, true, QuantMode::PERTENSOR_MODE, | ||
| 36 | + false, true>; | ||
| 37 | +using Fp16HiFloat8 = Components<half, hifloat8_t, half, half, 1024, 2, true, QuantMode::PERCHANNEL_MODE, true, false>; | ||
| 38 | +using Bf16HiFloat8 = Components<bfloat16_t, hifloat8_t, bfloat16_t, bfloat16_t, 256, 4, false, | ||
| 39 | + QuantMode::PERTENSOR_MODE, false, false>; | ||
| 40 | + | ||
| 41 | +TEST(WeightQuantBatchMatmulTest, InstantiatesSupportedB8Matrix) | ||
| 42 | +{ | ||
| 43 | + ASSERT_NE(&weight_quant_batch_matmul_kernel_entry<Fp16Int8>, nullptr); | ||
| 44 | + ASSERT_NE(&weight_quant_batch_matmul_kernel_entry<Fp16Int8Offset>, nullptr); | ||
| 45 | + ASSERT_NE(&weight_quant_batch_matmul_kernel_entry<Bf16Int8>, nullptr); | ||
| 46 | + ASSERT_NE(&weight_quant_batch_matmul_kernel_entry<Fp16Fp8>, nullptr); | ||
| 47 | + ASSERT_NE(&weight_quant_batch_matmul_kernel_entry<Bf16Fp8>, nullptr); | ||
| 48 | + ASSERT_NE(&weight_quant_batch_matmul_kernel_entry<Fp16HiFloat8>, nullptr); | ||
| 49 | + ASSERT_NE(&weight_quant_batch_matmul_kernel_entry<Bf16HiFloat8>, nullptr); | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +template <typename Component> | ||
| 53 | +void CheckConvertedWeightL1BankAddresses(int64_t baseN, int64_t kbL1, bool hasBias) | ||
| 54 | +{ | ||
| 55 | + using BlockMmad = typename Component::BlockMmad; | ||
| 56 | + using Element = typename BlockMmad::AType; | ||
| 57 | + typename BlockMmad::Params params{}; | ||
| 58 | + params.l1TileShape = asc::te::make_shape(int64_t{128}, baseN, kbL1, kbL1); | ||
| 59 | + params.l0TileShape = asc::te::make_shape(int64_t{128}, baseN, int64_t{64}); | ||
| 60 | + params.kSize = static_cast<uint64_t>(kbL1); | ||
| 61 | + params.hasBias = hasBias; | ||
| 62 | + BlockMmad blockMmad; | ||
| 63 | + blockMmad.Init(params); | ||
| 64 | + auto ping = blockMmad.template GetShareMemPtr<asc::te::location::l1, Element>(0U); | ||
| 65 | + auto pong = blockMmad.template GetShareMemPtr<asc::te::location::l1, Element>(1U); | ||
| 66 | + auto pingAddress = reinterpret_cast<uintptr_t>(ping.get()); | ||
| 67 | + auto pongAddress = reinterpret_cast<uintptr_t>(pong.get()); | ||
| 68 | + auto weightBytes = static_cast<uint64_t>(baseN * kbL1) * sizeof(Element); | ||
| 69 | + | ||
| 70 | + // Converted B occupies the two ends of L1. The second base depends on W, | ||
| 71 | + // not on the A half-buffer span or on the optional Bias reservation. | ||
| 72 | + EXPECT_EQ(pongAddress - pingAddress, AscendC::TOTAL_L1_SIZE - weightBytes); | ||
| 73 | + EXPECT_EQ(reinterpret_cast<uintptr_t>((pong + 1U).get()) - pongAddress, sizeof(Element)); | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +TEST(WeightQuantBatchMatmulTest, SharesConvertedWeightL1BankAddresses) | ||
| 77 | +{ | ||
| 78 | + for (bool hasBias : {false, true}) { | ||
| 79 | + SCOPED_TRACE(hasBias); | ||
| 80 | + CheckConvertedWeightL1BankAddresses<Fp16Int8>(128, 128, hasBias); // W = 32 KiB | ||
| 81 | + CheckConvertedWeightL1BankAddresses<Fp16Int8Offset>(128, 256, hasBias); // W = 64 KiB, FP32 Bias | ||
| 82 | + CheckConvertedWeightL1BankAddresses<Bf16Int8>(256, 256, hasBias); // W = 128 KiB | ||
| 83 | + CheckConvertedWeightL1BankAddresses<Bf16Fp8>(128, 128, hasBias); // BF16 with FP32 Bias | ||
| 84 | + } | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +} // namespace | ||
| @@ -0,0 +1,181 @@ | |||
| 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 | +#include <array> | ||
| 11 | +#include <string> | ||
| 12 | +#include "gtest/gtest.h" | ||
| 13 | +#include "wqmm_test_utils.h" | ||
| 14 | +#include "wqmm_copy_observer.h" | ||
| 15 | +#include "blaze/gemm/tile/arch35/copy_ub_to_l1.h" | ||
| 16 | + | ||
| 17 | +namespace { | ||
| 18 | +using namespace WeightQuantBatchMatmulUT; | ||
| 19 | +using Axes = std::array<int64_t, 4>; | ||
| 20 | +struct CopyCase { | ||
| 21 | + std::string name; | ||
| 22 | + bool zn; | ||
| 23 | + bool bf16; | ||
| 24 | + Axes shape, srcStride, dstShape, dstStride; | ||
| 25 | +}; | ||
| 26 | +int64_t Offset(const Axes& shape, const Axes& stride, int64_t row, int64_t col) | ||
| 27 | +{ | ||
| 28 | + return row % shape[0] * stride[0] + row / shape[0] * stride[1] + col % shape[2] * stride[2] + | ||
| 29 | + col / shape[2] * stride[3]; | ||
| 30 | +} | ||
| 31 | +size_t Extent(const Axes& shape, const Axes& stride) | ||
| 32 | +{ | ||
| 33 | + int64_t size = 1; | ||
| 34 | + for (size_t i = 0; i < shape.size(); ++i) | ||
| 35 | + size += (shape[i] - 1) * stride[i]; | ||
| 36 | + return size; | ||
| 37 | +} | ||
| 38 | +auto Nested(const Axes& a) | ||
| 39 | +{ | ||
| 40 | + return asc::te::make_shape(asc::te::make_shape(a[0], a[1]), asc::te::make_shape(a[2], a[3])); | ||
| 41 | +} | ||
| 42 | +struct CopyArgs { | ||
| 43 | + Axes shape, srcStride, dstShape, dstStride; | ||
| 44 | + uint64_t srcWords, dstWords; | ||
| 45 | +}; | ||
| 46 | +// The common UT links k3_pvwrap.cpp with empty PV memory operations. Observe | ||
| 47 | +// the actual SDK instruction instead of claiming to validate simulated DMA. | ||
| 48 | +template <typename T, bool Zn> | ||
| 49 | +__global__ __aicore__ void CopyKernel(GM_ADDR config, GM_ADDR captured) | ||
| 50 | +{ | ||
| 51 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); | ||
| 52 | + if ASCEND_IS_AIV { | ||
| 53 | + if (AscendC::GetSubBlockIdx() != 0) | ||
| 54 | + return; | ||
| 55 | + const auto& a = *reinterpret_cast<const CopyArgs*>(config); | ||
| 56 | + auto* record = reinterpret_cast<CopyInstruction*>(captured); | ||
| 57 | + observedCopy = record; | ||
| 58 | + using Pattern = AscendC::Std::conditional_t<Zn, Blaze::Gemm::zn_row_padding_layout_ptn, | ||
| 59 | + Blaze::Gemm::nz_col_padding_layout_ptn>; | ||
| 60 | + using Destination = AscendC::Std::conditional_t<Zn, asc::te::zn_layout_ptn, asc::te::nz_layout_ptn>; | ||
| 61 | + auto sl = asc::te::make_pattern_layout<Pattern, asc::te::layout_trait_default<T>>(Nested(a.shape), | ||
| 62 | + Nested(a.srcStride)); | ||
| 63 | + auto dl = asc::te::make_pattern_layout<Destination, asc::te::layout_trait_default<T>>(Nested(a.dstShape), | ||
| 64 | + Nested(a.dstStride)); | ||
| 65 | + AscendC::LocalTensor<uint16_t> ub(AscendC::TPosition::VECCALC, 0, a.srcWords); | ||
| 66 | + AscendC::LocalTensor<uint16_t> l1(AscendC::TPosition::A1, 0, a.dstWords); | ||
| 67 | + auto* srcBase = reinterpret_cast<T*>(ub.GetPhyAddr()); | ||
| 68 | + auto* dstBase = reinterpret_cast<T*>(l1.GetPhyAddr()); | ||
| 69 | + auto src = asc::te::make_tensor(asc::te::make_mem_ptr<asc::te::location::ub>(srcBase + 32), sl); | ||
| 70 | + auto dst = asc::te::make_tensor(asc::te::make_mem_ptr<asc::te::location::l1>(dstBase + 48), dl); | ||
| 71 | + auto copyUB2L1 = asc::te::make_copy(Blaze::Gemm::Tile::CopyPaddedUBToL1{}); | ||
| 72 | + asc::te::copy(copyUB2L1, dst, src); | ||
| 73 | + observedCopy = nullptr; | ||
| 74 | + record->src -= reinterpret_cast<uintptr_t>(srcBase); | ||
| 75 | + record->dst -= reinterpret_cast<uintptr_t>(dstBase); | ||
| 76 | + } | ||
| 77 | +} | ||
| 78 | +std::vector<CopyCase> Cases() | ||
| 79 | +{ | ||
| 80 | + std::vector<CopyCase> base; | ||
| 81 | + auto zn = [&](const char* name, int64_t k, int64_t n, int64_t sp, int64_t dn) { | ||
| 82 | + base.push_back({name, | ||
| 83 | + true, | ||
| 84 | + false, | ||
| 85 | + {16, Align16(k) / 16, 1, n}, | ||
| 86 | + {1, sp * 16, 0, 16}, | ||
| 87 | + {16, Align16(k) / 16, 16, Align16(dn) / 16}, | ||
| 88 | + {1, Align16(dn) * 16, 16, 256}}); | ||
| 89 | + }; | ||
| 90 | + auto nz = [&](const char* name, int64_t k, int64_t n, int64_t sp, int64_t dk) { | ||
| 91 | + base.push_back({name, | ||
| 92 | + false, | ||
| 93 | + false, | ||
| 94 | + {1, k, 16, Align16(n) / 16}, | ||
| 95 | + {0, 16, 1, sp * 16}, | ||
| 96 | + {16, Align16(dk) / 16, 16, Align16(n) / 16}, | ||
| 97 | + {16, 256, 1, Align16(dk) * 16}}); | ||
| 98 | + }; | ||
| 99 | + zn("zn_singleton", 1, 1, 2, 16); | ||
| 100 | + nz("nz_singleton", 1, 1, 2, 16); | ||
| 101 | + zn("zn_vf", 256, 64, 65, 256); | ||
| 102 | + zn("zn_vf_tail", 129, 37, 65, 256); | ||
| 103 | + nz("nz_vf", 64, 256, 65, 256); | ||
| 104 | + nz("nz_vf_tail", 37, 129, 65, 256); | ||
| 105 | + base.push_back({"zn_blocked", true, false, {16, 2, 16, 2}, {1, 544, 16, 256}, {16, 2, 16, 2}, {1, 576, 16, 256}}); | ||
| 106 | + base.push_back({"nz_blocked", false, false, {16, 2, 16, 2}, {16, 256, 1, 544}, {16, 2, 16, 2}, {16, 256, 1, 576}}); | ||
| 107 | + std::vector<CopyCase> all; | ||
| 108 | + for (auto c : base) | ||
| 109 | + for (bool bf16 : {false, true}) { | ||
| 110 | + c.bf16 = bf16; | ||
| 111 | + auto named = c; | ||
| 112 | + named.name += bf16 ? "_bf16" : "_fp16"; | ||
| 113 | + all.push_back(named); | ||
| 114 | + } | ||
| 115 | + return all; | ||
| 116 | +} | ||
| 117 | +class WqmmCopyTest : public testing::TestWithParam<CopyCase> {}; | ||
| 118 | +TEST_P(WqmmCopyTest, InstructionMatchesCoordinatesAndSentinelModel) | ||
| 119 | +{ | ||
| 120 | + const auto& c = GetParam(); | ||
| 121 | + CopyArgs a{c.shape, | ||
| 122 | + c.srcStride, | ||
| 123 | + c.dstShape, | ||
| 124 | + c.dstStride, | ||
| 125 | + 32 + Extent(c.shape, c.srcStride) + 32, | ||
| 126 | + 48 + Extent(c.dstShape, c.dstStride) + 32}; | ||
| 127 | + std::vector<uint16_t> src(a.srcWords, 0xCDCD), initial(a.dstWords, 0xA5A5), expected(initial); | ||
| 128 | + std::vector<bool> written(a.dstWords, false); | ||
| 129 | + for (int64_t row = 0; row < c.shape[0] * c.shape[1]; ++row) { | ||
| 130 | + for (int64_t col = 0; col < c.shape[2] * c.shape[3]; ++col) { | ||
| 131 | + size_t si = 32 + Offset(c.shape, c.srcStride, row, col), | ||
| 132 | + di = 48 + Offset(c.dstShape, c.dstStride, row, col); | ||
| 133 | + ASSERT_LT(si, src.size() - 32); | ||
| 134 | + ASSERT_LT(di, expected.size() - 32); | ||
| 135 | + ASSERT_FALSE(written[di]); | ||
| 136 | + written[di] = true; | ||
| 137 | + src[si] = expected[di] = static_cast<uint16_t>(row * 257 + col * 17 + 0x1357); | ||
| 138 | + } | ||
| 139 | + } | ||
| 140 | + GmBuffer config(sizeof(a)), capture(sizeof(CopyInstruction)); | ||
| 141 | + config.Set(std::vector<CopyArgs>{a}); | ||
| 142 | + using Kernel = decltype(&CopyKernel<half, true>); | ||
| 143 | + Kernel fn = c.bf16 ? (c.zn ? &CopyKernel<bfloat16_t, true> : &CopyKernel<bfloat16_t, false>) : | ||
| 144 | + (c.zn ? &CopyKernel<half, true> : &CopyKernel<half, false>); | ||
| 145 | + AscendC::SetKernelMode(KernelMode::MIX_MODE); | ||
| 146 | + ASSERT_TRUE(KERNEL_RUN_KF(fn, 1U, config.Get(), capture.Get())); | ||
| 147 | + const auto& instruction = *reinterpret_cast<const CopyInstruction*>(capture.Get()); | ||
| 148 | + ASSERT_EQ(instruction.calls, 1U) | ||
| 149 | + << "UB-to-L1 observer must intercept exactly one instruction; check SDK ABI and --wrap"; | ||
| 150 | + ASSERT_EQ(instruction.src, 64U); | ||
| 151 | + ASSERT_EQ(instruction.dst, 96U); | ||
| 152 | + ASSERT_EQ(instruction.sid, 0); | ||
| 153 | + // Derive instruction geometry from independent logical-coordinate walks. | ||
| 154 | + const int64_t groups = c.zn ? c.shape[1] : c.shape[3]; | ||
| 155 | + const int64_t rows = c.zn ? c.shape[0] : c.shape[0] * c.shape[1]; | ||
| 156 | + const int64_t cols = c.zn ? c.shape[2] * c.shape[3] : c.shape[2]; | ||
| 157 | + const auto sourcePitch = Offset(c.shape, c.srcStride, c.zn ? rows : 0, c.zn ? 0 : cols); | ||
| 158 | + const auto targetPitch = Offset(c.dstShape, c.dstStride, c.zn ? rows : 0, c.zn ? 0 : cols); | ||
| 159 | + ASSERT_EQ(instruction.count, groups); | ||
| 160 | + ASSERT_EQ(instruction.length * 16, rows * cols); | ||
| 161 | + ASSERT_EQ((instruction.length + instruction.srcGap) * 16, sourcePitch); | ||
| 162 | + ASSERT_EQ((instruction.length + instruction.dstGap) * 16, targetPitch); | ||
| 163 | + // This is an explicit instruction address model, not CPU-DMA readback. | ||
| 164 | + auto actual = initial; | ||
| 165 | + for (uint64_t group = 0; group < instruction.count; ++group) { | ||
| 166 | + size_t si = instruction.src / 2 + group * (instruction.length + instruction.srcGap) * 16; | ||
| 167 | + size_t di = instruction.dst / 2 + group * (instruction.length + instruction.dstGap) * 16; | ||
| 168 | + size_t words = instruction.length * 16; | ||
| 169 | + ASSERT_LE(si + words, src.size() - 32); | ||
| 170 | + ASSERT_LE(di + words, actual.size() - 32); | ||
| 171 | + std::copy_n(src.begin() + si, words, actual.begin() + di); | ||
| 172 | + } | ||
| 173 | + auto mismatch = std::mismatch(expected.begin(), expected.end(), actual.begin()); | ||
| 174 | + if (mismatch.first != expected.end()) { | ||
| 175 | + FAIL() << "destination word " << (mismatch.first - expected.begin()) << ": expected " << *mismatch.first | ||
| 176 | + << ", actual " << *mismatch.second; | ||
| 177 | + } | ||
| 178 | +} | ||
| 179 | +INSTANTIATE_TEST_SUITE_P(PaddedLayouts, WqmmCopyTest, testing::ValuesIn(Cases()), | ||
| 180 | + [](const testing::TestParamInfo<CopyCase>& p) { return p.param.name; }); | ||
| 181 | +} // namespace | ||
| @@ -0,0 +1,29 @@ | |||
| 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 | +#include "wqmm_copy_observer.h" | ||
| 11 | + | ||
| 12 | +// GNU ld --wrap observes this one CCE intrinsic. It does not mock layouts, | ||
| 13 | +// routing, Copy arithmetic or the SDK call, and stays inert outside a capture. | ||
| 14 | +extern "C" void __real__Z17copy_ubuf_to_cbufPvS_htttt(void*, void*, uint8_t, uint16_t, uint16_t, uint16_t, uint16_t); | ||
| 15 | +extern "C" void __wrap__Z17copy_ubuf_to_cbufPvS_htttt(void* dst, void* src, uint8_t sid, uint16_t count, | ||
| 16 | + uint16_t length, uint16_t srcGap, uint16_t dstGap) | ||
| 17 | +{ | ||
| 18 | + if (auto* record = WeightQuantBatchMatmulUT::observedCopy) { | ||
| 19 | + ++record->calls; | ||
| 20 | + record->src = reinterpret_cast<uintptr_t>(src); | ||
| 21 | + record->dst = reinterpret_cast<uintptr_t>(dst); | ||
| 22 | + record->sid = sid; | ||
| 23 | + record->count = count; | ||
| 24 | + record->length = length; | ||
| 25 | + record->srcGap = srcGap; | ||
| 26 | + record->dstGap = dstGap; | ||
| 27 | + } | ||
| 28 | + __real__Z17copy_ubuf_to_cbufPvS_htttt(dst, src, sid, count, length, srcGap, dstGap); | ||
| 29 | +} | ||
| @@ -0,0 +1,54 @@ | |||
| 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 | +#include <array> | ||
| 11 | +#include "gtest/gtest.h" | ||
| 12 | +#include "wqmm_test_utils.h" | ||
| 13 | +#include "blaze/gemm/utils/layout_struct.h" | ||
| 14 | + | ||
| 15 | +namespace { | ||
| 16 | +using namespace WeightQuantBatchMatmulUT; | ||
| 17 | +template <typename T, bool Zn> | ||
| 18 | +void CheckPaddingLayout(int64_t k, int64_t n, int64_t pitch) | ||
| 19 | +{ | ||
| 20 | + auto layout = [&] { | ||
| 21 | + if constexpr (Zn) | ||
| 22 | + return Blaze::Gemm::ZnRowPaddingUBLayout<T>{}(k, n, pitch); | ||
| 23 | + else | ||
| 24 | + return Blaze::Gemm::NzColPaddingUBLayout<T>{}(k, n, pitch); | ||
| 25 | + }(); | ||
| 26 | + using Pattern = asc::te::get_layout_pattern<decltype(layout)>; | ||
| 27 | + using ExpectedPattern = AscendC::Std::conditional_t<Zn, Blaze::Gemm::zn_row_padding_layout_ptn, | ||
| 28 | + Blaze::Gemm::nz_col_padding_layout_ptn>; | ||
| 29 | + static_assert(AscendC::Std::is_same_v<Pattern, ExpectedPattern>); | ||
| 30 | + auto shape = asc::te::get_shape(layout); | ||
| 31 | + EXPECT_EQ(int64_t(asc::te::get<0, 0>(shape)), Zn ? 16 : 1); | ||
| 32 | + EXPECT_EQ(int64_t(asc::te::get<0, 1>(shape)), Zn ? Align16(k) / 16 : k); | ||
| 33 | + EXPECT_EQ(int64_t(asc::te::get<1, 0>(shape)), Zn ? 1 : 16); | ||
| 34 | + EXPECT_EQ(int64_t(asc::te::get<1, 1>(shape)), Zn ? n : Align16(n) / 16); | ||
| 35 | + auto rows = Zn ? Align16(k) : k, cols = Zn ? n : Align16(n); | ||
| 36 | + for (int64_t row = 0; row < rows; ++row) | ||
| 37 | + for (int64_t col = 0; col < cols; ++col) { | ||
| 38 | + int64_t reference = Zn ? (row / 16 * pitch + col * 16 + row % 16) : | ||
| 39 | + (col / 16 * pitch + row * 16 + col % 16); | ||
| 40 | + ASSERT_EQ(int64_t(layout(asc::te::make_coord(row, col))), reference); | ||
| 41 | + } | ||
| 42 | +} | ||
| 43 | +TEST(WqmmLayoutTest, ProductionPaddingHelpersKeepFixedPitchOnTails) | ||
| 44 | +{ | ||
| 45 | + // Singleton, C0 boundary, partial tile and full VF tile. | ||
| 46 | + for (const auto& shape : {std::array<int64_t, 2>{1, 1}, {16, 16}, {129, 37}, {256, 64}}) { | ||
| 47 | + const auto outer = shape[0], inner = shape[1]; | ||
| 48 | + CheckPaddingLayout<half, true>(outer, inner, 65 * 16); | ||
| 49 | + CheckPaddingLayout<bfloat16_t, true>(outer, inner, 65 * 16); | ||
| 50 | + CheckPaddingLayout<half, false>(inner, outer, 65 * 16); | ||
| 51 | + CheckPaddingLayout<bfloat16_t, false>(inner, outer, 65 * 16); | ||
| 52 | + } | ||
| 53 | +} | ||
| 54 | +} // namespace | ||
| @@ -0,0 +1,174 @@ | |||
| 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 | +#include <array> | ||
| 11 | +#include "gtest/gtest.h" | ||
| 12 | +#include "wqmm_test_utils.h" | ||
| 13 | +#include "blaze/gemm/block/block_scheduler_wqmm.h" | ||
| 14 | + | ||
| 15 | +namespace { | ||
| 16 | +using namespace WeightQuantBatchMatmulUT; | ||
| 17 | +using Shape = asc::te::shape<uint64_t, uint64_t, uint64_t>; | ||
| 18 | +using Scheduler = Blaze::Gemm::Block::BlockSchedulerWqmmTailResplit<Shape>; | ||
| 19 | +using Tile = std::array<uint64_t, 7>; // range, local M/N index, M/N origin, M/N extent | ||
| 20 | +constexpr uint32_t MAIN = 0, FIRST_TAIL = 1, SECOND_TAIL = 2; | ||
| 21 | +constexpr uint64_t MAX_CORES = 8, CASES = 8; | ||
| 22 | +struct ScheduleCase { | ||
| 23 | + uint64_t m, n, k, recordBase, capacity; | ||
| 24 | + Scheduler::Params params; | ||
| 25 | +}; | ||
| 26 | +// Each core has its own bounded slice; unused slices retain poison. Output is | ||
| 27 | +// compared exactly, not by hashes, with a global round-robin ownership oracle. | ||
| 28 | +template <uint32_t Range> | ||
| 29 | +void Append(const Scheduler& s, Tile* out, uint64_t capacity, uint64_t& count, uint64_t mi, uint64_t nCount) | ||
| 30 | +{ | ||
| 31 | + auto m = s.GetBlockCoordM(mi); | ||
| 32 | + for (uint64_t ni = 0; ni < nCount; ++ni) { | ||
| 33 | + auto n = s.GetBlockCoordN<Range>(ni); | ||
| 34 | + if (count < capacity) | ||
| 35 | + out[count] = {Range, mi, ni, m, n, s.GetBlockShapeM(m), s.GetBlockShapeN<Range>(n)}; | ||
| 36 | + ++count; | ||
| 37 | + } | ||
| 38 | +} | ||
| 39 | +__global__ __aicore__ void SchedulerKernel(GM_ADDR configs, GM_ADDR records, GM_ADDR counts) | ||
| 40 | +{ | ||
| 41 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); | ||
| 42 | + uint64_t core, lane; | ||
| 43 | + if ASCEND_IS_AIC { | ||
| 44 | + core = AscendC::GetBlockIdx(); | ||
| 45 | + lane = 0; | ||
| 46 | + } else { | ||
| 47 | + core = AscendC::GetBlockIdx() / AscendC::GetSubBlockNum(); | ||
| 48 | + lane = 1 + AscendC::GetSubBlockIdx(); | ||
| 49 | + } | ||
| 50 | + auto* cases = reinterpret_cast<const ScheduleCase*>(configs); | ||
| 51 | + auto* output = reinterpret_cast<Tile*>(records); | ||
| 52 | + auto* totals = reinterpret_cast<uint64_t*>(counts); | ||
| 53 | + for (uint64_t trial = 0; trial < CASES; ++trial) { | ||
| 54 | + const auto& c = cases[trial]; | ||
| 55 | + if (core >= c.params.cubeNumBlocksM * c.params.cubeNumBlocksN) | ||
| 56 | + continue; | ||
| 57 | + Scheduler s(asc::te::make_shape(c.m, c.n, c.k), c.params); | ||
| 58 | + auto nums = s.GetBlockNums(); | ||
| 59 | + auto* dst = output + c.recordBase + (lane * MAX_CORES + core) * c.capacity; | ||
| 60 | + uint64_t count = 0; | ||
| 61 | + for (uint64_t mi = 0; mi < asc::te::get<0>(nums); ++mi) { | ||
| 62 | + Append<MAIN>(s, dst, c.capacity, count, mi, asc::te::get<1>(nums)); | ||
| 63 | + Append<FIRST_TAIL>(s, dst, c.capacity, count, mi, asc::te::get<2>(nums)); | ||
| 64 | + Append<SECOND_TAIL>(s, dst, c.capacity, count, mi, asc::te::get<3>(nums)); | ||
| 65 | + } | ||
| 66 | + uint64_t at = (trial * 3 * MAX_CORES + lane * MAX_CORES + core) * 2; | ||
| 67 | + totals[at] = count; | ||
| 68 | + totals[at + 1] = s.GetCoreNums(); | ||
| 69 | + } | ||
| 70 | +} | ||
| 71 | +using Streams = std::vector<std::vector<Tile>>; | ||
| 72 | +Streams Oracle(const ScheduleCase& c) | ||
| 73 | +{ | ||
| 74 | + const auto& p = c.params; | ||
| 75 | + Streams expected(p.cubeNumBlocksM * p.cubeNumBlocksN); | ||
| 76 | + const std::array<uint64_t, 3> counts{p.mainBlockCount, p.firstTailBlockCount, p.secondTailBlockCount}; | ||
| 77 | + const std::array<uint64_t, 3> sizes{p.mainBlockSize, p.firstTailBlockSize, p.secondTailBlockSize}; | ||
| 78 | + auto span = (c.m + p.cubeNumBlocksM - 1) / p.cubeNumBlocksM; | ||
| 79 | + for (uint64_t cm = 0; cm < p.cubeNumBlocksM; ++cm) { | ||
| 80 | + auto stop = std::min(c.m, (cm + 1) * span); | ||
| 81 | + uint64_t mi = 0; | ||
| 82 | + for (auto row = cm * span; row < stop; row += p.mL1Tile, ++mi) { | ||
| 83 | + uint64_t start = 0; | ||
| 84 | + for (uint32_t stage = 0; stage < 3; ++stage) { | ||
| 85 | + std::vector<uint64_t> ni(p.cubeNumBlocksN, 0); | ||
| 86 | + for (uint64_t j = 0; j < counts[stage]; ++j) { | ||
| 87 | + auto owner = (j + (stage == SECOND_TAIL ? counts[FIRST_TAIL] : 0)) % p.cubeNumBlocksN; | ||
| 88 | + auto col = start + j * sizes[stage]; | ||
| 89 | + expected[cm * p.cubeNumBlocksN + owner].push_back({stage, mi, ni[owner]++, row, col, | ||
| 90 | + std::min(stop - row, uint64_t(p.mL1Tile)), | ||
| 91 | + std::min(c.n - col, sizes[stage])}); | ||
| 92 | + } | ||
| 93 | + start += counts[stage] * sizes[stage]; | ||
| 94 | + } | ||
| 95 | + } | ||
| 96 | + } | ||
| 97 | + return expected; | ||
| 98 | +} | ||
| 99 | +TEST(WqmmSchedulerTest, BoundarySchedulesMatchOnAicAndBothAivSubcores) | ||
| 100 | +{ | ||
| 101 | + // Params: M tile, three N counts, three N sizes, M/N core counts. | ||
| 102 | + std::vector<ScheduleCase> cases{ | ||
| 103 | + {1, 1, 1, 0, 0, {16, 1, 0, 0, 16, 8, 4, 1, 1}}, // singleton | ||
| 104 | + {33, 96, 256, 0, 0, {16, 3, 0, 0, 32, 16, 8, 2, 2}}, // main only, M tail | ||
| 105 | + {17, 29, 257, 0, 0, {16, 0, 2, 0, 32, 16, 8, 1, 4}}, // first tail only, idle N cores | ||
| 106 | + {1, 17, 64, 0, 0, {16, 0, 0, 3, 32, 16, 8, 1, 4}}, // second tail only | ||
| 107 | + {65, 101, 513, 0, 0, {16, 2, 1, 3, 32, 16, 8, 2, 4}}, // all ranges, N2 wraps | ||
| 108 | + {31, 157, 512, 0, 0, {16, 2, 5, 2, 32, 16, 8, 1, 4}}, // first tail spans a core round | ||
| 109 | + {33, 95, 128, 0, 0, {16, 2, 2, 0, 32, 16, 8, 2, 4}}, // no second tail | ||
| 110 | + {5, 65, 129, 0, 0, {2, 2, 0, 1, 32, 16, 8, 4, 2}}, // idle M core, empty first tail | ||
| 111 | + }; | ||
| 112 | + ASSERT_EQ(cases.size(), CASES); | ||
| 113 | + uint64_t recordCount = 0; | ||
| 114 | + for (auto& c : cases) { | ||
| 115 | + auto oracle = Oracle(c); | ||
| 116 | + for (const auto& stream : oracle) | ||
| 117 | + c.capacity = std::max(c.capacity, uint64_t(stream.size())); | ||
| 118 | + ++c.capacity; // guard record after the longest stream | ||
| 119 | + c.recordBase = recordCount; | ||
| 120 | + recordCount += c.capacity * 3 * MAX_CORES; | ||
| 121 | + } | ||
| 122 | + GmBuffer configs(cases.size() * sizeof(ScheduleCase)), records(recordCount * sizeof(Tile)), | ||
| 123 | + counts(CASES * 3 * MAX_CORES * 2 * 8); | ||
| 124 | + configs.Set(cases); | ||
| 125 | + std::memset(records.Get(), 0xA5, recordCount * sizeof(Tile)); | ||
| 126 | + std::memset(counts.Get(), 0xFF, CASES * 3 * MAX_CORES * 2 * 8); | ||
| 127 | + AscendC::SetKernelMode(KernelMode::MIX_MODE); | ||
| 128 | + ASSERT_TRUE(KERNEL_RUN_KF(SchedulerKernel, MAX_CORES, configs.Get(), records.Get(), counts.Get())); | ||
| 129 | + auto* actual = reinterpret_cast<Tile*>(records.Get()); | ||
| 130 | + auto* total = reinterpret_cast<uint64_t*>(counts.Get()); | ||
| 131 | + uint64_t mTails = 0, nTails = 0, emptyCores = 0; | ||
| 132 | + for (uint64_t trial = 0; trial < CASES; ++trial) { | ||
| 133 | + SCOPED_TRACE(trial); | ||
| 134 | + const auto& c = cases[trial]; | ||
| 135 | + auto expected = Oracle(c); | ||
| 136 | + uint64_t area = 0; | ||
| 137 | + for (uint64_t core = 0; core < MAX_CORES; ++core) { | ||
| 138 | + for (uint64_t lane = 0; lane < 3; ++lane) { | ||
| 139 | + auto at = (trial * 3 * MAX_CORES + lane * MAX_CORES + core) * 2; | ||
| 140 | + auto* data = actual + c.recordBase + (lane * MAX_CORES + core) * c.capacity; | ||
| 141 | + uint64_t size = core < expected.size() ? expected[core].size() : 0; | ||
| 142 | + if (core < expected.size()) { | ||
| 143 | + ASSERT_EQ(total[at], size); | ||
| 144 | + ASSERT_EQ(total[at + 1], expected.size()); | ||
| 145 | + for (uint64_t j = 0; j < size; ++j) | ||
| 146 | + ASSERT_EQ(data[j], expected[core][j]); | ||
| 147 | + } else { | ||
| 148 | + ASSERT_EQ(total[at], UINT64_MAX); | ||
| 149 | + } | ||
| 150 | + for (uint64_t j = size; j < c.capacity; ++j) | ||
| 151 | + for (auto word : data[j]) | ||
| 152 | + ASSERT_EQ(word, 0xA5A5A5A5A5A5A5A5ULL); | ||
| 153 | + } | ||
| 154 | + if (core >= expected.size()) | ||
| 155 | + continue; | ||
| 156 | + emptyCores += expected[core].empty(); | ||
| 157 | + for (const auto& t : expected[core]) { | ||
| 158 | + ASSERT_GT(t[5], 0U); | ||
| 159 | + ASSERT_GT(t[6], 0U); | ||
| 160 | + area += t[5] * t[6]; | ||
| 161 | + mTails += t[5] < uint64_t(c.params.mL1Tile); | ||
| 162 | + auto tile = t[0] == MAIN ? | ||
| 163 | + c.params.mainBlockSize : | ||
| 164 | + (t[0] == FIRST_TAIL ? c.params.firstTailBlockSize : c.params.secondTailBlockSize); | ||
| 165 | + nTails += t[6] < tile; | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | + ASSERT_EQ(area, c.m * c.n); | ||
| 169 | + } | ||
| 170 | + EXPECT_GT(mTails, 0U); | ||
| 171 | + EXPECT_GT(nTails, 0U); | ||
| 172 | + EXPECT_GT(emptyCores, 0U); | ||
| 173 | +} | ||
| 174 | +} // namespace | ||
| @@ -0,0 +1,63 @@ | |||
| 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 weight_quant_batch_matmul.h | ||
| 13 | + * \brief Kernel UT assembly for the B8 ND weight-antiquant GemmUniversal specialization. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#pragma once | ||
| 17 | + | ||
| 18 | +#include "blaze_kernel_stub.h" | ||
| 19 | +#include "kernel_operator.h" | ||
| 20 | +#include "tensor_api/tensor.h" | ||
| 21 | + | ||
| 22 | +#include "blaze/gemm/kernel/kernel_wqmm_mix_antiquant.h" | ||
| 23 | +#include "blaze/gemm/block/block_scheduler_wqmm.h" | ||
| 24 | + | ||
| 25 | +namespace WeightQuantBatchMatmulUT { | ||
| 26 | + | ||
| 27 | +template <class XType, class WeightType, class ScaleType, class YType, uint32_t UbInner, uint32_t UbBufferNum, | ||
| 28 | + bool TransB, Blaze::Gemm::QuantMode AntiquantType, bool HasOffset, bool BiasFp32> | ||
| 29 | +struct Components { | ||
| 30 | + using DispatchPolicy = Blaze::Gemm::MatmulWithWeightAntiquant<2, UbInner, UbBufferNum, AntiquantType, HasOffset>; | ||
| 31 | + using ProblemShape = asc::te::shape<int64_t, int64_t, int64_t>; | ||
| 32 | + using LayoutA = asc::te::nd_ext_layout_ptn; | ||
| 33 | + using LayoutB = AscendC::Std::conditional_t<TransB, asc::te::nd_ext_layout_ptn, asc::te::dn_ext_layout_ptn>; | ||
| 34 | + using LayoutScale = asc::te::nd_ext_layout_ptn; | ||
| 35 | + using LayoutC = asc::te::nd_ext_layout_ptn; | ||
| 36 | + using LayoutBias = asc::te::nd_ext_layout_ptn; | ||
| 37 | + using BiasType = AscendC::Std::conditional_t<BiasFp32, float, XType>; | ||
| 38 | + using BTypes = AscendC::Std::tuple<WeightType, ScaleType>; | ||
| 39 | + using BLayouts = AscendC::Std::tuple<LayoutB, LayoutScale>; | ||
| 40 | + using BlockMmad = Blaze::Gemm::Block::BlockMmad<DispatchPolicy, XType, LayoutA, BTypes, BLayouts, YType, LayoutC, | ||
| 41 | + BiasType, LayoutBias>; | ||
| 42 | + using Scheduler = Blaze::Gemm::Block::BlockSchedulerWqmmTailResplit<ProblemShape>; | ||
| 43 | + using Kernel = Blaze::Gemm::Kernel::GemmUniversal<ProblemShape, BlockMmad, void, Scheduler>; | ||
| 44 | +}; | ||
| 45 | + | ||
| 46 | +} // namespace WeightQuantBatchMatmulUT | ||
| 47 | + | ||
| 48 | +template <class Components> | ||
| 49 | +__global__ __aicore__ void weight_quant_batch_matmul_kernel_entry(GM_ADDR xGm, GM_ADDR weightGm, GM_ADDR scaleGm, | ||
| 50 | + GM_ADDR offsetGm, GM_ADDR biasGm, GM_ADDR yGm, | ||
| 51 | + GM_ADDR tilingGm) | ||
| 52 | +{ | ||
| 53 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); | ||
| 54 | + using Kernel = typename Components::Kernel; | ||
| 55 | + auto params = *reinterpret_cast<const typename Kernel::Params*>(tilingGm); | ||
| 56 | + params.mmadParams.aGmAddr = xGm; | ||
| 57 | + params.mmadParams.cGmAddr = yGm; | ||
| 58 | + params.mmadParams.biasGmAddr = biasGm; | ||
| 59 | + params.prologueParams.bGmAddr = weightGm; | ||
| 60 | + params.prologueParams.scaleGmAddr = scaleGm; | ||
| 61 | + params.prologueParams.offsetGmAddr = offsetGm; | ||
| 62 | + Kernel{}(params); | ||
| 63 | +} | ||
| @@ -0,0 +1,19 @@ | |||
| 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 | +#pragma once | ||
| 11 | +#include <cstdint> | ||
| 12 | +namespace WeightQuantBatchMatmulUT { | ||
| 13 | +struct CopyInstruction { | ||
| 14 | + uint64_t calls = 0, src = 0, dst = 0; | ||
| 15 | + uint16_t count = 0, length = 0, srcGap = 0, dstGap = 0; | ||
| 16 | + uint8_t sid = 0; | ||
| 17 | +}; | ||
| 18 | +inline thread_local CopyInstruction* observedCopy = nullptr; | ||
| 19 | +} // namespace WeightQuantBatchMatmulUT | ||
| @@ -0,0 +1,49 @@ | |||
| 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 | +#pragma once | ||
| 11 | + | ||
| 12 | +#include <algorithm> | ||
| 13 | +#include <cstdint> | ||
| 14 | +#include <cstring> | ||
| 15 | +#include <stdexcept> | ||
| 16 | +#include <vector> | ||
| 17 | +#include "blaze_kernel_stub.h" | ||
| 18 | +#include "kernel_ut_runner.h" | ||
| 19 | +#include "tikicpulib.h" | ||
| 20 | +#include "kernel_operator.h" | ||
| 21 | +#include "tensor_api/tensor.h" | ||
| 22 | + | ||
| 23 | +namespace WeightQuantBatchMatmulUT { | ||
| 24 | +class GmBuffer { | ||
| 25 | +public: | ||
| 26 | + explicit GmBuffer(size_t bytes) : bytes_(bytes), address_(static_cast<GM_ADDR>(AscendC::GmAlloc(bytes))) | ||
| 27 | + { | ||
| 28 | + if (!address_) | ||
| 29 | + throw std::bad_alloc(); | ||
| 30 | + std::memset(address_, 0, bytes_); | ||
| 31 | + } | ||
| 32 | + ~GmBuffer() { AscendC::GmFree(address_); } | ||
| 33 | + GmBuffer(const GmBuffer&) = delete; | ||
| 34 | + GmBuffer& operator=(const GmBuffer&) = delete; | ||
| 35 | + GM_ADDR Get() const { return address_; } | ||
| 36 | + template <typename T> | ||
| 37 | + void Set(const std::vector<T>& values) | ||
| 38 | + { | ||
| 39 | + if (values.size() * sizeof(T) > bytes_) | ||
| 40 | + throw std::out_of_range("GM allocation"); | ||
| 41 | + std::memcpy(address_, values.data(), values.size() * sizeof(T)); | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | +private: | ||
| 45 | + size_t bytes_; | ||
| 46 | + GM_ADDR address_; | ||
| 47 | +}; | ||
| 48 | +inline int64_t Align16(int64_t value) { return (value + 15) / 16 * 16; } | ||
| 49 | +} // namespace WeightQuantBatchMatmulUT | ||


后面那个**没有必要吧