Merged
feat(gmmfr): migrate arch35 quantized kernels to Blaze/Tensor API #447
zhangzhizhuoAdd on Sep 30
feat(gmmfr): migrate arch35 quantized kernels to Blaze/Tensor API #447
Merged
Merged fromzhangzhizhuo/ops-tensorgmmfrintocann/ops-tensormaster
Total: 34 files changed+3598-457
| @@ -13,7 +13,7 @@ | |||
| 13 | | [block_epilogue_dequant](./block/block_epilogue_dequant.md) | MIX 模板 dequant 向量后处理,AIV 侧 int32→fp32 × scale + bias → bf16/fp16/fp32 | | 13 | | [block_epilogue_dequant](./block/block_epilogue_dequant.md) | MIX 模板 dequant 向量后处理,AIV 侧 int32→fp32 × scale + bias → bf16/fp16/fp32 | |
| 14 | | [block_epilogue_qbmm_pertensor_streamk](./block/block_epilogue_qbmm_pertensor_streamk.md) | QBMM per-tensor StreamK 专用后处理,归约 raw partial 后应用 scale/bias | | 14 | | [block_epilogue_qbmm_pertensor_streamk](./block/block_epilogue_qbmm_pertensor_streamk.md) | QBMM per-tensor StreamK 专用后处理,归约 raw partial 后应用 scale/bias | |
| 15 | | [block_epilogue_per_token_scale](./block/block_epilogue_per_token_scale.md) | 应用 per-token scale 和可选 row-sum offset 修正 | | 15 | | [block_epilogue_per_token_scale](./block/block_epilogue_per_token_scale.md) | 应用 per-token scale 和可选 row-sum offset 修正 | |
| 16 | -| [block_epilogue_finalize_routing](./block/block_epilogue_finalize_routing.md) | GroupedMatmulFinalizeRouting 通用后处理,完成 logit 融合、类型转换和 rowIndex 原子写回 | | 16 | +| [block_epilogue_finalize_routing](./block/block_epilogue_finalize_routing.md) | GroupedMatmulFinalizeRouting 通用后处理,支持 MX 全量化、pertoken 全量化和 MX A8W4 | |
| 17 | | [block_epilogue_fmm_with_scale_add](./block/block_epilogue_fmm_with_scale_add.md) | FusedMatMul scale_add 向量后处理,执行 alpha × (x1@x2) + beta × x3 | | 17 | | [block_epilogue_fmm_with_scale_add](./block/block_epilogue_fmm_with_scale_add.md) | FusedMatMul scale_add 向量后处理,执行 alpha × (x1@x2) + beta × x3 | |
| 18 | | [block_epilogue_confidence_head_fused](./block/block_epilogue_confidence_head_fused.md) | FP32 温度/clamp/sigmoid、K=0 bias 输入及 UB ping/pong 写回 | | 18 | | [block_epilogue_confidence_head_fused](./block/block_epilogue_confidence_head_fused.md) | FP32 温度/clamp/sigmoid、K=0 bias 输入及 UB ping/pong 写回 | |
| 19 | | [block_epilogue_matmul_with_sigmoid](./block/block_epilogue_matmul_with_sigmoid.md) | FusedMatMul sigmoid 向量后处理,执行 sigmoid(x1@x2 + bias) | | 19 | | [block_epilogue_matmul_with_sigmoid](./block/block_epilogue_matmul_with_sigmoid.md) | FusedMatMul sigmoid 向量后处理,执行 sigmoid(x1@x2 + bias) | |
| @@ -2,60 +2,73 @@ | |||
| 2 | 2 | ||
| 3 | ## 功能说明 | 3 | ## 功能说明 |
| 4 | 4 | ||
| 5 | -`BlockEpilogueFinalizeRouting` 是 `GroupedMatmulFinalizeRouting` TensorAPI Kernel 的通用 AIV 侧后处理组件。它接收 MMAD 产生的 FP32 结果,融合逐 token 的 logit,并根据 `rowIndex` 对 y 进行原子加写回。 | 5 | +`BlockEpilogueFinalizeRouting` 是 GroupedMatmulFinalizeRouting 的 AIV 后处理组件,支持 MX 全量化、pertoken 全量化和 MX A8W4。每个 AIC tile 按 M 维拆给两个 AIV 子核处理。组件从 UB 读取 MMAD 结果,按模式执行反量化和 logit 加权,再根据 rowIndex 写回输出。确定性 pertoken 先写 workspace,再按输入行顺序归并。 |
| 6 | 6 | ||
| 7 | -一个 AIC tile 会由两个 AIV 子核在 M 维均分处理。L0C-to-UB 使用单块 FP32 缓冲,输出 UB 和 logit UB 使用 ping-pong 缓冲,使向量计算与 GM 搬运能够交替执行。 | 7 | +## 模板参数 |
| 8 | 8 | ||
| 9 | -## 模板约束 | 9 | +```cpp |
| 10 | +template <typename DataTypeOut, typename DataTypeIn, typename DataTypeLogit, | ||
| 11 | + typename RowIndexType, typename DataTypeX2Scale = float, | ||
| 12 | + bool IsDeter = false, FinalizeRoutingMode Mode = FinalizeRoutingMode::MX> | ||
| 13 | +class BlockEpilogueFinalizeRouting; | ||
| 14 | +``` | ||
| 10 | 15 | ||
| 11 | -| 类型 | 约束 | | 16 | +| 参数 | 约束 | |
| 12 | | --- | --- | | 17 | | --- | --- | |
| 13 | -| `DataTypeIn` | FP32 MMAD 输出 | | 18 | +| `Mode` | `MX`、`PERTOKEN` 或 `A8W4`。仅传前四个模板参数时使用 MX 接口 | |
| 14 | -| `DataTypeOut` | FP32 或 BF16 | | 19 | +| `DataTypeOut` | FP32 或 BF16。A8W4 要求 FP32 | |
| 15 | -| `DataTypeLogit` | FP32 或 BF16;FP32 输出时 BF16 logit 在组件内转换为 FP32 | | 20 | +| `DataTypeIn` | MX 和 A8W4 要求 FP32。Pertoken 支持 INT32 或 FP32,须与 MMAD 的累加类型一致 | |
| 16 | -| `RowIndexType` | FP32 输出时为 INT64;BF16 输出时为 INT32 | | 21 | +| `DataTypeLogit` | FP32 或 BF16。A8W4 要求 FP32,pertoken 算子组装使用 FP32 | |
| 17 | -| FP32 输出 | logit 以 FP32 参与乘法 | | 22 | +| `RowIndexType` | MX 的 FP32 输出对应 INT64,BF16 输出对应 INT32。Pertoken 支持 INT32 或 INT64,A8W4 要求 INT64 | |
| 18 | -| BF16 输出 | logit 可为 FP32 或 BF16 | | 23 | +| `DataTypeX2Scale` | Pertoken 每列 scale 的类型,支持 FP32 或 BF16 | |
| 24 | +| `IsDeter` | 仅 pertoken 模式支持设为 `true` | | ||
| 19 | 25 | ||
| 20 | -## 参数 | 26 | +算子接口可施加更严格的类型组合约束。Pertoken 的逐 token scale 类型为 FP32,bias 类型为 BF16。 |
| 21 | 27 | ||
| 22 | -| 字段 | 说明 | | 28 | +## Params |
| 23 | -| --- | --- | | ||
| 24 | -| `yGmAddr` | 输出 y 的 GM 地址 | | ||
| 25 | -| `logitGmAddr` | logit 的 GM 地址 | | ||
| 26 | -| `rowIndexGmAddr` | rowIndex 的 GM 地址 | | ||
| 27 | -| `x1ScaleGmAddr`、`x2ScaleGmAddr`、`biasGmAddr` | 保持与 Kernel 参数结构一致的地址字段;后处理不读取这些字段 | | ||
| 28 | -| `baseM`、`baseN` | tile 基础大小 | | ||
| 29 | 29 | ||
| 30 | -`UpdateGlobalAddr` 在处理新 group 时根据 group 的基地址更新 logit 和 rowIndex 的 GM 视图。 | 30 | +| 字段 | 适用模式 | 说明 | |
| 31 | +| --- | --- | --- | | ||
| 32 | +| `yGmAddr` | 全部 | 输出基址 | | ||
| 33 | +| `x2ScaleGmAddr` | 全部 | Pertoken 必需的每列 ScaleB,形状为 `[E, N]`。MX 和 A8W4 的 Epilogue 不读取此字段 | | ||
| 34 | +| `x1ScaleGmAddr` | 全部 | Pertoken 可选的逐 token ScaleA,形状为 `[M]`,空指针表示省略该项。MX 和 A8W4 的 Epilogue 不读取此字段 | | ||
| 35 | +| `biasGmAddr` | 全部 | Pertoken 可选 bias,形状为 `[E, N]`。MX 和 A8W4 的 bias 由 MMAD 侧处理 | | ||
| 36 | +| `logitGmAddr` | 全部 | 每个输入行对应一个 logit | | ||
| 37 | +| `rowIndexGmAddr` | 全部 | 每个输入行对应一个输出行号 | | ||
| 38 | +| `baseM`、`baseN` | MX | 原 MX 聚合参数的末尾两个字段,默认值均为 256 | | ||
| 39 | +| `workspaceGmAddr` | Pertoken、A8W4 | 确定性 pertoken 的 workspace 基址 | | ||
| 40 | +| `nSize` | Pertoken、A8W4 | 初始化时使用的完整输出列数 | | ||
| 31 | 41 | ||
| 32 | -## BF16 输出路径 | 42 | +表格按聚合初始化顺序列出字段。输入地址、输出地址和 `Params` 对象须在组件使用期间有效。调用方负责初始化输出 y、校验 GM 容量和有效行号,并通过跨核通知保证 MMAD 结果就绪。 |
| 33 | 43 | ||
| 34 | -BF16 输出时,Epilogue 保持与量化通路一致的 BF16 计算顺序: | 44 | +## 调用接口 |
| 35 | 45 | ||
| 36 | -1. 将 L0C-to-UB 中的 FP32 MMAD 结果转换为 BF16。 | 46 | +所有模式通过 `Init(params)` 初始化组件,通过 `GetL0c2UbTensor(rows, cols)` 获取 Fixpipe 的 UB 目标。AIC 与 AIV 须使用相同的 UB 基址和行跨度。MX 也提供无参 `GetL0c2UbTensor()`,返回累加区的 LocalTensor。 |
| 37 | -2. logit 为 FP32 时先转换为 BF16;logit 已为 BF16 时直接使用。 | ||
| 38 | -3. 使用 BF16 乘法得到输出,并写入 BF16 输出 UB。 | ||
| 39 | -4. 使用 BF16 原子加写回 `y[rowIndex, nOffset:nOffset + curN]`。 | ||
| 40 | 47 | ||
| 41 | -FP32 输出路径保持 FP32 logit 和 FP32 MMAD 结果的乘法,再以 FP32 原子加写回。 | 48 | +- **MX**。每组调用 `UpdateNextProblem(problemShape)` 设置输出列数,并调用 `UpdateGlobalAddr(baseOffset)` 更新元数据地址。分组偏移使用 `baseOffset` 的 logit 坐标,同时推进 logit 和 rowIndex 的 GM 基址。随后调用 `operator()(blockShape, blockCoord)` 消费 tile,返回前等待该 tile 写回完成。 |
| 42 | -当 logit 输入为 BF16 时,组件会先将其转换为 FP32,再执行相同的 FP32 乘法路径。算子接口的运行时 dtype 校验仍以接口约束为准。 | 49 | +- **Pertoken 和 A8W4**。调用 `operator()(problemShape, blockShape, blockCoord, baseOffset, groupAccumM = 0)` 消费 tile。`problemShape` 的 N 为完整输出列数。`BlockCoord` 的坐标依次为输出列、bias、ScaleB、ScaleA、logit 和 rowIndex 的元素偏移。`baseOffset` 表示分组或分段的基址偏移,`blockCoord` 表示 tile 内寻址所用的偏移。A8W4 延后消费时传入待消费 tile 所属分组的偏移。 |
| 43 | 50 | ||
| 44 | -## 执行流程 | 51 | +### A8W4 路由参数预取 |
| 45 | 52 | ||
| 46 | -1. 根据 AIV 子核编号切分当前 tile 的 M 维,获取本子核处理范围。 | 53 | +按 tile 顺序调用 `PrefetchRoutingMetadata(rows, mOffset, groupMOffset)`,每个实际 tile 预取一次。预取使用原始 GM 基址,可跨组提前执行。生产和消费各自推进双缓冲索引。没有行可处理的 AIV 也须执行对应的消费调用,释放槽位。Kernel 须在组件析构前消费最后一个已预取的 tile。 |
| 47 | -2. 从 L0C-to-UB 缓冲读取 FP32 结果,并按行从 GM 读取 logit。 | ||
| 48 | -3. 向量侧执行结果与 logit 的广播乘法及所需类型转换。 | ||
| 49 | -4. 对本子核的每一行读取 `rowIndex`,通过 `SetAtomicAdd` 将结果写入 y 的对应行和 N 范围。 | ||
| 50 | -5. 通过 V/MTE2/MTE3 event 管理 logit 搬入、向量计算和 y 写回的双缓冲依赖。 | ||
| 51 | 54 | ||
| 52 | -## 注意事项 | 55 | +### 确定性 pertoken |
| 53 | 56 | ||
| 54 | -- 写回使用原子加,目标 y 必须满足调用方约定的初始化条件。 | 57 | +`groupAccumM` 表示当前分段在 workspace 窗口内的起始行。组件先将逐输入行的贡献线性写入 workspace。Kernel 通过 `PrefetchRowIndicesFromBase` 和 `GetPrefetchedRowIndex` 读取窗口内的行号,再按既定顺序调用 `DeterministicFlushRow(mOffset, outRow, nSize)`,保证同一输出行按输入行顺序累加。 |
| 55 | -- `rowIndex` 的类型受输出 dtype 约束;不能混用 BF16 输出与 INT64 rowIndex,或 FP32 输出与 INT32 rowIndex。 | 58 | + |
| 56 | -- L0C-to-UB 缓冲以 FP32 保存 MMAD 结果,BF16 转换发生在向量后处理阶段。 | 59 | +## 计算与写回 |
| 60 | + | ||
| 61 | +- **MX**。对 MMAD 已应用 MX scale 和 bias 的 FP32 结果执行 logit 加权。 | ||
| 62 | +- **Pertoken**。将 INT32 累加值转换为 FP32,FP32 累加值直接使用。依次乘 ScaleB、可选 ScaleA,加可选 bias,再乘 logit。 | ||
| 63 | +- **A8W4**。将 MMAD 结果乘 64,再乘 logit。对当前 AIV 负责的整块结果原地加权,写回后等待搬出完成,随后权重转换可复用该 UB 区域。 | ||
| 64 | + | ||
| 65 | +FP32 输出使用 FP32 乘法和原子加。BF16 输出先将计算结果和 logit 转为 BF16,再执行 BF16 乘法和原子加。非确定性模式将每行贡献加到 `y[rowIndex, nOffset:nOffset + cols]`。MX 和 pertoken 要求有效行号,A8W4 跳过负行号。 | ||
| 66 | + | ||
| 67 | +MX 和 pertoken 的 UB 累加区按 M≤128、N≤256 规划,输出分段最多 32 行并使用双缓冲。Pertoken 的累加行跨度按 256 B 对齐,MX 和 A8W4 的累加行跨度按 32 个元素对齐。A8W4 的累加和输出区域从 80 KiB 开始,rowIndex 和 logit 的双缓冲分别从 242 KiB 和 244 KiB 开始。调用方须遵循配套 Kernel 的 UB 复用和同步约定。 | ||
| 57 | 68 | ||
| 58 | ## 相关文件 | 69 | ## 相关文件 |
| 59 | 70 | ||
| 60 | -- 实现:[block_epilogue_finalize_routing.h](../../../../include/blaze/epilogue/block/block_epilogue_finalize_routing.h) | 71 | +- [头文件](../../../../include/blaze/epilogue/block/block_epilogue_finalize_routing.h) |
| 61 | -- Kernel:[kernel_qgmm_mx_mix_finalize_routing.h](../../gemm/kernel/kernel_qgmm_mx_mix_finalize_routing.md) | 72 | +- [GroupedMatmulFinalizeRouting Kernel 使用指南](../../gemm/kernel/grouped_matmul_finalize_routing.md) |
| 73 | +- [MX 全量化 Kernel](../../gemm/kernel/kernel_qgmm_mx_mix_finalize_routing.md) | ||
| 74 | +- [Pertoken 全量化 Kernel](../../gemm/kernel/kernel_qgmm_mix_pertoken_finalize_routing.md) | ||
| @@ -11,6 +11,7 @@ | |||
| 11 | | [arch35/swish](./arch35/swish.md) | FP32 Swish → BF16 RINT,尾部补零到 32 元素边界 | | 11 | | [arch35/swish](./arch35/swish.md) | FP32 Swish → BF16 RINT,尾部补零到 32 元素边界 | |
| 12 | | [arch35/dequant](./arch35/dequant.md) | Tile 级反量化(双轴 API:类模板 tag 选量化对象、Run 模板 `DequantMode` 选粒度):Fp4ToFp8Tag per-group 权重 → FP8;B32ToFpTag int32/fp32 ×scale + bias → fp32/bf16/fp16 | | 12 | | [arch35/dequant](./arch35/dequant.md) | Tile 级反量化(双轴 API:类模板 tag 选量化对象、Run 模板 `DequantMode` 选粒度):Fp4ToFp8Tag per-group 权重 → FP8;B32ToFpTag int32/fp32 ×scale + bias → fp32/bf16/fp16 | |
| 13 | | [arch35/mx_quant](./arch35/mx_quant.md) | Tile 级 MX 动态量化链(eMax → scale → FP8/FP4 量化 → 布局转置) | | 13 | | [arch35/mx_quant](./arch35/mx_quant.md) | Tile 级 MX 动态量化链(eMax → scale → FP8/FP4 量化 → 布局转置) | |
| 14 | +| [arch35/process_shared_input](./arch35/process_shared_input.md) | GM→UB 前处理组件:ProcessSharedInput 完成 BF16 shared input 加权初始化,支持 FP32/BF16 输出 | | ||
| 14 | | `arch35/initialize_empty_softmax.h` | BlockAttnResPrepare 空输入场景的 softmax 统计量初始化 | | 15 | | `arch35/initialize_empty_softmax.h` | BlockAttnResPrepare 空输入场景的 softmax 统计量初始化 | |
| 15 | | `arch35/reduce_square.h` | Tile 级 V 平方和归约,BlockAttnResPrepare 依赖 | | 16 | | `arch35/reduce_square.h` | Tile 级 V 平方和归约,BlockAttnResPrepare 依赖 | |
| 16 | | `arch35/rms_softmax.h` | Tile 级 RMS-softmax 计算,BlockAttnResPrepare 依赖 | | 17 | | `arch35/rms_softmax.h` | Tile 级 RMS-softmax 计算,BlockAttnResPrepare 依赖 | |
| @@ -15,6 +15,7 @@ | |||
| 15 | #include "blaze/epilogue/tile/arch35/gelu.h" | 15 | #include "blaze/epilogue/tile/arch35/gelu.h" |
| 16 | #include "blaze/epilogue/tile/arch35/initialize_empty_softmax.h" | 16 | #include "blaze/epilogue/tile/arch35/initialize_empty_softmax.h" |
| 17 | #include "blaze/epilogue/tile/arch35/mx_quant.h" | 17 | #include "blaze/epilogue/tile/arch35/mx_quant.h" |
| 18 | +#include "blaze/epilogue/tile/arch35/process_shared_input.h" | ||
| 18 | #include "blaze/epilogue/tile/arch35/reduce_square.h" | 19 | #include "blaze/epilogue/tile/arch35/reduce_square.h" |
| 19 | #include "blaze/epilogue/tile/arch35/rms_softmax.h" | 20 | #include "blaze/epilogue/tile/arch35/rms_softmax.h" |
| 20 | #include "blaze/epilogue/tile/arch35/sigmoid.h" | 21 | #include "blaze/epilogue/tile/arch35/sigmoid.h" |
| @@ -3,7 +3,7 @@ | |||
| 3 | 3 | ||
| 4 | ## 功能说明 | 4 | ## 功能说明 |
| 5 | 5 | ||
| 6 | -这是 QBMM/GMM 共用的 arch35 BlockMmad,负责 AIC(Cube)侧的单 tile | 6 | +本组件是 QBMM、GMM 和 GMMFR 共用的 arch35 BlockMmad,负责 AIC(Cube)侧的单 tile |
| 7 | MX MMAD。B 和 bias 由 Kernel 内的 AIV(Vector)前处理写入共享 L1,因此本 BlockMmad 不接收 | 7 | MX MMAD。B 和 bias 由 Kernel 内的 AIV(Vector)前处理写入共享 L1,因此本 BlockMmad 不接收 |
| 8 | B/Bias Tensor,也不执行 B GM→L1 搬运。 | 8 | B/Bias Tensor,也不执行 B GM→L1 搬运。 |
| 9 | 9 | ||
| @@ -17,15 +17,17 @@ B/Bias Tensor,也不执行 B GM→L1 搬运。 | |||
| 17 | 17 | ||
| 18 | ### 架构和 policy | 18 | ### 架构和 policy |
| 19 | 19 | ||
| 20 | -仅支持 `__NPU_ARCH__ == 3510`(arch35)。`DispatchPolicy` 指定 K 分块方式和 ScaleB 来源: | 20 | +本文接口面向 DAV_3510(arch35)。`DispatchPolicy` 指定 K 分块方式和 ScaleB 来源: |
| 21 | 21 | ||
| 22 | - `MatmulWithWeightQuantMx`:固定 K 分块,AIC 从 GM 搬运 ScaleB。 | 22 | - `MatmulWithWeightQuantMx`:固定 K 分块,AIC 从 GM 搬运 ScaleB。 |
| 23 | - `GroupedMatmulWithWeightQuantMx`:执行 GMM Kernel 根据当前 M/N 选择的 ka/kb/k0,A 在 ka 窗口内跨 B 块复用; | 23 | - `GroupedMatmulWithWeightQuantMx`:执行 GMM Kernel 根据当前 M/N 选择的 ka/kb/k0,A 在 ka 窗口内跨 B 块复用; |
| 24 | ScaleB 由 AIV 转换并写入 L1,AIC 只消费其 L1 视图。 | 24 | ScaleB 由 AIV 转换并写入 L1,AIC 只消费其 L1 视图。 |
| 25 | 25 | ||
| 26 | -GMM 的构造参数包含 L1 分区、缓冲容量、ready/free 标志和初始 B 槽位写入许可, | 26 | +- `GroupedMatmulFinalizeRoutingWithWeightQuantMx`:动态 K 分块,由 AIC 搬运 ScaleB,结果写入 split-M UB。 |
| 27 | + | ||
| 28 | +GMM/GMMFR 的构造参数包含 L1 分区、缓冲容量、ready/free 标志和初始 B 槽位写入许可, | ||
| 27 | 由配套 Kernel 提供;ka/kb/k0 随每个 tile 的四个 Tensor 传入计算接口。 | 29 | 由配套 Kernel 提供;ka/kb/k0 随每个 tile 的四个 Tensor 传入计算接口。 |
| 28 | -两条路径共用 L0 搬运、bias 累加、K64 补零、MMAD 和 Fixpipe 写回。 | 30 | +三种策略共用 L0 搬运、bias 累加、K64 补零和 MMAD。QBMM/GMM 写回 GM,GMMFR 写回 UB,由后续 epilogue 完成路由。 |
| 29 | 31 | ||
| 30 | ### 模板类型约束 | 32 | ### 模板类型约束 |
| 31 | 33 | ||
| @@ -35,7 +37,7 @@ GMM 的构造参数包含 L1 分区、缓冲容量、ready/free 标志和初始 | |||
| 35 | - 配套 GMM Kernel 的 A 输入使用 `nd_ext_layout_ptn` 布局。 | 37 | - 配套 GMM Kernel 的 A 输入使用 `nd_ext_layout_ptn` 布局。 |
| 36 | - `LayoutB` 必须是转置布局:NZ 使用 `zn_layout_ptn`,ND 使用 `dn_ext_layout_ptn`。 | 38 | - `LayoutB` 必须是转置布局:NZ 使用 `zn_layout_ptn`,ND 使用 `dn_ext_layout_ptn`。 |
| 37 | - 当前算子组装中 `LayoutC`/`LayoutBias` 均为 `nd_ext_layout_ptn`;bias 可选,有 bias 时 | 39 | - 当前算子组装中 `LayoutC`/`LayoutBias` 均为 `nd_ext_layout_ptn`;bias 可选,有 bias 时 |
| 38 | - `BiasType` 与 `CType` 一致。 | 40 | + QBMM/GMM 的 `BiasType` 与 `CType` 一致;GMMFR 的 `CType=float`、`BiasType=bfloat16_t`。 |
| 39 | 41 | ||
| 40 | ### 缓冲和同步 | 42 | ### 缓冲和同步 |
| 41 | 43 | ||
| @@ -54,18 +56,19 @@ template < | |||
| 54 | class ATypeTuple, class LayoutATuple, class BTypeTuple, class LayoutBTuple, | 56 | class ATypeTuple, class LayoutATuple, class BTypeTuple, class LayoutBTuple, |
| 55 | class CType, class LayoutC, class BiasType, class LayoutBias> | 57 | class CType, class LayoutC, class BiasType, class LayoutBias> |
| 56 | class BlockMmad; | 58 | class BlockMmad; |
| 57 | -// DispatchPolicy 为 MatmulWithWeightQuantMx 或 GroupedMatmulWithWeightQuantMx。 | 59 | +// DispatchPolicy 为 QBMM、GMM 或 GMMFR 的 WeightQuantMxPolicy 别名。 |
| 58 | ``` | 60 | ``` |
| 59 | 61 | ||
| 60 | `dispatch_policy.h` 中的策略只声明调度类型和两类行为,不包含 K 分块算法: | 62 | `dispatch_policy.h` 中的策略只声明调度类型和两类行为,不包含 K 分块算法: |
| 61 | 63 | ||
| 62 | - QBMM:`K_SCHEDULE=WeightPrologueMxKSchedule::FIXED`,`SCALE_B_SOURCE=WeightPrologueMxScaleBSource::AIC`。 | 64 | - QBMM:`K_SCHEDULE=WeightPrologueMxKSchedule::FIXED`,`SCALE_B_SOURCE=WeightPrologueMxScaleBSource::AIC`。 |
| 63 | - GMM:`K_SCHEDULE=WeightPrologueMxKSchedule::DYNAMIC`,`SCALE_B_SOURCE=WeightPrologueMxScaleBSource::AIV`。 | 65 | - GMM:`K_SCHEDULE=WeightPrologueMxKSchedule::DYNAMIC`,`SCALE_B_SOURCE=WeightPrologueMxScaleBSource::AIV`。 |
| 66 | +- GMMFR:`K_SCHEDULE=WeightPrologueMxKSchedule::DYNAMIC`,`SCALE_B_SOURCE=WeightPrologueMxScaleBSource::AIC`。 | ||
| 64 | 67 | ||
| 65 | 公共实现按上述枚举选择入口和 ScaleB 搬运分支。动态 K 的选择属于 | 68 | 公共实现按上述枚举选择入口和 ScaleB 搬运分支。动态 K 的选择属于 |
| 66 | [GMM Kernel](../kernel/kernel_wqgmm_mix_weight_prologue.md#动态-k-分块选择): | 69 | [GMM Kernel](../kernel/kernel_wqgmm_mix_weight_prologue.md#动态-k-分块选择): |
| 67 | AIC、AIV 共用 Kernel 内的 `CalcDynamicKBlock`,Block 只按传入的 ka/kb/k0 执行。 | 70 | AIC、AIV 共用 Kernel 内的 `CalcDynamicKBlock`,Block 只按传入的 ka/kb/k0 执行。 |
| 68 | -GMM 的 L1 布局与握手配置由 Params 工厂提供。 | 71 | +GMM 的 L1 布局与握手配置由 Kernel 配置;GMMFR 的对应参数由其 Kernel 私有方法配置。 |
| 69 | 72 | ||
| 70 | | 模板参数 | 公开类型别名 | | 73 | | 模板参数 | 公开类型别名 | |
| 71 | | :--- | :--- | | 74 | | :--- | :--- | |
| @@ -109,7 +112,7 @@ struct Params { | |||
| 109 | | :--- | :--- | | 112 | | :--- | :--- | |
| 110 | | `aGmAddr` | A 矩阵 GM 地址 | | 113 | | `aGmAddr` | A 矩阵 GM 地址 | |
| 111 | | `scaleAGmAddr` / `scaleBGmAddr` | ScaleA/ScaleB GM 地址 | | 114 | | `scaleAGmAddr` / `scaleBGmAddr` | ScaleA/ScaleB GM 地址 | |
| 112 | -| `cGmAddr` | 输出 C GM 地址 | | 115 | +| `cGmAddr` | QBMM/GMM 输出 C GM 地址;GMMFR 的结果由传入的 UB Tensor 接收 | |
| 113 | | `biasGmAddr` | Bias GM 地址,由配套 Kernel 的 AIV 分支使用 | | 116 | | `biasGmAddr` | Bias GM 地址,由配套 Kernel 的 AIV 分支使用 | |
| 114 | | `l1TileShape` | `(baseM, baseN, kL1, scaleKL1)` | | 117 | | `l1TileShape` | `(baseM, baseN, kL1, scaleKL1)` | |
| 115 | | `l0TileShape` | `(baseM, baseN, baseK)` | | 118 | | `l0TileShape` | `(baseM, baseN, baseK)` | |
| @@ -169,7 +172,7 @@ __aicore__ inline void operator()( | |||
| 169 | uint64_t kaL1Size, uint64_t kbL1Size, uint64_t l0KSize); | 172 | uint64_t kaL1Size, uint64_t kbL1Size, uint64_t l0KSize); |
| 170 | ``` | 173 | ``` |
| 171 | 174 | ||
| 172 | -A、ScaleA、C Tensor 为当前 scheduler tile 的 GM slice。QBMM 的 ScaleB 也传当前 tile 的 GM slice; | 175 | +A、ScaleA Tensor 为当前 scheduler tile 的 GM slice;QBMM/GMM 的 C 为 GM slice,GMMFR 的 C 为 split-M UB Tensor。QBMM/GMMFR 的 ScaleB 传当前 tile 的 GM slice; |
| 173 | GMM 的入口额外接收 ka/kb/k0;AIC 不解引用或切分传入的 ScaleB GM Tensor,直接消费 AIV 写入的 L1 ScaleB。 | 176 | GMM 的入口额外接收 ka/kb/k0;AIC 不解引用或切分传入的 ScaleB GM Tensor,直接消费 AIV 写入的 L1 ScaleB。 |
| 174 | B/bias 不作为参数传入,而由 AIV 通过共享 L1 提供。 | 177 | B/bias 不作为参数传入,而由 AIV 通过共享 L1 提供。 |
| 175 | QBMM 的固定 K 来自构造时的 tiling 参数;GMM 的 ka/kb/k0 必须由 Kernel 随当前 tile 传入。 | 178 | QBMM 的固定 K 来自构造时的 tiling 参数;GMM 的 ka/kb/k0 必须由 Kernel 随当前 tile 传入。 |
| @@ -194,12 +197,12 @@ L1 分区、缓冲容量和 ready/free 标志编号由 GMM Kernel 配置,AIC | |||
| 194 | 197 | ||
| 195 | ## 计算流程 | 198 | ## 计算流程 |
| 196 | 199 | ||
| 197 | -1. Scale 窗口开始时,AIC 在对应 L1 槽位锁保护下搬运 ScaleA;QBMM 还由 AIC 搬运 ScaleB,GMM 的 ScaleB 由 AIV 转换后写入 L1。 | 200 | +1. Scale 窗口开始时,AIC 在对应 L1 槽位锁保护下搬运 ScaleA;QBMM/GMMFR 还由 AIC 搬运 ScaleB,GMM 的 ScaleB 由 AIV 转换后写入 L1。 |
| 198 | 2. A 窗口开始时,AIC 在对应 L1 槽位锁保护下搬运 A,随后清理当前 B 块的 `[Align32(K), Align64(K))` 物理尾部。 | 201 | 2. A 窗口开始时,AIC 在对应 L1 槽位锁保护下搬运 A,随后清理当前 B 块的 `[Align32(K), Align64(K))` 物理尾部。 |
| 199 | 3. 等待 AIV 为当前 L1 weight buffer 设置 ready 标志。 | 202 | 3. 等待 AIV 为当前 L1 weight buffer 设置 ready 标志。 |
| 200 | 4. QBMM 按固定 `baseK`、GMM 按动态 `k0` 将 A、B、ScaleA、ScaleB 搬入 L0, | 203 | 4. QBMM 按固定 `baseK`、GMM 按动态 `k0` 将 A、B、ScaleA、ScaleB 搬入 L0, |
| 201 | - 使用 `MmadTraitMX` 累加到 L0C。 | 204 | + 使用 `MmadTraitMX` 累加到 L0C。GMMFR 同样消费 Kernel 提供的动态 K 分块。 |
| 202 | -5. 首个 K tile 消费 AIV 已按 `1/64` 缩放的 bias,Fixpipe 将结果写回 C。 | 205 | +5. 首个 K tile 消费 AIV 已按 `1/64` 缩放的 bias。QBMM/GMM 经 Fixpipe 写回 GM,GMMFR 经 Fixpipe 写入 UB 后由 epilogue 乘 64 并执行路由。 |
| 203 | 6. 释放 weight buffer,允许 AIV 继续生产下一 tile。 | 206 | 6. 释放 weight buffer,允许 AIV 继续生产下一 tile。 |
| 204 | 207 | ||
| 205 | GMM 的 A 槽位按 ka 窗口切换,Scale 槽位按独立的 4096 元素 K 窗口切换;两者均可跨多个 kb 块复用。 | 208 | GMM 的 A 槽位按 ka 窗口切换,Scale 槽位按独立的 4096 元素 K 窗口切换;两者均可跨多个 kb 块复用。 |
| @@ -237,3 +240,12 @@ blockMmad(gmBlockA, gmBlockScaleA, tensorScaleBGm, gmBlockC, kaL1Size, kbL1Size, | |||
| 237 | - `GemmUniversal` Weight Prologue 特化的 AIC 计算侧。 | 240 | - `GemmUniversal` Weight Prologue 特化的 AIC 计算侧。 |
| 238 | - 配套 Kernel 支持 arch35 MXA8W4 Weight ND/NZ 输入,并由 AIV 负责 packed FP4→FP8 和 bias 前处理。 | 241 | - 配套 Kernel 支持 arch35 MXA8W4 Weight ND/NZ 输入,并由 AIV 负责 packed FP4→FP8 和 bias 前处理。 |
| 239 | - 不适合单独调用;没有对应 AIV producer 时,B/bias L1 数据和 ready 标志不存在。 | 242 | - 不适合单独调用;没有对应 AIV producer 时,B/bias L1 数据和 ready 标志不存在。 |
| 243 | + | ||
| 244 | + | ||
| 245 | +## GMMFR 输出与缓冲约定 | ||
| 246 | + | ||
| 247 | +`GroupedMatmulFinalizeRoutingWithWeightQuantMx` 使用公共特化的动态 K 入口,由 AIC 从 GM 搬运 ScaleB。配套 Kernel 提供有效的 L1 分区和 AIV 权重生产端。 | ||
| 248 | + | ||
| 249 | +GMMFR 的结果目标为 split-M UB。公共 BlockMmad 在完成 MMAD 后、Fixpipe 写 UB 前等待两个 AIV 子核交还 W8/输出区域,使用跨核事件 3 及其双 AIV 对应编号。UB 输出不在 Fixpipe 中乘 64;公共 routing epilogue 执行该乘法,再乘 logit。QBMM/GMM 的 GM 输出在 Fixpipe 写回时乘 64。 | ||
| 250 | + | ||
| 251 | +调用方应使用 [GMMFR A8W4 Kernel](../kernel/kernel_wqgmm_mx_mix_finalize_routing.md) 配套组装,不得省略 AIV producer、结果缓冲释放或最终消费通知。 | ||
| @@ -21,6 +21,9 @@ | |||
| 21 | | [kernel_qbmm_mix](./kernel_qbmm_mix.md) | 支持多 Batch 的 A8W8 MIX Matmul,AIC 计算、AIV 反量化 | | 21 | | [kernel_qbmm_mix](./kernel_qbmm_mix.md) | 支持多 Batch 的 A8W8 MIX Matmul,AIC 计算、AIV 反量化 | |
| 22 | | [kernel_qbmm_mix_without_batch](./kernel_qbmm_mix_without_batch.md) | Batch 固定为 1 的 A8W8 MIX Matmul,不处理多 Batch 广播 | | 22 | | [kernel_qbmm_mix_without_batch](./kernel_qbmm_mix_without_batch.md) | Batch 固定为 1 的 A8W8 MIX Matmul,不处理多 Batch 广播 | |
| 23 | | [kernel_qgmm_mx_basic](./kernel_qgmm_mx_basic.md) | MX 量化 Grouped Matmul,支持 group list 与 tail split | | 23 | | [kernel_qgmm_mx_basic](./kernel_qgmm_mx_basic.md) | MX 量化 Grouped Matmul,支持 group list 与 tail split | |
| 24 | +| [grouped_matmul_finalize_routing](./grouped_matmul_finalize_routing.md) | GMMFR 三数据流的接口、存储、初始化及调用约束 | | ||
| 25 | +| [kernel_qgmm_mix_pertoken_finalize_routing](./kernel_qgmm_mix_pertoken_finalize_routing.md) | pertoken 全量化 GMMFR,支持可选 token scale 和确定性 workspace | | ||
| 26 | +| [kernel_wqgmm_mx_mix_finalize_routing](./kernel_wqgmm_mx_mix_finalize_routing.md) | MX A8W4 GMMFR,FP32 路由输出、AIV 权重转换和路由参数预取 | | ||
| 24 | | [kernel_qgmm_mx_mix_finalize_routing](./kernel_qgmm_mx_mix_finalize_routing.md) | GroupedMatmulFinalizeRouting MX TensorAPI Kernel,支持 shared input、logit 融合和 rowIndex 原子写回 | | 27 | | [kernel_qgmm_mx_mix_finalize_routing](./kernel_qgmm_mx_mix_finalize_routing.md) | GroupedMatmulFinalizeRouting MX TensorAPI Kernel,支持 shared input、logit 融合和 rowIndex 原子写回 | |
| 25 | | [kernel_qgmm_swiglu_mx](./kernel_qgmm_swiglu_mx.md) | MXFP8 Grouped Matmul + SwiGLU mode 2 + MX 输出量化,支持 ND/DN/NZ/ZN weight | | 28 | | [kernel_qgmm_swiglu_mx](./kernel_qgmm_swiglu_mx.md) | MXFP8 Grouped Matmul + SwiGLU mode 2 + MX 输出量化,支持 ND/DN/NZ/ZN weight | |
| 26 | | [kernel_qgmm_mix_fixpipe_quant](./kernel_qgmm_mix_fixpipe_quant.md) | 量化 Grouped Matmul,通过 Fixpipe 输出,支持 per-channel/per-group 和可选 offset 后处理 | | 29 | | [kernel_qgmm_mix_fixpipe_quant](./kernel_qgmm_mix_fixpipe_quant.md) | 量化 Grouped Matmul,通过 Fixpipe 输出,支持 per-channel/per-group 和可选 offset 后处理 | |
| @@ -38,7 +41,7 @@ | |||
| 38 | 41 | ||
| 39 | ## 公共框架 | 42 | ## 公共框架 |
| 40 | 43 | ||
| 41 | -所有 Kernel 组件均基于 [kernel.md](./kernel.md) 公共框架实现,统一包含: | 44 | +多数 Kernel 组件基于 [kernel.md](./kernel.md) 公共框架实现,统一包含: |
| 42 | - 模板参数 | 45 | - 模板参数 |
| 43 | - 数据结构,如 `Params`、`Arguments` | 46 | - 数据结构,如 `Params`、`Arguments` |
| 44 | - 核心方法,如 `Init`、`operator()` | 47 | - 核心方法,如 `Init`、`operator()` |
| @@ -0,0 +1,51 @@ | |||
| 1 | +# GroupedMatmulFinalizeRouting 组件使用指南 | ||
| 2 | + | ||
| 3 | +## 适用范围 | ||
| 4 | + | ||
| 5 | +本组组件面向 Ascend950、DAV_3510(arch35),在分组矩阵乘之后执行 logit 加权和路由累加。组件属于 device 侧 C++ 接口,不解析 aclTensor,不执行算子 Host 的类型、形状和 workspace 校验。调用方负责提供合法的模板组合、存储格式和 tiling。 | ||
| 6 | + | ||
| 7 | +| 数据流 | 输入与权重 | 计算组件 | Kernel 入口 | | ||
| 8 | +| --- | --- | --- | --- | | ||
| 9 | +| pertoken 全量化 | INT8、FP8 E4M3FN、HIFLOAT8 的同类型输入;A 为 ND,B 可按组件能力配置 ND/DN/NZ/ZN | `BlockMmad<MatmulWithScaleMix<...>>` | `GemmUniversal<ProblemShape, Mmad, Epilogue, Scheduler>` | | ||
| 10 | +| MX 全量化 | 同为 MXFP8 或同为 MXFP4;A 为 ND,B 可配置 ND/DN/NZ/ZN | `BlockMmad<GroupedMatmulWithScaleMx<...>>` | `GemmUniversal<ProblemShape, Mmad, tuple<Prologue,Epilogue>, Scheduler>` | | ||
| 11 | +| MX A8W4 | FP8 E4M3FN × packed FP4 E2M1;A 为 ND,B 为转置 WeightNZ | `BlockMmad<GroupedMatmulFinalizeRoutingWithWeightQuantMx,...>` | `GmmWqgmmMxFinalizeRoutingKernel` | | ||
| 12 | + | ||
| 13 | +以上 pertoken 列列出算子集成使用的组合;组件模板还允许 E5M2 等类型,其模板准入不等同于 aclnn 接口支持范围。MX WeightNZ 的数据类型限制见 [MX Kernel](./kernel_qgmm_mx_mix_finalize_routing.md)。 | ||
| 14 | + | ||
| 15 | +## 张量语义 | ||
| 16 | + | ||
| 17 | +逻辑输入 A 为 `[M,K]`,分组数为 E,每组逻辑权重为 `[K,N]`,输出为 `[batch,N]`。groupList、logit 和 rowIndex 分别描述专家分组、输入行权重和输出行映射。 | ||
| 18 | + | ||
| 19 | +- `groupListType=0`:INT64 累计行数列表,非递减,末项为 M;相邻值相等表示空组。 | ||
| 20 | +- `groupListType=1`:INT64 行数列表,每项非负,总和为 M。 | ||
| 21 | +- logit 含 M 个元素;rowIndex 含 M 个元素。除 A8W4 的负索引跳过规则外,rowIndex 必须落在 `[0,batch)`。 | ||
| 22 | +- shared input 为 BF16,逻辑形状为 `[sharedInputLen,N]`。其第 0 行写入 y 的 `sharedInputOffset` 行,先乘 `residualScale`,随后与路由贡献累加。 | ||
| 23 | +- `sharedInputOffset`、`sharedInputLen`、batch 的单位均为行;`0 <= offset` 且 `offset+len <= batch`。len 为 0 时不读取 shared input。 | ||
| 24 | +- pertoken 的 ScaleB 为每组每列一个元素,逻辑 `[E,N]`;可选 ScaleA 为每输入行一个 FP32 元素 `[M]`。ScaleB 为 FP32 或 BF16,bias 为可选 BF16 `[E,N]`。 | ||
| 25 | +- MX ScaleA/ScaleB 为 E8M0,每 32 个 K 元素共享一个 scale;尾 K 的 scale 存储须满足 K64 对齐。ScaleA 为 `[M,ceil(K/64),2]`;非转置 ScaleB 为 `[E,ceil(K/64),N,2]`,转置 ScaleB 为 `[E,N,ceil(K/64),2]`。 | ||
| 26 | + | ||
| 27 | +非转置 B 的逻辑存储为 `[E,K,N]`;转置 B 为 `[E,N,K]`。NZ/ZN 的 padding 和组跨度由权重 dtype、布局共同确定,不能用逻辑元素数代替存储字节数。FP4 两个元素占一个字节。 | ||
| 28 | + | ||
| 29 | +## 调用次序 | ||
| 30 | + | ||
| 31 | +1. 选择 Kernel、Mmad、Epilogue 和 Scheduler 的模板组合。 | ||
| 32 | +2. 填入当前设备的核数、分组参数、合法的 M/N/K 分块及 GM 地址;FP4 地址偏移以 packed 存储换算。 | ||
| 33 | +3. 分配并清零输出,分配可选 workspace,构造 Kernel 的 `Params`。 | ||
| 34 | +4. 通过 `KERNEL_TYPE_MIX_AIC_1_2` 启动,一个 AIC 配两个 AIV,调用 Kernel 的 `operator()`。 | ||
| 35 | +5. 等待 stream 完成后读取输出。包含原子累加的路径不承诺不同调度之间逐位一致。 | ||
| 36 | + | ||
| 37 | +三个数据流均要求调用方在每次启动前清零输出 y。Kernel 的 shared input 处理仅覆盖对应窗口,随后 epilogue 将路由贡献累加到 y。单独调用 epilogue 时,也须由调用方准备正确的输出初值。 | ||
| 38 | + | ||
| 39 | +## Tiling 与资源 | ||
| 40 | + | ||
| 41 | +baseM/baseN/baseK、kAL1/kBL1、MX scaleKL1 均按原始维度元素数计量;scaleKL1 不是 E8M0 元素个数。对齐、L0/L1/UB 容量和事件编号必须与选定组件一致。MX scale 窗口应覆盖完整 K64 块,并与操作数 K 分块配套。 | ||
| 42 | + | ||
| 43 | +MX 和 pertoken epilogue 的缓冲按最大 M=128、N=256 规划,调用方不能超出对应布局容量。A8W4 使用专用的 M≤256、N≤256 tile 和固定 UB 分区,其 kernel 配套构造 L1 参数。相同核上的组件不得在缓冲生命周期内占用同一 UB 地址或相同事件编号。 | ||
| 44 | + | ||
| 45 | +确定性 pertoken 调用须为 Kernel 和 Epilogue 同时配置 workspace、deterWorkspaceSize 和实际 AIC 核数,详见 [pertoken Kernel](./kernel_qgmm_mix_pertoken_finalize_routing.md)。 | ||
| 46 | + | ||
| 47 | +## 使用示例与测试 | ||
| 48 | + | ||
| 49 | +- [GMMFR 直调示例](../../../../examples/acl/grouped_matmul/grouped_matmul_finalize_routing/README.md):统一目标覆盖 pertoken、MX WeightND、MX WeightNZ 和 A8W4,包含 FP32/BF16 输出。 | ||
| 50 | +- [Kernel UT](../../../../tests/ut/op_kernel/grouped_matmul_finalize_routing/README.md):组件组装和 CPU 仿真执行检查。 | ||
| 51 | +- 三种量化模式共用 [BlockEpilogueFinalizeRouting](../../epilogue/block/block_epilogue_finalize_routing.md)。Pertoken 和 A8W4 使用 [ProcessSharedInput](../../epilogue/tile/arch35/process_shared_input.md)。 | ||
| @@ -0,0 +1,75 @@ | |||
| 1 | +# KernelQgmmMixPertokenFinalizeRouting | ||
| 2 | + | ||
| 3 | +## 功能与接口 | ||
| 4 | + | ||
| 5 | +本组件为 arch35 pertoken 全量化 GroupedMatmulFinalizeRouting 的 `GemmUniversal` 特化。AIC 执行量化矩阵乘并写出 split-M UB 结果,AIV 执行 per-channel/per-token 反量化、可选 BF16 bias、logit 加权和路由写回。 | ||
| 6 | + | ||
| 7 | +```cpp | ||
| 8 | +using Policy = Blaze::Gemm::MatmulWithScaleMix< | ||
| 9 | + 0, false, Blaze::Gemm::KernelQgmmMixPertokenFinalizeRouting>; | ||
| 10 | +using Mmad = Blaze::Gemm::Block::BlockMmad<Policy, AType, LayoutA, | ||
| 11 | + AscendC::Std::tuple<BType>, LayoutB, AccType, LayoutC, bfloat16_t, LayoutBias>; | ||
| 12 | +using Epilogue = Blaze::Epilogue::Block::BlockEpilogueFinalizeRouting< | ||
| 13 | + OutType, AccType, float, RowIndexType, WeightScaleType, IsDeterministic, | ||
| 14 | + Blaze::Epilogue::Block::FinalizeRoutingMode::PERTOKEN>; | ||
| 15 | +using Kernel = Blaze::Gemm::Kernel::GemmUniversal< | ||
| 16 | + ProblemShape, Mmad, Epilogue, Blaze::Gemm::Block::BlockSchedulerGmmSwatWithTailSplit>; | ||
| 17 | +// Kernel kernel; kernel(params); | ||
| 18 | +``` | ||
| 19 | + | ||
| 20 | +代码中的类型由调用方声明。`ProblemShape` 是 `(M,N,K,1)` 的四维 shape;调度入口由 Policy 的 `ScheduleType` 选择。 | ||
| 21 | + | ||
| 22 | +## 类型和布局 | ||
| 23 | + | ||
| 24 | +A/B 的模板准入类型为 INT8、FP8 E4M3FN/E5M2、HIFLOAT8,实际组合还须满足底层 MMAD 的类型配对要求。算子集成常用 INT8×INT8、E4M3FN×E4M3FN、HIFLOAT8×HIFLOAT8。 | ||
| 25 | + | ||
| 26 | +- A:`nd_ext_layout_ptn`。 | ||
| 27 | +- B:`nd_ext_layout_ptn`、`dn_ext_layout_ptn`、`nz_layout_ptn`、`zn_layout_ptn`。 | ||
| 28 | +- INT8 输入的 AccType 为 INT32;FP8/HIFLOAT8 为 FP32。Epilogue 的 DataTypeIn 必须与 Mmad::L0CType 一致。 | ||
| 29 | +- OutType 为 FP32 或 BF16;logit 为 FP32;WeightScaleType 为 FP32 或 BF16;rowIndex 为 INT32 或 INT64。 | ||
| 30 | +- 本 Kernel 不处理 INT32 Cube bias,BF16 bias 由 Epilogue 在 scale 乘法之后相加。 | ||
| 31 | + | ||
| 32 | +## Params | ||
| 33 | + | ||
| 34 | +| 字段 | 含义 | | ||
| 35 | +| --- | --- | | ||
| 36 | +| `problemShape` | 全局逻辑 `(M,N,K,1)` | | ||
| 37 | +| `mmadParams` | `Mmad::Params`;输入 A/B 的 GM 地址,具体分块参数由 Kernel 组装 | | ||
| 38 | +| `sharedInputParams` | `residualGm,yGmAddr,sharedInputOffset,sharedInputLen,n,batch,residualScale`;offset/len 按行计 | | ||
| 39 | +| `epilogueParams` | 输出、scale、bias、logit、rowIndex 和可选确定性 workspace 地址 | | ||
| 40 | +| `groupListGmAddr` | INT64 分组列表 | | ||
| 41 | +| `gmmParams` | 下述 `GmmTiling` | | ||
| 42 | + | ||
| 43 | +`GmmTiling` 字段按声明顺序为: | ||
| 44 | + | ||
| 45 | +```cpp | ||
| 46 | +uint32_t groupNum, batch, sharedInputOffset, sharedInputLen; | ||
| 47 | +float residualScale; | ||
| 48 | +uint32_t baseM, baseN, baseK, kAL1, kBL1, l1BufferNum; | ||
| 49 | +uint8_t hasBias, dbL0C, groupListType; | ||
| 50 | +uint32_t deterWorkspaceSize, coreNum; | ||
| 51 | +``` | ||
| 52 | + | ||
| 53 | +baseM/baseN/baseK 和 kAL1/kBL1 均以矩阵元素数计,deterWorkspaceSize 以字节计;coreNum 是实际启动的 AIC 核数。hasBias 与 bias 指针须一致。ScaleB、logit、rowIndex 为必需数据,ScaleA 为 nullptr 时跳过逐 token scale。 | ||
| 54 | + | ||
| 55 | +## 输出初始化和计算顺序 | ||
| 56 | + | ||
| 57 | +调用方须在每次调用前清零输出 y。Kernel 在开始矩阵乘前,将 shared input 区间按 residualScale 写入 y。随后按 group 和调度 tile 计算,AIC/AIV 使用成对同步保护结果 UB。 | ||
| 58 | + | ||
| 59 | +每个 INT8 累加结果先转换为 FP32;依次乘 ScaleB、可选 ScaleA,再加可选 bias,最后乘 logit 并路由到 y。具体转换和写回规则见 [Epilogue](../../epilogue/block/block_epilogue_finalize_routing.md)。 | ||
| 60 | + | ||
| 61 | +## 确定性模式 | ||
| 62 | + | ||
| 63 | +`IsDeterministic=false` 使用 Epilogue 原子写回。`IsDeterministic=true` 将每个输入行贡献先写入 workspace,再按输入行次序归并。输出行按 `rowIndex % (2*coreNum)` 分配给 AIV;并行调用的 coreNum 必须与实际启动配置一致。 | ||
| 64 | + | ||
| 65 | +调用方必须设置 `gmmParams.deterWorkspaceSize` 和 `epilogueParams.workspaceGmAddr`。地址指向用户 workspace,不含系统 workspace 偏移。有效行窗口为: | ||
| 66 | + | ||
| 67 | +```text | ||
| 68 | +windowRows = floor(deterWorkspaceSize / (N * sizeof(OutType)) / baseM) * baseM | ||
| 69 | +``` | ||
| 70 | + | ||
| 71 | +windowRows 至少为 baseM。每个专家的 M 按当前窗口剩余行数分段,所有核按相同的分段边界同步;窗口写满后先按输入行顺序归并,再复用 workspace。单个专家可以跨越多个窗口。workspace 可写且大小不少于 deterWorkspaceSize,调用方须避免与输出/输入重叠。该组件只提供 pertoken 的确定性处理,不为 MX 或 A8W4 提供该模式。 | ||
| 72 | + | ||
| 73 | +## 相关资料 | ||
| 74 | + | ||
| 75 | +[组件总览](./grouped_matmul_finalize_routing.md);[实现](../../../../include/blaze/gemm/kernel/kernel_qgmm_mix_pertoken_finalize_routing.h)。 | ||
| @@ -0,0 +1,62 @@ | |||
| 1 | +# GmmWqgmmMxFinalizeRoutingKernel | ||
| 2 | + | ||
| 3 | +## 功能与类型 | ||
| 4 | + | ||
| 5 | +本组件在 arch35 执行 FP8 E4M3FN 激活与 packed FP4 权重的分组矩阵乘,并完成 logit 加权与 FP32 路由累加。AIV 将 packed FP4 转换为 FP8 并写入 L1;AIC 通过公共 MX BlockMmad 执行矩阵乘,结果经 split-M Fixpipe 写入 UB。 | ||
| 6 | + | ||
| 7 | +AType 为 `fp8_e4m3fn_t`;BType 为 `fp4x2_e2m1_t` 或组件模板允许的 `fp4x2_e1m2_t`。算子集成使用 E2M1。ScaleA/ScaleB 均为 E8M0,bias/shared input 为 BF16,logit/y 为 FP32,rowIndex 为 INT64。A 使用 ND,B 使用转置 WeightNZ(`zn_layout_ptn`);不提供非转置 B 或 BF16 输出入口。 | ||
| 8 | + | ||
| 9 | +## 组件组装 | ||
| 10 | + | ||
| 11 | +```cpp | ||
| 12 | +using Policy = Blaze::Gemm::GroupedMatmulFinalizeRoutingWithWeightQuantMx; | ||
| 13 | +// Mmad 的 A/B 参数分别是 (数据类型, E8M0),layout 参数是对应二元 tuple。 | ||
| 14 | +using Mmad = Blaze::Gemm::Block::BlockMmad<Policy, ATypes, ALayouts, BTypes, BLayouts, | ||
| 15 | + float, asc::te::nd_ext_layout_ptn, bfloat16_t, asc::te::nd_ext_layout_ptn>; | ||
| 16 | +using Kernel = Blaze::Gemm::Kernel::GmmWqgmmMxFinalizeRoutingKernel< | ||
| 17 | + ProblemShape, Mmad, Scheduler, WeightPrologue, Epilogue, OutputInit>; | ||
| 18 | +``` | ||
| 19 | + | ||
| 20 | +`ProblemShape` 为三维 `(K,N,groupNum)`,不能与全量化 Kernel 的 `(M,N,K,1)` 混用。Scheduler 使用 `BlockSchedulerWqgmmNResplit`;WeightPrologue、OutputInit 分别使用本头文件的 `GmmWqgmmFrWeightPrologue`、`GmmWqgmmFrOutputInit`;Epilogue 的 Mode 为 A8W4。 | ||
| 21 | + | ||
| 22 | +## Params | ||
| 23 | + | ||
| 24 | +| 字段 | 含义 | | ||
| 25 | +| --- | --- | | ||
| 26 | +| `problemShape` | `(K,N,groupNum)` | | ||
| 27 | +| `mmad` | ScaleA/ScaleB、bias、A、y 等 GM 地址;L1 分区及动态 K 由 Kernel 配置 | | ||
| 28 | +| `scheduler` | N 主块/两级尾块数量与宽度、核数、baseM、N | | ||
| 29 | +| `prologue.ptrB` | 连续 packed FP4 权重的基址 | | ||
| 30 | +| `epilogue` | 输出、logit、rowIndex 地址;`nSize` 是完整 N,不是 tile N | | ||
| 31 | +| `outputInit` | 输出与 shared input 的初始化范围 | | ||
| 32 | +| `ptrGroupList` | INT64 分组列表 | | ||
| 33 | +| `groupListType` | 0 为累计行数,1 为每组行数 | | ||
| 34 | +| `hasBias` | 是否读取 BF16 bias;与 bias 地址一致 | | ||
| 35 | + | ||
| 36 | +`outputInit` 的字段按顺序为: | ||
| 37 | + | ||
| 38 | +```cpp | ||
| 39 | +float* ptrY; | ||
| 40 | +bfloat16_t* ptrSharedInput; | ||
| 41 | +uint64_t nSize, sharedInputOffset, sharedInputLen; | ||
| 42 | +float sharedInputWeight; | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +GM 指针具有 `__gm__` 地址空间。nSize 是列数,sharedInputOffset/sharedInputLen 以行为单位。无 shared input 时 len 为 0,ptrSharedInput 可为 nullptr。 | ||
| 46 | + | ||
| 47 | +## 存储与执行约束 | ||
| 48 | + | ||
| 49 | +- WeightNZ 的 K0=32、N0=16。K 必须为 32 的倍数,N 必须为 16 的倍数;每组 packed FP4 权重占 `K*N/2` 字节,各组连续存放。逻辑转置权重 `[N,K]` 存为 `[K/32,N/16,16,32]` 的分形排列,不支持通过扩大组间存储步长补齐不对齐的 K/N。 | ||
| 50 | +- ScaleA 为 `[M,ceil(K/64),2]`;ScaleB 为 `[E,N,ceil(K/64),2]`。分组 A/ScaleA/logit/rowIndex 的行偏移按 groupList 推进。 | ||
| 51 | +- tile M/N 不超过 256;scheduler 的 coreNum 与实际启动 AIC 核数相同。空专家不生成计算 tile。 | ||
| 52 | +- kernel 为每个 tile 选择 ka/kb/k0,并保证 AIC/AIV 使用相同的权重 K 分块;公共 BlockMmad 由 AIC 搬运 ScaleB。 | ||
| 53 | +- 输出/权重转换共用部分 UB,必须使用配套组件的缓冲与同步协议。rowIndex 预取使用 242 KiB 起的两个 1 KiB 槽,logit 使用 244 KiB 起的两个 512 B 槽。 | ||
| 54 | +- AIV 在当前 tile 的前两段权重处理后预取当前 tile 的路由参数,再消费上一 tile。Fixpipe 写 UB 前,AIC 等待两个 AIV 释放输出区域。 | ||
| 55 | +- FP32 累加结果经 Epilogue 乘以 64,再乘 logit。该因子用于恢复权重转换的计算比例,调用方不应再乘一次。 | ||
| 56 | +- 非负 rowIndex 必须小于 batch;负 rowIndex 跳过对应行的路由贡献。写回采用 FP32 原子加,不提供确定性模板入口。 | ||
| 57 | + | ||
| 58 | +## 使用方法 | ||
| 59 | + | ||
| 60 | +`Kernel kernel; kernel(params);` 必须位于 `KERNEL_TYPE_MIX_AIC_1_2` 入口内。调用方须在每次调用前清零 y;OutputInit 仅在 shared input 区间写入缩放值。最终输出是该初值与所有路由贡献之和。 | ||
| 61 | + | ||
| 62 | +完整组装示例见 [量化直调示例](../../../../examples/acl/grouped_matmul/grouped_matmul_finalize_routing/README.md)。[实现文件](../../../../include/blaze/gemm/kernel/kernel_wqgmm_mx_mix_finalize_routing.h)。 | ||
| @@ -124,7 +124,7 @@ C++(ACL 直调)样例位于 `acl/` 下;Python(torch 接口)样例位 | |||
| 124 | | `acl/block_attn_res_prepare/` | block_attn_res_prepare | Attention residual prepare 样例 | | 124 | | `acl/block_attn_res_prepare/` | block_attn_res_prepare | Attention residual prepare 样例 | |
| 125 | | `acl/weight_quant_batch_matmul_mx/` | weight_quant_batch_matmul_mx_swat | 权重量化批量矩阵乘法样例 | | 125 | | `acl/weight_quant_batch_matmul_mx/` | weight_quant_batch_matmul_mx_swat | 权重量化批量矩阵乘法样例 | |
| 126 | | `acl/weight_quant_batch_matmul/` | [weight_quant_batch_matmul_antiquant](acl/weight_quant_batch_matmul/weight_quant_batch_matmul_antiquant/README.md) | INT8 权重反量化矩阵乘,FP16/BF16 输入、两种权重存储方向及尾块 | | 126 | | `acl/weight_quant_batch_matmul/` | [weight_quant_batch_matmul_antiquant](acl/weight_quant_batch_matmul/weight_quant_batch_matmul_antiquant/README.md) | INT8 权重反量化矩阵乘,FP16/BF16 输入、两种权重存储方向及尾块 | |
| 127 | -| `acl/grouped_matmul/` | quant_grouped_matmul_mx, quant_grouped_matmul_activation_quant_mx, [quant_grouped_matmul_swiglu_quant_mx](acl/grouped_matmul/quant_grouped_matmul_swiglu_quant_mx/README.md), [quant_grouped_matmul_cubeonly](acl/grouped_matmul/quant_grouped_matmul_cubeonly/README.md), [grouped_matmul_mx_a8w4](acl/grouped_matmul/grouped_matmul_mx_a8w4/README.md), [grouped_matmul_no_quant](acl/grouped_matmul/grouped_matmul_no_quant/README.md), [grouped_matmul_finalize_routing_mx](acl/grouped_matmul/grouped_matmul_finalize_routing_mx/README.md) | Grouped MatMul 与量化、激活量化、SwiGLU MX、非量化及 FinalizeRouting MX 样例 | | 127 | +| `acl/grouped_matmul/` | quant_grouped_matmul_mx, quant_grouped_matmul_activation_quant_mx, [quant_grouped_matmul_swiglu_quant_mx](acl/grouped_matmul/quant_grouped_matmul_swiglu_quant_mx/README.md), [quant_grouped_matmul_cubeonly](acl/grouped_matmul/quant_grouped_matmul_cubeonly/README.md), [grouped_matmul_mx_a8w4](acl/grouped_matmul/grouped_matmul_mx_a8w4/README.md), [grouped_matmul_no_quant](acl/grouped_matmul/grouped_matmul_no_quant/README.md), [grouped_matmul_finalize_routing](acl/grouped_matmul/grouped_matmul_finalize_routing/README.md) | Grouped MatMul 与量化、激活量化、SwiGLU MX、非量化及 FinalizeRouting(per-token/MX/A8W4)样例 | |
| 128 | | `acl/weight_quant_matmul/` | [quant_batch_matmul_pergroup_a8w4](acl/weight_quant_matmul/quant_batch_matmul_pergroup_a8w4/README.md) | T-CG per-group 权重反量化 A8W4 矩阵乘样例 | | 128 | | `acl/weight_quant_matmul/` | [quant_batch_matmul_pergroup_a8w4](acl/weight_quant_matmul/quant_batch_matmul_pergroup_a8w4/README.md) | T-CG per-group 权重反量化 A8W4 矩阵乘样例 | |
| 129 | | `acl/quant_matmul_activation_quant/` | [quant_matmul_activation_quant](acl/quant_matmul_activation_quant/quant_matmul_activation_quant/README.md) | 量化矩阵乘 + GELU/SwiGLU/Swish + MX 量化,支持 ND/NZ | | 129 | | `acl/quant_matmul_activation_quant/` | [quant_matmul_activation_quant](acl/quant_matmul_activation_quant/quant_matmul_activation_quant/README.md) | 量化矩阵乘 + GELU/SwiGLU/Swish + MX 量化,支持 ND/NZ | |
| 130 | | `acl/transpose_quant_batch_matmul/` | tqbmm_mx | 转置量化批量矩阵乘法样例 | | 130 | | `acl/transpose_quant_batch_matmul/` | tqbmm_mx | 转置量化批量矩阵乘法样例 | |
| @@ -1,10 +1,13 @@ | |||
| 1 | ops_example_add_executable(quant_grouped_matmul_mx VER ascend950 quant_grouped_matmul_mx/quant_grouped_matmul_mx.cpp) | 1 | ops_example_add_executable(quant_grouped_matmul_mx VER ascend950 quant_grouped_matmul_mx/quant_grouped_matmul_mx.cpp) |
| 2 | ops_example_add_executable(quant_grouped_matmul_cubeonly VER ascend950 quant_grouped_matmul_cubeonly/quant_grouped_matmul_cubeonly.cpp) | 2 | ops_example_add_executable(quant_grouped_matmul_cubeonly VER ascend950 quant_grouped_matmul_cubeonly/quant_grouped_matmul_cubeonly.cpp) |
| 3 | -ops_example_add_executable(grouped_matmul_finalize_routing_mx VER ascend950 | ||
| 4 | - grouped_matmul_finalize_routing_mx/grouped_matmul_finalize_routing_mx.cpp) | ||
| 5 | ops_example_add_executable(quant_grouped_matmul_activation_quant_mx VER ascend950 | 3 | ops_example_add_executable(quant_grouped_matmul_activation_quant_mx VER ascend950 |
| 6 | quant_grouped_matmul_activation_quant_mx/quant_grouped_matmul_activation_quant_mx.cpp) | 4 | quant_grouped_matmul_activation_quant_mx/quant_grouped_matmul_activation_quant_mx.cpp) |
| 7 | ops_example_add_executable(quant_grouped_matmul_swiglu_quant_mx VER ascend950 | 5 | ops_example_add_executable(quant_grouped_matmul_swiglu_quant_mx VER ascend950 |
| 8 | quant_grouped_matmul_swiglu_quant_mx/quant_grouped_matmul_swiglu_quant_mx.cpp) | 6 | quant_grouped_matmul_swiglu_quant_mx/quant_grouped_matmul_swiglu_quant_mx.cpp) |
| 9 | ops_example_add_executable(grouped_matmul_mx_a8w4 VER ascend950 grouped_matmul_mx_a8w4/grouped_matmul_mx_a8w4.cpp) | 7 | ops_example_add_executable(grouped_matmul_mx_a8w4 VER ascend950 grouped_matmul_mx_a8w4/grouped_matmul_mx_a8w4.cpp) |
| 10 | ops_example_add_executable(grouped_matmul_no_quant VER ascend950 grouped_matmul_no_quant/grouped_matmul_no_quant.cpp) | 8 | ops_example_add_executable(grouped_matmul_no_quant VER ascend950 grouped_matmul_no_quant/grouped_matmul_no_quant.cpp) |
| 9 | + | ||
| 10 | +ops_example_add_executable(grouped_matmul_finalize_routing_mx VER ascend950 | ||
| 11 | + grouped_matmul_finalize_routing_mx/grouped_matmul_finalize_routing_mx.cpp) | ||
| 12 | +ops_example_add_executable(grouped_matmul_finalize_routing VER ascend950 | ||
| 13 | + grouped_matmul_finalize_routing/grouped_matmul_finalize_routing.cpp) | ||
| @@ -0,0 +1,77 @@ | |||
| 1 | +# GroupedMatmulFinalizeRouting 示例 | ||
| 2 | + | ||
| 3 | +## 功能与目录 | ||
| 4 | + | ||
| 5 | +本示例面向 Ascend950(DAV_3510、arch35),通过 CSV 参数选择量化模式、权重格式和数据类型,直接组装 ops-tensor 的 Kernel、BlockMmad、Epilogue 和 Scheduler。它是 device 组件的调用示例,不依赖 ops-transformer 的 aclnn 入口。 | ||
| 6 | + | ||
| 7 | +本目录使用单一目标 `grouped_matmul_finalize_routing`,包含同名 CPP、CSV、CONF,以及组件组装头 `gmmfr_kernel.h`。数据生成和精度校验脚本为 `examples/acl/grouped_matmul/scripts/gen_gmmfr_quant_data.py`、`verify_gmmfr_quant_result.py`,遵循统一执行器的目录约定。 | ||
| 8 | + | ||
| 9 | +## 支持组合 | ||
| 10 | + | ||
| 11 | +| quant_mode | weight_format | dtype(A) | B | output_dtype | logit_dtype | | ||
| 12 | +| --- | --- | --- | --- | --- | --- | | ||
| 13 | +| pertoken | NZ | int8、fp8_e4m3fn、hifloat8 | 与 A 同类型,转置 WeightNZ | float32 | float32 | | ||
| 14 | +| mx | ND | fp8_e4m3fn、fp8_e5m2、fp4_e2m1 | 与 A 同类型,非转置 ND | float32 | float32 | | ||
| 15 | +| mx | NZ | fp4_e2m1 | 同类型,非转置 WeightNZ | bfloat16 | bfloat16 | | ||
| 16 | +| mx | NZ | fp8_e4m3fn | 同类型,非转置 WeightNZ | bfloat16、float32 | float32 | | ||
| 17 | +| a8w4 | NZ | fp8_e4m3fn | packed FP4 E2M1,转置 WeightNZ | float32 | float32 | | ||
| 18 | + | ||
| 19 | +A 为 ND,bias/shared input 为 BF16。FP32 输出使用 INT64 rowIndex,BF16 输出使用 INT32 rowIndex。本表列出本示例提供的组合,不代表组件模板或 aclnn 接口的全部能力。 | ||
| 20 | + | ||
| 21 | +CSV 共 22 条:pertoken 的三个类型、MX WeightND 的三个类型及 A8W4 各有对齐与 M 尾块场景,共 14 条;另有 3 条 MX WeightNZ FP32/BF16 输出场景,以及 5 条 INT8 确定性场景(尾块、大 N、单专家跨窗口、跨组窗口及恰好写满窗口)。尾块场景覆盖可选 token scale、非零 bias/shared input、空专家和累计分组列表。 | ||
| 22 | + | ||
| 23 | +## 构建与执行 | ||
| 24 | + | ||
| 25 | +从 ops-tensor 根目录执行: | ||
| 26 | + | ||
| 27 | +```bash | ||
| 28 | +source /usr/local/Ascend/cann/set_env.sh | ||
| 29 | +git submodule update --init include/tensor_api | ||
| 30 | +python3 -m pip install numpy ml_dtypes | ||
| 31 | +bash examples/acl/common/run.sh --ops=grouped_matmul --target=grouped_matmul_finalize_routing -j1 | ||
| 32 | +``` | ||
| 33 | + | ||
| 34 | +统一 runner 依次完成编译、生成输入、执行 NPU kernel 和 CPU golden 对比。`--ti=0` 选择首条场景;`--build-only` 仅构建,`--skip-build` 复用可执行文件。输入与输出位于本目录的 `input/`、`output/`;runner 执行后清理生成数据,结果汇总写入同目录的 `grouped_matmul_finalize_routing_result.csv`。 | ||
| 35 | + | ||
| 36 | +本示例使用仓库固定版本的 tensor_api 子模块及配套 CANN 编译器。Kernel 启动类型为 `KERNEL_TYPE_MIX_AIC_1_2`,一个 AIC 配两个 AIV。 | ||
| 37 | + | ||
| 38 | +## 配置字段与约束 | ||
| 39 | + | ||
| 40 | +- `quant_mode,weight_format,dtype,output_dtype,logit_dtype`:取上表组合。A8W4 的 B 固定为 FP4 E2M1。 | ||
| 41 | +- `e,m,k,n,batch`:正整数,m 是所有专家的输入总行数;示例要求 K/N 为 64 的倍数。非转置 NZ 的 K0=16,FP8/FP4 的 N0 分别为 32/64;转置 NZ 的 K0=32、N0=16。 | ||
| 42 | +- `bias,tokenScale`:0/1;tokenScale 仅控制 pertoken 可选的逐 token FP32 scale。MX/A8W4 的 E8M0 ScaleA 始终必需。 | ||
| 43 | +- `sharedLen,sharedOffset`:行数,非负且和不超过 batch;shared input 缩放权重固定为 0.5。 | ||
| 44 | +- `groupType`:0 为 INT64 累计行数列表,1 为 INT64 行数列表。`emptyGroup=1` 生成一个空专家。 | ||
| 45 | +- `deterministic`:仅 pertoken INT8 支持。`workspaceRows=0` 为完整 M 分配 workspace;非零值必须是 baseM 的正整数倍,可用于验证单专家跨窗口处理。 | ||
| 46 | +- pertoken ScaleB 为 FP32 `[E,N]`,可选 ScaleA 为 FP32 `[M]`。MX/A8W4 的 ScaleA/ScaleB 为 E8M0,每 32 个 K 元素一组。 | ||
| 47 | + | ||
| 48 | +pertoken/MX 全量化使用 baseM=32、baseN=64、baseK=64;K 操作数与 MX scale 的 L1 窗口均按完整 K 配置。这是示例的固定 tiling,扩展大 K 时调用方须重新检查 L1 等资源容量。A8W4 使用配套动态 K 分块和 N 重切分调度。上述约束不等同于算子 Host 的完整支持范围。 | ||
| 49 | + | ||
| 50 | +可执行文件接收以下位置参数,由 CONF 提供: | ||
| 51 | + | ||
| 52 | +```text | ||
| 53 | +quant_mode weight_format dtype output_dtype logit_dtype E M K N batch bias tokenScale sharedLen sharedOffset groupType dataDir outputPath [deterministic [workspaceRows]] | ||
| 54 | +``` | ||
| 55 | + | ||
| 56 | +dataDir 内包含 `x.bin,weight.bin,scale_b.bin,bias.bin,scale_a.bin,groups.bin,shared.bin,logit.bin,rows.bin`;程序检查配置组合和输入字节数。可选输入保留占位文件,由开关决定是否传入有效地址。Kernel 启动前将输出置零。 | ||
| 57 | + | ||
| 58 | +## 数据与精度验证 | ||
| 59 | + | ||
| 60 | +生成脚本使用明确的有限低精度编码构造非零输入;HIFLOAT8 取值为 ±1、±0.5,FP4 每两个存储元素打包成一个字节。CPU reference 独立执行分组矩阵乘、scale、bias、logit 和路由累加;输出初值包含 shared input 的贡献。 | ||
| 61 | + | ||
| 62 | +BF16 reference 在矩阵乘结果转 BF16、logit 转 BF16、BF16 乘法和每次路由加法后分别舍入,不能替换成全部 FP32 累加结束后只转换一次。 | ||
| 63 | + | ||
| 64 | +- pertoken、MX WeightND、A8W4:FP32 逐元素 atol=rtol=1e-4,不允许错误元素。 | ||
| 65 | +- MX WeightNZ:FP32 atol=rtol=4e-3,错误元素比例不超过 4e-3;BF16 atol=rtol=2e-2,错误元素比例不超过 2e-2。 | ||
| 66 | + | ||
| 67 | +所有模式均拒绝 NaN/Inf、空输出和长度不一致。阈值用于本示例的验证,不是组件的通用精度承诺。 | ||
| 68 | + | ||
| 69 | +## 组件组装 | ||
| 70 | + | ||
| 71 | +`gmmfr_kernel.h` 的 `Run<Flow,A,B,Deterministic,Out,Logit,RowIndex>` 封装示例组装,不属于 Blaze 公共 API。CSV 中的确定性 INT8 用例同时覆盖完整 workspace 和有限窗口配置。 | ||
| 72 | + | ||
| 73 | +[组件使用指南](../../../../docs/API/gemm/kernel/grouped_matmul_finalize_routing.md);[Kernel UT](../../../../tests/ut/op_kernel/grouped_matmul_finalize_routing/README.md)。 | ||
| 74 | + | ||
| 75 | +输出 y 由示例调用端在启动 kernel 前清零;kernel 仅写入 shared input 初值并累加路由结果。 | ||
| 76 | + | ||
| 77 | +`deterministic=1` 仅用于 pertoken INT8,调用方提供按 M 向上对齐到 baseM 后的 FP32 workspace,验证有序路由累加。 | ||
| @@ -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 | + | ||
| 11 | +#pragma once | ||
| 12 | +#include <cstdint> | ||
| 13 | +#include "blaze/epilogue/block/block_epilogue_finalize_routing.h" | ||
| 14 | +#include "blaze/gemm/block/block_mmad.h" | ||
| 15 | +#include "blaze/gemm/block/block_scheduler_gmm_swat_with_tail_split.h" | ||
| 16 | +#include "blaze/gemm/kernel/kernel_universal.h" | ||
| 17 | +#include "blaze/gemm/kernel/kernel_wqgmm_mx_mix_finalize_routing.h" | ||
| 18 | + | ||
| 19 | +namespace GmmfrExample { | ||
| 20 | + | ||
| 21 | +inline constexpr uint32_t BASE_M = 32; | ||
| 22 | +inline constexpr uint32_t BASE_N = 64; | ||
| 23 | +inline constexpr uint32_t BASE_K = 64; | ||
| 24 | +inline constexpr float DEFAULT_SHARED_INPUT_WEIGHT = 0.5F; | ||
| 25 | +enum class Flow : uint32_t { PERTOKEN, MX_ND, MX_NZ, A8W4 }; | ||
| 26 | + | ||
| 27 | +// Dense group configuration; output/logit/index types are selected by Run template parameters. | ||
| 28 | +struct Config { | ||
| 29 | + int64_t m{32}; | ||
| 30 | + int64_t n{128}; | ||
| 31 | + int64_t k{128}; | ||
| 32 | + uint32_t groups{2}; | ||
| 33 | + uint32_t batch{16}; | ||
| 34 | + uint32_t cores{1}; | ||
| 35 | + uint32_t hasBias{0}; | ||
| 36 | + uint32_t tokenScale{1}; | ||
| 37 | + uint32_t sharedLen{0}; | ||
| 38 | + uint32_t sharedOffset{0}; | ||
| 39 | + uint32_t groupListType{1}; | ||
| 40 | + float sharedWeight{DEFAULT_SHARED_INPUT_WEIGHT}; | ||
| 41 | + uint32_t workspaceRows{0}; | ||
| 42 | +}; | ||
| 43 | +struct Arguments { | ||
| 44 | + GM_ADDR x; | ||
| 45 | + GM_ADDR weight; | ||
| 46 | + GM_ADDR scaleB; | ||
| 47 | + GM_ADDR bias; | ||
| 48 | + GM_ADDR scaleA; | ||
| 49 | + GM_ADDR groupList; | ||
| 50 | + GM_ADDR sharedInput; | ||
| 51 | + GM_ADDR logit; | ||
| 52 | + GM_ADDR rowIndex; | ||
| 53 | + GM_ADDR y; | ||
| 54 | + GM_ADDR workspace{nullptr}; | ||
| 55 | +}; | ||
| 56 | + | ||
| 57 | +template <Flow Mode, typename A, typename B = A, bool Deterministic = false, typename Out = float, | ||
| 58 | + typename Logit = float, typename RowIndex = int64_t> | ||
| 59 | +__aicore__ inline void Run(const Arguments& args, const Config& c) | ||
| 60 | +{ | ||
| 61 | + using ND = asc::te::nd_ext_layout_ptn; | ||
| 62 | + using Scheduler = Blaze::Gemm::Block::BlockSchedulerGmmSwatWithTailSplit; | ||
| 63 | + using Shape = asc::te::shape<int64_t, int64_t, int64_t, int64_t>; | ||
| 64 | + const auto bias = c.hasBias != 0 ? args.bias : nullptr; | ||
| 65 | + const auto shared = c.sharedLen != 0 ? args.sharedInput : nullptr; | ||
| 66 | + if constexpr (Mode == Flow::PERTOKEN) { | ||
| 67 | + using Acc = AscendC::Std::conditional_t<AscendC::Std::is_same_v<A, int8_t>, int32_t, float>; | ||
| 68 | + using Policy = Blaze::Gemm::MatmulWithScaleMix<0, false, Blaze::Gemm::KernelQgmmMixPertokenFinalizeRouting>; | ||
| 69 | + using Mmad = Blaze::Gemm::Block::BlockMmad<Policy, A, ND, AscendC::Std::tuple<B>, asc::te::zn_layout_ptn, Acc, | ||
| 70 | + ND, bfloat16_t, ND>; | ||
| 71 | + using Epi = Blaze::Epilogue::Block::BlockEpilogueFinalizeRouting< | ||
| 72 | + float, Acc, float, int64_t, float, Deterministic, Blaze::Epilogue::Block::FinalizeRoutingMode::PERTOKEN>; | ||
| 73 | + using Kernel = Blaze::Gemm::Kernel::GemmUniversal<Shape, Mmad, Epi, Scheduler>; | ||
| 74 | + typename Kernel::Params p{}; | ||
| 75 | + p.problemShape = {c.m, c.n, c.k, 1}; | ||
| 76 | + p.mmadParams.aGmAddr = args.x; | ||
| 77 | + p.mmadParams.bGmAddr = args.weight; | ||
| 78 | + p.sharedInputParams = {shared, args.y, c.sharedOffset, c.sharedLen, static_cast<int32_t>(c.n), | ||
| 79 | + c.batch, c.sharedWeight}; | ||
| 80 | + p.epilogueParams = {args.y, args.scaleB, c.tokenScale != 0 ? args.scaleA : nullptr, | ||
| 81 | + bias, args.logit, args.rowIndex}; | ||
| 82 | + p.gmmParams = {c.groups, | ||
| 83 | + c.batch, | ||
| 84 | + c.sharedOffset, | ||
| 85 | + c.sharedLen, | ||
| 86 | + c.sharedWeight, | ||
| 87 | + BASE_M, | ||
| 88 | + BASE_N, | ||
| 89 | + BASE_K, | ||
| 90 | + static_cast<uint32_t>(c.k), | ||
| 91 | + static_cast<uint32_t>(c.k), | ||
| 92 | + 2, | ||
| 93 | + static_cast<uint8_t>(c.hasBias), | ||
| 94 | + 1, | ||
| 95 | + static_cast<uint8_t>(c.groupListType), | ||
| 96 | + 0, | ||
| 97 | + c.cores}; | ||
| 98 | + if constexpr (Deterministic) { | ||
| 99 | + const uint64_t windowRows = c.workspaceRows != 0 ? c.workspaceRows : ((c.m + BASE_M - 1) / BASE_M) * BASE_M; | ||
| 100 | + const uint32_t windowBytes = static_cast<uint32_t>(windowRows * c.n * sizeof(float)); | ||
| 101 | + p.gmmParams.deterWorkspaceSize = windowBytes; | ||
| 102 | + p.epilogueParams.workspaceGmAddr = args.workspace; | ||
| 103 | + } | ||
| 104 | + p.groupListGmAddr = args.groupList; | ||
| 105 | + Kernel kernel; | ||
| 106 | + kernel(p); | ||
| 107 | + } else if constexpr (Mode == Flow::MX_ND || Mode == Flow::MX_NZ) { | ||
| 108 | + using Policy = Blaze::Gemm::GroupedMatmulWithScaleMx<0, false, Blaze::Gemm::KernelQgmmMxMixFinalizeRouting>; | ||
| 109 | + using WeightLayout = AscendC::Std::conditional_t<Mode == Flow::MX_NZ, asc::te::nz_layout_ptn, ND>; | ||
| 110 | + using Mmad = Blaze::Gemm::Block::BlockMmad<Policy, A, ND, B, WeightLayout, float, ND, bfloat16_t, ND>; | ||
| 111 | + using Prologue = Blaze::Gemm::Kernel::BlockPrologueFinalizeRouting<Out, bfloat16_t>; | ||
| 112 | + using Epi = Blaze::Epilogue::Block::BlockEpilogueFinalizeRouting<Out, float, Logit, RowIndex>; | ||
| 113 | + using Kernel = Blaze::Gemm::Kernel::GemmUniversal<Shape, Mmad, AscendC::Std::tuple<Prologue, Epi>, Scheduler>; | ||
| 114 | + typename Kernel::Params p{}; | ||
| 115 | + p.problemShape = {c.m, c.n, c.k, 1}; | ||
| 116 | + p.blockMmadParams = {args.x, args.weight, args.y, bias, args.scaleA, args.scaleB}; | ||
| 117 | + p.prologueParams = {shared, args.y, c.sharedOffset, c.sharedLen, static_cast<int32_t>(c.n), | ||
| 118 | + c.batch, c.sharedWeight}; | ||
| 119 | + p.epilogueParams = {args.y, args.scaleB, args.scaleA, bias, args.logit, args.rowIndex}; | ||
| 120 | + p.groupListGmAddr = args.groupList; | ||
| 121 | + p.gmmParams = {c.groups, | ||
| 122 | + c.batch, | ||
| 123 | + c.sharedOffset, | ||
| 124 | + c.sharedLen, | ||
| 125 | + c.sharedWeight, | ||
| 126 | + BASE_M, | ||
| 127 | + BASE_N, | ||
| 128 | + BASE_K, | ||
| 129 | + static_cast<uint32_t>(c.k), | ||
| 130 | + static_cast<uint32_t>(c.k), | ||
| 131 | + static_cast<uint32_t>(c.k), | ||
| 132 | + static_cast<uint32_t>(c.k), | ||
| 133 | + static_cast<uint8_t>(c.hasBias), | ||
| 134 | + 1, | ||
| 135 | + static_cast<uint8_t>(c.groupListType)}; | ||
| 136 | + Kernel kernel; | ||
| 137 | + kernel(p); | ||
| 138 | + } else { | ||
| 139 | + using Policy = Blaze::Gemm::GroupedMatmulFinalizeRoutingWithWeightQuantMx; | ||
| 140 | + using Mmad = Blaze::Gemm::Block::BlockMmad< | ||
| 141 | + Policy, AscendC::Std::tuple<A, fp8_e8m0_t>, AscendC::Std::tuple<ND, asc::te::scalea_nd_layout_ptn>, | ||
| 142 | + AscendC::Std::tuple<B, fp8_e8m0_t>, | ||
| 143 | + AscendC::Std::tuple<asc::te::zn_layout_ptn, asc::te::scaleb_dn_layout_ptn>, float, ND, bfloat16_t, ND>; | ||
| 144 | + using Prologue = Blaze::Gemm::Kernel::GmmWqgmmFrWeightPrologue<A, B, bfloat16_t>; | ||
| 145 | + using Epi = Blaze::Epilogue::Block::BlockEpilogueFinalizeRouting< | ||
| 146 | + float, float, float, int64_t, float, false, Blaze::Epilogue::Block::FinalizeRoutingMode::A8W4>; | ||
| 147 | + using Init = Blaze::Gemm::Kernel::GmmWqgmmFrOutputInit; | ||
| 148 | + using Resplit = Blaze::Gemm::Kernel::BlockSchedulerWqgmmNResplit<asc::te::shape<uint64_t, uint64_t, uint64_t>>; | ||
| 149 | + using Kernel = Blaze::Gemm::Kernel::GmmWqgmmMxFinalizeRoutingKernel< | ||
| 150 | + asc::te::shape<uint64_t, uint64_t, uint64_t>, Mmad, Resplit, Prologue, Epi, Init>; | ||
| 151 | + typename Kernel::Params p{}; | ||
| 152 | + p.problemShape = {static_cast<uint64_t>(c.k), static_cast<uint64_t>(c.n), c.groups}; | ||
| 153 | + p.mmad.aGmAddr = args.x; | ||
| 154 | + p.mmad.scaleAGmAddr = args.scaleA; | ||
| 155 | + p.mmad.scaleBGmAddr = args.scaleB; | ||
| 156 | + p.mmad.biasGmAddr = bias; | ||
| 157 | + p.mmad.cGmAddr = args.y; | ||
| 158 | + constexpr uint64_t MAIN_BLOCK_N = 256; | ||
| 159 | + constexpr int32_t BASE_M_A8W4 = 256; | ||
| 160 | + p.scheduler.mainBlockCount = Blaze::Gemm::CeilDiv(static_cast<uint64_t>(c.n), MAIN_BLOCK_N); | ||
| 161 | + p.scheduler.mainBlockSize = MAIN_BLOCK_N; | ||
| 162 | + p.scheduler.coreNum = c.cores; | ||
| 163 | + p.scheduler.baseM = BASE_M_A8W4; | ||
| 164 | + p.scheduler.nSize = static_cast<uint64_t>(c.n); | ||
| 165 | + p.prologue = {reinterpret_cast<__gm__ B*>(args.weight)}; | ||
| 166 | + p.epilogue = {args.y, nullptr, nullptr, nullptr, args.logit, args.rowIndex}; | ||
| 167 | + p.epilogue.nSize = c.n; | ||
| 168 | + p.outputInit = {reinterpret_cast<__gm__ float*>(args.y), | ||
| 169 | + reinterpret_cast<__gm__ bfloat16_t*>(shared), | ||
| 170 | + static_cast<uint64_t>(c.n), | ||
| 171 | + c.sharedOffset, | ||
| 172 | + c.sharedLen, | ||
| 173 | + c.sharedWeight}; | ||
| 174 | + p.ptrGroupList = args.groupList; | ||
| 175 | + p.groupListType = c.groupListType; | ||
| 176 | + p.hasBias = c.hasBias; | ||
| 177 | + Kernel kernel; | ||
| 178 | + kernel(p); | ||
| 179 | + } | ||
| 180 | +} | ||
| 181 | +} // namespace GmmfrExample | ||
Aexamples/acl/grouped_matmul/grouped_matmul_finalize_routing/grouped_matmul_finalize_routing.conf+9-0
| @@ -0,0 +1,9 @@ | |||
| 1 | +[scripts] | ||
| 2 | +gen_data=gen_gmmfr_quant_data.py | ||
| 3 | +verify=verify_gmmfr_quant_result.py | ||
| 4 | +[gen_data] | ||
| 5 | +params=--quant-mode:quant_mode,--weight-format:weight_format,--dtype:dtype,--output-dtype:output_dtype,--logit-dtype:logit_dtype,--e:e,--m:m,--k:k,--n:n,--batch:batch,--bias:bias,--token-scale:tokenScale,--shared-len:sharedLen,--shared-offset:sharedOffset,--group-type:groupType,--empty-group:emptyGroup,--output-dir:$OUTPUT_DIR | ||
| 6 | +[kernel] | ||
| 7 | +params=quant_mode,weight_format,dtype,output_dtype,logit_dtype,e,m,k,n,batch,bias,tokenScale,sharedLen,sharedOffset,groupType,$OUTPUT_DIR,$OUTPUT_DIR/npu_out.bin,deterministic,workspaceRows | ||
| 8 | +[verify] | ||
| 9 | +params=$OUTPUT_DIR/golden_y.bin,$OUTPUT_DIR/npu_out.bin,--quant-mode:quant_mode,--weight-format:weight_format,--dtype:output_dtype | ||
Aexamples/acl/grouped_matmul/grouped_matmul_finalize_routing/grouped_matmul_finalize_routing.cpp+291-0
| @@ -0,0 +1,291 @@ | |||
| 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 <algorithm> | ||
| 12 | +#include <cstdint> | ||
| 13 | +#include <fstream> | ||
| 14 | +#include <iostream> | ||
| 15 | +#include <memory> | ||
| 16 | +#include <limits> | ||
| 17 | +#include <initializer_list> | ||
| 18 | +#include <stdexcept> | ||
| 19 | +#include <string> | ||
| 20 | +#include <vector> | ||
| 21 | +#include "acl/acl.h" | ||
| 22 | +#include "data_utils.h" | ||
| 23 | +#include "platform/platform_ascendc.h" | ||
| 24 | +#include "gmmfr_kernel.h" | ||
| 25 | + | ||
| 26 | +using GmmfrExample::Arguments; | ||
| 27 | +using GmmfrExample::Config; | ||
| 28 | +using GmmfrExample::Flow; | ||
| 29 | +namespace { | ||
| 30 | +class DeviceBuffer { | ||
| 31 | +public: | ||
| 32 | + explicit DeviceBuffer(size_t bytes) : bytes_(bytes) | ||
| 33 | + { | ||
| 34 | + ACL_CHECK(aclrtMalloc(reinterpret_cast<void**>(&ptr_), bytes_, ACL_MEM_MALLOC_HUGE_FIRST)); | ||
| 35 | + } | ||
| 36 | + ~DeviceBuffer() | ||
| 37 | + { | ||
| 38 | + if (ptr_ != nullptr) { | ||
| 39 | + aclrtFree(ptr_); | ||
| 40 | + } | ||
| 41 | + } | ||
| 42 | + DeviceBuffer(const DeviceBuffer&) = delete; | ||
| 43 | + DeviceBuffer& operator=(const DeviceBuffer&) = delete; | ||
| 44 | + uint8_t* Get() const { return ptr_; } | ||
| 45 | + size_t Size() const { return bytes_; } | ||
| 46 | + | ||
| 47 | +private: | ||
| 48 | + uint8_t* ptr_{nullptr}; | ||
| 49 | + size_t bytes_{0}; | ||
| 50 | +}; | ||
| 51 | + | ||
| 52 | +std::vector<uint8_t> ReadFile(const std::string& path, size_t bytes) | ||
| 53 | +{ | ||
| 54 | + std::vector<uint8_t> data(bytes); | ||
| 55 | + std::ifstream input(path, std::ios::binary); | ||
| 56 | + if (!input) { | ||
| 57 | + throw std::runtime_error("failed to open input file: " + path); | ||
| 58 | + } | ||
| 59 | + input.read(reinterpret_cast<char*>(data.data()), static_cast<std::streamsize>(bytes)); | ||
| 60 | + if (input.gcount() != static_cast<std::streamsize>(bytes)) { | ||
| 61 | + throw std::runtime_error("input file size mismatch: " + path); | ||
| 62 | + } | ||
| 63 | + return data; | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +void CopyToDevice(DeviceBuffer& dst, const std::vector<uint8_t>& host) | ||
| 67 | +{ | ||
| 68 | + ACL_CHECK(aclrtMemcpy(dst.Get(), dst.Size(), host.data(), host.size(), ACL_MEMCPY_HOST_TO_DEVICE)); | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +void WriteFile(const std::string& path, const std::vector<uint8_t>& data) | ||
| 72 | +{ | ||
| 73 | + std::ofstream output(path, std::ios::binary); | ||
| 74 | + if (!output) { | ||
| 75 | + throw std::runtime_error("failed to open output file: " + path); | ||
| 76 | + } | ||
| 77 | + output.write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size())); | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +template <Flow Mode, typename A, typename B = A, typename Out = float, typename Logit = float, | ||
| 81 | + typename RowIndex = int64_t, bool Deterministic = false> | ||
| 82 | +__global__ __aicore__ void QuantKernel(GM_ADDR x, GM_ADDR w, GM_ADDR sb, GM_ADDR bias, GM_ADDR sa, GM_ADDR groups, | ||
| 83 | + GM_ADDR shared, GM_ADDR logit, GM_ADDR rows, GM_ADDR y, GM_ADDR workspace, | ||
| 84 | + int64_t m, int64_t n, int64_t k, uint32_t e, uint32_t batch, uint32_t cores, | ||
| 85 | + uint32_t hasBias, uint32_t tokenScale, uint32_t sharedLen, uint32_t sharedOffset, | ||
| 86 | + uint32_t groupType, uint32_t workspaceRows) | ||
| 87 | +{ | ||
| 88 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); | ||
| 89 | + AscendC::InitSocState(); | ||
| 90 | + const Config config{m, | ||
| 91 | + n, | ||
| 92 | + k, | ||
| 93 | + e, | ||
| 94 | + batch, | ||
| 95 | + cores, | ||
| 96 | + hasBias, | ||
| 97 | + tokenScale, | ||
| 98 | + sharedLen, | ||
| 99 | + sharedOffset, | ||
| 100 | + groupType, | ||
| 101 | + GmmfrExample::DEFAULT_SHARED_INPUT_WEIGHT, | ||
| 102 | + workspaceRows}; | ||
| 103 | + GmmfrExample::Run<Mode, A, B, Deterministic, Out, Logit, RowIndex>( | ||
| 104 | + {x, w, sb, bias, sa, groups, shared, logit, rows, y, workspace}, config); | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +template <Flow Mode, typename A, typename B = A, typename Out = float, typename Logit = float, | ||
| 108 | + typename RowIndex = int64_t, bool Deterministic = false> | ||
| 109 | +void Execute(const Arguments& a, const Config& c, aclrtStream stream) | ||
| 110 | +{ | ||
| 111 | + QuantKernel<Mode, A, B, Out, Logit, RowIndex, Deterministic> | ||
| 112 | + <<<c.cores, 0, stream>>>(a.x, a.weight, a.scaleB, a.bias, a.scaleA, a.groupList, a.sharedInput, a.logit, | ||
| 113 | + a.rowIndex, a.y, a.workspace, c.m, c.n, c.k, c.groups, c.batch, c.cores, c.hasBias, | ||
| 114 | + c.tokenScale, c.sharedLen, c.sharedOffset, c.groupListType, c.workspaceRows); | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +size_t Bytes(std::initializer_list<uint64_t> dimensions, size_t elementBytes = 1) | ||
| 118 | +{ | ||
| 119 | + size_t size = elementBytes; | ||
| 120 | + for (uint64_t dimension : dimensions) { | ||
| 121 | + if (dimension != 0 && size > std::numeric_limits<size_t>::max() / dimension) { | ||
| 122 | + throw std::overflow_error("tensor byte count overflows size_t"); | ||
| 123 | + } | ||
| 124 | + size *= dimension; | ||
| 125 | + } | ||
| 126 | + return size; | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +uint32_t ReadU32(const char* text) | ||
| 130 | +{ | ||
| 131 | + const auto value = std::stoull(text); | ||
| 132 | + if (value > std::numeric_limits<uint32_t>::max()) { | ||
| 133 | + throw std::invalid_argument("integer exceeds uint32 range"); | ||
| 134 | + } | ||
| 135 | + return static_cast<uint32_t>(value); | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +int RunCase(int argc, char** argv) | ||
| 139 | +{ | ||
| 140 | + if (argc < 18 || argc > 20) { | ||
| 141 | + throw std::invalid_argument("expected quantMode,weightFormat,dtype,outputDtype,logitDtype," | ||
| 142 | + "E,M,K,N,batch,bias,tokenScale,sharedLen,sharedOffset,groupType,dataDir,outputPath" | ||
| 143 | + "[,deterministic[,workspaceRows]]"); | ||
| 144 | + } | ||
| 145 | + const std::string quantMode = argv[1], weightFormat = argv[2], dtype = argv[3]; | ||
| 146 | + const std::string outputDtype = argv[4], logitDtype = argv[5]; | ||
| 147 | + if ((quantMode != "pertoken" && quantMode != "mx" && quantMode != "a8w4") || | ||
| 148 | + (weightFormat != "ND" && weightFormat != "NZ") || (quantMode != "mx" && weightFormat != "NZ")) { | ||
| 149 | + throw std::invalid_argument("unsupported quantization mode/weight format combination"); | ||
| 150 | + } | ||
| 151 | + const std::string mode = quantMode == "mx" ? (weightFormat == "ND" ? "mx_nd" : "mx_nz") : quantMode; | ||
| 152 | + const bool bf16Output = outputDtype == "bfloat16"; | ||
| 153 | + const bool deterministic = argc >= 19 && ReadU32(argv[18]) != 0; | ||
| 154 | + if (deterministic && (mode != "pertoken" || dtype != "int8")) { | ||
| 155 | + throw std::invalid_argument("deterministic example requires pertoken INT8"); | ||
| 156 | + } | ||
| 157 | + const bool bf16Logit = logitDtype == "bfloat16"; | ||
| 158 | + const bool nzTypes = mode == "mx_nz" && | ||
| 159 | + ((dtype == "fp4_e2m1" && bf16Output && bf16Logit) || (dtype == "fp8_e4m3fn" && !bf16Logit)); | ||
| 160 | + if ((outputDtype != "float32" && !bf16Output) || (logitDtype != "float32" && !bf16Logit) || | ||
| 161 | + (mode == "mx_nz" ? !nzTypes : (bf16Output || bf16Logit))) { | ||
| 162 | + throw std::invalid_argument("unsupported output/logit type for selected quantization mode"); | ||
| 163 | + } | ||
| 164 | + Config c{}; | ||
| 165 | + c.groups = ReadU32(argv[6]); | ||
| 166 | + c.m = std::stoll(argv[7]); | ||
| 167 | + c.k = std::stoll(argv[8]); | ||
| 168 | + c.n = std::stoll(argv[9]); | ||
| 169 | + c.batch = ReadU32(argv[10]); | ||
| 170 | + c.hasBias = ReadU32(argv[11]); | ||
| 171 | + c.tokenScale = ReadU32(argv[12]); | ||
| 172 | + c.sharedLen = ReadU32(argv[13]); | ||
| 173 | + c.sharedOffset = ReadU32(argv[14]); | ||
| 174 | + c.groupListType = ReadU32(argv[15]); | ||
| 175 | + c.workspaceRows = argc == 20 ? ReadU32(argv[19]) : 0; | ||
| 176 | + if (c.workspaceRows != 0 && | ||
| 177 | + (!deterministic || c.workspaceRows < GmmfrExample::BASE_M || c.workspaceRows % GmmfrExample::BASE_M != 0)) { | ||
| 178 | + throw std::invalid_argument("workspaceRows requires deterministic mode and a positive multiple of baseM"); | ||
| 179 | + } | ||
| 180 | + if (c.m <= 0 || c.n <= 0 || c.k <= 0 || c.groups == 0 || c.batch == 0 || c.k % 64 != 0 || c.n % 64 != 0 || | ||
| 181 | + c.n > std::numeric_limits<int32_t>::max() || c.hasBias > 1 || c.tokenScale > 1 || c.groupListType > 1 || | ||
| 182 | + c.sharedOffset > c.batch || c.sharedLen > c.batch - c.sharedOffset || | ||
| 183 | + (mode != "pertoken" && mode != "mx_nd" && mode != "mx_nz" && mode != "a8w4")) { | ||
| 184 | + throw std::invalid_argument("invalid example configuration; K and N must be multiples of 64"); | ||
| 185 | + } | ||
| 186 | + const bool supported = (mode == "pertoken" && (dtype == "int8" || dtype == "fp8_e4m3fn" || dtype == "hifloat8")) || | ||
| 187 | + (mode == "mx_nd" && (dtype == "fp8_e4m3fn" || dtype == "fp8_e5m2" || dtype == "fp4_e2m1")) || | ||
| 188 | + (mode == "a8w4" && dtype == "fp8_e4m3fn") || nzTypes; | ||
| 189 | + if (!supported) { | ||
| 190 | + throw std::invalid_argument("unsupported mode/dtype combination"); | ||
| 191 | + } | ||
| 192 | + c.cores = static_cast<uint32_t>(GetAicCoreNum()); | ||
| 193 | + const std::string dir = argv[16]; | ||
| 194 | + const bool mx = mode != "pertoken"; | ||
| 195 | + const bool fp4a = dtype == "fp4_e2m1"; | ||
| 196 | + const bool fp4b = fp4a || mode == "a8w4"; | ||
| 197 | + const size_t scaleWidth = mx ? static_cast<size_t>(c.k / 32) : sizeof(float); | ||
| 198 | + const std::vector<size_t> expected{ | ||
| 199 | + Bytes({static_cast<uint64_t>(c.m), static_cast<uint64_t>(c.k)}) / (fp4a ? 2U : 1U), | ||
| 200 | + Bytes({c.groups, static_cast<uint64_t>(c.k), static_cast<uint64_t>(c.n)}) / (fp4b ? 2U : 1U), | ||
| 201 | + Bytes({c.groups, static_cast<uint64_t>(c.n)}, scaleWidth), | ||
| 202 | + Bytes({c.groups, static_cast<uint64_t>(c.n)}, sizeof(bfloat16_t)), | ||
| 203 | + Bytes({static_cast<uint64_t>(c.m)}, scaleWidth), | ||
| 204 | + c.groups * sizeof(int64_t), | ||
| 205 | + Bytes({std::max(1U, c.sharedLen), static_cast<uint64_t>(c.n)}, sizeof(bfloat16_t)), | ||
| 206 | + Bytes({static_cast<uint64_t>(c.m)}, bf16Logit ? sizeof(bfloat16_t) : sizeof(float)), | ||
| 207 | + Bytes({static_cast<uint64_t>(c.m)}, bf16Output ? sizeof(int32_t) : sizeof(int64_t))}; | ||
| 208 | + std::vector<std::vector<uint8_t>> inputs; | ||
| 209 | + for (const auto* name : {"x", "weight", "scale_b", "bias", "scale_a", "groups", "shared", "logit", "rows"}) { | ||
| 210 | + const std::string path = dir + "/" + name + ".bin"; | ||
| 211 | + std::ifstream f(path, std::ios::binary | std::ios::ate); | ||
| 212 | + if (!f || f.tellg() <= 0) { | ||
| 213 | + throw std::runtime_error("missing or empty input: " + path); | ||
| 214 | + } | ||
| 215 | + if (static_cast<size_t>(f.tellg()) != expected.at(inputs.size())) { | ||
| 216 | + throw std::runtime_error("input size does not match mode/shape: " + path); | ||
| 217 | + } | ||
| 218 | + inputs.emplace_back(ReadFile(path, expected.at(inputs.size()))); | ||
| 219 | + } | ||
| 220 | + std::vector<DeviceBuffer*> buffers; | ||
| 221 | + // Allocation lifetime is owned by unique_ptr; the pointer list supplies the launch arguments. | ||
| 222 | + std::vector<std::unique_ptr<DeviceBuffer>> owners; | ||
| 223 | + for (const auto& host : inputs) { | ||
| 224 | + owners.emplace_back(std::make_unique<DeviceBuffer>(host.size())); | ||
| 225 | + CopyToDevice(*owners.back(), host); | ||
| 226 | + buffers.push_back(owners.back().get()); | ||
| 227 | + } | ||
| 228 | + DeviceBuffer y(Bytes({c.batch, static_cast<uint64_t>(c.n)}, bf16Output ? sizeof(bfloat16_t) : sizeof(float))); | ||
| 229 | + CopyToDevice(y, std::vector<uint8_t>(y.Size(), 0)); | ||
| 230 | + const uint64_t workspaceRows = c.workspaceRows != 0 ? c.workspaceRows : | ||
| 231 | + ((static_cast<uint64_t>(c.m) + GmmfrExample::BASE_M - 1) / | ||
| 232 | + GmmfrExample::BASE_M) * | ||
| 233 | + GmmfrExample::BASE_M; | ||
| 234 | + const size_t workspaceBytes = deterministic ? Bytes({workspaceRows, static_cast<uint64_t>(c.n)}, sizeof(float)) : 1; | ||
| 235 | + if (deterministic && workspaceBytes > std::numeric_limits<uint32_t>::max()) { | ||
| 236 | + throw std::overflow_error("deterministic workspace exceeds uint32 byte capacity"); | ||
| 237 | + } | ||
| 238 | + DeviceBuffer workspace(workspaceBytes); | ||
| 239 | + const Arguments a{buffers[0]->Get(), buffers[1]->Get(), buffers[2]->Get(), buffers[3]->Get(), | ||
| 240 | + buffers[4]->Get(), buffers[5]->Get(), buffers[6]->Get(), buffers[7]->Get(), | ||
| 241 | + buffers[8]->Get(), y.Get(), workspace.Get()}; | ||
| 242 | + aclrtStream stream = nullptr; | ||
| 243 | + ACL_CHECK(aclrtCreateStream(&stream)); | ||
| 244 | + if (deterministic) | ||
| 245 | + Execute<Flow::PERTOKEN, int8_t, int8_t, float, float, int64_t, true>(a, c, stream); | ||
| 246 | + else if (mode == "pertoken" && dtype == "int8") | ||
| 247 | + Execute<Flow::PERTOKEN, int8_t>(a, c, stream); | ||
| 248 | + else if (mode == "pertoken" && dtype == "fp8_e4m3fn") | ||
| 249 | + Execute<Flow::PERTOKEN, fp8_e4m3fn_t>(a, c, stream); | ||
| 250 | + else if (mode == "pertoken" && dtype == "hifloat8") | ||
| 251 | + Execute<Flow::PERTOKEN, hifloat8_t>(a, c, stream); | ||
| 252 | + else if (mode == "mx_nd" && dtype == "fp8_e4m3fn") | ||
| 253 | + Execute<Flow::MX_ND, fp8_e4m3fn_t>(a, c, stream); | ||
| 254 | + else if (mode == "mx_nd" && dtype == "fp8_e5m2") | ||
| 255 | + Execute<Flow::MX_ND, fp8_e5m2_t>(a, c, stream); | ||
| 256 | + else if (mode == "mx_nd" && dtype == "fp4_e2m1") | ||
| 257 | + Execute<Flow::MX_ND, fp4x2_e2m1_t>(a, c, stream); | ||
| 258 | + else if (mode == "mx_nz" && dtype == "fp4_e2m1") | ||
| 259 | + Execute<Flow::MX_NZ, fp4x2_e2m1_t, fp4x2_e2m1_t, bfloat16_t, bfloat16_t, int32_t>(a, c, stream); | ||
| 260 | + else if (mode == "mx_nz" && bf16Output) | ||
| 261 | + Execute<Flow::MX_NZ, fp8_e4m3fn_t, fp8_e4m3fn_t, bfloat16_t, float, int32_t>(a, c, stream); | ||
| 262 | + else if (mode == "mx_nz") | ||
| 263 | + Execute<Flow::MX_NZ, fp8_e4m3fn_t>(a, c, stream); | ||
| 264 | + else if (mode == "a8w4" && dtype == "fp8_e4m3fn") | ||
| 265 | + Execute<Flow::A8W4, fp8_e4m3fn_t, fp4x2_e2m1_t>(a, c, stream); | ||
| 266 | + else { | ||
| 267 | + throw std::invalid_argument("unsupported mode/dtype combination"); | ||
| 268 | + } | ||
| 269 | + ACL_CHECK(aclrtSynchronizeStream(stream)); | ||
| 270 | + ACL_CHECK(aclrtDestroyStream(stream)); | ||
| 271 | + std::vector<uint8_t> result(y.Size()); | ||
| 272 | + ACL_CHECK(aclrtMemcpy(result.data(), result.size(), y.Get(), y.Size(), ACL_MEMCPY_DEVICE_TO_HOST)); | ||
| 273 | + WriteFile(argv[17], result); | ||
| 274 | + return 0; | ||
| 275 | +} | ||
| 276 | +} // namespace | ||
| 277 | + | ||
| 278 | +int main(int argc, char** argv) | ||
| 279 | +{ | ||
| 280 | + try { | ||
| 281 | + ACL_CHECK(aclInit(nullptr)); | ||
| 282 | + ACL_CHECK(aclrtSetDevice(0)); | ||
| 283 | + const int result = RunCase(argc, argv); | ||
| 284 | + ACL_CHECK(aclrtResetDevice(0)); | ||
| 285 | + ACL_CHECK(aclFinalize()); | ||
| 286 | + return result; | ||
| 287 | + } catch (const std::exception& e) { | ||
| 288 | + std::cerr << e.what() << std::endl; | ||
| 289 | + return 1; | ||
| 290 | + } | ||
| 291 | +} | ||
Aexamples/acl/grouped_matmul/grouped_matmul_finalize_routing/grouped_matmul_finalize_routing.csv+23-0
| @@ -0,0 +1,23 @@ | |||
| 1 | +caseName,quant_mode,weight_format,dtype,output_dtype,logit_dtype,e,m,k,n,batch,bias,tokenScale,sharedLen,sharedOffset,groupType,emptyGroup,deterministic,workspaceRows | ||
| 2 | +pertoken_int8_aligned,pertoken,NZ,int8,float32,float32,2,32,128,128,16,0,1,0,0,1,0,0,0 | ||
| 3 | +pertoken_int8_tail,pertoken,NZ,int8,float32,float32,3,37,128,192,19,1,0,17,1,0,1,0,0 | ||
| 4 | +pertoken_fp8_e4m3fn_aligned,pertoken,NZ,fp8_e4m3fn,float32,float32,2,32,128,128,16,0,1,0,0,1,0,0,0 | ||
| 5 | +pertoken_fp8_e4m3fn_tail,pertoken,NZ,fp8_e4m3fn,float32,float32,3,37,128,192,19,1,0,17,1,0,1,0,0 | ||
| 6 | +pertoken_hifloat8_aligned,pertoken,NZ,hifloat8,float32,float32,2,32,128,128,16,0,1,0,0,1,0,0,0 | ||
| 7 | +pertoken_hifloat8_tail,pertoken,NZ,hifloat8,float32,float32,3,37,128,192,19,1,0,17,1,0,1,0,0 | ||
| 8 | +mx_nd_fp8_e4m3fn_aligned,mx,ND,fp8_e4m3fn,float32,float32,2,32,128,128,16,0,1,0,0,1,0,0,0 | ||
| 9 | +mx_nd_fp8_e4m3fn_tail,mx,ND,fp8_e4m3fn,float32,float32,3,37,128,192,19,1,0,17,1,0,1,0,0 | ||
| 10 | +mx_nd_fp8_e5m2_aligned,mx,ND,fp8_e5m2,float32,float32,2,32,128,128,16,0,1,0,0,1,0,0,0 | ||
| 11 | +mx_nd_fp8_e5m2_tail,mx,ND,fp8_e5m2,float32,float32,3,37,128,192,19,1,0,17,1,0,1,0,0 | ||
| 12 | +mx_nd_fp4_e2m1_aligned,mx,ND,fp4_e2m1,float32,float32,2,32,128,128,16,0,1,0,0,1,0,0,0 | ||
| 13 | +mx_nd_fp4_e2m1_tail,mx,ND,fp4_e2m1,float32,float32,3,37,128,192,19,1,0,17,1,0,1,0,0 | ||
| 14 | +a8w4_fp8_e4m3fn_aligned,a8w4,NZ,fp8_e4m3fn,float32,float32,2,32,128,128,16,0,1,0,0,1,0,0,0 | ||
| 15 | +a8w4_fp8_e4m3fn_tail,a8w4,NZ,fp8_e4m3fn,float32,float32,3,37,128,192,19,1,0,17,1,0,1,0,0 | ||
| 16 | +gmmfr_mxfp4_weight_nz_bf16_output_bf16_logit,mx,NZ,fp4_e2m1,bfloat16,bfloat16,2,32,64,64,16,0,1,0,0,1,0,0,0 | ||
| 17 | +gmmfr_mxfp8_e4m3_weight_nz_bf16_output_fp32_logit,mx,NZ,fp8_e4m3fn,bfloat16,float32,2,32,64,64,16,0,1,0,0,1,0,0,0 | ||
| 18 | +gmmfr_mxfp8_e4m3_weight_nz_fp32_output_fp32_logit,mx,NZ,fp8_e4m3fn,float32,float32,2,32,64,64,16,0,1,0,0,1,0,0,0 | ||
| 19 | +pertoken_int8_deterministic_tail,pertoken,NZ,int8,float32,float32,3,37,128,192,19,1,0,17,1,0,1,1,0 | ||
| 20 | +pertoken_int8_deterministic_large_n,pertoken,NZ,int8,float32,float32,16,512,128,2048,128,1,1,64,1,1,0,1,0 | ||
| 21 | +pertoken_int8_deterministic_group_over_window,pertoken,NZ,int8,float32,float32,1,193,128,192,97,0,0,0,0,1,0,1,32 | ||
| 22 | +pertoken_int8_deterministic_groups_cross_window,pertoken,NZ,int8,float32,float32,3,257,128,192,129,1,1,64,1,0,1,1,64 | ||
| 23 | +pertoken_int8_deterministic_exact_window,pertoken,NZ,int8,float32,float32,4,128,128,128,64,1,0,32,0,1,0,1,32 | ||
| @@ -19,7 +19,7 @@ | |||
| 19 | 19 | ||
| 20 | #include "acl/acl.h" | 20 | #include "acl/acl.h" |
| 21 | #include "blaze/epilogue/block/block_epilogue_finalize_routing.h" | 21 | #include "blaze/epilogue/block/block_epilogue_finalize_routing.h" |
| 22 | -#include "blaze/gemm/block/block_mmad_qgmm_mx.h" | 22 | +#include "blaze/gemm/block/block_mmad.h" |
| 23 | #include "blaze/gemm/block/block_scheduler_gmm_swat_with_tail_split.h" | 23 | #include "blaze/gemm/block/block_scheduler_gmm_swat_with_tail_split.h" |
| 24 | #include "blaze/gemm/kernel/kernel_universal.h" | 24 | #include "blaze/gemm/kernel/kernel_universal.h" |
| 25 | #include "blaze/gemm/policy/dispatch_policy.h" | 25 | #include "blaze/gemm/policy/dispatch_policy.h" |
| @@ -0,0 +1,222 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | + | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | + | ||
| 8 | +"""Generate quantized GMMFR example inputs and an independent CPU reference.""" | ||
| 9 | + | ||
| 10 | +import argparse | ||
| 11 | +from pathlib import Path | ||
| 12 | +import numpy as np | ||
| 13 | +import ml_dtypes | ||
| 14 | + | ||
| 15 | +# Exact finite values with explicit storage encodings, including HIFLOAT8. | ||
| 16 | +CODES = { | ||
| 17 | + "int8": ([1, 2, -1, -2], [1, 2, -1, -2], np.int8), | ||
| 18 | + "fp8_e4m3fn": ([0x38, 0x30, 0xB8, 0xB0], [1, 0.5, -1, -0.5], np.uint8), | ||
| 19 | + "fp8_e5m2": ([0x3C, 0x38, 0xBC, 0xB8], [1, 0.5, -1, -0.5], np.uint8), | ||
| 20 | + "hifloat8": ([0x08, 0x18, 0x88, 0x98], [1, 0.5, -1, -0.5], np.uint8), | ||
| 21 | + "fp4_e2m1": ([2, 1, 10, 9], [1, 0.5, -1, -0.5], np.uint8), | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def pack(values): | ||
| 26 | + a = np.asarray(values, np.uint8).reshape(-1) | ||
| 27 | + if a.size % 2: | ||
| 28 | + raise ValueError("FP4 requires an even element count") | ||
| 29 | + return a[::2] | (a[1::2] << 4) | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def generate(a): | ||
| 33 | + if a.quant_mode != "mx" and a.weight_format != "NZ": | ||
| 34 | + raise ValueError("pertoken/A8W4 examples require WeightNZ") | ||
| 35 | + a.mode = ( | ||
| 36 | + ("mx_nd" if a.weight_format == "ND" else "mx_nz") | ||
| 37 | + if a.quant_mode == "mx" | ||
| 38 | + else a.quant_mode | ||
| 39 | + ) | ||
| 40 | + bf16 = a.output_dtype == "bfloat16" | ||
| 41 | + nz_types = a.mode == "mx_nz" and ( | ||
| 42 | + (a.dtype == "fp4_e2m1" and bf16 and a.logit_dtype == "bfloat16") | ||
| 43 | + or (a.dtype == "fp8_e4m3fn" and a.logit_dtype == "float32") | ||
| 44 | + ) | ||
| 45 | + if (a.mode == "mx_nz" and not nz_types) or ( | ||
| 46 | + a.mode != "mx_nz" and (bf16 or a.logit_dtype != "float32") | ||
| 47 | + ): | ||
| 48 | + raise ValueError("unsupported output/logit type for selected quantization mode") | ||
| 49 | + if ( | ||
| 50 | + min(a.e, a.m, a.k, a.n, a.batch) <= 0 | ||
| 51 | + or a.k % 64 | ||
| 52 | + or a.n % 64 | ||
| 53 | + or a.shared_len < 0 | ||
| 54 | + or a.shared_offset < 0 | ||
| 55 | + or a.shared_offset + a.shared_len > a.batch | ||
| 56 | + ): | ||
| 57 | + raise ValueError( | ||
| 58 | + "positive dimensions, K/N multiples of 64 and a valid shared-input interval are required" | ||
| 59 | + ) | ||
| 60 | + allowed = { | ||
| 61 | + "pertoken": {"int8", "fp8_e4m3fn", "hifloat8"}, | ||
| 62 | + "mx_nd": {"fp8_e4m3fn", "fp8_e5m2", "fp4_e2m1"}, | ||
| 63 | + "mx_nz": {"fp8_e4m3fn", "fp4_e2m1"}, | ||
| 64 | + "a8w4": {"fp8_e4m3fn"}, | ||
| 65 | + } | ||
| 66 | + if a.dtype not in allowed[a.mode]: | ||
| 67 | + raise ValueError("unsupported mode/dtype pair") | ||
| 68 | + counts = np.full(a.e, a.m // a.e, np.int64) | ||
| 69 | + counts[-1] += a.m - int(counts.sum()) | ||
| 70 | + if a.empty_group and a.e > 1: | ||
| 71 | + counts[0] += counts[1] | ||
| 72 | + counts[1] = 0 | ||
| 73 | + groups = np.cumsum(counts) if a.group_type == 0 else counts | ||
| 74 | + rng = np.random.default_rng(a.seed) | ||
| 75 | + codes, values, storage = CODES[a.dtype] | ||
| 76 | + xi = rng.integers(0, 4, (a.m, a.k)) | ||
| 77 | + x = np.asarray(values, np.float32)[xi] | ||
| 78 | + xc = np.asarray(codes, storage)[xi] | ||
| 79 | + w_dtype = "fp4_e2m1" if a.mode == "a8w4" else a.dtype | ||
| 80 | + wc, wv, wt = CODES[w_dtype] | ||
| 81 | + wi = rng.integers(0, 4, (a.e, a.k, a.n)) | ||
| 82 | + w = np.asarray(wv, np.float32)[wi] | ||
| 83 | + raw_w = np.asarray(wc, wt)[wi] | ||
| 84 | + if a.mode == "mx_nz": | ||
| 85 | + # Non-transposed WeightNZ: [E,N1,K1,16,N0], N0=32 (FP8) or 64 (FP4). | ||
| 86 | + n0 = 64 if w_dtype == "fp4_e2m1" else 32 | ||
| 87 | + raw_w = raw_w.reshape(a.e, a.k // 16, 16, a.n // n0, n0).transpose( | ||
| 88 | + 0, 3, 1, 2, 4 | ||
| 89 | + ) | ||
| 90 | + elif a.mode != "mx_nd": | ||
| 91 | + # Transposed WeightNZ: [E,K1,N1,16,32], K0 is 32 for INT8/FP8 and A8W4. | ||
| 92 | + raw_w = ( | ||
| 93 | + raw_w.transpose(0, 2, 1) | ||
| 94 | + .reshape(a.e, a.n // 16, 16, a.k // 32, 32) | ||
| 95 | + .transpose(0, 3, 1, 2, 4) | ||
| 96 | + ) | ||
| 97 | + if w_dtype == "fp4_e2m1": | ||
| 98 | + raw_w = pack(raw_w) | ||
| 99 | + if a.dtype == "fp4_e2m1": | ||
| 100 | + xc = pack(xc) | ||
| 101 | + bias = ( | ||
| 102 | + np.where(np.arange(a.e * a.n) % 2, 0.25, -0.25).reshape(a.e, a.n) | ||
| 103 | + if a.bias | ||
| 104 | + else np.zeros((a.e, a.n)) | ||
| 105 | + ).astype(ml_dtypes.bfloat16) | ||
| 106 | + shared = ( | ||
| 107 | + np.where(np.arange(max(1, a.shared_len) * a.n) % 3, 0.5, -0.5).reshape( | ||
| 108 | + max(1, a.shared_len), a.n | ||
| 109 | + ) | ||
| 110 | + ).astype(ml_dtypes.bfloat16) | ||
| 111 | + logit_type = ml_dtypes.bfloat16 if a.logit_dtype == "bfloat16" else np.float32 | ||
| 112 | + logits = np.where(np.arange(a.m) % 2, 0.5, 0.25).astype(logit_type) | ||
| 113 | + indices = ((np.arange(a.m) * 7 + 3) % a.batch).astype( | ||
| 114 | + np.int32 if bf16 else np.int64 | ||
| 115 | + ) | ||
| 116 | + if a.mode == "pertoken": | ||
| 117 | + sa = np.where(np.arange(a.m) % 2, 0.5, 1).astype(np.float32) | ||
| 118 | + sb = ( | ||
| 119 | + np.where(np.arange(a.e * a.n) % 3, 0.5, 2) | ||
| 120 | + .reshape(a.e, a.n) | ||
| 121 | + .astype(np.float32) | ||
| 122 | + ) | ||
| 123 | + else: | ||
| 124 | + sa = ( | ||
| 125 | + np.where(np.arange(a.m * a.k // 32) % 2, 126, 127) | ||
| 126 | + .reshape(a.m, a.k // 32) | ||
| 127 | + .astype(np.uint8) | ||
| 128 | + ) | ||
| 129 | + sb = ( | ||
| 130 | + np.where(np.arange(a.e * a.n * a.k // 32) % 3, 127, 128) | ||
| 131 | + .reshape(a.e, a.n, a.k // 32) | ||
| 132 | + .astype(np.uint8) | ||
| 133 | + ) | ||
| 134 | + golden = np.zeros((a.batch, a.n), ml_dtypes.bfloat16 if bf16 else np.float32) | ||
| 135 | + if a.shared_len: | ||
| 136 | + golden[a.shared_offset : a.shared_offset + a.shared_len] = ( | ||
| 137 | + shared[: a.shared_len].astype(np.float32) * 0.5 | ||
| 138 | + ) | ||
| 139 | + start = 0 | ||
| 140 | + for expert, count in enumerate(counts): | ||
| 141 | + end = start + int(count) | ||
| 142 | + if a.mode == "pertoken": | ||
| 143 | + acc = (x[start:end] @ w[expert]) * sb[expert] | ||
| 144 | + if a.token_scale: | ||
| 145 | + acc *= sa[start:end, None] | ||
| 146 | + else: | ||
| 147 | + acc = np.zeros((int(count), a.n), np.float32) | ||
| 148 | + for b, lo in enumerate(range(0, a.k, 32)): | ||
| 149 | + ascale = np.exp2(sa[start:end, b].astype(np.int32) - 127).astype( | ||
| 150 | + np.float32 | ||
| 151 | + ) | ||
| 152 | + bscale = np.exp2(sb[expert, :, b].astype(np.int32) - 127).astype( | ||
| 153 | + np.float32 | ||
| 154 | + ) | ||
| 155 | + acc += (x[start:end, lo : lo + 32] * ascale[:, None]) @ ( | ||
| 156 | + w[expert, lo : lo + 32] * bscale | ||
| 157 | + ) | ||
| 158 | + if a.bias: | ||
| 159 | + acc += bias[expert].astype(np.float32) | ||
| 160 | + if bf16: | ||
| 161 | + # Match BF16 result/logit conversion, BF16 product and per-row BF16 atomic add. | ||
| 162 | + result = acc.astype(ml_dtypes.bfloat16).astype(np.float32) | ||
| 163 | + logit = logits[start:end].astype(ml_dtypes.bfloat16).astype(np.float32) | ||
| 164 | + contribution = (result * logit[:, None]).astype(ml_dtypes.bfloat16) | ||
| 165 | + for source, row in enumerate(indices[start:end]): | ||
| 166 | + golden[row] = ( | ||
| 167 | + golden[row].astype(np.float32) | ||
| 168 | + + contribution[source].astype(np.float32) | ||
| 169 | + ).astype(ml_dtypes.bfloat16) | ||
| 170 | + else: | ||
| 171 | + np.add.at( | ||
| 172 | + golden, | ||
| 173 | + indices[start:end], | ||
| 174 | + acc * logits[start:end, None].astype(np.float32), | ||
| 175 | + ) | ||
| 176 | + start = end | ||
| 177 | + scale_b = sb | ||
| 178 | + if a.mode in ("mx_nd", "mx_nz"): | ||
| 179 | + scale_b = sb.reshape(a.e, a.n, a.k // 64, 2).transpose(0, 2, 1, 3) | ||
| 180 | + out = Path(a.output_dir) | ||
| 181 | + out.mkdir(parents=True, exist_ok=True) | ||
| 182 | + for name, value in { | ||
| 183 | + "x": xc, | ||
| 184 | + "weight": raw_w, | ||
| 185 | + "scale_b": scale_b, | ||
| 186 | + "scale_a": sa, | ||
| 187 | + "bias": bias, | ||
| 188 | + "groups": groups, | ||
| 189 | + "shared": shared, | ||
| 190 | + "logit": logits, | ||
| 191 | + "rows": indices, | ||
| 192 | + "golden_y": golden, | ||
| 193 | + }.items(): | ||
| 194 | + np.ascontiguousarray(value).tofile(out / (name + ".bin")) | ||
| 195 | + print(f"Generated {a.mode}/{a.dtype}: E={a.e}, M={a.m}, K={a.k}, N={a.n}") | ||
| 196 | + | ||
| 197 | + | ||
| 198 | +def parse_args(): | ||
| 199 | + p = argparse.ArgumentParser(description=__doc__) | ||
| 200 | + p.add_argument("--quant-mode", choices=("pertoken", "mx", "a8w4"), required=True) | ||
| 201 | + p.add_argument("--weight-format", choices=("ND", "NZ"), required=True) | ||
| 202 | + p.add_argument("--output-dtype", choices=("float32", "bfloat16"), required=True) | ||
| 203 | + p.add_argument("--logit-dtype", choices=("float32", "bfloat16"), required=True) | ||
| 204 | + p.add_argument("--dtype", choices=tuple(CODES), required=True) | ||
| 205 | + for name in ("e", "m", "k", "n", "batch"): | ||
| 206 | + p.add_argument("--" + name, type=int, required=True) | ||
| 207 | + for name in ("bias", "token-scale", "group-type", "empty-group"): | ||
| 208 | + p.add_argument( | ||
| 209 | + "--" + name, | ||
| 210 | + type=int, | ||
| 211 | + choices=(0, 1), | ||
| 212 | + default=0 if name != "token-scale" else 1, | ||
| 213 | + ) | ||
| 214 | + p.add_argument("--shared-len", type=int, default=0) | ||
| 215 | + p.add_argument("--shared-offset", type=int, default=0) | ||
| 216 | + p.add_argument("--seed", type=int, default=20261026) | ||
| 217 | + p.add_argument("--output-dir", required=True) | ||
| 218 | + return p.parse_args() | ||
| 219 | + | ||
| 220 | + | ||
| 221 | +if __name__ == "__main__": | ||
| 222 | + generate(parse_args()) | ||
| @@ -0,0 +1,70 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | + | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | + | ||
| 8 | +"""Compare GMMFR outputs against the CPU reference using the selected example accuracy contract.""" | ||
| 9 | + | ||
| 10 | +import argparse | ||
| 11 | +from pathlib import Path | ||
| 12 | +import sys | ||
| 13 | +import numpy as np | ||
| 14 | +import ml_dtypes | ||
| 15 | + | ||
| 16 | +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "common")) | ||
| 17 | +from metrics import write_metrics_json | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def main(): | ||
| 21 | + p = argparse.ArgumentParser(description=__doc__) | ||
| 22 | + p.add_argument("golden") | ||
| 23 | + p.add_argument("actual") | ||
| 24 | + p.add_argument("--quant-mode", choices=("pertoken", "mx", "a8w4"), required=True) | ||
| 25 | + p.add_argument("--weight-format", choices=("ND", "NZ"), required=True) | ||
| 26 | + p.add_argument("--dtype", choices=("float32", "bfloat16"), required=True) | ||
| 27 | + a = p.parse_args() | ||
| 28 | + nz = a.quant_mode == "mx" and a.weight_format == "NZ" | ||
| 29 | + if a.dtype == "bfloat16" and not nz: | ||
| 30 | + raise ValueError("BF16 output is supported only by the MX WeightNZ example") | ||
| 31 | + value_tol, ratio_tol = ( | ||
| 32 | + ((2e-2, 2e-2) if a.dtype == "bfloat16" else (4e-3, 4e-3)) if nz else (1e-4, 0.0) | ||
| 33 | + ) | ||
| 34 | + dtype = ml_dtypes.bfloat16 if a.dtype == "bfloat16" else np.float32 | ||
| 35 | + g = np.fromfile(a.golden, dtype=dtype).astype(np.float32) | ||
| 36 | + x = np.fromfile(a.actual, dtype=dtype).astype(np.float32) | ||
| 37 | + if g.size == 0 or x.shape != g.shape: | ||
| 38 | + raise ValueError("empty or inconsistent output size") | ||
| 39 | + ok = ( | ||
| 40 | + np.isfinite(g) | ||
| 41 | + & np.isfinite(x) | ||
| 42 | + & np.isclose(x, g, rtol=value_tol, atol=value_tol) | ||
| 43 | + ) | ||
| 44 | + status = ( | ||
| 45 | + "pass" | ||
| 46 | + if np.all(np.isfinite(g) & np.isfinite(x)) and float(np.mean(~ok)) <= ratio_tol | ||
| 47 | + else "fail" | ||
| 48 | + ) | ||
| 49 | + write_metrics_json( | ||
| 50 | + [ | ||
| 51 | + { | ||
| 52 | + "name": "output", | ||
| 53 | + "max_abs_diff": float(np.max(np.abs(x - g))), | ||
| 54 | + "error_ratio": float(np.mean(~ok)), | ||
| 55 | + "ratio_tol": ratio_tol, | ||
| 56 | + "status": status, | ||
| 57 | + } | ||
| 58 | + ], | ||
| 59 | + status, | ||
| 60 | + str(Path(a.actual).resolve().parent), | ||
| 61 | + ) | ||
| 62 | + if status != "pass": | ||
| 63 | + raise ValueError(f"CPU golden comparison failed: {int((~ok).sum())}/{g.size}") | ||
| 64 | + print( | ||
| 65 | + f"PASS: dtype={a.dtype}, rtol=atol={value_tol}, mismatch ratio <= {ratio_tol}" | ||
| 66 | + ) | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +if __name__ == "__main__": | ||
| 70 | + main() | ||
| @@ -20,6 +20,7 @@ | |||
| 20 | #include "blaze/epilogue/tile/arch35/gelu.h" | 20 | #include "blaze/epilogue/tile/arch35/gelu.h" |
| 21 | #include "blaze/epilogue/tile/arch35/initialize_empty_softmax.h" | 21 | #include "blaze/epilogue/tile/arch35/initialize_empty_softmax.h" |
| 22 | #include "blaze/epilogue/tile/arch35/mx_quant.h" | 22 | #include "blaze/epilogue/tile/arch35/mx_quant.h" |
| 23 | +#include "blaze/epilogue/tile/arch35/process_shared_input.h" | ||
| 23 | #include "blaze/epilogue/tile/arch35/reduce_square.h" | 24 | #include "blaze/epilogue/tile/arch35/reduce_square.h" |
| 24 | #include "blaze/epilogue/tile/arch35/rms_softmax.h" | 25 | #include "blaze/epilogue/tile/arch35/rms_softmax.h" |
| 25 | #include "blaze/epilogue/tile/arch35/sigmoid.h" | 26 | #include "blaze/epilogue/tile/arch35/sigmoid.h" |
| @@ -68,10 +68,11 @@ public: | |||
| 68 | AscendC::Std::is_same_v<ScaleBType, AscendC::fp8_e8m0_t>, | 68 | AscendC::Std::is_same_v<ScaleBType, AscendC::fp8_e8m0_t>, |
| 69 | "Weight Quant MX expects E8M0 scales"); | 69 | "Weight Quant MX expects E8M0 scales"); |
| 70 | 70 | ||
| 71 | - // 只接受现有两种策略组合,避免未配套的调度类型、分块及 ScaleB 来源进入公共流水。 | 71 | + // Accept the paired QBMM, GMM and finalize-routing schedules only. |
| 72 | static_assert(AscendC::Std::is_same_v<DispatchPolicy, MatmulWithWeightQuantMx> || | 72 | static_assert(AscendC::Std::is_same_v<DispatchPolicy, MatmulWithWeightQuantMx> || |
| 73 | - AscendC::Std::is_same_v<DispatchPolicy, GroupedMatmulWithWeightQuantMx>, | 73 | + AscendC::Std::is_same_v<DispatchPolicy, GroupedMatmulWithWeightQuantMx> || |
| 74 | - "MX weight prologue supports only QBMM fixed K/AIC ScaleB or GMM dynamic K/AIV ScaleB"); | 74 | + AscendC::Std::is_same_v<DispatchPolicy, GroupedMatmulFinalizeRoutingWithWeightQuantMx>, |
| 75 | + "MX weight prologue requires a supported QBMM, GMM or finalize-routing policy"); | ||
| 75 | 76 | ||
| 76 | struct Params { | 77 | struct Params { |
| 77 | GM_ADDR aGmAddr{nullptr}; | 78 | GM_ADDR aGmAddr{nullptr}; |
| @@ -400,6 +401,10 @@ private: | |||
| 400 | PostProcess(releaseScaleBuffer, l1BufIdx); | 401 | PostProcess(releaseScaleBuffer, l1BufIdx); |
| 401 | scaleWindowIter = releaseScaleBuffer ? 0U : scaleWindowIter + 1U; | 402 | scaleWindowIter = releaseScaleBuffer ? 0U : scaleWindowIter + 1U; |
| 402 | } | 403 | } |
| 404 | + if constexpr (AscendC::Std::is_same_v<DispatchPolicy, GroupedMatmulFinalizeRoutingWithWeightQuantMx>) { | ||
| 405 | + // The next two weight strips are staged before AIV releases its W8/output arena. | ||
| 406 | + Sync::WaitForVector<SyncProtocol::MODE, PIPE_FIX>(FINALIZE_ROUTING_OUTPUT_FREE_FLAG, true); | ||
| 407 | + } | ||
| 403 | CopyCL0c2Gm(tensorC, tensorL0C, l0cSlot); | 408 | CopyCL0c2Gm(tensorC, tensorL0C, l0cSlot); |
| 404 | } | 409 | } |
| 405 | 410 | ||
| @@ -644,10 +649,16 @@ private: | |||
| 644 | template <typename TensorC, typename TensorL0C> | 649 | template <typename TensorC, typename TensorL0C> |
| 645 | __aicore__ inline void CopyCL0c2Gm(const TensorC& tensorC, const TensorL0C& tensorL0C, const BufferSlot& l0cSlot) | 650 | __aicore__ inline void CopyCL0c2Gm(const TensorC& tensorC, const TensorL0C& tensorL0C, const BufferSlot& l0cSlot) |
| 646 | { | 651 | { |
| 647 | - constexpr uint64_t FP32_64_AS_UINT64 = 0x42800000; | 652 | + if constexpr (AscendC::Std::is_same_v<asc::te::get_mem_location<TensorC>, asc::te::location::ub>) { |
| 648 | - auto copyL0C2GM = asc::te::make_copy(asc::te::copy_l0c_to_gm{}); | 653 | + auto copyL0C2UB = asc::te::make_copy(asc::te::copy_l0c_to_ub{}, Tile::CopyL0C2UBTraitMixSplitM{}); |
| 649 | - asc::te::copy(copyL0C2GM.with(asc::te::l0c_to_gm_params{asc::te::unit_flag_mode::enable_update}), tensorC, | 654 | + asc::te::copy(copyL0C2UB.with(asc::te::l0c_to_ub_params{asc::te::unit_flag_mode::enable_update}), tensorC, |
| 650 | - tensorL0C, FP32_64_AS_UINT64); | 655 | + tensorL0C); |
| 656 | + } else { | ||
| 657 | + constexpr uint64_t FP32_64_AS_UINT64 = 0x42800000; | ||
| 658 | + auto copyL0C2GM = asc::te::make_copy(asc::te::copy_l0c_to_gm{}); | ||
| 659 | + asc::te::copy(copyL0C2GM.with(asc::te::l0c_to_gm_params{asc::te::unit_flag_mode::enable_update}), tensorC, | ||
| 660 | + tensorL0C, FP32_64_AS_UINT64); | ||
| 661 | + } | ||
| 651 | } | 662 | } |
| 652 | 663 | ||
| 653 | __aicore__ inline void PostProcess(bool releaseScaleBuffer, uint64_t l1BufIdx) | 664 | __aicore__ inline void PostProcess(bool releaseScaleBuffer, uint64_t l1BufIdx) |
| @@ -660,6 +671,7 @@ private: | |||
| 660 | } | 671 | } |
| 661 | 672 | ||
| 662 | using BufferLayout = BufferIdLayout<QUADRUPLE_BUFFER_COUNT, QUADRUPLE_BUFFER_COUNT, DOUBLE_BUFFER_COUNT>; | 673 | using BufferLayout = BufferIdLayout<QUADRUPLE_BUFFER_COUNT, QUADRUPLE_BUFFER_COUNT, DOUBLE_BUFFER_COUNT>; |
| 674 | + static constexpr uint16_t FINALIZE_ROUTING_OUTPUT_FREE_FLAG = 3U; | ||
| 663 | static constexpr uint32_t SCALE_A_SLOT_BASE = 0U; | 675 | static constexpr uint32_t SCALE_A_SLOT_BASE = 0U; |
| 664 | static constexpr uint32_t SCALE_B_SLOT_BASE = DOUBLE_BUFFER_COUNT; | 676 | static constexpr uint32_t SCALE_B_SLOT_BASE = DOUBLE_BUFFER_COUNT; |
| 665 | // Disjoint local lock IDs: A 0..3, scales 4..7, B 8..11, BT 12, L0C 13, L0 14..15. | 677 | // Disjoint local lock IDs: A 0..3, scales 4..7, B 8..11, BT 12, L0C 13, L0 14..15. |
| @@ -0,0 +1,507 @@ | |||
| 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 kernel_qgmm_mix_pertoken_finalize_routing.h | ||
| 13 | + * \brief TensorAPI kernel schedule for GroupedMatmulFinalizeRouting per-token dequant | ||
| 14 | + * (INT8/FP8/HIFLOAT8 full quantization). AIC runs the quantized MMAD | ||
| 15 | + * (BlockMmad with MatmulWithScaleMix, L0C -> UB split-M fixpipe); AIV runs the | ||
| 16 | + * shared-input initialization and the dequant + logit + finalize-routing epilogue. | ||
| 17 | + */ | ||
| 18 | + | ||
| 19 | +#pragma once | ||
| 20 | + | ||
| 21 | +#include <cstdint> | ||
| 22 | + | ||
| 23 | +#include "kernel_basic_intf.h" | ||
| 24 | +#include "tensor_api/tensor.h" | ||
| 25 | + | ||
| 26 | +#include "blaze/epilogue/tile/compute.h" | ||
| 27 | +#include "blaze/gemm/kernel/kernel_universal_decl.h" | ||
| 28 | +#include "blaze/gemm/policy/dispatch_policy.h" | ||
| 29 | +#include "blaze/gemm/utils/common_utils.h" | ||
| 30 | +#include "blaze/gemm/utils/layout_utils.h" | ||
| 31 | +#include "blaze/gemm/utils/sync.h" | ||
| 32 | + | ||
| 33 | +namespace Blaze { | ||
| 34 | +namespace Gemm { | ||
| 35 | +namespace Kernel { | ||
| 36 | + | ||
| 37 | +template <class ProblemShape_, class BlockMmad_, class BlockEpilogue_, class BlockScheduler_> | ||
| 38 | +class GemmUniversal<ProblemShape_, BlockMmad_, BlockEpilogue_, BlockScheduler_, | ||
| 39 | + AscendC::Std::enable_if_t<AscendC::Std::is_same_v< | ||
| 40 | + KernelQgmmMixPertokenFinalizeRouting, typename BlockMmad_::DispatchPolicy::ScheduleType>>> { | ||
| 41 | +public: | ||
| 42 | + using ProblemShape = ProblemShape_; | ||
| 43 | + using BlockMmad = BlockMmad_; | ||
| 44 | + using BlockEpilogue = BlockEpilogue_; | ||
| 45 | + using BlockScheduler = BlockScheduler_; | ||
| 46 | + using AType = typename BlockMmad::AType; | ||
| 47 | + using BType = typename BlockMmad::BType; | ||
| 48 | + using CType = typename BlockEpilogue::DataTypeOut; | ||
| 49 | + static_assert(AscendC::Std::is_one_of_v<CType, float, bfloat16_t>, | ||
| 50 | + "GMM FR per-token initialization requires float/bfloat16_t output."); | ||
| 51 | + // The Mix block names its accumulator dtype L0CType (int32 for INT8, float otherwise). | ||
| 52 | + using MmadCType = typename BlockMmad::L0CType; | ||
| 53 | + using LayoutA = typename BlockMmad::LayoutA; | ||
| 54 | + using LayoutB = typename BlockMmad::LayoutB; | ||
| 55 | + using LayoutBias = typename BlockMmad::LayoutBias; | ||
| 56 | + static_assert((AscendC::Std::is_one_of_v<AType, int8_t, fp8_e4m3fn_t, fp8_e5m2_t, hifloat8_t>), | ||
| 57 | + "GMM FR per-token dequant requires quantized AType (int8/fp8/hifloat8)."); | ||
| 58 | + static_assert((AscendC::Std::is_one_of_v<BType, int8_t, fp8_e4m3fn_t, fp8_e5m2_t, hifloat8_t>), | ||
| 59 | + "GMM FR per-token dequant requires quantized BType (int8/fp8/hifloat8)."); | ||
| 60 | + static_assert(AscendC::Std::is_same_v<LayoutA, asc::te::nd_ext_layout_ptn>, | ||
| 61 | + "GMM FR per-token dequant only supports ND LayoutA."); | ||
| 62 | + static_assert(AscendC::Std::is_one_of_v<LayoutB, asc::te::nd_ext_layout_ptn, asc::te::dn_ext_layout_ptn, | ||
| 63 | + asc::te::nz_layout_ptn, asc::te::zn_layout_ptn>, | ||
| 64 | + "GMM FR per-token dequant only supports ND/DN/NZ/ZN LayoutB."); | ||
| 65 | + static_assert(AscendC::Std::is_same_v<MmadCType, float> || AscendC::Std::is_same_v<MmadCType, int32_t>, | ||
| 66 | + "GMM FR per-token dequant requires float/int32 MMAD output."); | ||
| 67 | + static_assert(AscendC::Std::is_same_v<typename BlockEpilogue::DataTypeIn, MmadCType>, | ||
| 68 | + "Epilogue accumulator dtype must match the MMAD output dtype."); | ||
| 69 | + | ||
| 70 | + using BlockMmadParams = typename BlockMmad::Params; | ||
| 71 | + using BlockEpilogueParams = typename BlockEpilogue::Params; | ||
| 72 | + using BlockShape = typename BlockMmad::BlockShape; | ||
| 73 | + using SchedulerProblemShape = typename BlockScheduler::ProblemShape; | ||
| 74 | + using SchedulerBlockShape = typename BlockScheduler::BlockShape; | ||
| 75 | + using SchedulerBlockCoord = typename BlockScheduler::BlockCoord; | ||
| 76 | + using EpilogueBlockShape = typename BlockEpilogue::BlockShape; | ||
| 77 | + using EpilogueBlockCoord = typename BlockEpilogue::BlockCoord; | ||
| 78 | + | ||
| 79 | + struct GmmTiling { | ||
| 80 | + uint32_t groupNum; | ||
| 81 | + uint32_t batch; | ||
| 82 | + uint32_t sharedInputOffset; | ||
| 83 | + uint32_t sharedInputLen; | ||
| 84 | + float residualScale; | ||
| 85 | + uint32_t baseM; | ||
| 86 | + uint32_t baseN; | ||
| 87 | + uint32_t baseK; | ||
| 88 | + uint32_t kAL1; | ||
| 89 | + uint32_t kBL1; | ||
| 90 | + uint32_t l1BufferNum; | ||
| 91 | + uint8_t hasBias; | ||
| 92 | + uint8_t dbL0C; | ||
| 93 | + uint8_t groupListType; | ||
| 94 | + uint32_t deterWorkspaceSize; | ||
| 95 | + uint32_t coreNum; | ||
| 96 | + }; | ||
| 97 | + | ||
| 98 | + struct SharedInputParams { | ||
| 99 | + GM_ADDR residualGm{nullptr}; | ||
| 100 | + GM_ADDR yGmAddr{nullptr}; | ||
| @@ -18,10 +18,9 @@ | |||
| 18 | #include <cstdint> | 18 | #include <cstdint> |
| 19 | 19 | ||
| 20 | #include "kernel_basic_intf.h" | 20 | #include "kernel_basic_intf.h" |
| 21 | -#include "reg_compute/kernel_reg_compute_intf.h" | 21 | +#include "blaze/epilogue/tile/compute.h" |
| 22 | #include "blaze/gemm/kernel/kernel_universal_decl.h" | 22 | #include "blaze/gemm/kernel/kernel_universal_decl.h" |
| 23 | #include "blaze/gemm/policy/dispatch_policy.h" | 23 | #include "blaze/gemm/policy/dispatch_policy.h" |
| 24 | -#include "blaze/gemm/utils/buffer_manager.h" | ||
| 25 | #include "blaze/gemm/utils/common_utils.h" | 24 | #include "blaze/gemm/utils/common_utils.h" |
| 26 | #include "blaze/gemm/utils/layout_utils.h" | 25 | #include "blaze/gemm/utils/layout_utils.h" |
| 27 | #include "blaze/gemm/utils/sync.h" | 26 | #include "blaze/gemm/utils/sync.h" |
| @@ -31,22 +30,6 @@ namespace Blaze { | |||
| 31 | namespace Gemm { | 30 | namespace Gemm { |
| 32 | namespace Kernel { | 31 | namespace Kernel { |
| 33 | 32 | ||
| 34 | -#ifdef __NPU_ARCH__ | ||
| 35 | -static constexpr AscendC::Reg::CastTrait CAST_GMM_FR_BF16_TO_FP32 = { | ||
| 36 | - AscendC::Reg::RegLayout::ZERO, AscendC::Reg::SatMode::UNKNOWN, AscendC::Reg::MaskMergeMode::ZEROING, | ||
| 37 | - AscendC::RoundMode::UNKNOWN}; | ||
| 38 | -#endif // __NPU_ARCH__ | ||
| 39 | - | ||
| 40 | -__aicore__ inline uint16_t FloatToBf16Bits(float value) | ||
| 41 | -{ | ||
| 42 | - union { | ||
| 43 | - float f; | ||
| 44 | - uint32_t u; | ||
| 45 | - } converter{value}; | ||
| 46 | - uint32_t roundingBias = 0x7FFFU + ((converter.u >> 16) & 1U); | ||
| 47 | - return static_cast<uint16_t>((converter.u + roundingBias) >> 16); | ||
| 48 | -} | ||
| 49 | - | ||
| 50 | #define GMM_FR_PROLOGUE_CLASS_LOCAL_PARAMS template <typename DataTypeOut_, typename DataTypeIn_> | 33 | #define GMM_FR_PROLOGUE_CLASS_LOCAL_PARAMS template <typename DataTypeOut_, typename DataTypeIn_> |
| 51 | #define GMM_FR_PROLOGUE_FUNC_LOCAL_PARAMS DataTypeOut_, DataTypeIn_ | 34 | #define GMM_FR_PROLOGUE_FUNC_LOCAL_PARAMS DataTypeOut_, DataTypeIn_ |
| 52 | 35 | ||
| @@ -81,14 +64,6 @@ public: | |||
| 81 | 64 | ||
| 82 | private: | 65 | private: |
| 83 | __aicore__ inline void InitAllLocalTensor(); | 66 | __aicore__ inline void InitAllLocalTensor(); |
| 84 | - __aicore__ inline void Compute(uint64_t singleCount, uint64_t outOffset, uint64_t baseOffset, uint64_t curCount); | ||
| 85 | - __aicore__ inline void CopyInShareInput(uint64_t residualUbOffset, uint64_t offset, uint64_t size); | ||
| 86 | - __aicore__ inline void CopyOutShareInput(uint64_t yUbOffset, uint64_t offset, uint64_t size); | ||
| 87 | - static __simd_vf__ inline void VfDoSharedCastAndMuls(__ubuf__ DataTypeOut* dstPtr, | ||
| 88 | - __ubuf__ DataTypeIn* residualLocalUbAddr, float sharedWeight, | ||
| 89 | - uint16_t sharedWeightBf16, uint16_t loopNum, | ||
| 90 | - uint64_t curCount); | ||
| 91 | - | ||
| 92 | const Params* params_{nullptr}; | 67 | const Params* params_{nullptr}; |
| 93 | uint64_t shareInputUbPingOffset_{0}; | 68 | uint64_t shareInputUbPingOffset_{0}; |
| 94 | uint64_t shareInputUbPongOffset_{0}; | 69 | uint64_t shareInputUbPongOffset_{0}; |
| @@ -107,35 +82,6 @@ __aicore__ inline void BlockPrologueFinalizeRouting<GMM_FR_PROLOGUE_FUNC_LOCAL_P | |||
| 107 | InitAllLocalTensor(); | 82 | InitAllLocalTensor(); |
| 108 | } | 83 | } |
| 109 | 84 | ||
| 110 | -GMM_FR_PROLOGUE_CLASS_LOCAL_PARAMS | ||
| 111 | -__aicore__ inline void BlockPrologueFinalizeRouting<GMM_FR_PROLOGUE_FUNC_LOCAL_PARAMS>::CopyInShareInput( | ||
| 112 | - uint64_t residualUbOffset, uint64_t offset, uint64_t size) | ||
| 113 | -{ | ||
| 114 | - const auto layout = asc::te::make_layout(asc::te::make_shape(size), asc::te::make_stride(1L)); | ||
| 115 | - const auto residualGm = asc::te::make_tensor( | ||
| 116 | - asc::te::make_mem_ptr<asc::te::location::gm>(reinterpret_cast<__gm__ DataTypeIn*>(params_->residualGm) + | ||
| 117 | - offset), | ||
| 118 | - layout); | ||
| 119 | - const auto residualUb = asc::te::make_tensor( | ||
| 120 | - asc::te::make_mem_ptr<asc::te::location::ub, DataTypeIn>(residualUbOffset), layout); | ||
| 121 | - asc::te::copy(asc::te::make_copy(asc::te::copy_gm_to_ub{}), residualUb, residualGm); | ||
| 122 | -} | ||
| 123 | - | ||
| 124 | -GMM_FR_PROLOGUE_CLASS_LOCAL_PARAMS | ||
| 125 | -__aicore__ inline void BlockPrologueFinalizeRouting<GMM_FR_PROLOGUE_FUNC_LOCAL_PARAMS>::CopyOutShareInput( | ||
| 126 | - uint64_t yUbOffset, uint64_t offset, uint64_t size) | ||
| 127 | -{ | ||
| 128 | - if (size == 0) { | ||
| 129 | - return; | ||
| 130 | - } | ||
| 131 | - const auto layout = asc::te::make_layout(asc::te::make_shape(size), asc::te::make_stride(1L)); | ||
| 132 | - const auto yGm = asc::te::make_tensor( | ||
| 133 | - asc::te::make_mem_ptr<asc::te::location::gm>(reinterpret_cast<__gm__ DataTypeOut*>(params_->yGmAddr) + offset), | ||
| 134 | - layout); | ||
| 135 | - const auto yUb = asc::te::make_tensor(asc::te::make_mem_ptr<asc::te::location::ub, DataTypeOut>(yUbOffset), layout); | ||
| 136 | - asc::te::copy(asc::te::make_copy(asc::te::copy_ub_to_gm{}), yGm, yUb); | ||
| 137 | -} | ||
| 138 | - | ||
| 139 | GMM_FR_PROLOGUE_CLASS_LOCAL_PARAMS | 85 | GMM_FR_PROLOGUE_CLASS_LOCAL_PARAMS |
| 140 | __aicore__ inline void BlockPrologueFinalizeRouting<GMM_FR_PROLOGUE_FUNC_LOCAL_PARAMS>::InitAllLocalTensor() | 86 | __aicore__ inline void BlockPrologueFinalizeRouting<GMM_FR_PROLOGUE_FUNC_LOCAL_PARAMS>::InitAllLocalTensor() |
| 141 | { | 87 | { |
| @@ -145,88 +91,6 @@ __aicore__ inline void BlockPrologueFinalizeRouting<GMM_FR_PROLOGUE_FUNC_LOCAL_P | |||
| 145 | ubOutPongOffset_ = ubOutPingOffset_ + GMM_FR_UB_DOUBLE_BUFFER_LEN * sizeof(DataTypeOut); | 91 | ubOutPongOffset_ = ubOutPingOffset_ + GMM_FR_UB_DOUBLE_BUFFER_LEN * sizeof(DataTypeOut); |
| 146 | } | 92 | } |
| 147 | 93 | ||
| 148 | -#ifdef __NPU_ARCH__ | ||
| 149 | -GMM_FR_PROLOGUE_CLASS_LOCAL_PARAMS | ||
| 150 | -__simd_vf__ inline void BlockPrologueFinalizeRouting<GMM_FR_PROLOGUE_FUNC_LOCAL_PARAMS>::VfDoSharedCastAndMuls( | ||
| 151 | - __ubuf__ DataTypeOut* dstPtr, __ubuf__ DataTypeIn* residualLocalUbAddr, float sharedWeight, | ||
| 152 | - uint16_t sharedWeightBf16, uint16_t loopNum, uint64_t curCount) | ||
| 153 | -{ | ||
| 154 | - constexpr uint32_t vectorRegLen = AscendC::IsSameType<DataTypeOut, bfloat16_t>::value ? | ||
| 155 | - AscendC::VECTOR_REG_WIDTH / sizeof(float) : | ||
| 156 | - AscendC::VECTOR_REG_WIDTH / sizeof(DataTypeOut); | ||
| 157 | - uint32_t elementNum = static_cast<uint32_t>(curCount); | ||
| 158 | - AscendC::Reg::MaskReg mask; | ||
| 159 | - uint16_t oneRepeatSize = vectorRegLen; | ||
| 160 | - if constexpr (AscendC::IsSameType<DataTypeOut, bfloat16_t>::value) { | ||
| 161 | - for (uint16_t i = 0; i < loopNum; ++i) { | ||
| 162 | - mask = AscendC::Reg::UpdateMask<float>(elementNum); | ||
| 163 | - AscendC::Reg::RegTensor<DataTypeIn> vSrcReg; | ||
| 164 | - AscendC::Reg::RegTensor<uint16_t> vSharedWeightReg; | ||
| 165 | - AscendC::Reg::RegTensor<bfloat16_t> vDstReg; | ||
| 166 | - AscendC::Reg::Duplicate<uint16_t, AscendC::Reg::MaskMergeMode::ZEROING>(vSharedWeightReg, sharedWeightBf16, | ||
| 167 | - mask); | ||
| 168 | - AscendC::Reg::LoadAlign<DataTypeIn, AscendC::Reg::LoadDist::DIST_UNPACK_B16>( | ||
| 169 | - vSrcReg, residualLocalUbAddr + i * oneRepeatSize); | ||
| 170 | - AscendC::Reg::Mul<bfloat16_t, AscendC::Reg::MaskMergeMode::ZEROING>( | ||
| 171 | - vDstReg, vSrcReg, reinterpret_cast<AscendC::Reg::RegTensor<bfloat16_t>&>(vSharedWeightReg), mask); | ||
| 172 | - AscendC::Reg::StoreAlign<bfloat16_t, AscendC::Reg::StoreDist::DIST_PACK_B32>(dstPtr + i * oneRepeatSize, | ||
| 173 | - vDstReg, mask); | ||
| 174 | - } | ||
| 175 | - } else { | ||
| 176 | - for (uint16_t i = 0; i < loopNum; ++i) { | ||
| 177 | - mask = AscendC::Reg::UpdateMask<DataTypeOut>(elementNum); | ||
| 178 | - AscendC::Reg::RegTensor<DataTypeIn> vSrcReg; | ||
| 179 | - AscendC::Reg::RegTensor<DataTypeOut> vRegCast; | ||
| 180 | - AscendC::Reg::RegTensor<DataTypeOut> vDstReg; | ||
| 181 | - AscendC::Reg::LoadAlign<DataTypeIn, AscendC::Reg::LoadDist::DIST_UNPACK_B16>( | ||
| 182 | - vSrcReg, residualLocalUbAddr + i * oneRepeatSize); | ||
| 183 | - AscendC::Reg::Cast<DataTypeOut, DataTypeIn, CAST_GMM_FR_BF16_TO_FP32>(vRegCast, vSrcReg, mask); | ||
| 184 | - AscendC::Reg::Muls(vDstReg, vRegCast, sharedWeight, mask); | ||
| 185 | - AscendC::Reg::StoreAlign<DataTypeOut, AscendC::Reg::StoreDist::DIST_NORM_B32>(dstPtr + i * oneRepeatSize, | ||
| 186 | - vDstReg, mask); | ||
| 187 | - } | ||
| 188 | - } | ||
| 189 | -} | ||
| 190 | -#endif // __NPU_ARCH__ | ||
| 191 | - | ||
| 192 | -GMM_FR_PROLOGUE_CLASS_LOCAL_PARAMS | ||
| 193 | -__aicore__ inline void BlockPrologueFinalizeRouting<GMM_FR_PROLOGUE_FUNC_LOCAL_PARAMS>::Compute(uint64_t singleCount, | ||
| 194 | - uint64_t outOffset, | ||
| 195 | - uint64_t baseOffset, | ||
| 196 | - uint64_t curCount) | ||
| 197 | -{ | ||
| 198 | - uint32_t pingPongId = 0; | ||
| 199 | - for (uint32_t offset = 0; offset < singleCount; offset += curCount) { | ||
| 200 | - if (unlikely(offset + curCount > singleCount)) { | ||
| 201 | - curCount = singleCount - offset; | ||
| 202 | - } | ||
| 203 | - const uint64_t residualUbOffset = pingPongId == 0 ? shareInputUbPingOffset_ : shareInputUbPongOffset_; | ||
| 204 | - const Gemm::BufferSlot bufferSlot{0UL, static_cast<uint8_t>(pingPongId)}; | ||
| 205 | - { | ||
| 206 | - auto mte2Lock = bufferSlot.LockMte2(); | ||
| 207 | - CopyInShareInput(residualUbOffset, baseOffset + offset, curCount); | ||
| 208 | - } | ||
| 209 | - const uint64_t yUbOffset = pingPongId == 0 ? ubOutPingOffset_ : ubOutPongOffset_; | ||
| 210 | - auto residualLocalUbAddr = reinterpret_cast<__ubuf__ DataTypeIn*>(residualUbOffset); | ||
| 211 | - auto outUbAddr = reinterpret_cast<__ubuf__ DataTypeOut*>(yUbOffset); | ||
| 212 | - constexpr uint32_t vectorRegLen = AscendC::IsSameType<DataTypeOut, bfloat16_t>::value ? | ||
| 213 | - AscendC::VECTOR_REG_WIDTH / sizeof(float) : | ||
| 214 | - AscendC::VECTOR_REG_WIDTH / sizeof(DataTypeOut); | ||
| 215 | - uint16_t loopNum = CeilDiv(curCount, static_cast<uint64_t>(vectorRegLen)); | ||
| 216 | - uint16_t sharedWeightBf16 = FloatToBf16Bits(params_->residualScale); | ||
| 217 | - { | ||
| 218 | - auto vectorLock = bufferSlot.LockV(); | ||
| 219 | - asc_vf_call<VfDoSharedCastAndMuls>(outUbAddr, residualLocalUbAddr, params_->residualScale, sharedWeightBf16, | ||
| 220 | - loopNum, curCount); | ||
| 221 | - } | ||
| 222 | - { | ||
| 223 | - auto mte3Lock = bufferSlot.LockMte3(); | ||
| 224 | - CopyOutShareInput(yUbOffset, outOffset + offset, curCount); | ||
| 225 | - } | ||
| 226 | - pingPongId = (pingPongId + 1) & 1; | ||
| 227 | - } | ||
| 228 | -} | ||
| 229 | - | ||
| 230 | GMM_FR_PROLOGUE_CLASS_LOCAL_PARAMS | 94 | GMM_FR_PROLOGUE_CLASS_LOCAL_PARAMS |
| 231 | __aicore__ inline void BlockPrologueFinalizeRouting<GMM_FR_PROLOGUE_FUNC_LOCAL_PARAMS>::operator()() | 95 | __aicore__ inline void BlockPrologueFinalizeRouting<GMM_FR_PROLOGUE_FUNC_LOCAL_PARAMS>::operator()() |
| 232 | { | 96 | { |
| @@ -257,7 +121,19 @@ __aicore__ inline void BlockPrologueFinalizeRouting<GMM_FR_PROLOGUE_FUNC_LOCAL_P | |||
| 257 | singleCount = totalOutput - baseOffset; | 121 | singleCount = totalOutput - baseOffset; |
| 258 | } | 122 | } |
| 259 | const uint64_t outOffset = firstZeroSize + baseOffset; | 123 | const uint64_t outOffset = firstZeroSize + baseOffset; |
| 260 | - Compute(singleCount, outOffset, baseOffset, GMM_FR_UB_DOUBLE_BUFFER_LEN); | 124 | + using ProcessSharedInput = Blaze::Epilogue::Tile::ProcessSharedInput<DataTypeOut>; |
| 125 | + const auto layout = asc::te::make_layout(asc::te::make_shape(singleCount), asc::te::make_stride(1L)); | ||
| 126 | + const auto sharedInput = asc::te::make_tensor( | ||
| 127 | + asc::te::make_mem_ptr<asc::te::location::gm>(reinterpret_cast<__gm__ bfloat16_t*>(params_->residualGm) + | ||
| 128 | + baseOffset), | ||
| 129 | + layout); | ||
| 130 | + const auto sharedOutput = asc::te::make_tensor( | ||
| 131 | + asc::te::make_mem_ptr<asc::te::location::gm>(reinterpret_cast<__gm__ DataTypeOut*>(params_->yGmAddr) + | ||
| 132 | + outOffset), | ||
| 133 | + layout); | ||
| 134 | + ProcessSharedInput::Run(sharedInput, sharedOutput, params_->residualScale, | ||
| 135 | + {shareInputUbPingOffset_, shareInputUbPongOffset_, ubOutPingOffset_, ubOutPongOffset_, | ||
| 136 | + GMM_FR_UB_DOUBLE_BUFFER_LEN}); | ||
| 261 | } | 137 | } |
| 262 | 138 | ||
| 263 | template <class ProblemShape_, class BlockMmad_, class BlockPrologue_, class BlockEpilogue_, class BlockScheduler_> | 139 | template <class ProblemShape_, class BlockMmad_, class BlockPrologue_, class BlockEpilogue_, class BlockScheduler_> |
| @@ -14,10 +14,10 @@ | |||
| 14 | * (kernel_universal_decl.h) and then every kernel_xx.h specialization fragment in this directory. | 14 | * (kernel_universal_decl.h) and then every kernel_xx.h specialization fragment in this directory. |
| 15 | * Users of these kernels include this header only; the fragments themselves include | 15 | * Users of these kernels include this header only; the fragments themselves include |
| 16 | * kernel_universal_decl.h so they stay self-contained without including this header back. | 16 | * kernel_universal_decl.h so they stay self-contained without including this header back. |
| 17 | - * The only kernel headers not aggregated here are kernel_wqgmm_mix_weight_prologue.h, which defines | 17 | + * Standalone kernel classes are included directly rather than aggregated here: |
| 18 | - * the standalone GmmWeightQuantMxKernel class rather than a GemmUniversal specialization, and | 18 | + * kernel_wqgmm_mix_weight_prologue.h defines GmmWeightQuantMxKernel, and |
| 19 | - * kernel_gmm_fixpipe_quant.h, which is a deprecated rename shim for kernel_qgmm_mix_fixpipe_quant.h; | 19 | + * kernel_wqgmm_mx_mix_finalize_routing.h defines GmmWqgmmMxFinalizeRoutingKernel. |
| 20 | - * users of those two include them directly. | 20 | + * The deprecated rename shim kernel_gmm_fixpipe_quant.h is also included directly. |
| 21 | */ | 21 | */ |
| 22 | #pragma once | 22 | #pragma once |
| 23 | 23 | ||
| @@ -59,3 +59,4 @@ | |||
| 59 | #include "blaze/gemm/kernel/kernel_wqmm_mix_antiquant.h" | 59 | #include "blaze/gemm/kernel/kernel_wqmm_mix_antiquant.h" |
| 60 | #include "blaze/gemm/kernel/kernel_wqmm_mix_pergroup.h" | 60 | #include "blaze/gemm/kernel/kernel_wqmm_mix_pergroup.h" |
| 61 | #include "blaze/gemm/kernel/kernel_rotate_quant.h" | 61 | #include "blaze/gemm/kernel/kernel_rotate_quant.h" |
| 62 | +#include "blaze/gemm/kernel/kernel_qgmm_mix_pertoken_finalize_routing.h" | ||
| @@ -56,8 +56,11 @@ struct KernelGmmSwiGluMixMx {}; // MIX AIC+AIV schedule for Gro | |||
| 56 | struct KernelMatmulEmuSplitWeight {}; // Double bf16 matmul to simulate fp32 (AIC+AIV) | 56 | struct KernelMatmulEmuSplitWeight {}; // Double bf16 matmul to simulate fp32 (AIC+AIV) |
| 57 | struct KernelMmadWithScaleMxMix {}; // Multi-block with Mx scale, epilogue after block mmad | 57 | struct KernelMmadWithScaleMxMix {}; // Multi-block with Mx scale, epilogue after block mmad |
| 58 | struct KernelQgmmMxMixFinalizeRouting {}; // MIX AIC+AIV schedule for GroupedMatmulFinalizeRouting MX | 58 | struct KernelQgmmMxMixFinalizeRouting {}; // MIX AIC+AIV schedule for GroupedMatmulFinalizeRouting MX |
| 59 | -struct KernelGroupedMmadNoQuant {}; // Grouped multi-block without quantization | 59 | +// MIX AIC+AIV schedule for GroupedMatmulFinalizeRouting per-token dequant (INT8/FP8/HIFLOAT8 |
| 60 | -struct KernelMmadAPrefetchBAntiquant {}; // AIV weight dequantization and AIC matrix multiplication | 60 | +// full-quantization, L0C -> UB splitM -> vector dequant + logit muls + routing scatter). |
| 61 | +struct KernelQgmmMixPertokenFinalizeRouting {}; | ||
| 62 | +struct KernelGroupedMmadNoQuant {}; // Grouped multi-block without quantization | ||
| 63 | +struct KernelMmadAPrefetchBAntiquant {}; // AIV weight dequantization and AIC matrix multiplication | ||
| 61 | 64 | ||
| 62 | struct KernelRotateQuant {}; // Rotate quantization single-matmul with MXFP4/FP8 AIC+AIV | 65 | struct KernelRotateQuant {}; // Rotate quantization single-matmul with MXFP4/FP8 AIC+AIV |
| 63 | 66 | ||
| @@ -164,6 +167,10 @@ struct MatmulWithWeightQuantPergroup { | |||
| 164 | using GroupedMatmulWithWeightQuantMx = WeightQuantMxPolicy<KernelWqgmmMxMix, WeightPrologueMxKSchedule::DYNAMIC, | 167 | using GroupedMatmulWithWeightQuantMx = WeightQuantMxPolicy<KernelWqgmmMxMix, WeightPrologueMxKSchedule::DYNAMIC, |
| 165 | WeightPrologueMxScaleBSource::AIV>; | 168 | WeightPrologueMxScaleBSource::AIV>; |
| 166 | 169 | ||
| 170 | +// Finalize routing uses dynamic K blocking with AIC ScaleB loads and a deferred AIV epilogue. | ||
| 171 | +using GroupedMatmulFinalizeRoutingWithWeightQuantMx = WeightQuantMxPolicy< | ||
| 172 | + KernelWqgmmMxMix, WeightPrologueMxKSchedule::DYNAMIC, WeightPrologueMxScaleBSource::AIC>; | ||
| 173 | + | ||
| 167 | /** | 174 | /** |
| 168 | * @struct GroupedMatmulWithScaleMx | 175 | * @struct GroupedMatmulWithScaleMx |
| 169 | * @brief Grouped Mx matrix multiplication with scaleA and scaleB | 176 | * @brief Grouped Mx matrix multiplication with scaleA and scaleB |
| @@ -0,0 +1,40 @@ | |||
| 1 | +# GroupedMatmulFinalizeRouting Kernel UT | ||
| 2 | + | ||
| 3 | +## 覆盖范围 | ||
| 4 | + | ||
| 5 | +本测试目录使用 Google Test、tikicpulib 和 KERNEL_RUN_KF 检查 arch35 GMMFR 的模板组装及 CPU 仿真执行是否完成。 | ||
| 6 | + | ||
| 7 | +| 测试文件 | 覆盖内容 | | ||
| 8 | +| --- | --- | | ||
| 9 | +| test_grouped_matmul_finalize_routing.cpp | 9 条 MX WeightNZ/ND/DN/ZN 用例,含 FP32/BF16 输出及 mixed FP8 | | ||
| 10 | +| test_grouped_matmul_finalize_routing_quant.cpp | 5 条固定小 shape 用例,覆盖 INT8/FP8/HIFLOAT8 pertoken、INT8 确定性和 A8W4 入口 | | ||
| 11 | + | ||
| 12 | +UT 使用非零量化输入,直接组装公开 Kernel/BlockMmad/Epilogue,不依赖 example 或 ops-transformer。仅检查模板编译和 KERNEL_RUN_KF 执行完成,不读取输出或比较 golden。尾块、bias/shared input 和精度场景由 example 覆盖。 | ||
| 13 | + | ||
| 14 | +CPU 调试使用 `grouped_matmul_finalize_routing_cpu_debug_compat.h`:复用 GMM A8W4 的设备类型、bias 常量及 UB 地址适配,将寄存器转换的 CastTrait 参数转交给 SDK 的枚举参数接口。转换仍由 SDK 实现执行;兼容宏仅在组件头文件包含期间生效,随后取消定义。 | ||
| 15 | + | ||
| 16 | +## 构建和运行 | ||
| 17 | + | ||
| 18 | +在已安装配套 CANN 与 tikicpulib 的环境,从 ops-tensor 根目录执行: | ||
| 19 | + | ||
| 20 | +```bash | ||
| 21 | +source /usr/local/Ascend/cann/set_env.sh | ||
| 22 | +bash build.sh --opkernel -u --ops=grouped_matmul_finalize_routing | ||
| 23 | +``` | ||
| 24 | + | ||
| 25 | +也可以独立配置: | ||
| 26 | + | ||
| 27 | +```bash | ||
| 28 | +cmake -S tests/ut/op_kernel -B build/kernel_ut \ | ||
| 29 | + -DOP_KERNEL_OPS=grouped_matmul_finalize_routing -DKERNEL_UT_SOC=ascend950 \ | ||
| 30 | + -DASCEND_HOME_PATH="$ASCEND_HOME_PATH" | ||
| 31 | +cmake --build build/kernel_ut -j2 | ||
| 32 | +./build/kernel_ut/ops_tensor_kernel_ut_ascend950 \ | ||
| 33 | + --gtest_filter='GroupedMatmulFinalizeRouting*' | ||
| 34 | +``` | ||
| 35 | + | ||
| 36 | +## 检查边界 | ||
| 37 | + | ||
| 38 | +这些测试检查模板组装、调度和执行完成,不作为 NPU 数值精度证明。KERNEL_RUN_KF 传播子进程的崩溃、断言和失败状态。构建时应使用与当前 tensor_api 配套的 CANN 和 tikicpulib。 | ||
| 39 | + | ||
| 40 | +NPU 数值验证使用 [量化直调示例](../../../../examples/acl/grouped_matmul/grouped_matmul_finalize_routing/README.md) 的独立 CPU golden;同一目标也覆盖 MX WeightNZ/BF16 输出。 | ||
| @@ -0,0 +1,62 @@ | |||
| 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 grouped_matmul_finalize_routing_cpu_debug_compat.h | ||
| 13 | + * \brief CPU-debug type, bias-constant and register-cast compatibility for GMMFR UT. | ||
| 14 | + */ | ||
| 15 | +#pragma once | ||
| 16 | + | ||
| 17 | +#if defined(ASCENDC_CPU_DEBUG) | ||
| 18 | +#include "blaze_kernel_stub.h" | ||
| 19 | +#include "kernel_operator.h" | ||
| 20 | +#include "grouped_matmul_mx_a8w4/grouped_matmul_mx_a8w4_cpu_debug_stub.h" | ||
| 21 | + | ||
| 22 | +namespace AscendC::Reg { | ||
| 23 | + | ||
| 24 | +// CPU debug implements enum-based CastImpl overloads. Forward the device CastTrait | ||
| 25 | +// options to those SDK implementations without replacing the conversion itself. | ||
| 26 | +// A class adapter avoids the GCC 13 ICE for reference non-type parameters in function templates. | ||
| 27 | +template <typename T_, typename U_, const CastTrait& Trait_> | ||
| 28 | +class GmmfrCpuCast { | ||
| 29 | +public: | ||
| 30 | + GmmfrCpuCast(RegTensor<T_>& dst, RegTensor<U_>& src, MaskReg& mask) | ||
| 31 | + { | ||
| 32 | + if constexpr (AscendC::IsSameType<T_, bfloat16_t>::value && AscendC::IsSameType<U_, float>::value) { | ||
| 33 | + CastImpl<T_, U_, Trait_.roundMode, Trait_.layoutMode, Trait_.mrgMode>(dst, src, mask); | ||
| 34 | + } else if constexpr (AscendC::IsSameType<T_, float>::value && AscendC::IsSameType<U_, int32_t>::value) { | ||
| 35 | + CastImpl<T_, U_, Trait_.roundMode, Trait_.mrgMode>(dst, src, mask); | ||
| 36 | + } else if constexpr (Trait_.roundMode == RoundMode::UNKNOWN && Trait_.satMode == SatMode::UNKNOWN) { | ||
| 37 | + CastImpl<T_, U_, Trait_.layoutMode, Trait_.mrgMode>(dst, src, mask); | ||
| 38 | + } else { | ||
| 39 | + CastImpl<T_, U_, Trait_.roundMode, Trait_.satMode, Trait_.layoutMode, Trait_.mrgMode>(dst, src, mask); | ||
| 40 | + } | ||
| 41 | + } | ||
| 42 | +}; | ||
| 43 | + | ||
| 44 | +} // namespace AscendC::Reg | ||
| 45 | + | ||
| 46 | +namespace AscendC { | ||
| 47 | + | ||
| 48 | +// The Cast macro also reaches AscendC::Cast calls in the aggregate headers. | ||
| 49 | +template <typename... Args> | ||
| 50 | +inline decltype(auto) GmmfrCpuCast(Args&&... args) | ||
| 51 | +{ | ||
| 52 | + return Cast(static_cast<Args&&>(args)...); | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +} // namespace AscendC | ||
| 56 | + | ||
| 57 | +// The including UT header undefines these immediately after the component includes. | ||
| 58 | +#define Cast GmmfrCpuCast | ||
| 59 | +#define __fp8e4m3 fp8_e4m3fn_t | ||
| 60 | +#define __fp4e2m1x2 fp4x2_e2m1_t | ||
| 61 | +#define __fp4e1m2x2 fp4x2_e1m2_t | ||
| 62 | +#endif | ||
| @@ -8,15 +8,23 @@ | |||
| 8 | 8 | ||
| 9 | #include <cstdint> | 9 | #include <cstdint> |
| 10 | #include <type_traits> | 10 | #include <type_traits> |
| 11 | +#include "grouped_matmul_finalize_routing_cpu_debug_compat.h" | ||
| 11 | #include "blaze_kernel_stub.h" | 12 | #include "blaze_kernel_stub.h" |
| 12 | #include "kernel_operator.h" | 13 | #include "kernel_operator.h" |
| 13 | #include "tensor_api/tensor.h" | 14 | #include "tensor_api/tensor.h" |
| 14 | #include "blaze/epilogue/block/block_epilogue_finalize_routing.h" | 15 | #include "blaze/epilogue/block/block_epilogue_finalize_routing.h" |
| 15 | -#include "blaze/gemm/block/block_mmad_qgmm_mx.h" | 16 | +#include "blaze/gemm/block/block_mmad.h" |
| 16 | #include "blaze/gemm/block/block_scheduler_gmm_swat_with_tail_split.h" | 17 | #include "blaze/gemm/block/block_scheduler_gmm_swat_with_tail_split.h" |
| 17 | #include "blaze/gemm/kernel/kernel_universal.h" | 18 | #include "blaze/gemm/kernel/kernel_universal.h" |
| 18 | #include "blaze/gemm/policy/dispatch_policy.h" | 19 | #include "blaze/gemm/policy/dispatch_policy.h" |
| 19 | 20 | ||
| 21 | +#if defined(ASCENDC_CPU_DEBUG) | ||
| 22 | +#undef __fp4e1m2x2 | ||
| 23 | +#undef __fp4e2m1x2 | ||
| 24 | +#undef __fp8e4m3 | ||
| 25 | +#undef Cast | ||
| 26 | +#endif | ||
| 27 | + | ||
| 20 | namespace GroupedMatmulFinalizeRoutingUt { | 28 | namespace GroupedMatmulFinalizeRoutingUt { |
| 21 | struct AlignedCaseConfig { | 29 | struct AlignedCaseConfig { |
| 22 | static constexpr int64_t GROUP_NUM = 2; | 30 | static constexpr int64_t GROUP_NUM = 2; |
| @@ -73,14 +81,7 @@ __aicore__ inline void Run(GM_ADDR x, GM_ADDR weight, GM_ADDR weightScale, GM_AD | |||
| 73 | params.blockMmadParams = {x, weight, y, bias, xScale, weightScale}; | 81 | params.blockMmadParams = {x, weight, y, bias, xScale, weightScale}; |
| 74 | params.prologueParams = {sharedInput, y, 0, Config::SHARED_INPUT_LEN, static_cast<int32_t>(Config::N), | 82 | params.prologueParams = {sharedInput, y, 0, Config::SHARED_INPUT_LEN, static_cast<int32_t>(Config::N), |
| 75 | Config::BATCH, 1.0F}; | 83 | Config::BATCH, 1.0F}; |
| 76 | - params.epilogueParams = {y, | 84 | + params.epilogueParams = {y, weightScale, xScale, bias, logit, rowIndex}; |
| 77 | - weightScale, | ||
| 78 | - xScale, | ||
| 79 | - bias, | ||
| 80 | - logit, | ||
| 81 | - rowIndex, | ||
| 82 | - static_cast<int32_t>(Config::BASE_M), | ||
| 83 | - static_cast<int32_t>(Config::BASE_N)}; | ||
| 84 | params.groupListGmAddr = groupList; | 85 | params.groupListGmAddr = groupList; |
| 85 | params.gmmParams = {static_cast<uint32_t>(Config::GROUP_NUM), | 86 | params.gmmParams = {static_cast<uint32_t>(Config::GROUP_NUM), |
| 86 | static_cast<uint32_t>(Config::BATCH), | 87 | static_cast<uint32_t>(Config::BATCH), |
| @@ -134,3 +134,9 @@ TEST(GroupedMatmulFinalizeRoutingKernelTest, MxFp4WeightDnFp32OutputTailWithBias | |||
| 134 | RunCase<GroupedMatmulFinalizeRoutingUt::TailCaseConfig, fp4x2_e2m1_t, fp4x2_e2m1_t, float, float, int64_t, | 134 | RunCase<GroupedMatmulFinalizeRoutingUt::TailCaseConfig, fp4x2_e2m1_t, fp4x2_e2m1_t, float, float, int64_t, |
| 135 | asc::te::dn_ext_layout_ptn>(); | 135 | asc::te::dn_ext_layout_ptn>(); |
| 136 | } | 136 | } |
| 137 | + | ||
| 138 | +TEST(GroupedMatmulFinalizeRoutingKernelTest, MxFp4WeightNdFp32Output) | ||
| 139 | +{ | ||
| 140 | + RunCase<GroupedMatmulFinalizeRoutingUt::AlignedCaseConfig, fp4x2_e2m1_t, fp4x2_e2m1_t, float, float, int64_t, | ||
| 141 | + asc::te::nd_ext_layout_ptn>(); | ||
| 142 | +} | ||
Atests/ut/op_kernel/grouped_matmul_finalize_routing/test_grouped_matmul_finalize_routing_quant.cpp+160-0
| @@ -0,0 +1,160 @@ | |||
| 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 <algorithm> | ||
| 12 | +#include <cstdint> | ||
| 13 | +#include "gtest/gtest.h" | ||
| 14 | +#include "grouped_matmul_finalize_routing_cpu_debug_compat.h" | ||
| 15 | +#include "blaze_kernel_stub.h" | ||
| 16 | +#include "kernel_ut_runner.h" | ||
| 17 | +#include "tikicpulib.h" | ||
| 18 | +#include "kernel_operator.h" | ||
| 19 | +#include "tensor_api/tensor.h" | ||
| 20 | +#include "blaze/epilogue/block/block_epilogue_finalize_routing.h" | ||
| 21 | +#include "blaze/gemm/block/block_mmad.h" | ||
| 22 | +#include "blaze/gemm/block/block_scheduler_gmm_swat_with_tail_split.h" | ||
| 23 | +#include "blaze/gemm/kernel/kernel_universal.h" | ||
| 24 | +#include "blaze/gemm/kernel/kernel_wqgmm_mx_mix_finalize_routing.h" | ||
| 25 | + | ||
| 26 | +#if defined(ASCENDC_CPU_DEBUG) | ||
| 27 | +#undef __fp4e1m2x2 | ||
| 28 | +#undef __fp4e2m1x2 | ||
| 29 | +#undef __fp8e4m3 | ||
| 30 | +#undef Cast | ||
| 31 | +#endif | ||
| 32 | + | ||
| 33 | +namespace { | ||
| 34 | +constexpr uint32_t GROUPS = 2, M = 32, K = 128, N = 128, BATCH = 16; | ||
| 35 | +constexpr uint32_t BASE_M = 32, BASE_N = 64, BASE_K = 64; | ||
| 36 | +constexpr uint32_t WORKSPACE_BYTES = M * N * sizeof(float); | ||
| 37 | + | ||
| 38 | +class GmBuffer { | ||
| 39 | +public: | ||
| 40 | + explicit GmBuffer(size_t bytes) : ptr_(static_cast<GM_ADDR>(AscendC::GmAlloc(bytes))) | ||
| 41 | + { | ||
| 42 | + if (ptr_ != nullptr) { | ||
| 43 | + std::fill_n(ptr_, bytes, 0U); | ||
| 44 | + } | ||
| 45 | + } | ||
| 46 | + ~GmBuffer() | ||
| 47 | + { | ||
| 48 | + if (ptr_ != nullptr) { | ||
| 49 | + AscendC::GmFree(ptr_); | ||
| 50 | + } | ||
| 51 | + } | ||
| 52 | + GmBuffer(const GmBuffer&) = delete; | ||
| 53 | + GmBuffer& operator=(const GmBuffer&) = delete; | ||
| 54 | + GM_ADDR Get() const { return ptr_; } | ||
| 55 | + | ||
| 56 | +private: | ||
| 57 | + GM_ADDR ptr_{nullptr}; | ||
| 58 | +}; | ||
| 59 | + | ||
| 60 | +// Fixed-shape smoke entry: instantiate the public components and check completion. | ||
| 61 | +template <typename A, bool A8W4 = false, bool Deterministic = false> | ||
| 62 | +__global__ __aicore__ void QuantSmoke(GM_ADDR x, GM_ADDR weight, GM_ADDR scaleB, GM_ADDR scaleA, GM_ADDR groups, | ||
| 63 | + GM_ADDR logit, GM_ADDR rows, GM_ADDR y, GM_ADDR workspace) | ||
| 64 | +{ | ||
| 65 | + KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2); | ||
| 66 | + AscendC::InitSocState(); | ||
| 67 | + using ND = asc::te::nd_ext_layout_ptn; | ||
| 68 | + using Shape = asc::te::shape<int64_t, int64_t, int64_t, int64_t>; | ||
| 69 | + using namespace Blaze::Gemm; | ||
| 70 | + if constexpr (!A8W4) { | ||
| 71 | + using Acc = AscendC::Std::conditional_t<AscendC::Std::is_same_v<A, int8_t>, int32_t, float>; | ||
| 72 | + using Policy = MatmulWithScaleMix<0, false, KernelQgmmMixPertokenFinalizeRouting>; | ||
| 73 | + using Mmad = Block::BlockMmad<Policy, A, ND, AscendC::Std::tuple<A>, asc::te::zn_layout_ptn, Acc, ND, | ||
| 74 | + bfloat16_t, ND>; | ||
| 75 | + using Epi = Blaze::Epilogue::Block::BlockEpilogueFinalizeRouting< | ||
| 76 | + float, Acc, float, int64_t, float, Deterministic, Blaze::Epilogue::Block::FinalizeRoutingMode::PERTOKEN>; | ||
| 77 | + using KernelType = Kernel::GemmUniversal<Shape, Mmad, Epi, Block::BlockSchedulerGmmSwatWithTailSplit>; | ||
| 78 | + typename KernelType::Params p{}; | ||
| 79 | + p.problemShape = {M, N, K, 1}; | ||
| 80 | + p.mmadParams.aGmAddr = x; | ||
| 81 | + p.mmadParams.bGmAddr = weight; | ||
| 82 | + p.sharedInputParams = {nullptr, y, 0, 0, N, BATCH, 1.0F}; | ||
| 83 | + p.epilogueParams = {y, scaleB, scaleA, nullptr, logit, rows}; | ||
| 84 | + p.gmmParams = {GROUPS, BATCH, 0, 0, 1.0F, BASE_M, BASE_N, BASE_K, K, K, 2, 0, 1, 1, 0, 1}; | ||
| 85 | + if constexpr (Deterministic) { | ||
| 86 | + p.gmmParams.deterWorkspaceSize = WORKSPACE_BYTES; | ||
| 87 | + p.epilogueParams.workspaceGmAddr = workspace; | ||
| 88 | + } | ||
| 89 | + p.groupListGmAddr = groups; | ||
| 90 | + KernelType kernel; | ||
| 91 | + kernel(p); | ||
| 92 | + } else { | ||
| 93 | + using Policy = GroupedMatmulFinalizeRoutingWithWeightQuantMx; | ||
| 94 | + using Mmad = Block::BlockMmad< | ||
| 95 | + Policy, AscendC::Std::tuple<fp8_e4m3fn_t, fp8_e8m0_t>, | ||
| 96 | + AscendC::Std::tuple<ND, asc::te::scalea_nd_layout_ptn>, AscendC::Std::tuple<fp4x2_e2m1_t, fp8_e8m0_t>, | ||
| 97 | + AscendC::Std::tuple<asc::te::zn_layout_ptn, asc::te::scaleb_dn_layout_ptn>, float, ND, bfloat16_t, ND>; | ||
| 98 | + using Prologue = Kernel::GmmWqgmmFrWeightPrologue<fp8_e4m3fn_t, fp4x2_e2m1_t, bfloat16_t>; | ||
| 99 | + using Epi = Blaze::Epilogue::Block::BlockEpilogueFinalizeRouting< | ||
| 100 | + float, float, float, int64_t, float, false, Blaze::Epilogue::Block::FinalizeRoutingMode::A8W4>; | ||
| 101 | + using Resplit = Kernel::BlockSchedulerWqgmmNResplit<asc::te::shape<uint64_t, uint64_t, uint64_t>>; | ||
| 102 | + using KernelType = Kernel::GmmWqgmmMxFinalizeRoutingKernel< | ||
| 103 | + asc::te::shape<uint64_t, uint64_t, uint64_t>, Mmad, Resplit, Prologue, Epi, Kernel::GmmWqgmmFrOutputInit>; | ||
| 104 | + typename KernelType::Params p{}; | ||
| 105 | + p.problemShape = {K, N, GROUPS}; | ||
| 106 | + p.mmad.aGmAddr = x; | ||
| 107 | + p.mmad.scaleAGmAddr = scaleA; | ||
| 108 | + p.mmad.scaleBGmAddr = scaleB; | ||
| 109 | + p.mmad.cGmAddr = y; | ||
| 110 | + p.scheduler = {1, 256, 0, 0, 0, 0, 1, 0, 256, N}; | ||
| 111 | + p.prologue = {reinterpret_cast<__gm__ fp4x2_e2m1_t*>(weight)}; | ||
| 112 | + p.epilogue = {y, nullptr, nullptr, nullptr, logit, rows}; | ||
| 113 | + p.epilogue.nSize = N; | ||
| 114 | + p.outputInit = {reinterpret_cast<__gm__ float*>(y), nullptr, N, 0, 0, 1.0F}; | ||
| 115 | + p.ptrGroupList = groups; | ||
| 116 | + p.groupListType = 1; | ||
| 117 | + KernelType kernel; | ||
| 118 | + kernel(p); | ||
| 119 | + } | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +template <typename A, bool A8W4 = false, bool Deterministic = false> | ||
| 123 | +void RunSmoke() | ||
| 124 | +{ | ||
| 125 | + const size_t scaleABytes = M * (A8W4 ? K / 32 : sizeof(float)); | ||
| 126 | + const size_t scaleBBytes = GROUPS * N * (A8W4 ? K / 32 : sizeof(float)); | ||
| 127 | + GmBuffer x(M * K), weight(GROUPS * K * N / (A8W4 ? 2U : 1U)); | ||
| 128 | + GmBuffer scaleA(scaleABytes), scaleB(scaleBBytes), groups(GROUPS * sizeof(int64_t)); | ||
| 129 | + GmBuffer logit(M * sizeof(float)), rows(M * sizeof(int64_t)), y(BATCH * N * sizeof(float)); | ||
| 130 | + GmBuffer workspace(Deterministic ? WORKSPACE_BYTES : 1U); | ||
| 131 | + for (auto* p : {&x, &weight, &scaleA, &scaleB, &groups, &logit, &rows, &y, &workspace}) { | ||
| 132 | + ASSERT_NE(p->Get(), nullptr); | ||
| 133 | + } | ||
| 134 | + std::fill_n(reinterpret_cast<int64_t*>(groups.Get()), GROUPS, M / GROUPS); | ||
| 135 | + std::fill_n(reinterpret_cast<float*>(logit.Get()), M, 1.0F); | ||
| 136 | + if constexpr (A8W4) { | ||
| 137 | + std::fill_n(scaleA.Get(), scaleABytes, 0x7FU); | ||
| 138 | + std::fill_n(scaleB.Get(), scaleBBytes, 0x7FU); | ||
| 139 | + } else { | ||
| 140 | + std::fill_n(reinterpret_cast<float*>(scaleA.Get()), M, 1.0F); | ||
| 141 | + std::fill_n(reinterpret_cast<float*>(scaleB.Get()), GROUPS * N, 1.0F); | ||
| 142 | + } | ||
| 143 | + for (uint32_t i = 0; i < M; ++i) { | ||
| 144 | + reinterpret_cast<int64_t*>(rows.Get())[i] = i % BATCH; | ||
| 145 | + } | ||
| 146 | + constexpr uint8_t INPUT_VALUE = AscendC::Std::is_same_v<A, int8_t> ? 1 : 0x38; | ||
| 147 | + std::fill_n(x.Get(), M * K, INPUT_VALUE); | ||
| 148 | + std::fill_n(weight.Get(), GROUPS * K * N / (A8W4 ? 2U : 1U), A8W4 ? 0x22 : INPUT_VALUE); | ||
| 149 | + AscendC::SetKernelMode(KernelMode::MIX_MODE); | ||
| 150 | + auto entry = QuantSmoke<A, A8W4, Deterministic>; | ||
| 151 | + ASSERT_TRUE(KERNEL_RUN_KF(entry, 1U, x.Get(), weight.Get(), scaleB.Get(), scaleA.Get(), groups.Get(), logit.Get(), | ||
这里 x 和 weight 都是 0,跑完也没校验 y,反量化或者路由累加算错了也能过。补下非零输入和 golden 对比吧,bias、sharedInput 和尾块也需要覆盖下。 ![]() ![]() | |||
| 152 | + rows.Get(), y.Get(), workspace.Get())); | ||
| 153 | +} | ||
| 154 | +} // namespace | ||
| 155 | + | ||
| 156 | +TEST(GroupedMatmulFinalizeRoutingQuantTest, PertokenInt8) { RunSmoke<int8_t>(); } | ||
| 157 | +TEST(GroupedMatmulFinalizeRoutingQuantTest, PertokenFp8) { RunSmoke<fp8_e4m3fn_t>(); } | ||
| 158 | +TEST(GroupedMatmulFinalizeRoutingQuantTest, PertokenHifloat8) { RunSmoke<hifloat8_t>(); } | ||
| 159 | +TEST(GroupedMatmulFinalizeRoutingQuantTest, PertokenInt8Deterministic) { RunSmoke<int8_t, false, true>(); } | ||
| 160 | +TEST(GroupedMatmulFinalizeRoutingQuantTest, MxA8W4) { RunSmoke<fp8_e4m3fn_t, true>(); } | ||


空检视意见,防止意外合入