Merged
gmmmxfp4支持二级量化 #15129
gmmmxfp4支持二级量化 #15129
Merged
zhangzhizhuoAdd on 26 days ago
Total: 45 files changed+6081-1
@@ -7,7 +7,7 @@
7# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.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.8# See LICENSE in the root of the software repository for the full text of the License.
9# ----------------------------------------------------------------------------9# ----------------------------------------------------------------------------
10-set(OPTENSOR_TAG_ID 28a75a4932551a70ea6a9cd38adc0fa917a2900d)10+set(OPTENSOR_TAG_ID 82ae6b010328294ee64c7c4b5a50f4a39ee4a206)
11 11 
12if(EXISTS "${PROJECT_SOURCE_DIR}/../ops-tensor")12if(EXISTS "${PROJECT_SOURCE_DIR}/../ops-tensor")
13 get_filename_component(OPTENSOR_SOURCE_PATH13 get_filename_component(OPTENSOR_SOURCE_PATH
@@ -0,0 +1,3 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# Licensed under CANN Open Software License Agreement Version 2.0.
3+add_subdirectory(op_host)
@@ -0,0 +1,55 @@
1+# DualLevelGroupedMatmul
2+ 
3+## 产品支持情况
4+ 
5+| 产品 | 是否支持 |
6+| :--- | :---: |
7+| <term>Ascend 950PR&950DT系列产品</term> | √ |
8+| <term>Atlas A3系列产品</term> | × |
kknan
kknankknan9 days ago

split item的默认值是多少

likedislike
zhangzhizhuo
zhangzhizhuo
8 days ago Comments:
likedislike
9+| <term>Atlas A2系列产品</term> | × |
10+| <term>Atlas 200I/500 A2推理产品</term> | × |
11+| <term>Atlas推理系列产品</term> | × |
12+| <term>Atlas训练系列产品</term> | × |
13+ 
14+## 功能说明
15+ 
16+- 算子功能:沿左矩阵的 M 轴分组,按专家执行 MXFP4 E2M1 双级量化矩阵乘。各专家共用 K、N,权重采用 FRACTAL_NZ 格式,输出为 FP16 或 BF16。
17+- 计算流程:按 `level1_group_size` 应用 E8M0 level1 scale,按 `level0_group_size` 划分 K 段。每段的 FP32 部分和乘以该段两侧的 FP32 level0 scale 后跨段累加,最后加入可选 bias 并转换为输出类型。
18+ 
19+## 参数说明
20+ 
21+下表按算子原型的注册顺序列出参数。M 为总行数,E 为专家数,K 为归约维度,N 为输出列数。权重和权重 level1 scale 的转置形状为传入算子原型的形状。ACLNN 和 PyTorch 调用方的视图、步长及命名见各自的接口文档。
22+ 
23+| 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 数据格式 |
24+| :--- | :---: | :--- | :--- | :---: |
25+| x | 输入 | 左矩阵,形状为 `(M,K)`。 | FLOAT4_E2M1 | ND |
26+| x_level0_scale | 输入 | 左矩阵的 level0 scale,形状为 `(M,ceil(K/level0_group_size))`。 | FLOAT | ND |
27+| x_level1_scale | 输入 | 左矩阵的 level1 scale,形状为 `(M,ceil(K/(2×level1_group_size)),2)`。 | FLOAT8_E8M0 | ND |
28+| weight | 输入 | 全部专家的权重。非转置时为 `(E,K,N)`,转置时为 `(E,N,K)`。 | FLOAT4_E2M1 | FRACTAL_NZ |
29+| weight_level0_scale | 输入 | 权重的 level0 scale,形状固定为 `(E,ceil(K/level0_group_size),N)`。 | FLOAT | ND |
30+| weight_level1_scale | 输入 | 权重的 level1 scale。非转置时为 `(E,ceil(K/(2×level1_group_size)),N,2)`,转置时为 `(E,N,ceil(K/(2×level1_group_size)),2)`。 | FLOAT8_E8M0 | ND |
31+| grouplist | 输入 | 专家分组信息。类型 0/1 的形状为 `(E,)`,类型 2 为 `(E,2)`。 | INT64 | ND |
32+| bias | 可选输入 | 专家偏置,形状为 `(E,N)`,缺省时按 0 处理。 | FLOAT | ND |
33+| y | 输出 | 矩阵乘结果,形状为 `(M,N)`。 | FLOAT16、BF16 | ND |
34+| transpose_weight | 可选属性 | 权重是否转置,默认值为 `false`。 | BOOL | - |
35+| group_list_type | 可选属性 | 0 表示累计结束位置,1 表示各组行数,2 表示稀疏分组列表,默认值为 0。 | INT | - |
36+| tuning_config | 可选属性 | 调优配置,仅支持 `[0]`,默认值为 `[0]`。 | LIST_INT | - |
37+| dtype | 必选属性 | 输出类型对应的 GE 枚举,支持 FLOAT16 或 BF16。 | INT | - |
38+| level0_group_size | 可选属性 | 一个 FP32 scale 覆盖的 K 元素数,仅支持 512,默认值为 512。 | INT | - |
39+| level1_group_size | 可选属性 | 一个 E8M0 scale 覆盖的 K 元素数,仅支持 32,默认值为 32。 | INT | - |
40+ 
41+## 约束说明
42+ 
43+- 当前仅支持沿输入矩阵的行维度分组。输入和权重的秩分别固定为 2 和 3,可在秩已知时推导含未知维度的输出形状,实际 tiling 使用具体维度。M、E 须大于 0,K 须为大于 2 的偶数,N 须大于 1。非转置权重的 N 也须为偶数。
44+- 每个张量包含全部专家所需的数据。ACLNN 和 PyTorch 接口中的矩阵、scale、可选 bias 和输出均通过长度为 1 的列表表示,分组信息通过单个张量传入。
45+- 分组列表须完整覆盖 M 行。类型 2 的每行为 `[专家编号, 行数]`。非零行组在前,零行组在后,两类分组内部均按专家编号递增排列。输入和输出按列表顺序分段,权重、权重 scale 和 bias 按专家编号索引。完整约束见 [ACLNN 约束说明](docs/aclnnDualLevelGroupedMatmulWeightNz.md#约束说明)。
46+- 支持 Torch 单算子调用,不支持图模式。
47+ 
48+## 调用说明
49+ 
50+| 调用方式 | 调用样例 | 说明 |
51+| :--- | :--- | :--- |
52+| ACLNN API | [C++ 示例](examples/arch35/test_aclnn_dual_level_grouped_matmul_weight_nz.cpp) | 通过 [aclnnDualLevelGroupedMatmulWeightNz](docs/aclnnDualLevelGroupedMatmulWeightNz.md) 两段式接口调用。 |
53+| PyTorch API | [Python 示例](examples/test_torch_dual_level_grouped_matmul.py) | 通过 [dual_level_grouped_matmul](docs/torchapi_dual_level_grouped_matmul.md) 接口调用。 |
54+ 
55+构建算子包及运行示例见 [示例说明](examples/README.md)。UT 和精度验证见 [测试说明](tests/README.md)。
@@ -0,0 +1,591 @@
1+# aclnnDualLevelGroupedMatmulWeightNz
2+ 
3+## 产品支持情况
4+ 
5+<!-- npu="950" id1 -->
6+- <term>Ascend 950PR&950DT系列产品</term>:支持
7+<!-- end id1 -->
8+<!-- npu="A3" id2 -->
9+- <term>Atlas A3系列产品</term>:不支持
10+<!-- end id2 -->
11+<!-- npu="910b" id3 -->
12+- <term>Atlas A2系列产品</term>:不支持
13+<!-- end id3 -->
14+<!-- npu="310b" id4 -->
15+- <term>Atlas 200I/500 A2推理产品</term>:不支持
16+<!-- end id4 -->
17+<!-- npu="310p" id5 -->
18+- <term>Atlas推理系列产品</term>:不支持
19+<!-- end id5 -->
20+<!-- npu="910" id6 -->
21+- <term>Atlas训练系列产品</term>:不支持
22+<!-- end id6 -->
23+ 
24+## 功能说明
25+ 
26+当前支持根据 `groupListOptional` 沿输入矩阵的行维度分组。每组输入与对应专家的 FRACTAL_NZ 权重相乘,跨 K 段累加后加入可选偏置。
27+ 
28+先用两侧 level1 缩放因子还原输入和权重,再计算每个 level0 K 段的部分和。
29+ 
30+$$
31+P_{h,i,j} = \sum_{k \in G_h}
32+ \left(X_{i,k} \cdot S^{X,1}_{i,k}\right)
33+ \left(W_{e,k,j} \cdot S^{W,1}_{e,k,j}\right)
34+$$
35+ 
36+将各段部分和乘以相应的 level0 缩放因子,以 FP32 累加后加入偏置,再转换为输出类型。
37+ 
38+$$
39+Y_{i,j} = \operatorname{Cast}_{\mathrm{RINT}}\left(
40+ \sum_h P_{h,i,j} \cdot S^{X,0}_{i,h} \cdot S^{W,0}_{e,h,j} + B_{e,j}
41+\right)
42+$$
43+ 
44+$i$ 和 $j$ 分别索引输入行和输出列,$e$ 是该行对应的专家。$G_h$ 是第 $h$ 个 level0 分组的 K 范围,由 `level0GroupSize` 决定。$S^{X,1}_{i,k}$ 和 $S^{W,1}_{e,k,j}$ 分别取两侧覆盖位置 $k$ 的 level1 缩放因子,分组大小由 `level1GroupSize` 决定。输出公式中的 $S^{X,0}$ 和 $S^{W,0}$ 按 K 段索引。省略偏置时,$B_{e,j}$ 取 0。RINT 表示舍入到最近可表示值,等距时取偶数。
45+ 
46+## 函数原型
47+ 
48+本接口采用[两段式调用](../../../../docs/zh/context/two_phase_api.md)。先调用 `aclnnDualLevelGroupedMatmulWeightNzGetWorkspaceSize` 获取工作空间大小和执行器,再调用 `aclnnDualLevelGroupedMatmulWeightNz` 执行计算。
49+ 
50+```c++
51+aclnnStatus aclnnDualLevelGroupedMatmulWeightNzGetWorkspaceSize(
52+ const aclTensorList *x, const aclTensorList *weight, const aclTensorList *biasOptional,
53+ const aclTensorList *scaleOptional, const aclTensorList *perTokenScaleOptional,
54+ const aclTensor *groupListOptional, const aclTensorList *xLevel0Scale,
55+ const aclTensorList *weightLevel0Scale, int64_t level0GroupSize, int64_t level1GroupSize,
56+ int64_t splitItem, int64_t groupType, int64_t groupListType,
57+ aclIntArray *tuningConfigOptional, aclTensorList *out,
58+ uint64_t *workspaceSize, aclOpExecutor **executor);
59+```
60+ 
61+```c++
62+aclnnStatus aclnnDualLevelGroupedMatmulWeightNz(
63+ void *workspace,
64+ uint64_t workspaceSize,
65+ aclOpExecutor *executor,
66+ aclrtStream stream);
67+```
68+ 
69+## aclnnDualLevelGroupedMatmulWeightNzGetWorkspaceSize
70+ 
71+ - **参数说明:**
72+ 
73+ <table style="table-layout: fixed; width: 1483px;">
zhangzhizhuo
zhangzhizhuozhangzhizhuo9 days ago

如果某个参数有默认值,补充默认值。例如splititem

likedislike
74+ <colgroup>
75+ <col style="width: 220px">
76+ <col style="width: 90px">
77+ <col style="width: 240px">
78+ <col style="width: 370px">
79+ <col style="width: 150px">
80+ <col style="width: 110px">
81+ <col style="width: 190px">
82+ <col style="width: 113px">
83+ </colgroup>
84+ <thead>
85+ <tr>
86+ <th>参数名</th>
87+ <th>输入/输出</th>
88+ <th>描述</th>
89+ <th>使用说明</th>
90+ <th>数据类型</th>
91+ <th>数据格式</th>
92+ <th>维度(shape)</th>
93+ <th>非连续Tensor</th>
94+ </tr>
95+ </thead>
96+ <tbody>
97+ <tr>
98+ <td>x(const aclTensorList *)</td>
99+ <td>输入</td>
100+ <td>左矩阵。</td>
@@ -0,0 +1,232 @@
1+# dual_level_grouped_matmul
2+ 
3+## 产品支持情况
4+ 
5+<!-- npu="950" id1 -->
6+- <term>Ascend 950PR&950DT系列产品</term>:支持
7+<!-- end id1 -->
8+<!-- npu="A3" id2 -->
9+- <term>Atlas A3系列产品</term>:不支持
10+<!-- end id2 -->
11+<!-- npu="910b" id3 -->
12+- <term>Atlas A2系列产品</term>:不支持
13+<!-- end id3 -->
14+<!-- npu="310b" id4 -->
15+- <term>Atlas 200I/500 A2推理产品</term>:不支持
16+<!-- end id4 -->
17+<!-- npu="310p" id5 -->
18+- <term>Atlas推理系列产品</term>:不支持
19+<!-- end id5 -->
20+<!-- npu="910" id6 -->
21+- <term>Atlas训练系列产品</term>:不支持
22+<!-- end id6 -->
23+ 
24+## 功能说明
25+ 
26+当前支持根据 `group_list` 沿输入矩阵的行维度分组。每组输入与对应专家的 FRACTAL_NZ 权重相乘,跨 K 段累加后加入可选偏置。
27+ 
28+先用两侧 level1 缩放因子还原输入和权重,再计算每个 level0 K 段的部分和。
29+ 
30+$$
31+P_{h,i,j} = \sum_{k \in G_h}
32+ \left(X_{i,k} \cdot S^{X,1}_{i,k}\right)
33+ \left(W_{e,k,j} \cdot S^{W,1}_{e,k,j}\right)
34+$$
35+ 
36+将各段部分和乘以相应的 level0 缩放因子,以 FP32 累加后加入偏置,再转换为输出类型。
37+ 
38+$$
39+Y_{i,j} = \operatorname{Cast}_{\mathrm{RINT}}\left(
40+ \sum_h P_{h,i,j} \cdot S^{X,0}_{i,h} \cdot S^{W,0}_{e,h,j} + B_{e,j}
41+\right)
42+$$
43+ 
44+$i$ 和 $j$ 分别索引输入行和输出列,$e$ 是该行对应的专家。$G_h$ 是第 $h$ 个 level0 分组的 K 范围,由 `level0_group_size` 决定。$S^{X,1}_{i,k}$ 和 $S^{W,1}_{e,k,j}$ 分别取两侧覆盖位置 $k$ 的 level1 缩放因子,分组大小由 `level1_group_size` 决定。输出公式中的 $S^{X,0}$ 和 $S^{W,0}$ 按 K 段索引。省略偏置时,$B_{e,j}$ 取 0。RINT 表示舍入到最近可表示值,等距时取偶数。
45+ 
46+## 函数原型
47+ 
48+```python
49+cann_ops_transformer.dual_level_grouped_matmul(
50+ x, weight, x_level0_scale, x_level1_scale,
51+ weight_level0_scale, weight_level1_scale,
52+ level0_group_size=512, level1_group_size=32, *,
53+ group_list=None, bias=None, offset=None, antiquant_scale=None, antiquant_offset=None,
54+ activation_input=None, activation_quant_scale=None,
55+ activation_quant_offset=None, split_item=3, group_type=0,
56+ group_list_type=0, act_type=0, tuning_config=None,
57+ output_dtype=torch.bfloat16, x_dtype=None, weight_dtype=None,
58+ scale_dtype=None, per_token_scale_dtype=None,
59+) -> List[Tensor]
60+```
61+ 
62+## 参数说明
63+ 
64+| 参数名 | 参数类型 | 可选/必选 | 描述 | 数据类型 | 维度(shape) |
65+| --- | --- | --- | --- | --- | --- |
66+| x | List[Tensor] | 必选 | 左矩阵,逻辑形状 (M,K),M 为输入行数,K 为归约长度。 | FP4 E2M1 | (M,K/2) |
67+| weight | List[Tensor] | 必选 | 专家权重,E 为专家数,N 为输出列数。 | FP4 E2M1 | 非转置 (E,K,N/2),转置 view (E,K/2,N)。 |
68+| x_level0_scale | List[Tensor] | 必选 | 输入矩阵的 level0 缩放因子,格式为 ND。 | `torch.float32` | (M,ceil(K/level0_group_size)) |
69+| x_level1_scale | List[Tensor] | 必选 | 输入矩阵的 level1 缩放因子,格式为 ND。 | E8M0 | (M,ceil(K/(2×level1_group_size)),2) |
70+| weight_level0_scale | List[Tensor] | 必选 | 各专家权重的 level0 缩放因子,格式为 ND。 | `torch.float32` | (E,ceil(K/level0_group_size),N) |
71+| weight_level1_scale | List[Tensor] | 必选 | 各专家权重的 level1 缩放因子,采用与权重转置状态匹配的 ND 视图。 | E8M0 | (E,ceil(K/(2×level1_group_size)),N,2) |
72+| level0_group_size | int | 可选 | 每组 FP32 level0 scale 覆盖的 K 元素数,默认值为 512。 | - | - |
73+| level1_group_size | int | 可选 | 每组 E8M0 level1 scale 覆盖的 K 元素数,默认值为 32。 | - | - |
74+| group_list | Tensor | 必选 | 仅通过关键字传入,用于指定专家分组。 | `torch.int64` | type=0/1 为 (E,),type=2 为 (E,2)。 |
75+| bias | List[Tensor] | 可选 | 专家偏置,默认值为 `None`。 | `torch.float32` | (E,N) |
76+| group_list_type | int | 可选 | 0 为累计结束位置,1 为各组行数,2 为稀疏分组列表。默认值为 0,传入 `None` 时同样按 0 处理。 | - | - |
77+| split_item | int | 可选 | 输出配置,支持 2 或 3,默认值为 3。本接口的输入和输出 TensorList 长度均为 1,两种取值等价。 | - | - |
78+| group_type | int | 可选 | 仅支持 0,默认 0。 | - | - |
79+| act_type | int | 可选 | 默认值为 0,表示无激活。传入 `None` 时同样按 0 处理。 | - | - |
80+| x_dtype、weight_dtype | int | 可选 | GMM 兼容参数。调用时使用默认值 `None`,接口按 FP4 E2M1 解释矩阵中的打包字节。 | - | - |
81+| scale_dtype、per_token_scale_dtype | int | 可选 | GMM 兼容参数。调用时使用默认值 `None`,接口按 E8M0 解释权重和左矩阵的 level1 scale 字节。 | - | - |
82+| offset、antiquant_scale、antiquant_offset | List[Tensor] | 可选 | 预留参数。仅支持默认值 `None`。 | - | - |
83+| activation_input、activation_quant_scale、activation_quant_offset | List[Tensor] | 可选 | 预留参数。仅支持默认值 `None`。 | - | - |
84+| tuning_config | List[int] | 可选 | 默认值为 `None`。显式配置时支持 `[0]`。 | - | - |
85+| output_dtype | `torch.dtype` | 可选 | 默认 `torch.bfloat16`,传入 `None` 时也使用默认类型。 | `torch.float16`、`torch.bfloat16` | - |
86+ 
87+## 返回值说明
88+ 
89+返回长度为 1 的 TensorList,唯一元素为 (M,N) 的 ND 张量,位于与 x 相同的 NPU。输出类型由 `output_dtype` 决定,为 `torch.float16` 或 `torch.bfloat16`。
90+ 
91+## 约束说明
92+ 
93+- 支持 Torch 单算子调用,不支持图模式。
94+- 接口中的 TensorList 在 PyTorch 中以 `List[Tensor]` 表示。输入 TensorList 以及提供的 `bias` 均须包含一个张量,所有输入须位于同一 NPU。
95+- `weight` 须为 FRACTAL_NZ,其余输入须为 ND。除规定的转置 `weight_level1_scale` 视图外,ND 输入须连续。各输入的存储偏移须为 0。
96+- 专家数须大于 0,归约长度须为偶数。非转置权重的输出列数还须为偶数。非空 Tensor 场景下,归约长度须大于 2,输出列数须大于 1。维度上限和地址范围见 [ACLNN 约束说明](aclnnDualLevelGroupedMatmulWeightNz.md#约束说明)。
97+- 支持 M 为 0 或 N 为 0 的空 Tensor 场景,此时允许 K 为 0。返回的 TensorList 包含一个形状为 `(M,N)` 的空 Tensor。
98+- `group_list` 须完整覆盖 M 行,允许专家的行数为 0。
99+ - `group_list_type=0` 表示累计结束位置,各项须非负且非递减,最后一项须等于 M。
100+ - `group_list_type=1` 表示各组行数,各项须非负,总和须等于 M。
101+ - `group_list_type=2` 表示稀疏分组,形状为 `(E,2)`,每行为 `[expert_id, row_count]`。专家编号须在 `[0,E)` 内,各组行数须非负且总和等于 M。非零行组在前,零行组在后,两类分组内部均按专家编号递增排列。输入和输出按列表顺序分段,权重、权重缩放因子和偏置按专家编号选取。
102+ - 分组值无效时,输出无效。
103+- 当前版本仅支持两级分组大小的默认值。level1 scale 末维的两个元素分别对应连续的两个 level1 分组。
104+ 
105+- MXFP4 E2M1 二级量化场景支持权重转置和非转置,偏置可省略。
106+ - 非空参数支持的数据类型组合见下表。
107+ 
108+ | 场景 | x、weight | x_level0_scale、weight_level0_scale | x_level1_scale、weight_level1_scale | bias | group_list | 输出 |
109+ | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
110+ | MXFP4 E2M1 二级量化,FP16 输出 | FP4 E2M1 | `torch.float32` | E8M0 | `torch.float32` | `torch.int64` | `torch.float16` |
111+ | MXFP4 E2M1 二级量化,BF16 输出 | FP4 E2M1 | `torch.float32` | E8M0 | `torch.float32` | `torch.int64` | `torch.bfloat16` |
112+ 
113+ - FP4 E2M1 的 `x` 和 `weight` 打包成 `torch.int8` 或 `torch.uint8` 张量。每个字节存储两个 FP4 E2M1 元素,低半字节在前。
114+ - E8M0 的 `x_level1_scale` 和 `weight_level1_scale` 以 `torch.int8` 或 `torch.uint8` 张量传入,每个字节存储一个 E8M0 编码。
115+ - 转置 weight 先以 (E,N,K/2) 的字节张量进行 NZ 格式转换,再 transpose(1,2),得到 (E,K/2,N)。转置 weight_level1_scale 由连续的 (E,N,ceil(K/(2×level1_group_size)),2) 张量 transpose(1,2) 得到。
116+ - 调用前须完成矩阵和 level1 scale 的量化与打包,并按参数表构造对应的 PyTorch Tensor。
117+ 
118+## 确定性计算
119+ 
120+默认支持确定性计算。
121+ 
122+## 调用示例
123+ 
124+调用示例代码如下,仅供参考,PyTorch 扩展的安装及执行过程请参考[运行 PyTorch 示例](../examples/README.md#运行-pytorch-示例)。
125+ 
126+<!-- npu="950" id12 -->
127+- <term>Ascend 950PR&950DT系列产品</term>:
128+ 
129+ 以下示例将打包后的 FP4 权重转换为 FRACTAL_NZ,显式传入两级 group size,调用 Torch 单算子接口执行分组矩阵乘并校验 BF16 输出。示例省略 `split_item`,使用默认值 3。完整源码见[仓内示例](../examples/test_torch_dual_level_grouped_matmul.py)。
130+ 
131+ ```python
132+ # Copyright (c) 2026 Huawei Technologies Co., Ltd.
133+ # Licensed under CANN Open Software License Agreement Version 2.0.
134+ """Run a dual-level MXFP4 grouped matmul and check both experts' outputs."""
135+ 
136+ import importlib
137+ import os
138+ 
139+ import torch
140+ import torch_npu
141+ 
142+ 
143+ def main():
144+ ops = importlib.import_module(
145+ os.environ.get("CANN_TRANSFORMER_PACKAGE", "cann_ops_transformer")
146+ )
147+ m, k, n, experts = 32, 640, 128, 2
148+ level0_group_size, level1_group_size = 512, 32
149+ fp4_elements_per_byte = 2
150+ mx_scale_pair = 2
151+ level1_pairs = k // (mx_scale_pair * level1_group_size)
152+ level0_groups = (k + level0_group_size - 1) // level0_group_size
153+ group_rows = m // experts
154+ packed_fp4_ones = 0x22
155+ e8m0_one, e8m0_two = 127, 128
156+ weight_level1_scale = 2
157+ tail_level0_scale = 2
158+ bias_step = 16
159+ format_nz, format_nd = 29, 2
160+ device = "npu:0"
161+ 
162+ x = torch.full(
163+ (m, k // fp4_elements_per_byte),
164+ packed_fp4_ones,
165+ dtype=torch.int8,
166+ device=device,
167+ )
168+ weight = torch_npu.npu_format_cast(
169+ torch.full(
170+ (experts, k, n // fp4_elements_per_byte),
171+ packed_fp4_ones,
172+ dtype=torch.int8,
173+ device=device,
174+ ),
175+ format_nz,
176+ )
177+ x_level0 = torch.ones((m, level0_groups), dtype=torch.float32, device=device)
178+ x_level0[:, 1] = tail_level0_scale
179+ weight_level0 = torch.ones(
180+ (experts, level0_groups, n), dtype=torch.float32, device=device
181+ )
182+ weight_level0[:, 1, :] = tail_level0_scale
183+ x_level1 = torch.full(
184+ (m, level1_pairs, mx_scale_pair), e8m0_one, dtype=torch.uint8, device=device
185+ )
186+ weight_level1 = torch_npu.npu_format_cast(
187+ torch.full(
188+ (experts, level1_pairs, n, mx_scale_pair),
189+ e8m0_two,
190+ dtype=torch.uint8,
191+ device=device,
192+ ),
193+ format_nd,
194+ )
195+ group_list = torch.tensor([group_rows] * experts, dtype=torch.int64, device=device)
196+ bias = torch.full((experts, n), bias_step, dtype=torch.float32, device=device)
197+ bias[1, :] = bias_step + bias_step
198+ 
199+ (output,) = ops.dual_level_grouped_matmul(
200+ [x],
201+ [weight],
202+ [x_level0],
203+ [x_level1],
204+ [weight_level0],
205+ [weight_level1],
206+ level0_group_size=level0_group_size,
207+ level1_group_size=level1_group_size,
208+ group_list=group_list,
209+ group_list_type=1,
210+ bias=[bias],
211+ output_dtype=torch.bfloat16,
212+ )
213+ 
214+ matmul = weight_level1_scale * (
215+ level0_group_size
216+ + (k - level0_group_size) * tail_level0_scale * tail_level0_scale
217+ )
218+ expected = torch.arange(1, experts + 1, dtype=torch.float32) * bias_step + matmul
219+ expected = (
220+ expected.repeat_interleave(group_rows)
221+ .unsqueeze(1)
222+ .expand(m, n)
223+ .to(torch.bfloat16)
224+ )
225+ torch.testing.assert_close(output.cpu(), expected, rtol=0, atol=0)
226+ print(f"DualLevelGroupedMatmul passed, BF16 shape {tuple(output.shape)}")
227+ 
228+ 
229+ if __name__ == "__main__":
230+ main()
231+ ```
232+<!-- end id12 -->
@@ -0,0 +1,46 @@
1+# DualLevelGroupedMatmul 示例
2+ 
3+两个示例执行同一组双级量化 GMM。M=32、K=640、N=128,两个专家各处理 16 行,权重为非转置 FRACTAL_NZ,输出为 BF16。
4+ 
5+- x 和 weight 的每个 FP4 元素均为 1,每字节为 `0x22`。两侧 E8M0 scale 的编码分别为 127 和 128,对应 1 和 2。
6+- 第一段 512 个 K 元素的两侧 level0 scale 均为 1。余下 128 个 K 元素的两侧 level0 scale 均为 2。两个专家分别使用 bias 16 和 32。
7+- 输出形状为 `(32,128)`,按行检查每个元素。矩阵乘结果为 `2 × (512 + 128 × 4) = 2048`,加 bias 后前 16 行为 2064,后 16 行为 2080。校验失败时程序返回非零状态。
8+ 
9+## 构建并安装算子包
10+ 
11+准备 Ascend 950 的 CANN 开发环境。构建前,将包含双级量化 Blaze 组件的配套 `ops-tensor` 源码放在 `ops-transformer` 同级目录,并在 `ops-tensor` 根目录运行 `git submodule update --init include/tensor_api`。
12+ 
13+在 `ops-transformer` 根目录运行以下命令。将安装路径替换为实际目录,并按环境填写 CANN 路径和安装包文件名。
14+ 
15+```bash
16+source /usr/local/Ascend/cann/set_env.sh
17+bash build.sh --pkg --experimental --soc=ascend950 \
18+ --ops=dual_level_grouped_matmul --vendor_name=dual_level_gmm -j4
19+bash build_out/cann-ops-transformer-dual_level_gmm_linux-x86_64.run \
20+ --quiet --nox11 --install-path=/absolute/install/path
21+source /absolute/install/path/vendors/dual_level_gmm_transformer/bin/set_env.bash
22+```
23+ 
24+## 运行 ACLNN 示例
25+ 
26+在加载上述环境后,从 `ops-transformer` 根目录执行仓库的[标准示例命令](../../../../docs/zh/invocation/quick_op_invocation.md)。
27+ 
28+```bash
29+bash build.sh --experimental --run_example dual_level_grouped_matmul eager cust \
30+ --example_name=dual_level_grouped_matmul_weight_nz --vendor_name=dual_level_gmm --soc=ascend950
31+```
32+ 
33+程序使用设备 0,在内存中构造张量,通过已安装算子包执行两段式 ACLNN 接口并同步 Stream。
34+ 
35+## 运行 PyTorch 示例
36+ 
37+在同一环境安装与 CANN 配套的 PyTorch、TorchNPU,以及编译 Torch 扩展所需的 C++ 编译器和 Ninja。从 `ops-transformer` 根目录执行以下命令。其中 `dlgmm` 为 Python 扩展的包名后缀。
38+ 
39+```bash
40+TORCH_EXTENSION_EXPERIMENTAL=TRUE TORCH_EXTENSION_OPS=dual_level_grouped_matmul \
41+ TORCH_EXTENSION_VENDOR=dlgmm python3 -m pip install ./torch_extension --no-build-isolation
42+CANN_TRANSFORMER_PACKAGE=cann_ops_transformer_dlgmm \
43+ python3 experimental/gmm/dual_level_grouped_matmul/examples/test_torch_dual_level_grouped_matmul.py
44+```
45+ 
46+首次在 NPU 上调用时,Torch 扩展会编译 C++ 适配层。转置、FP16、无 bias 和稀疏分组场景见 [ST 测试说明](../tests/README.md)。
@@ -0,0 +1,226 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include <cstdint>
12+#include <cstring>
13+#include <iostream>
14+#include <memory>
15+#include <stdexcept>
16+#include <string>
17+#include <vector>
18+ 
19+#include "acl/acl.h"
20+#include "aclnnop/aclnn_dual_level_grouped_matmul_weight_nz.h"
21+ 
22+namespace {
23+constexpr int32_t DEVICE_ID = 0;
24+constexpr int64_t M = 32;
25+constexpr int64_t K = 640;
26+constexpr int64_t N = 128;
27+constexpr int64_t EXPERTS = 2;
28+constexpr int64_t GROUP_ROWS = M / EXPERTS;
29+constexpr int64_t LEVEL0_GROUP_SIZE = 512;
30+constexpr int64_t LEVEL1_GROUP_SIZE = 32;
31+constexpr int64_t LEVEL0_GROUPS = (K + LEVEL0_GROUP_SIZE - 1) / LEVEL0_GROUP_SIZE;
32+constexpr int64_t FP4_ELEMENTS_PER_BYTE = 2;
33+constexpr int64_t MX_SCALE_PAIR = 2;
34+constexpr int64_t LEVEL1_PAIRS = K / (MX_SCALE_PAIR * LEVEL1_GROUP_SIZE);
35+constexpr float SECOND_LEVEL0_SCALE = 2.0F;
36+constexpr float EXPERT_BIAS_STEP = 16.0F;
37+constexpr float WEIGHT_LEVEL1_SCALE = 2.0F;
38+constexpr uint32_t BF16_TO_FP32_SHIFT = 16;
39+constexpr int64_t NZ_K = 16;
40+constexpr int64_t NZ_N = 64;
41+constexpr uint8_t FP4_ONES = 0x22;
42+constexpr uint8_t E8M0_ONE = 127;
43+constexpr uint8_t E8M0_TWO = 128;
44+ 
45+void Check(int status, const char* operation)
46+{
47+ if (status != ACL_SUCCESS) {
48+ throw std::runtime_error(std::string(operation) + " failed, status=" + std::to_string(status));
49+ }
50+}
51+ 
52+struct Runtime {
53+ aclrtStream stream = nullptr;
54+ bool initialized = false;
55+ bool deviceSet = false;
56+ 
57+ ~Runtime()
58+ {
59+ if (stream != nullptr) {
60+ aclrtDestroyStream(stream);
61+ }
62+ if (deviceSet) {
63+ aclrtResetDevice(DEVICE_ID);
64+ }
65+ if (initialized) {
66+ aclFinalize();
67+ }
68+ }
69+ 
70+ void Init()
71+ {
72+ Check(aclInit(nullptr), "aclInit");
73+ initialized = true;
74+ Check(aclrtSetDevice(DEVICE_ID), "aclrtSetDevice");
75+ deviceSet = true;
76+ Check(aclrtCreateStream(&stream), "aclrtCreateStream");
77+ }
78+};
79+ 
80+struct DeviceBuffer {
81+ void* addr = nullptr;
82+ 
83+ ~DeviceBuffer()
84+ {
85+ if (addr != nullptr) {
86+ aclrtFree(addr);
87+ }
88+ }
89+ 
90+ void Allocate(size_t bytes)
91+ {
92+ if (bytes != 0) {
93+ Check(aclrtMalloc(&addr, bytes, ACL_MEM_MALLOC_HUGE_FIRST), "aclrtMalloc");
94+ }
95+ }
96+};
97+ 
98+struct Tensor {
99+ DeviceBuffer buffer;
100+ aclTensor* desc = nullptr;
101+ aclTensorList* list = nullptr;
102+ 
103+ ~Tensor()
104+ {
105+ if (list != nullptr) {
106+ aclDestroyTensorList(list);
107+ } else if (desc != nullptr) {
108+ aclDestroyTensor(desc);
109+ }
110+ }
111+ 
112+ template <typename T>
113+ void Create(const std::vector<T>& host, const std::vector<int64_t>& shape, aclDataType dtype,
114+ aclFormat format = ACL_FORMAT_ND, const std::vector<int64_t>& nzShape = {})
115+ {
116+ const size_t bytes = host.size() * sizeof(T);
117+ buffer.Allocate(bytes);
118+ Check(aclrtMemcpy(buffer.addr, bytes, host.data(), bytes, ACL_MEMCPY_HOST_TO_DEVICE), "copy input");
119+ std::vector<int64_t> strides(shape.size(), 1);
120+ for (size_t i = shape.size() - 1; i > 0; --i) {
121+ strides[i - 1] = strides[i] * shape[i];
122+ }
123+ const auto& storage = nzShape.empty() ? shape : nzShape;
124+ desc = aclCreateTensor(shape.data(), shape.size(), dtype, strides.data(), 0, format, storage.data(),
125+ storage.size(), buffer.addr);
126+ if (desc == nullptr) {
127+ throw std::runtime_error("aclCreateTensor failed");
128+ }
129+ }
130+ 
131+ aclTensorList* AsList()
132+ {
133+ list = aclCreateTensorList(&desc, 1);
134+ if (list == nullptr) {
135+ throw std::runtime_error("aclCreateTensorList failed");
136+ }
137+ return list;
138+ }
139+};
140+ 
141+void CheckOutput(const Tensor& y)
142+{
143+ std::vector<uint16_t> output(M * N);
144+ const size_t bytes = output.size() * sizeof(uint16_t);
145+ Check(aclrtMemcpy(output.data(), bytes, y.buffer.addr, bytes, ACL_MEMCPY_DEVICE_TO_HOST), "copy output");
146+ // Level1 contributes a factor of 2. The two level0 products are 1 and 4.
147+ constexpr float matmul =
148+ WEIGHT_LEVEL1_SCALE * (LEVEL0_GROUP_SIZE + (K - LEVEL0_GROUP_SIZE) * SECOND_LEVEL0_SCALE * SECOND_LEVEL0_SCALE);
149+ for (int64_t row = 0; row < M; ++row) {
150+ const float expected = matmul + EXPERT_BIAS_STEP * (row / GROUP_ROWS + 1);
151+ for (int64_t col = 0; col < N; ++col) {
152+ const uint32_t bits = static_cast<uint32_t>(output[row * N + col]) << BF16_TO_FP32_SHIFT;
153+ float actual;
154+ std::memcpy(&actual, &bits, sizeof(actual));
155+ if (actual != expected) {
156+ throw std::runtime_error("Output mismatch at [" + std::to_string(row) + ", " + std::to_string(col) +
157+ "], expected " + std::to_string(expected) + ", got " + std::to_string(actual));
158+ }
159+ }
160+ }
161+ std::cout << "DualLevelGroupedMatmulWeightNz passed, BF16 shape (" << M << ", " << N << ")\n";
162+}
163+ 
164+void RunExample(aclrtStream stream)
165+{
166+ Tensor x, weight, xLevel0, xLevel1, weightLevel0, weightLevel1, groupList, bias, y;
167+ x.Create(std::vector<uint8_t>(M * K / FP4_ELEMENTS_PER_BYTE, FP4_ONES), {M, K}, ACL_FLOAT4_E2M1);
168+ // Every FP4 element is 1, so the NZ buffer can be filled directly in storage order.
169+ weight.Create(std::vector<uint8_t>(EXPERTS * K * N / FP4_ELEMENTS_PER_BYTE, FP4_ONES), {EXPERTS, K, N},
170+ ACL_FLOAT4_E2M1, ACL_FORMAT_FRACTAL_NZ, {EXPERTS, N / NZ_N, K / NZ_K, NZ_K, NZ_N});
171+ 
172+ std::vector<float> xLevel0Host(M * LEVEL0_GROUPS, 1.0F);
173+ for (int64_t row = 0; row < M; ++row) {
174+ xLevel0Host[row * LEVEL0_GROUPS + 1] = SECOND_LEVEL0_SCALE;
175+ }
176+ std::vector<float> weightLevel0Host(EXPERTS * LEVEL0_GROUPS * N, 1.0F);
177+ std::vector<float> biasHost(EXPERTS * N, EXPERT_BIAS_STEP);
178+ for (int64_t expert = 0; expert < EXPERTS; ++expert) {
179+ for (int64_t col = 0; col < N; ++col) {
180+ weightLevel0Host[(expert * LEVEL0_GROUPS + 1) * N + col] = SECOND_LEVEL0_SCALE;
181+ biasHost[expert * N + col] = EXPERT_BIAS_STEP * (expert + 1);
182+ }
183+ }
184+ xLevel0.Create(xLevel0Host, {M, LEVEL0_GROUPS}, ACL_FLOAT);
185+ xLevel1.Create(std::vector<uint8_t>(M * LEVEL1_PAIRS * MX_SCALE_PAIR, E8M0_ONE), {M, LEVEL1_PAIRS, MX_SCALE_PAIR},
186+ ACL_FLOAT8_E8M0);
187+ weightLevel0.Create(weightLevel0Host, {EXPERTS, LEVEL0_GROUPS, N}, ACL_FLOAT);
188+ weightLevel1.Create(std::vector<uint8_t>(EXPERTS * LEVEL1_PAIRS * N * MX_SCALE_PAIR, E8M0_TWO),
189+ {EXPERTS, LEVEL1_PAIRS, N, MX_SCALE_PAIR}, ACL_FLOAT8_E8M0);
190+ groupList.Create(std::vector<int64_t>{GROUP_ROWS, GROUP_ROWS}, {EXPERTS}, ACL_INT64);
191+ bias.Create(biasHost, {EXPERTS, N}, ACL_FLOAT);
192+ y.Create(std::vector<uint16_t>(M * N, 0), {M, N}, ACL_BF16);
193+ 
194+ constexpr int64_t splitItem = 3;
195+ constexpr int64_t groupType = 0;
196+ constexpr int64_t groupListType = 1;
197+ uint64_t workspaceSize = 0;
198+ aclOpExecutor* executor = nullptr;
199+ Check(aclnnDualLevelGroupedMatmulWeightNzGetWorkspaceSize(
200+ x.AsList(), weight.AsList(), bias.AsList(), weightLevel1.AsList(), xLevel1.AsList(), groupList.desc,
201+ xLevel0.AsList(), weightLevel0.AsList(), LEVEL0_GROUP_SIZE, LEVEL1_GROUP_SIZE, splitItem, groupType,
202+ groupListType, nullptr, y.AsList(), &workspaceSize, &executor),
203+ "aclnnDualLevelGroupedMatmulWeightNzGetWorkspaceSize");
204+ std::unique_ptr<aclOpExecutor, decltype(&aclDestroyAclOpExecutor)> plan(executor, aclDestroyAclOpExecutor);
205+ DeviceBuffer workspace;
206+ workspace.Allocate(workspaceSize);
207+ const auto runStatus = aclnnDualLevelGroupedMatmulWeightNz(workspace.addr, workspaceSize, plan.release(), stream);
208+ const auto syncStatus = aclrtSynchronizeStream(stream);
209+ Check(runStatus, "aclnnDualLevelGroupedMatmulWeightNz");
210+ Check(syncStatus, "aclrtSynchronizeStream");
211+ CheckOutput(y);
212+}
213+} // namespace
214+ 
215+int main()
216+{
217+ try {
218+ Runtime runtime;
219+ runtime.Init();
220+ RunExample(runtime.stream);
221+ } catch (const std::exception& error) {
222+ std::cerr << error.what() << '\n';
223+ return 1;
224+ }
225+ return 0;
226+}
@@ -0,0 +1,99 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# Licensed under CANN Open Software License Agreement Version 2.0.
3+"""Run a dual-level MXFP4 grouped matmul and check both experts' outputs."""
4+ 
5+import importlib
6+import os
7+ 
8+import torch
9+import torch_npu
10+ 
11+ 
12+def main():
13+ ops = importlib.import_module(
14+ os.environ.get("CANN_TRANSFORMER_PACKAGE", "cann_ops_transformer")
15+ )
16+ m, k, n, experts = 32, 640, 128, 2
17+ level0_group_size, level1_group_size = 512, 32
18+ fp4_elements_per_byte = 2
19+ mx_scale_pair = 2
20+ level1_pairs = k // (mx_scale_pair * level1_group_size)
21+ level0_groups = (k + level0_group_size - 1) // level0_group_size
22+ group_rows = m // experts
23+ packed_fp4_ones = 0x22
24+ e8m0_one, e8m0_two = 127, 128
25+ weight_level1_scale = 2
26+ tail_level0_scale = 2
27+ bias_step = 16
28+ format_nz, format_nd = 29, 2
29+ device = "npu:0"
30+ 
31+ x = torch.full(
32+ (m, k // fp4_elements_per_byte),
33+ packed_fp4_ones,
34+ dtype=torch.int8,
35+ device=device,
36+ )
37+ weight = torch_npu.npu_format_cast(
38+ torch.full(
39+ (experts, k, n // fp4_elements_per_byte),
40+ packed_fp4_ones,
41+ dtype=torch.int8,
42+ device=device,
43+ ),
44+ format_nz,
45+ )
46+ x_level0 = torch.ones((m, level0_groups), dtype=torch.float32, device=device)
47+ x_level0[:, 1] = tail_level0_scale
48+ weight_level0 = torch.ones(
49+ (experts, level0_groups, n), dtype=torch.float32, device=device
50+ )
51+ weight_level0[:, 1, :] = tail_level0_scale
52+ x_level1 = torch.full(
53+ (m, level1_pairs, mx_scale_pair), e8m0_one, dtype=torch.uint8, device=device
54+ )
55+ weight_level1 = torch_npu.npu_format_cast(
56+ torch.full(
57+ (experts, level1_pairs, n, mx_scale_pair),
58+ e8m0_two,
59+ dtype=torch.uint8,
60+ device=device,
61+ ),
62+ format_nd,
63+ )
64+ group_list = torch.tensor([group_rows] * experts, dtype=torch.int64, device=device)
65+ bias = torch.full((experts, n), bias_step, dtype=torch.float32, device=device)
66+ bias[1, :] = bias_step + bias_step
67+ 
68+ (output,) = ops.dual_level_grouped_matmul(
69+ [x],
70+ [weight],
71+ [x_level0],
72+ [x_level1],
73+ [weight_level0],
74+ [weight_level1],
75+ level0_group_size=level0_group_size,
76+ level1_group_size=level1_group_size,
77+ group_list=group_list,
78+ group_list_type=1,
79+ bias=[bias],
80+ output_dtype=torch.bfloat16,
81+ )
82+ 
83+ matmul = weight_level1_scale * (
84+ level0_group_size
85+ + (k - level0_group_size) * tail_level0_scale * tail_level0_scale
86+ )
87+ expected = torch.arange(1, experts + 1, dtype=torch.float32) * bias_step + matmul
88+ expected = (
89+ expected.repeat_interleave(group_rows)
90+ .unsqueeze(1)
91+ .expand(m, n)
92+ .to(torch.bfloat16)
93+ )
94+ torch.testing.assert_close(output.cpu(), expected, rtol=0, atol=0)
95+ print(f"DualLevelGroupedMatmul passed, BF16 shape {tuple(output.shape)}")
96+ 
97+ 
98+if __name__ == "__main__":
99+ main()
@@ -0,0 +1,80 @@
1+// Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+// Licensed under CANN Open Software License Agreement Version 2.0.
3+#include "aclnn_dual_level_grouped_matmul_weight_nz.h"
4+#include "opdev/make_op_executor.h"
5+#include "opdev/op_def.h"
6+#include "opdev/op_dfx.h"
7+#include "opdev/op_executor.h"
8+#include "log/log.h"
9+ 
10+#include "dual_level_grouped_matmul.h"
11+#include "dual_level_grouped_matmul_checker.h"
12+using namespace op;
13+ 
14+namespace {
15+constexpr char API_NAME[] = "aclnnDualLevelGroupedMatmulWeightNz";
16+}
17+ 
18+extern "C" aclnnStatus aclnnDualLevelGroupedMatmulWeightNzGetWorkspaceSize(
19+ const aclTensorList* x, const aclTensorList* weight, const aclTensorList* biasOptional,
20+ const aclTensorList* scaleOptional, const aclTensorList* perTokenScaleOptional, const aclTensor* groupListOptional,
21+ const aclTensorList* xLevel0Scale, const aclTensorList* weightLevel0Scale, int64_t level0GroupSize,
22+ int64_t level1GroupSize, int64_t splitItem, int64_t groupType, int64_t groupListType,
23+ aclIntArray* tuningConfigOptional, aclTensorList* out, uint64_t* workspaceSize, aclOpExecutor** executor)
24+{
25+ L2_DFX_PHASE_1(aclnnDualLevelGroupedMatmulWeightNz,
26+ DFX_IN(x, weight, biasOptional, scaleOptional, perTokenScaleOptional, groupListOptional,
27+ xLevel0Scale, weightLevel0Scale, level0GroupSize, level1GroupSize, splitItem, groupType,
28+ groupListType, tuningConfigOptional),
29+ DFX_OUT(out));
30+ if (workspaceSize == nullptr) {
31+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(API_NAME, "workspaceSize", "must not be nullptr");
32+ return ACLNN_ERR_PARAM_NULLPTR;
33+ }
34+ if (executor == nullptr) {
35+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(API_NAME, "executor", "must not be nullptr");
36+ return ACLNN_ERR_PARAM_NULLPTR;
37+ }
38+ bool transposeWeight = false;
39+ const dual_level_gmm::DualLevelGroupedMatmulParams params{x,
40+ weight,
41+ biasOptional,
42+ scaleOptional,
43+ perTokenScaleOptional,
44+ groupListOptional,
45+ xLevel0Scale,
46+ weightLevel0Scale,
47+ level0GroupSize,
48+ level1GroupSize,
49+ splitItem,
50+ groupType,
51+ groupListType,
52+ tuningConfigOptional,
53+ out};
54+ const auto checkRet = dual_level_gmm::CheckParams(params, transposeWeight);
55+ if (checkRet != ACLNN_SUCCESS) {
56+ return checkRet;
57+ }
58+ auto uniqueExecutor = CREATE_EXECUTOR();
59+ CHECK_RET(uniqueExecutor.get() != nullptr, ACLNN_ERR_INNER_CREATE_EXECUTOR);
60+ if ((*out)[0]->IsEmpty()) {
61+ *workspaceSize = 0;
62+ uniqueExecutor.ReleaseTo(executor);
63+ return ACLNN_SUCCESS;
64+ }
65+ const auto ret =
66+ l0op::DualLevelGroupedMatmul(x, weight, biasOptional, scaleOptional, perTokenScaleOptional, groupListOptional,
67+ xLevel0Scale, weightLevel0Scale, transposeWeight, groupListType,
68+ tuningConfigOptional, level0GroupSize, level1GroupSize, out, uniqueExecutor.get());
69+ CHECK_RET(ret == ACLNN_SUCCESS, ret);
70+ *workspaceSize = uniqueExecutor.get()->GetWorkspaceSize();
71+ uniqueExecutor.ReleaseTo(executor);
72+ return ACLNN_SUCCESS;
73+}
74+ 
75+extern "C" aclnnStatus aclnnDualLevelGroupedMatmulWeightNz(void* workspace, uint64_t workspaceSize,
76+ aclOpExecutor* executor, aclrtStream stream)
77+{
78+ L2_DFX_PHASE_2(aclnnDualLevelGroupedMatmulWeightNz);
79+ return CommonOpExecutorRun(workspace, workspaceSize, executor, stream);
80+}
@@ -0,0 +1,69 @@
1+// Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+// Licensed under CANN Open Software License Agreement Version 2.0.
3+#ifndef ACLNN_DUAL_LEVEL_GROUPED_MATMUL_WEIGHT_NZ_H_
4+#define ACLNN_DUAL_LEVEL_GROUPED_MATMUL_WEIGHT_NZ_H_
5+ 
6+#include "aclnn/aclnn_base.h"
7+ 
8+#ifdef __cplusplus
9+extern "C" {
10+#endif
11+ 
12+/**
13+ * @brief Prepare split-M MXFP4 E2M1 grouped matmul on Ascend 950.
14+ * @param x Required one-element TensorList: E2M1 ND (M,K), M>0 and even K>2.
15+ * @param weight Required one-element TensorList: E2M1 FRACTAL_NZ, logical view (E,K,N).
16+ * Canonical contiguous or transposed strides select the physical layout; N>1.
17+ * @param biasOptional Optional one-element TensorList: FP32 ND (E,N); nullptr omits bias.
18+ * @param scaleOptional Required one-element TensorList: E8M0 logical (E,ceil(K/64),N,2).
19+ * Its physical layout must follow weight's transpose mode.
20+ * @param perTokenScaleOptional Required one-element TensorList: E8M0 ND (M,ceil(K/64),2).
21+ * @param groupListOptional Required INT64 ND: (E,) for types 0/1, (E,2) for type 2.
22+ * Type 0 holds cumulative end rows, type 1 row counts, type 2 [expert_id,row_count].
23+ * Row counts sum to M. For type 2, nonzero groups precede zero groups, with ascending expert IDs within each.
24+ * @param xLevel0Scale Required one-element TensorList: FP32 ND (M,ceil(K/512)).
25+ * @param weightLevel0Scale Required one-element TensorList: FP32 ND (E,ceil(K/512),N).
26+ * @param level0GroupSize Number of K elements per FP32 scale group; must be 512.
27+ * @param level1GroupSize Number of K elements per E8M0 scale group; must be 32.
28+ * @param splitItem Must be 2 or 3; both use one input/output tensor in this interface.
29+ * @param groupType Split axis; must be 0 (M).
30+ * @param groupListType Group encoding: 0, 1 or 2.
31+ * @param tuningConfigOptional nullptr or the single-element array {0}.
32+ * @param out Required one-element TensorList: FP16/BF16 ND (M,N).
33+ * @param workspaceSize Non-null output for required workspace bytes.
34+ * @param executor Non-null output for the prepared execution plan.
35+ * @retval ACLNN_SUCCESS Preparation succeeded; device execution is performed by phase 2.
36+ * @retval ACLNN_ERR_PARAM_NULLPTR A required pointer or TensorList element is null.
37+ * @retval ACLNN_ERR_PARAM_INVALID An attribute, shape, dtype, format, stride or offset is unsupported.
38+ * @note Deterministic by default for identical inputs and attributes in the same environment.
39+ * No additional determinism switch is required.
40+ * @note ND inputs/output must be dense with zero view offset. Weight and transposed scale
41+ * also require zero view offset. Device grouplist content checks do not return
42+ * synchronous ACLNN errors. Partial sums and level0 accumulation use FP32; bias is last.
43+ * ND denotes the actual device storage layout, not only logical contiguous strides.
44+ */
45+__attribute__((visibility("default"))) aclnnStatus aclnnDualLevelGroupedMatmulWeightNzGetWorkspaceSize(
46+ const aclTensorList* x, const aclTensorList* weight, const aclTensorList* biasOptional,
47+ const aclTensorList* scaleOptional, const aclTensorList* perTokenScaleOptional, const aclTensor* groupListOptional,
48+ const aclTensorList* xLevel0Scale, const aclTensorList* weightLevel0Scale, int64_t level0GroupSize,
49+ int64_t level1GroupSize, int64_t splitItem, int64_t groupType, int64_t groupListType,
50+ aclIntArray* tuningConfigOptional, aclTensorList* out, uint64_t* workspaceSize, aclOpExecutor** executor);
51+ 
52+/**
53+ * @brief Execute a plan prepared by aclnnDualLevelGroupedMatmulWeightNzGetWorkspaceSize.
54+ * @param workspace Device workspace; may be nullptr when workspaceSize is zero.
55+ * @param workspaceSize Available workspace size in bytes.
56+ * @param executor Prepared plan returned by phase 1.
57+ * @param stream Target ACL runtime stream.
58+ * @return ACLNN execution status. Stream synchronization is the caller's responsibility.
59+ */
60+__attribute__((visibility("default"))) aclnnStatus aclnnDualLevelGroupedMatmulWeightNz(void* workspace,
61+ uint64_t workspaceSize,
62+ aclOpExecutor* executor,
63+ aclrtStream stream);
64+ 
65+#ifdef __cplusplus
66+}
67+#endif
68+ 
69+#endif
@@ -0,0 +1,70 @@
1+// Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+// Licensed under CANN Open Software License Agreement Version 2.0.
3+#include "dual_level_grouped_matmul.h"
4+#include "opdev/make_op_executor.h"
5+#include "opdev/op_def.h"
6+#include "opdev/op_dfx.h"
7+#include "opdev/op_log.h"
8+#include "util/math_util.h"
9+using namespace op;
10+namespace {
11+constexpr int64_t MX_SCALE_PAIR = 2;
12+constexpr size_t WEIGHT_N_AXIS = 2;
13+// Only the two GMM views are accepted. Reinterpret their storage without moving device data.
14+aclTensor* Normalize(const aclTensor* tensor, const Shape& shape, const Strides& strides, aclOpExecutor* executor)
15+{
16+ auto* view = executor->CreateView(tensor, shape, 0);
17+ if (view != nullptr) {
18+ view->SetOriginalShape(shape);
19+ view->SetStorageShape(tensor->GetStorageShape());
20+ view->SetStorageFormat(tensor->GetStorageFormat());
21+ view->SetViewStrides(strides);
22+ }
23+ return view;
24+}
25+} // namespace
26+namespace l0op {
27+OP_TYPE_REGISTER(DualLevelGroupedMatmul);
28+aclnnStatus DualLevelGroupedMatmul(const aclTensorList* x, const aclTensorList* weight,
29+ const aclTensorList* biasOptional, const aclTensorList* scaleOptional,
30+ const aclTensorList* perTokenScaleOptional, const aclTensor* groupListOptional,
31+ const aclTensorList* xLevel0Scale, const aclTensorList* weightLevel0Scale,
32+ bool transposeWeight, int64_t groupListType, const aclIntArray* tuningConfigOptional,
33+ int64_t level0GroupSize, int64_t level1GroupSize, aclTensorList* out,
34+ aclOpExecutor* executor)
35+{
36+ L0_DFX(DualLevelGroupedMatmul, x, weight, biasOptional, scaleOptional, perTokenScaleOptional, groupListOptional,
37+ xLevel0Scale, weightLevel0Scale, transposeWeight, groupListType, level0GroupSize, level1GroupSize, out);
38+ const auto* a = (*x)[0];
39+ const auto* w = (*weight)[0];
40+ const auto* a0 = (*xLevel0Scale)[0];
41+ const auto* b0 = (*weightLevel0Scale)[0];
42+ const auto* a1 = (*perTokenScaleOptional)[0];
43+ const auto* b1 = (*scaleOptional)[0];
44+ const auto* bias = biasOptional == nullptr ? nullptr : (*biasOptional)[0];
45+ auto* y = (*out)[0];
46+ const auto dtype = y->GetDataType();
47+ const auto& shape = w->GetViewShape();
48+ const auto e = shape.GetDim(0);
49+ const auto k = shape.GetDim(1);
50+ const auto n = shape.GetDim(WEIGHT_N_AXIS);
51+ const auto mxScaleGroups = Ops::Base::CeilDiv(k, level1GroupSize * MX_SCALE_PAIR);
52+ const bool transpose = transposeWeight;
53+ const int64_t weightRows = transpose ? n : k;
54+ const int64_t weightCols = transpose ? k : n;
55+ auto* weightView =
56+ Normalize(w, Shape{e, weightRows, weightCols}, Strides{weightRows * weightCols, weightCols, 1}, executor);
57+ const auto scaleRows = transpose ? n : mxScaleGroups;
58+ const auto scaleCols = transpose ? mxScaleGroups : n;
59+ auto* scaleView =
60+ Normalize(b1, Shape{e, scaleRows, scaleCols, MX_SCALE_PAIR},
61+ Strides{n * mxScaleGroups * MX_SCALE_PAIR, scaleCols * MX_SCALE_PAIR, MX_SCALE_PAIR, 1}, executor);
62+ CHECK_RET(weightView && scaleView, ACLNN_ERR_INNER_NULLPTR);
63+ const int64_t defaultTuning = 0;
64+ auto* config = tuningConfigOptional == nullptr ? executor->AllocIntArray(&defaultTuning, 1) : tuningConfigOptional;
65+ CHECK_RET(config != nullptr, ACLNN_ERR_INNER_NULLPTR);
66+ return ADD_TO_LAUNCHER_LIST_AICORE(
67+ DualLevelGroupedMatmul, OP_INPUT(a, a0, a1, weightView, b0, scaleView, groupListOptional, bias), OP_OUTPUT(y),
68+ OP_ATTR(transpose, groupListType, config, static_cast<int64_t>(dtype), level0GroupSize, level1GroupSize));
69+}
70+} // namespace l0op
@@ -0,0 +1,15 @@
1+// Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+// Licensed under CANN Open Software License Agreement Version 2.0.
3+#ifndef LEVEL0_DUAL_LEVEL_GROUPED_MATMUL_H_
4+#define LEVEL0_DUAL_LEVEL_GROUPED_MATMUL_H_
5+#include "opdev/op_executor.h"
6+namespace l0op {
7+aclnnStatus DualLevelGroupedMatmul(const aclTensorList* x, const aclTensorList* weight,
8+ const aclTensorList* biasOptional, const aclTensorList* scaleOptional,
9+ const aclTensorList* perTokenScaleOptional, const aclTensor* groupListOptional,
10+ const aclTensorList* xLevel0Scale, const aclTensorList* weightLevel0Scale,
11+ bool transposeWeight, int64_t groupListType, const aclIntArray* tuningConfigOptional,
12+ int64_t level0GroupSize, int64_t level1GroupSize, aclTensorList* out,
13+ aclOpExecutor* executor);
14+} // namespace l0op
15+#endif
@@ -0,0 +1,385 @@
1+// Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+// Licensed under CANN Open Software License Agreement Version 2.0.
3+#include "dual_level_grouped_matmul_checker.h"
4+#include "gmm/common/op_api/gmm_tensor_storage_check.h"
5+#include "opdev/op_executor.h"
6+#include "log/log.h"
7+#include "util/math_util.h"
8+#include <initializer_list>
9+#include <limits>
10+#include <string>
11+using namespace op;
12+namespace dual_level_gmm {
13+namespace {
14+constexpr char API_NAME[] = "aclnnDualLevelGroupedMatmulWeightNz";
15+constexpr int64_t MX_SCALE_PAIR = 2;
16+constexpr int64_t MX_SCALE_K = MX_SCALE_PAIR * LEVEL1_GROUP_SIZE;
17+constexpr int64_t FP4_ELEMENTS_PER_BYTE = 2;
18+constexpr int64_t MIN_K = FP4_ELEMENTS_PER_BYTE;
19+constexpr int64_t MATRIX_RANK = 2;
20+constexpr int64_t EXPERT_WEIGHT_RANK = 3;
21+constexpr int64_t SPLIT_ITEM_SINGLE_OUTPUT = 2;
22+constexpr int64_t SPLIT_ITEM_DEFAULT = 3;
23+constexpr int64_t SPARSE_GROUP_LIST = 2;
24+constexpr int64_t GROUP_LIST_PAIR_SIZE = 2;
25+constexpr int64_t WEIGHT_N_AXIS = 2;
26+constexpr int64_t NZ_ROWS = 16;
27+constexpr int64_t NZ_COLS = 64;
28+ 
29+template <typename Values>
30+std::string ValuesString(const Values& values)
31+{
32+ std::string out = "(";
33+ for (const auto value : values) {
34+ if (out.size() != 1) {
35+ out += ",";
36+ }
37+ out += std::to_string(value);
38+ }
39+ return out + ")";
40+}
41+ 
42+std::string ShapeString(const Shape& shape)
43+{
44+ std::string out = "(";
45+ for (size_t i = 0; i < shape.GetDimNum(); ++i) {
46+ if (i != 0) {
47+ out += ",";
48+ }
49+ out += std::to_string(shape.GetDim(i));
50+ }
51+ return out + ")";
52+}
53+ 
54+void LogTensorMismatch(const char* name, const aclTensor* tensor, const std::string& expected)
55+{
56+ const auto descriptor =
57+ "shape=" + ShapeString(tensor->GetViewShape()) + ", storage=" + ShapeString(tensor->GetStorageShape()) +
58+ ", stride=" + ValuesString(tensor->GetViewStrides()) + ", offset=" + std::to_string(tensor->GetViewOffset()) +
59+ ", dtype=" + std::to_string(static_cast<int>(tensor->GetDataType())) +
60+ ", format=" + std::to_string(static_cast<int>(tensor->GetStorageFormat()));
61+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(API_NAME, name, descriptor.c_str(), expected.c_str());
62+}
63+ 
64+bool MatchShape(const Shape& shape, std::initializer_list<int64_t> dims)
65+{
66+ if (shape.GetDimNum() != dims.size()) {
67+ return false;
68+ }
69+ size_t i = 0;
70+ for (auto dim : dims) {
71+ if (shape.GetDim(i++) != dim) {
72+ return false;
73+ }
74+ }
75+ return true;
76+}
77+ 
78+bool CheckShape(const aclTensor* tensor, std::initializer_list<int64_t> dims, const char* name)
79+{
80+ if (!MatchShape(tensor->GetViewShape(), dims)) {
81+ LogTensorMismatch(name, tensor, "logical shape=" + ValuesString(dims));
82+ return false;
83+ }
84+ return true;
85+}
86+ 
87+bool MatchStrides(const aclTensor* tensor, std::initializer_list<int64_t> dims)
88+{
89+ const auto& strides = tensor->GetViewStrides();
90+ if (tensor->GetViewOffset() != 0 || strides.size() != dims.size()) {
91+ return false;
92+ }
93+ size_t i = 0;
94+ for (auto stride : dims) {
95+ if (strides[i++] != stride) {
96+ return false;
97+ }
98+ }
99+ return true;
100+}
101+ 
102+bool IsDenseNd(const aclTensor* tensor)
103+{
104+ if (tensor->GetViewOffset() != 0 || tensor->GetStorageFormat() != Format::FORMAT_ND) {
105+ return false;
106+ }
107+ const auto& shape = tensor->GetViewShape();
108+ const auto& storage = tensor->GetStorageShape();
109+ const auto& strides = tensor->GetViewStrides();
110+ if (shape.GetDimNum() != storage.GetDimNum() || strides.size() != shape.GetDimNum()) {
111+ return false;
112+ }
113+ const bool empty = tensor->IsEmpty();
114+ int64_t stride = 1;
115+ for (size_t i = shape.GetDimNum(); i > 0; --i) {
116+ const auto dim = shape.GetDim(i - 1);
117+ if (dim < 0 || dim != storage.GetDim(i - 1) ||
118+ (!empty && (dim == 0 || strides[i - 1] != stride || stride > std::numeric_limits<int64_t>::max() / dim))) {
119+ return false;
120+ }
121+ if (!empty) {
122+ stride *= dim;
123+ }
124+ }
125+ return true;
126+}
127+ 
128+aclnnStatus CheckNotNull(const DualLevelGroupedMatmulParams& params)
129+{
130+ if (params.groupListOptional == nullptr) {
131+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(API_NAME, "groupListOptional", "must not be nullptr");
132+ return ACLNN_ERR_PARAM_NULLPTR;
133+ }
134+ struct NamedList {
135+ const char* name;
136+ const aclTensorList* list;
137+ };
138+ const NamedList lists[] = {{"x", params.x},
139+ {"weight", params.weight},
140+ {"scaleOptional", params.scaleOptional},
141+ {"perTokenScaleOptional", params.perTokenScaleOptional},
142+ {"xLevel0Scale", params.xLevel0Scale},
143+ {"weightLevel0Scale", params.weightLevel0Scale},
144+ {"out", params.out},
145+ {"biasOptional", params.biasOptional}};
146+ for (const auto& input : lists) {
147+ if (input.list == nullptr) {
148+ if (input.name == std::string("biasOptional")) {
149+ continue;
150+ }
151+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(API_NAME, input.name, "must not be nullptr");
152+ return ACLNN_ERR_PARAM_NULLPTR;
153+ }
154+ if (input.list->Size() != 1) {
155+ OP_LOGE_FOR_INVALID_TENSORNUM(API_NAME, input.name, input.list->Size(), "1");
156+ return ACLNN_ERR_PARAM_INVALID;
157+ }
158+ if ((*input.list)[0] == nullptr) {
159+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(API_NAME, input.name,
160+ "the TensorList element must not be nullptr");
161+ return ACLNN_ERR_PARAM_NULLPTR;
162+ }
163+ }
164+ return ACLNN_SUCCESS;
165+}
166+ 
167+bool CheckStorageBounds(const DualLevelGroupedMatmulParams& params)
168+{
169+ using gmm::CheckTensorListStorageBounds;
170+ // The caller's transposed weight and scale already describe their storage spans.
171+ return CheckTensorListStorageBounds(params.x, API_NAME, "x") &&
172+ CheckTensorListStorageBounds(params.weight, API_NAME, "weight") &&
173+ CheckTensorListStorageBounds(params.biasOptional, API_NAME, "biasOptional") &&
174+ CheckTensorListStorageBounds(params.scaleOptional, API_NAME, "scaleOptional") &&
175+ CheckTensorListStorageBounds(params.perTokenScaleOptional, API_NAME, "perTokenScaleOptional") &&
176+ gmm::CheckTensorStorageBounds(params.groupListOptional, API_NAME, "groupListOptional") &&
177+ CheckTensorListStorageBounds(params.xLevel0Scale, API_NAME, "xLevel0Scale") &&
178+ CheckTensorListStorageBounds(params.weightLevel0Scale, API_NAME, "weightLevel0Scale") &&
179+ CheckTensorListStorageBounds(params.out, API_NAME, "out");
180+}
181+ 
182+aclnnStatus CheckAttributes(const DualLevelGroupedMatmulParams& params)
183+{
184+ // With one x and one output tensor, splitItem=2 and 3 use the same layout.
185+ struct Attribute {
186+ const char* name;
187+ int64_t value;
188+ int64_t low;
189+ int64_t high;
190+ };
191+ const Attribute attributes[] = {{"splitItem", params.splitItem, SPLIT_ITEM_SINGLE_OUTPUT, SPLIT_ITEM_DEFAULT},
192+ {"groupType", params.groupType, 0, 0},
193+ {"groupListType", params.groupListType, 0, SPARSE_GROUP_LIST},
194+ {"level0GroupSize", params.level0GroupSize, LEVEL0_GROUP_SIZE, LEVEL0_GROUP_SIZE},
195+ {"level1GroupSize", params.level1GroupSize, LEVEL1_GROUP_SIZE, LEVEL1_GROUP_SIZE}};
196+ for (const auto& attr : attributes) {
197+ if (attr.value < attr.low || attr.value > attr.high) {
198+ const auto expected = "expected range [" + std::to_string(attr.low) + "," + std::to_string(attr.high) + "]";
199+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(API_NAME, attr.name, std::to_string(attr.value).c_str(),
200+ expected.c_str());
201+ return ACLNN_ERR_PARAM_INVALID;
202+ }
203+ }
204+ if (params.tuningConfigOptional != nullptr &&
205+ (params.tuningConfigOptional->Size() != 1 || (*params.tuningConfigOptional)[0] != 0)) {
206+ OP_LOGE_FOR_INVALID_ARGUMENT_WITH_REASON(API_NAME, "tuningConfigOptional", "expected nullptr or {0}");
207+ return ACLNN_ERR_PARAM_INVALID;
208+ }
209+ 
210+ return ACLNN_SUCCESS;
211+}
212+ 
213+aclnnStatus CheckDtype(const DualLevelGroupedMatmulParams& params)
214+{
215+ struct TypedInput {
216+ const char* name;
217+ const aclTensor* tensor;
218+ DataType expected;
219+ };
220+ const TypedInput inputs[] = {
221+ {"x", (*params.x)[0], DataType::DT_FLOAT4_E2M1},
222+ {"weight", (*params.weight)[0], DataType::DT_FLOAT4_E2M1},
223+ {"xLevel0Scale", (*params.xLevel0Scale)[0], DataType::DT_FLOAT},
224+ {"weightLevel0Scale", (*params.weightLevel0Scale)[0], DataType::DT_FLOAT},
225+ {"scaleOptional", (*params.scaleOptional)[0], DataType::DT_FLOAT8_E8M0},
226+ {"perTokenScaleOptional", (*params.perTokenScaleOptional)[0], DataType::DT_FLOAT8_E8M0},
227+ {"groupListOptional", params.groupListOptional, DataType::DT_INT64}};
228+ for (const auto& input : inputs) {
229+ if (input.tensor->GetDataType() != input.expected) {
230+ LogTensorMismatch(input.name, input.tensor, "dtype=" + std::to_string(static_cast<int>(input.expected)));
231+ return ACLNN_ERR_PARAM_INVALID;
232+ }
233+ }
234+ if (params.biasOptional != nullptr && (*params.biasOptional)[0]->GetDataType() != DataType::DT_FLOAT) {
235+ LogTensorMismatch("biasOptional", (*params.biasOptional)[0], "FP32 bias");
236+ return ACLNN_ERR_PARAM_INVALID;
237+ }
238+ const auto* output = (*params.out)[0];
239+ if (output->GetDataType() != DataType::DT_FLOAT16 && output->GetDataType() != DataType::DT_BF16) {
240+ LogTensorMismatch("out", output, "FP16 or BF16 output");
241+ return ACLNN_ERR_PARAM_INVALID;
242+ }
243+ return ACLNN_SUCCESS;
244+}
245+ 
246+aclnnStatus CheckWeightStorage(const aclTensor* w, const aclTensor* b1, bool transpose, int64_t e, int64_t k, int64_t n,
247+ int64_t mxScaleGroups)
248+{
249+ if (b1->GetStorageFormat() != Format::FORMAT_ND ||
250+ !MatchShape(b1->GetViewShape(), {e, mxScaleGroups, n, MX_SCALE_PAIR})) {
251+ LogTensorMismatch("scaleOptional", b1, "ND view=(E,ceil(K/64),N,2)");
252+ return ACLNN_ERR_PARAM_INVALID;
253+ }
254+ if (w->IsEmpty() && (transpose || n % FP4_ELEMENTS_PER_BYTE == 0) && w->GetViewOffset() == 0 &&
255+ b1->GetViewOffset() == 0) {
256+ return ACLNN_SUCCESS;
257+ }
258+ if (!transpose && (n % FP4_ELEMENTS_PER_BYTE != 0 || !MatchStrides(w, {k * n, n, 1}))) {
259+ LogTensorMismatch("weight", w, "even N and canonical NZ contiguous/transposed view with zero offset");
260+ return ACLNN_ERR_PARAM_INVALID;
261+ }
262+ const int64_t weightRows = transpose ? n : k;
263+ const int64_t weightCols = transpose ? k : n;
264+ const std::initializer_list<int64_t> nzShape{e, Ops::Base::CeilDiv(weightCols, NZ_COLS),
265+ Ops::Base::CeilDiv(weightRows, NZ_ROWS), NZ_ROWS, NZ_COLS};
266+ if (!MatchShape(w->GetStorageShape(), nzShape)) {
267+ LogTensorMismatch("weight", w, "NZ storage=" + ValuesString(nzShape));
268+ return ACLNN_ERR_PARAM_INVALID;
269+ }
270+ if (transpose) {
271+ if (!MatchShape(b1->GetStorageShape(), {e, n, mxScaleGroups, MX_SCALE_PAIR}) ||
272+ !MatchStrides(b1, {n * mxScaleGroups * MX_SCALE_PAIR, MX_SCALE_PAIR, mxScaleGroups * MX_SCALE_PAIR, 1})) {
273+ LogTensorMismatch("scaleOptional", b1, "transposed scale storage=(E,N,ceil(K/64),2) with zero offset");
274+ return ACLNN_ERR_PARAM_INVALID;
275+ }
276+ } else {
277+ if (!IsDenseNd(b1)) {
278+ LogTensorMismatch("scaleOptional", b1, "dense ND storage with zero offset");
279+ return ACLNN_ERR_PARAM_INVALID;
280+ }
281+ }
282+ 
283+ return ACLNN_SUCCESS;
284+}
285+ 
286+aclnnStatus CheckDenseInputs(const DualLevelGroupedMatmulParams& params)
287+{
288+ struct NamedTensor {
289+ const char* name;
290+ const aclTensor* tensor;
291+ };
292+ const NamedTensor inputs[] = {{"x", (*params.x)[0]},
293+ {"xLevel0Scale", (*params.xLevel0Scale)[0]},
294+ {"perTokenScaleOptional", (*params.perTokenScaleOptional)[0]},
295+ {"weightLevel0Scale", (*params.weightLevel0Scale)[0]},
296+ {"groupListOptional", params.groupListOptional},
297+ {"out", (*params.out)[0]}};
298+ for (const auto& input : inputs) {
299+ if (!IsDenseNd(input.tensor)) {
300+ LogTensorMismatch(input.name, input.tensor, "dense ND storage with zero offset");
301+ return ACLNN_ERR_PARAM_INVALID;
302+ }
303+ }
304+ if (params.biasOptional != nullptr && !IsDenseNd((*params.biasOptional)[0])) {
305+ LogTensorMismatch("biasOptional", (*params.biasOptional)[0], "dense ND storage with zero offset");
306+ return ACLNN_ERR_PARAM_INVALID;
307+ }
308+ return ACLNN_SUCCESS;
309+}
310+ 
311+aclnnStatus CheckShapeAndFormat(const DualLevelGroupedMatmulParams& params, bool& transposeWeight)
312+{
313+ const auto* a = (*params.x)[0];
314+ const auto* w = (*params.weight)[0];
315+ const auto* a0 = (*params.xLevel0Scale)[0];
316+ const auto* b0 = (*params.weightLevel0Scale)[0];
317+ const auto* a1 = (*params.perTokenScaleOptional)[0];
318+ const auto* b1 = (*params.scaleOptional)[0];
319+ const auto* bias = params.biasOptional == nullptr ? nullptr : (*params.biasOptional)[0];
320+ auto* y = (*params.out)[0];
321+ const auto& wShape = w->GetViewShape();
322+ if (wShape.GetDimNum() != EXPERT_WEIGHT_RANK || w->GetStorageFormat() != Format::FORMAT_FRACTAL_NZ) {
323+ LogTensorMismatch("weight", w, "rank=3 and FRACTAL_NZ format");
324+ return ACLNN_ERR_PARAM_INVALID;
325+ }
326+ const auto e = wShape.GetDim(0);
327+ const auto k = wShape.GetDim(1);
328+ const auto n = wShape.GetDim(WEIGHT_N_AXIS);
329+ const auto& xShape = a->GetViewShape();
330+ if (xShape.GetDimNum() != MATRIX_RANK) {
331+ LogTensorMismatch("x", a, "rank=2");
332+ return ACLNN_ERR_PARAM_INVALID;
333+ }
334+ const auto m = xShape.GetDim(0);
335+ const bool emptyOutput = m == 0 || n == 0;
336+ if (xShape.GetDim(1) == 0 && !emptyOutput) {
337+ LogTensorMismatch("x", a, "K may be zero only when M or N is zero");
338+ return ACLNN_ERR_PARAM_INVALID;
339+ }
kknan
kknankknan9 days ago

output的stride拦截是否加了

likedislike
zhangzhizhuo
zhangzhizhuo
8 days ago Comments:
likedislike
340+ constexpr int64_t maxDim = std::numeric_limits<int32_t>::max() - 1;
341+ if (e <= 0 || e > maxDim || k > maxDim || k % FP4_ELEMENTS_PER_BYTE != 0 || n > maxDim ||
342+ (!emptyOutput && (k <= MIN_K || n <= 1))) {
343+ LogTensorMismatch("weight", w,
344+ "positive E, even K, dimensions at most " + std::to_string(maxDim) +
345+ ", and K > 2 and N > 1 for nonempty output");
346+ return ACLNN_ERR_PARAM_INVALID;
347+ }
348+ const auto mxScaleGroups = Ops::Base::CeilDiv(k, MX_SCALE_K);
349+ const auto level0Groups = Ops::Base::CeilDiv(k, LEVEL0_GROUP_SIZE);
350+ if (m > maxDim) {
351+ LogTensorMismatch("x", a, "0<=M<=" + std::to_string(maxDim));
352+ return ACLNN_ERR_PARAM_INVALID;
353+ }
354+ CHECK_RET(CheckShape(a, {m, k}, "x") && CheckShape(a0, {m, level0Groups}, "xLevel0Scale") &&
355+ CheckShape(a1, {m, mxScaleGroups, MX_SCALE_PAIR}, "perTokenScaleOptional") &&
356+ CheckShape(b0, {e, level0Groups, n}, "weightLevel0Scale") &&
357+ (params.groupListType == SPARSE_GROUP_LIST ?
358+ CheckShape(params.groupListOptional, {e, GROUP_LIST_PAIR_SIZE}, "groupListOptional") :
359+ CheckShape(params.groupListOptional, {e}, "groupListOptional")) &&
360+ CheckShape(y, {m, n}, "out") && (bias == nullptr || CheckShape(bias, {e, n}, "biasOptional")),
361+ ACLNN_ERR_PARAM_INVALID);
362+ 
363+ CHECK_RET(CheckDenseInputs(params) == ACLNN_SUCCESS, ACLNN_ERR_PARAM_INVALID);
364+ transposeWeight = MatchStrides(w, {k * n, 1, k});
365+ return CheckWeightStorage(w, b1, transposeWeight, e, k, n, mxScaleGroups);
366+}
367+} // namespace
368+aclnnStatus CheckParams(const DualLevelGroupedMatmulParams& params, bool& transposeWeight)
369+{
370+ const auto checkNotNullRet = CheckNotNull(params);
371+ if (checkNotNullRet != ACLNN_SUCCESS) {
372+ return checkNotNullRet;
373+ }
374+ CHECK_RET(CheckStorageBounds(params), ACLNN_ERR_PARAM_INVALID);
375+ const auto checkAttributesRet = CheckAttributes(params);
376+ if (checkAttributesRet != ACLNN_SUCCESS) {
377+ return checkAttributesRet;
378+ }
379+ const auto checkDtypeRet = CheckDtype(params);
380+ if (checkDtypeRet != ACLNN_SUCCESS) {
381+ return checkDtypeRet;
382+ }
383+ return CheckShapeAndFormat(params, transposeWeight);
384+}
385+} // namespace dual_level_gmm
@@ -0,0 +1,29 @@
1+// Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+// Licensed under CANN Open Software License Agreement Version 2.0.
3+#ifndef DUAL_LEVEL_GROUPED_MATMUL_CHECKER_H_
4+#define DUAL_LEVEL_GROUPED_MATMUL_CHECKER_H_
5+#include "aclnn_dual_level_grouped_matmul_weight_nz.h"
6+namespace dual_level_gmm {
7+inline constexpr int64_t LEVEL0_GROUP_SIZE = 512;
8+inline constexpr int64_t LEVEL1_GROUP_SIZE = 32;
9+ 
10+struct DualLevelGroupedMatmulParams {
11+ const aclTensorList* x;
12+ const aclTensorList* weight;
13+ const aclTensorList* biasOptional;
14+ const aclTensorList* scaleOptional;
15+ const aclTensorList* perTokenScaleOptional;
16+ const aclTensor* groupListOptional;
17+ const aclTensorList* xLevel0Scale;
18+ const aclTensorList* weightLevel0Scale;
19+ int64_t level0GroupSize;
20+ int64_t level1GroupSize;
21+ int64_t splitItem;
22+ int64_t groupType;
23+ int64_t groupListType;
24+ const aclIntArray* tuningConfigOptional;
25+ aclTensorList* out;
26+};
27+aclnnStatus CheckParams(const DualLevelGroupedMatmulParams& params, bool& transposeWeight);
28+} // namespace dual_level_gmm
29+#endif
@@ -0,0 +1,19 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# Licensed under CANN Open Software License Agreement Version 2.0.
3+add_op_to_compiled_list()
4+if(BUILD_OPEN_PROJECT)
5+ target_sources(op_host_aclnnExc PRIVATE dual_level_grouped_matmul_def.cpp)
6+endif()
7+if(UT_TEST_ALL OR OP_HOST_UT OR OP_API_UT)
8+ add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../tests ${CMAKE_CURRENT_BINARY_DIR}/tests)
9+endif()
10+add_ops_compile_options(OP_NAME DualLevelGroupedMatmul OPTIONS --cce-auto-sync=on)
11+if(NOT BUILD_OPS_RTY_KERNEL)
12+ add_modules_sources(
13+ OP_API_INDEPENDENT ON
14+ OP_API_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../op_api
15+ OPTYPE dual_level_grouped_matmul
16+ ACLNNTYPE aclnn_exclude
17+ )
18+ target_include_directories(${OPHOST_NAME}_tiling_obj PRIVATE "${OPTENSOR_SOURCE_PATH}/include")
19+endif()
@@ -0,0 +1,50 @@
1+// Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+// Licensed under CANN Open Software License Agreement Version 2.0.
3+#include "register/op_def_registry.h"
4+#include "../op_kernel/dual_level_grouped_matmul_tiling_data.h"
5+ 
6+namespace ops {
7+class DualLevelGroupedMatmul : public OpDef {
8+public:
9+ explicit DualLevelGroupedMatmul(const char* name) : OpDef(name)
10+ {
11+ this->Input("x").ParamType(REQUIRED)
12+ .DataType({ge::DT_FLOAT4_E2M1, ge::DT_FLOAT4_E2M1})
13+ .Format({ge::FORMAT_ND, ge::FORMAT_ND}).UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
14+ this->Input("x_level0_scale").ParamType(REQUIRED)
15+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT})
16+ .Format({ge::FORMAT_ND, ge::FORMAT_ND}).UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
17+ this->Input("x_level1_scale").ParamType(REQUIRED)
18+ .DataType({ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0})
19+ .Format({ge::FORMAT_ND, ge::FORMAT_ND}).UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
20+ this->Input("weight").ParamType(REQUIRED)
21+ .DataType({ge::DT_FLOAT4_E2M1, ge::DT_FLOAT4_E2M1})
22+ .Format({ge::FORMAT_FRACTAL_NZ, ge::FORMAT_FRACTAL_NZ})
23+ .UnknownShapeFormat({ge::FORMAT_FRACTAL_NZ, ge::FORMAT_FRACTAL_NZ});
24+ this->Input("weight_level0_scale").ParamType(REQUIRED)
25+ .DataType({ge::DT_FLOAT, ge::DT_FLOAT})
26+ .Format({ge::FORMAT_ND, ge::FORMAT_ND}).UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
27+ this->Input("weight_level1_scale").ParamType(REQUIRED)
28+ .DataType({ge::DT_FLOAT8_E8M0, ge::DT_FLOAT8_E8M0})
29+ .Format({ge::FORMAT_ND, ge::FORMAT_ND}).UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
30+ this->Input("grouplist").ParamType(REQUIRED).DataType({ge::DT_INT64, ge::DT_INT64})
31+ .Format({ge::FORMAT_ND, ge::FORMAT_ND}).UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
32+ this->Input("bias").ParamType(OPTIONAL).DataType({ge::DT_FLOAT, ge::DT_FLOAT})
33+ .Format({ge::FORMAT_ND, ge::FORMAT_ND}).UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
34+ this->Output("y").ParamType(REQUIRED).DataType({ge::DT_FLOAT16, ge::DT_BF16})
35+ .Format({ge::FORMAT_ND, ge::FORMAT_ND}).UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
36+ this->Attr("transpose_weight").AttrType(OPTIONAL).Bool(false);
37+ this->Attr("group_list_type").AttrType(OPTIONAL).Int(0);
38+ this->Attr("tuning_config").AttrType(OPTIONAL).ListInt({0});
39+ this->Attr("dtype").AttrType(REQUIRED).Int();
40+ this->Attr("level0_group_size").AttrType(OPTIONAL).Int(::DualLevelGroupedMatmul::DEFAULT_LEVEL0_GROUP_SIZE);
41+ this->Attr("level1_group_size").AttrType(OPTIONAL).Int(::DualLevelGroupedMatmul::DEFAULT_LEVEL1_GROUP_SIZE);
42+ OpAICoreConfig config;
43+ config.DynamicCompileStaticFlag(true).DynamicFormatFlag(true)
44+ .DynamicRankSupportFlag(false).DynamicShapeSupportFlag(true)
45+ .NeedCheckSupportFlag(false).PrecisionReduceFlag(true);
46+ this->AICore().AddConfig("ascend950", config);
47+ }
48+};
49+OP_ADD(DualLevelGroupedMatmul);
50+} // namespace ops
@@ -0,0 +1,44 @@
1+// Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+// Licensed under CANN Open Software License Agreement Version 2.0.
3+#include "dual_level_grouped_matmul_tiling.h"
4+ 
5+namespace ge {
6+using optiling::DualLevelAttrIndex;
7+using optiling::DualLevelInputIndex;
8+using DualLevelGroupedMatmul::WEIGHT_NK_AXIS;
9+static graphStatus InferDualLevelGroupedMatmulShape(gert::InferShapeContext* ctx)
10+{
11+ const auto* x = ctx->GetInputShape(DualLevelInputIndex::X);
12+ const auto* w = ctx->GetInputShape(DualLevelInputIndex::WEIGHT);
13+ auto* y = ctx->GetOutputShape(0);
14+ const auto* attrs = ctx->GetAttrs();
15+ if (x == nullptr || w == nullptr || y == nullptr || attrs == nullptr || x->GetDimNum() != optiling::MATRIX_RANK ||
16+ w->GetDimNum() != optiling::EXPERT_WEIGHT_RANK) {
17+ return GRAPH_FAILED;
18+ }
19+ const auto* trans = attrs->GetAttrPointer<bool>(DualLevelAttrIndex::TRANSPOSE_WEIGHT);
20+ if (trans == nullptr) {
21+ return GRAPH_FAILED;
22+ }
23+ const int64_t wk = w->GetDim(*trans ? WEIGHT_NK_AXIS : 1);
24+ const int64_t xk = x->GetDim(1);
25+ if (wk >= 0 && xk >= 0 && wk != xk) {
26+ return GRAPH_FAILED;
27+ }
28+ *y = gert::Shape({x->GetDim(0), w->GetDim(*trans ? 1 : WEIGHT_NK_AXIS)});
29+ return GRAPH_SUCCESS;
30+}
31+static graphStatus InferDualLevelGroupedMatmulType(gert::InferDataTypeContext* ctx)
32+{
33+ const auto* attrs = ctx->GetAttrs();
34+ const auto* dtype = attrs == nullptr ? nullptr : attrs->GetAttrPointer<int64_t>(DualLevelAttrIndex::OUTPUT_DTYPE);
35+ if (dtype == nullptr || (*dtype != DT_FLOAT16 && *dtype != DT_BF16)) {
36+ return GRAPH_FAILED;
37+ }
38+ ctx->SetOutputDataType(0, static_cast<DataType>(*dtype));
39+ return GRAPH_SUCCESS;
40+}
41+IMPL_OP_INFERSHAPE(DualLevelGroupedMatmul)
42+ .InferShape(InferDualLevelGroupedMatmulShape)
43+ .InferDataType(InferDualLevelGroupedMatmulType);
44+} // namespace ge
@@ -0,0 +1,401 @@
1+// Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+// Licensed under CANN Open Software License Agreement Version 2.0.
3+#include "dual_level_grouped_matmul_tiling.h"
4+#include <algorithm>
5+#include <cstring>
6+#include <initializer_list>
7+#include <limits>
8+#include <string>
9+#include "platform/platform_ascendc.h"
10+#include "log/log.h"
11+#include "util/math_util.h"
12+ 
13+namespace optiling {
14+namespace {
15+using namespace DualLevelGroupedMatmul;
16+using Ops::Base::CeilDiv;
17+constexpr int64_t MX_SCALE_K = MX_SCALE_PAIR * DEFAULT_LEVEL1_GROUP_SIZE;
18+constexpr int64_t NZ_ROWS = 16;
19+constexpr int64_t NZ_COLS = 64;
20+constexpr uint64_t FP4_ELEMENTS_PER_BYTE = 2;
21+constexpr int64_t MIN_K = 2;
22+constexpr int64_t SPARSE_GROUP_LIST = 2;
23+constexpr int64_t GROUP_LIST_PAIR_SIZE = 2;
24+constexpr uint64_t NZ_BLOCK_BYTES = NZ_ROWS * NZ_COLS / FP4_ELEMENTS_PER_BYTE;
25+constexpr uint64_t KIBIBYTE = 1024;
26+constexpr uint64_t MIN_L1_BYTES = 512 * KIBIBYTE;
27+constexpr uint64_t MIN_L0_OPERAND_BYTES = 64 * KIBIBYTE;
28+constexpr uint64_t MIN_L0C_BYTES = 256 * KIBIBYTE;
29+constexpr uint64_t AIV_COUNT = 2;
30+ 
31+void ReportInvalid(const gert::TilingContext* ctx, const char* parameter, const std::string& actual,
32+ const std::string& reason)
33+{
34+ OP_LOGE_FOR_INVALID_VALUE_WITH_REASON(ctx->GetNodeName(), parameter, actual.c_str(), reason.c_str());
35+}
36+ 
37+// Per-AIV UB layout: partial slots, tiled accumulators, scale A window, scale B and bias.
38+// Match the L0 block geometry and UB layout of the dual-level BlockMmad and Epilogue.
39+uint64_t CalcEpilogueUbBytes(uint64_t m, uint64_t n)
40+{
41+ constexpr uint64_t L0_BASE_M = 128;
42+ constexpr uint64_t L0_BASE_N = 128;
43+ constexpr uint64_t PARTIAL_BUFFER_COUNT = 2;
44+ constexpr uint64_t SCALE_B_AND_BIAS_BUFFERS = 2;
45+ constexpr uint64_t SCALE0_WINDOW = 32;
46+ constexpr uint64_t PARTIAL_BYTES = L0_BASE_M / AIV_COUNT * L0_BASE_N * sizeof(float);
47+ const uint64_t mTiles = CeilDiv(m, L0_BASE_M);
48+ const uint64_t nTiles = CeilDiv(n, L0_BASE_N);
49+ const uint64_t accumulatorBytes = mTiles * nTiles * PARTIAL_BYTES;
50+ const uint64_t scaleABytes = mTiles * (L0_BASE_M / AIV_COUNT) * SCALE0_WINDOW * sizeof(float);
51+ return PARTIAL_BUFFER_COUNT * PARTIAL_BYTES + accumulatorBytes + scaleABytes +
52+ n * sizeof(float) * SCALE_B_AND_BIAS_BUFFERS;
53+}
54+ 
55+std::string ShapeString(const gert::Shape& shape)
56+{
57+ std::string out = "(";
58+ for (size_t i = 0; i < shape.GetDimNum(); ++i) {
59+ if (i != 0) {
60+ out += ",";
61+ }
62+ out += std::to_string(shape.GetDim(i));
63+ }
64+ return out + ")";
65+}
66+ 
67+std::string DimsString(std::initializer_list<int64_t> dims)
68+{
69+ std::string out = "(";
70+ for (auto dim : dims) {
71+ if (out.size() != 1) {
72+ out += ",";
73+ }
74+ out += std::to_string(dim);
75+ }
76+ return out + ")";
77+}
78+ 
79+bool Match(const gert::Shape& s, std::initializer_list<int64_t> dims)
80+{
81+ if (s.GetDimNum() != dims.size()) {
82+ return false;
83+ }
84+ size_t i = 0;
85+ for (const auto d : dims) {
86+ if (s.GetDim(i++) != d) {
87+ return false;
88+ }
89+ }
90+ return true;
91+}
92+ 
93+bool NdInput(gert::TilingContext* ctx, size_t i, ge::DataType dtype, std::initializer_list<int64_t> dims)
94+{
95+ const auto* desc = ctx->GetInputDesc(i);
96+ const auto* shape = ctx->GetInputShape(i);
97+ const bool valid = desc != nullptr && shape != nullptr && desc->GetDataType() == dtype &&
98+ desc->GetStorageFormat() == ge::FORMAT_ND && Match(shape->GetOriginShape(), dims) &&
99+ Match(shape->GetStorageShape(), dims);
100+ if (!valid && desc != nullptr && shape != nullptr) {
101+ ReportInvalid(ctx, "input",
102+ "index=" + std::to_string(i) + ", dtype=" + std::to_string(desc->GetDataType()) +
103+ ", format=" + std::to_string(desc->GetStorageFormat()) + ", origin=" +
104+ ShapeString(shape->GetOriginShape()) + ", storage=" + ShapeString(shape->GetStorageShape()),
105+ "expected ND, dtype=" + std::to_string(dtype) + ", shape=" + DimsString(dims));
106+ }
107+ if (desc == nullptr || shape == nullptr) {
108+ ReportInvalid(ctx, "input", "index=" + std::to_string(i), "descriptor and shape must be present");
109+ }
110+ return valid;
111+}
112+ 
113+bool ProductFits(std::initializer_list<uint64_t> factors)
114+{
115+ uint64_t v = 1;
116+ for (auto f : factors) {
117+ if (f != 0 && v > static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) / f) {
118+ return false;
119+ }
120+ v *= f;
121+ }
122+ return true;
123+}
124+ 
125+} // namespace
126+ 
127+ge::graphStatus DualLevelGroupedMatmulTiling::CheckAttributes()
128+{
129+ auto* ctx = context_;
130+ const auto* attrs = ctx->GetAttrs();
131+ const bool* trans = attrs->GetAttrPointer<bool>(DualLevelAttrIndex::TRANSPOSE_WEIGHT);
132+ const auto* groupType = attrs->GetAttrPointer<int64_t>(DualLevelAttrIndex::GROUP_LIST_TYPE);
133+ const auto* tuning = attrs->GetAttrPointer<gert::ContinuousVector>(DualLevelAttrIndex::TUNING_CONFIG);
134+ const auto* dtype = attrs->GetAttrPointer<int64_t>(DualLevelAttrIndex::OUTPUT_DTYPE);
135+ const auto* level0Size = attrs->GetAttrNum() > DualLevelAttrIndex::LEVEL0_GROUP_SIZE ?
136+ attrs->GetAttrPointer<int64_t>(DualLevelAttrIndex::LEVEL0_GROUP_SIZE) :
137+ nullptr;
138+ if (trans == nullptr || groupType == nullptr || dtype == nullptr || tuning == nullptr || *groupType < 0 ||
139+ *groupType > SPARSE_GROUP_LIST || tuning->GetSize() != 1 || tuning->GetData() == nullptr ||
140+ static_cast<const int64_t*>(tuning->GetData())[0] != 0) {
141+ ReportInvalid(ctx, "attributes", "invalid or missing",
142+ "expected transpose_weight and dtype, supported "
143+ "group_list_type, and tuning_config={0}");
144+ return ge::GRAPH_FAILED;
145+ }
146+ // Older callers can omit the appended group-size attributes.
147+ const int64_t segmentSize = level0Size == nullptr ? DEFAULT_LEVEL0_GROUP_SIZE : *level0Size;
148+ if (segmentSize != DEFAULT_LEVEL0_GROUP_SIZE) {
149+ ReportInvalid(ctx, "level0_group_size", std::to_string(segmentSize),
150+ "expected " + std::to_string(DEFAULT_LEVEL0_GROUP_SIZE));
151+ return ge::GRAPH_FAILED;
152+ }
153+ const auto* level1Size = attrs->GetAttrNum() > DualLevelAttrIndex::LEVEL1_GROUP_SIZE ?
154+ attrs->GetAttrPointer<int64_t>(DualLevelAttrIndex::LEVEL1_GROUP_SIZE) :
155+ nullptr;
156+ if (level1Size != nullptr && *level1Size != DEFAULT_LEVEL1_GROUP_SIZE) {
157+ ReportInvalid(ctx, "level1_group_size", std::to_string(*level1Size),
158+ "expected " + std::to_string(DEFAULT_LEVEL1_GROUP_SIZE));
159+ return ge::GRAPH_FAILED;
160+ }
161+ tilingData_.level0Size = static_cast<uint64_t>(segmentSize);
162+ transposeWeight_ = *trans;
163+ groupListType_ = *groupType;
164+ outputDtype_ = *dtype;
165+ return ge::GRAPH_SUCCESS;
166+}
167+ 
168+ge::graphStatus DualLevelGroupedMatmulTiling::GetShapeAttrs()
169+{
170+ auto* ctx = context_;
171+ auto& t = tilingData_;
172+ const auto* xs = ctx->GetInputShape(DualLevelInputIndex::X);
173+ const auto* ws = ctx->GetInputShape(DualLevelInputIndex::WEIGHT);
174+ const auto* wd = ctx->GetInputDesc(DualLevelInputIndex::WEIGHT);
175+ if (xs == nullptr || ws == nullptr || wd == nullptr || xs->GetOriginShape().GetDimNum() != MATRIX_RANK ||
176+ ws->GetOriginShape().GetDimNum() != EXPERT_WEIGHT_RANK) {
177+ ReportInvalid(ctx, "x/weight", "invalid or missing descriptors", "expected rank-two x and rank-three weight");
178+ return ge::GRAPH_FAILED;
179+ }
180+ t.m = xs->GetOriginShape().GetDim(0);
181+ t.k = xs->GetOriginShape().GetDim(1);
182+ t.experts = ws->GetOriginShape().GetDim(0);
183+ t.n = ws->GetOriginShape().GetDim(transposeWeight_ ? 1 : WEIGHT_NK_AXIS);
184+ const auto wk = ws->GetOriginShape().GetDim(transposeWeight_ ? WEIGHT_NK_AXIS : 1);
185+ // Packed FP4 rows need an even inner dimension, as in MXFP4 GMM.
186+ if (t.m <= 0 || t.n <= 1 || t.k <= MIN_K || t.experts <= 0 || wk != t.k || t.k % FP4_ELEMENTS_PER_BYTE != 0 ||
187+ (!transposeWeight_ && t.n % FP4_ELEMENTS_PER_BYTE != 0)) {
188+ ReportInvalid(ctx, "x/weight shape", DimsString({t.m, t.n, t.k, t.experts, wk}),
189+ "expected positive M and E, N greater than one, equal even K greater than two, "
190+ "and even N for non-transposed weight");
191+ return ge::GRAPH_FAILED;
192+ }
193+ return ge::GRAPH_SUCCESS;
194+}
195+ 
196+ge::graphStatus DualLevelGroupedMatmulTiling::CheckAddressBounds()
197+{
198+ auto& t = tilingData_;
199+ // Address products and hardware descriptor dimensions must be representable.
200+ constexpr int64_t maxDim = std::numeric_limits<int32_t>::max() - 1;
201+ if (std::max({t.m, t.n, t.k, t.experts}) > maxDim) {
202+ ReportInvalid(context_, "M,N,K,E", DimsString({t.m, t.n, t.k, t.experts}),
203+ "each dimension must be at most " + std::to_string(maxDim));
204+ return ge::GRAPH_FAILED;
205+ }
206+ const int64_t level0Size = static_cast<int64_t>(t.level0Size);
207+ const int64_t level0Groups = CeilDiv(t.k, level0Size);
208+ const int64_t mxScaleGroups = CeilDiv(t.k, MX_SCALE_K);
209+ const int64_t weightRows = transposeWeight_ ? t.n : t.k, weightCols = transposeWeight_ ? t.k : t.n;
210+ const int64_t weightRowBlocks = CeilDiv(weightRows, NZ_ROWS);
211+ const int64_t weightColBlocks = CeilDiv(weightCols, NZ_COLS);
212+ if (!ProductFits({static_cast<uint64_t>(t.m), static_cast<uint64_t>(t.k)}) ||
213+ // The MX kernel multiplies the padded FP4 element stride by expert
214+ // before converting the offset to packed bytes. Check that product too.
215+ !ProductFits({static_cast<uint64_t>(t.experts), static_cast<uint64_t>(weightColBlocks),
216+ static_cast<uint64_t>(weightRowBlocks), NZ_ROWS, NZ_COLS}) ||
217+ !ProductFits({static_cast<uint64_t>(t.experts), static_cast<uint64_t>(weightColBlocks),
218+ static_cast<uint64_t>(weightRowBlocks), NZ_BLOCK_BYTES}) ||
219+ !ProductFits({static_cast<uint64_t>(t.experts), static_cast<uint64_t>(t.n),
220+ static_cast<uint64_t>(mxScaleGroups), MX_SCALE_PAIR}) ||
221+ !ProductFits({static_cast<uint64_t>(t.m), static_cast<uint64_t>(t.n), sizeof(uint16_t)}) ||
222+ !ProductFits({static_cast<uint64_t>(t.m), static_cast<uint64_t>(level0Groups), sizeof(float)}) ||
223+ !ProductFits({static_cast<uint64_t>(t.experts), static_cast<uint64_t>(level0Groups), static_cast<uint64_t>(t.n),
224+ sizeof(float)})) {
225+ ReportInvalid(context_, "M,N,K,E", DimsString({t.m, t.n, t.k, t.experts}),
226+ "tensor offsets and padded weight element counts must fit int64");
227+ return ge::GRAPH_FAILED;
228+ }
229+ t.weightStrideBytes = static_cast<uint64_t>(weightColBlocks) * weightRowBlocks * NZ_BLOCK_BYTES;
230+ return ge::GRAPH_SUCCESS;
231+}
232+ 
233+ge::graphStatus DualLevelGroupedMatmulTiling::CheckInputShapes()
234+{
235+ auto* ctx = context_;
236+ auto& t = tilingData_;
237+ const auto* ws = ctx->GetInputShape(DualLevelInputIndex::WEIGHT);
238+ const auto* wd = ctx->GetInputDesc(DualLevelInputIndex::WEIGHT);
239+ const int64_t level0Size = static_cast<int64_t>(t.level0Size);
240+ const int64_t level0Groups = CeilDiv(t.k, level0Size);
241+ const int64_t mxScaleGroups = CeilDiv(t.k, MX_SCALE_K);
242+ const int64_t weightRows = transposeWeight_ ? t.n : t.k;
243+ const int64_t weightCols = transposeWeight_ ? t.k : t.n;
244+ const int64_t weightRowBlocks = CeilDiv(weightRows, NZ_ROWS);
245+ const int64_t weightColBlocks = CeilDiv(weightCols, NZ_COLS);
246+ // The individual-op runtime can normalize an NZ tensor's context storage
247+ // shape to its logical shape. Its format remains NZ; derive the physical
248+ // padded group stride from that logical shape in either representation.
249+ const bool validWeightStorage =
250+ Match(ws->GetStorageShape(), {t.experts, weightColBlocks, weightRowBlocks, NZ_ROWS, NZ_COLS}) ||
251+ Match(ws->GetStorageShape(), {t.experts, weightRows, weightCols});
252+ if (wd->GetDataType() != ge::DT_FLOAT4_E2M1 || wd->GetStorageFormat() != ge::FORMAT_FRACTAL_NZ ||
253+ !validWeightStorage) {
254+ ReportInvalid(ctx, "weight",
255+ "dtype=" + std::to_string(wd->GetDataType()) + ", format=" +
256+ std::to_string(wd->GetStorageFormat()) + ", storage=" + ShapeString(ws->GetStorageShape()),
257+ "expected FP4 E2M1 FRACTAL_NZ with the padded storage shape or its normalized logical shape");
258+ return ge::GRAPH_FAILED;
259+ }
260+ if (!NdInput(ctx, DualLevelInputIndex::X, ge::DT_FLOAT4_E2M1, {t.m, t.k}) ||
261+ !NdInput(ctx, DualLevelInputIndex::X_LEVEL0_SCALE, ge::DT_FLOAT, {t.m, level0Groups}) ||
262+ !NdInput(ctx, DualLevelInputIndex::X_LEVEL1_SCALE, ge::DT_FLOAT8_E8M0, {t.m, mxScaleGroups, MX_SCALE_PAIR}) ||
263+ !NdInput(ctx, DualLevelInputIndex::WEIGHT_LEVEL0_SCALE, ge::DT_FLOAT, {t.experts, level0Groups, t.n})) {
264+ return ge::GRAPH_FAILED;
265+ }
266+ const bool validGroups =
267+ groupListType_ == SPARSE_GROUP_LIST ?
268+ NdInput(ctx, DualLevelInputIndex::GROUP_LIST, ge::DT_INT64, {t.experts, GROUP_LIST_PAIR_SIZE}) :
269+ NdInput(ctx, DualLevelInputIndex::GROUP_LIST, ge::DT_INT64, {t.experts});
270+ const auto scaleRows = transposeWeight_ ? t.n : mxScaleGroups;
271+ const auto scaleCols = transposeWeight_ ? mxScaleGroups : t.n;
272+ if (!validGroups || !NdInput(ctx, DualLevelInputIndex::WEIGHT_LEVEL1_SCALE, ge::DT_FLOAT8_E8M0,
273+ {t.experts, scaleRows, scaleCols, MX_SCALE_PAIR})) {
274+ return ge::GRAPH_FAILED;
275+ }
276+ t.hasBias = ctx->GetOptionalInputShape(DualLevelInputIndex::BIAS) != nullptr;
277+ if (t.hasBias && !NdInput(ctx, DualLevelInputIndex::BIAS, ge::DT_FLOAT, {t.experts, t.n})) {
278+ return ge::GRAPH_FAILED;
279+ }
280+ return ge::GRAPH_SUCCESS;
281+}
282+ 
283+ge::graphStatus DualLevelGroupedMatmulTiling::CheckOutputShape()
284+{
285+ auto* ctx = context_;
286+ auto& t = tilingData_;
287+ const auto* yd = ctx->GetOutputDesc(0);
288+ const auto* ys = ctx->GetOutputShape(0);
289+ if (yd == nullptr || ys == nullptr || (outputDtype_ != ge::DT_FLOAT16 && outputDtype_ != ge::DT_BF16) ||
290+ yd->GetDataType() != outputDtype_ || yd->GetStorageFormat() != ge::FORMAT_ND ||
291+ !Match(ys->GetOriginShape(), {t.m, t.n}) || !Match(ys->GetStorageShape(), {t.m, t.n})) {
292+ ReportInvalid(ctx, "out", ys == nullptr ? "missing shape" : ShapeString(ys->GetStorageShape()),
293+ "expected FP16/BF16 ND output with shape " + DimsString({t.m, t.n}));
294+ return ge::GRAPH_FAILED;
295+ }
296+ return ge::GRAPH_SUCCESS;
297+}
298+ 
299+ge::graphStatus DualLevelGroupedMatmulTiling::GetPlatformInfo()
300+{
301+ auto* ctx = context_;
302+ auto& t = tilingData_;
303+ platform_ascendc::PlatformAscendC platform(ctx->GetPlatformInfo());
304+ if (platform.GetSocVersion() != platform_ascendc::SocVersion::ASCEND950 || platform.GetCoreNumAic() == 0 ||
305+ platform.GetCoreNumAiv() < platform.GetCoreNumAic() * AIV_COUNT) {
306+ ReportInvalid(ctx, "platform",
307+ "SoC=" + std::to_string(static_cast<int>(platform.GetSocVersion())) +
308+ ", AIC=" + std::to_string(platform.GetCoreNumAic()) +
309+ ", AIV=" + std::to_string(platform.GetCoreNumAiv()),
310+ "expected Ascend 950 with a Cube core and the required Vector cores per Cube core");
311+ return ge::GRAPH_FAILED;
312+ }
313+ uint64_t ub = 0, l1 = 0, l0a = 0, l0b = 0, l0c = 0;
314+ platform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, ub);
315+ platform.GetCoreMemSize(platform_ascendc::CoreMemType::L1, l1);
316+ platform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_A, l0a);
317+ platform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_B, l0b);
318+ platform.GetCoreMemSize(platform_ascendc::CoreMemType::L0_C, l0c);
319+ // All paths share the original MX L1 partitioning. Select a scheduler tile
320+ // from aggregate M/N; actual expert lengths are balanced on device.
321+ if (l1 < MIN_L1_BYTES || l0a < MIN_L0_OPERAND_BYTES || l0b < MIN_L0_OPERAND_BYTES || l0c < MIN_L0C_BYTES) {
322+ ReportInvalid(ctx, "core memory",
323+ "L1=" + std::to_string(l1) + ", L0A=" + std::to_string(l0a) + ", L0B=" + std::to_string(l0b) +
324+ ", L0C=" + std::to_string(l0c),
325+ "insufficient capacity for the dual-level MX buffers");
326+ return ge::GRAPH_FAILED;
327+ }
328+ t.coreNum = platform.GetCoreNumAic();
329+ ubSize_ = ub;
330+ libApiWorkspaceSize_ = platform.GetLibApiWorkSpaceSize();
331+ return ge::GRAPH_SUCCESS;
332+}
333+ 
334+ge::graphStatus DualLevelGroupedMatmulTiling::CalBasicBlock()
335+{
336+ auto* ctx = context_;
337+ auto& t = tilingData_;
338+ // Same selection rule as Ascend 950 GMM MXFP4, owned by this experimental operator.
339+ constexpr int64_t MAX_BASIC_BLOCK = 256;
340+ constexpr int64_t CUBE_BLOCK = 16;
341+ constexpr int64_t FP4_INNER_ALIGN = 64;
342+ t.baseM = Ops::Base::CeilAlign(std::min(t.m, MAX_BASIC_BLOCK), CUBE_BLOCK);
343+ t.baseN = Ops::Base::CeilAlign(std::min(t.n, MAX_BASIC_BLOCK), transposeWeight_ ? CUBE_BLOCK : FP4_INNER_ALIGN);
344+ const auto requiredUb = CalcEpilogueUbBytes(t.baseM, t.baseN);
345+ if (ubSize_ < requiredUb) {
346+ ReportInvalid(ctx, "UB", std::to_string(ubSize_),
347+ "expected at least " + std::to_string(requiredUb) + " bytes for the basic block");
348+ return ge::GRAPH_FAILED;
349+ }
350+ return ge::GRAPH_SUCCESS;
351+}
352+ 
353+ge::graphStatus DualLevelGroupedMatmulTiling::SaveTilingData()
354+{
355+ auto* ctx = context_;
356+ auto& t = tilingData_;
357+ t.transposeWeight = transposeWeight_;
358+ t.groupListType = groupListType_;
359+ t.outputBf16 = outputDtype_ == ge::DT_BF16;
360+ auto* raw = ctx->GetRawTilingData();
361+ auto* workspace = ctx->GetWorkspaceSizes(1);
362+ if (raw == nullptr || raw->GetData() == nullptr || raw->GetCapacity() < sizeof(t) || workspace == nullptr) {
363+ ReportInvalid(ctx, "tiling buffers", raw == nullptr ? "missing buffer" : std::to_string(raw->GetCapacity()),
364+ "expected workspace and a tiling buffer with capacity of at least " + std::to_string(sizeof(t)));
365+ return ge::GRAPH_FAILED;
366+ }
367+ std::memcpy(raw->GetData(), &t, sizeof(t));
368+ raw->SetDataSize(sizeof(t));
369+ workspace[0] = libApiWorkspaceSize_;
370+ ctx->SetBlockDim(t.coreNum);
371+ const auto key = t.outputBf16 ? (t.transposeWeight ? DLGMM_BF16_TRANSPOSE_TILING_KEY : DLGMM_BF16_TILING_KEY) :
372+ (t.transposeWeight ? DLGMM_FP16_TRANSPOSE_TILING_KEY : DLGMM_FP16_TILING_KEY);
373+ ctx->SetTilingKey(key);
374+ return ge::GRAPH_SUCCESS;
375+}
376+ 
377+ge::graphStatus DualLevelGroupedMatmulTiling::DoTiling()
378+{
379+ if (context_ == nullptr || context_->GetAttrs() == nullptr || context_->GetPlatformInfo() == nullptr) {
380+ return ge::GRAPH_FAILED;
381+ }
382+ const bool valid = CheckAttributes() == ge::GRAPH_SUCCESS && GetShapeAttrs() == ge::GRAPH_SUCCESS &&
383+ CheckAddressBounds() == ge::GRAPH_SUCCESS && CheckInputShapes() == ge::GRAPH_SUCCESS &&
384+ CheckOutputShape() == ge::GRAPH_SUCCESS && GetPlatformInfo() == ge::GRAPH_SUCCESS &&
385+ CalBasicBlock() == ge::GRAPH_SUCCESS && SaveTilingData() == ge::GRAPH_SUCCESS;
386+ return valid ? ge::GRAPH_SUCCESS : ge::GRAPH_FAILED;
387+}
388+namespace {
389+ge::graphStatus TilingDualLevelGroupedMatmul(gert::TilingContext* context)
390+{
391+ return DualLevelGroupedMatmulTiling(context).DoTiling();
392+}
393+ge::graphStatus TilingPrepareForDualLevelGroupedMatmul(gert::TilingParseContext*)
394+{
395+ return ge::GRAPH_SUCCESS;
396+}
397+} // namespace
398+IMPL_OP_OPTILING(DualLevelGroupedMatmul)
399+ .Tiling(TilingDualLevelGroupedMatmul)
400+ .TilingParse<DualLevelGroupedMatmulCompileInfo>(TilingPrepareForDualLevelGroupedMatmul);
401+} // namespace optiling
@@ -0,0 +1,58 @@
1+// Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+// Licensed under CANN Open Software License Agreement Version 2.0.
3+#ifndef DUAL_LEVEL_GROUPED_MATMUL_TILING_H_
4+#define DUAL_LEVEL_GROUPED_MATMUL_TILING_H_
5+#include "register/op_impl_registry.h"
6+#include "../op_kernel/dual_level_grouped_matmul_tiling_data.h"
7+namespace optiling {
8+struct DualLevelInputIndex {
9+ enum : size_t {
10+ X,
11+ X_LEVEL0_SCALE,
12+ X_LEVEL1_SCALE,
13+ WEIGHT,
14+ WEIGHT_LEVEL0_SCALE,
15+ WEIGHT_LEVEL1_SCALE,
16+ GROUP_LIST,
17+ BIAS
18+ };
19+};
20+struct DualLevelAttrIndex {
21+ enum : size_t {
22+ TRANSPOSE_WEIGHT,
23+ GROUP_LIST_TYPE,
24+ TUNING_CONFIG,
25+ OUTPUT_DTYPE,
26+ LEVEL0_GROUP_SIZE,
27+ LEVEL1_GROUP_SIZE
28+ };
29+};
30+inline constexpr size_t MATRIX_RANK = 2;
31+inline constexpr size_t EXPERT_WEIGHT_RANK = 3;
32+struct DualLevelGroupedMatmulCompileInfo {};
33+class DualLevelGroupedMatmulTiling {
34+public:
35+ explicit DualLevelGroupedMatmulTiling(gert::TilingContext* context)
36+ : context_(context)
37+ {}
38+ ge::graphStatus DoTiling();
39+ 
40+private:
41+ ge::graphStatus CheckAttributes();
42+ ge::graphStatus GetShapeAttrs();
43+ ge::graphStatus CheckAddressBounds();
44+ ge::graphStatus CheckInputShapes();
45+ ge::graphStatus CheckOutputShape();
46+ ge::graphStatus GetPlatformInfo();
47+ ge::graphStatus CalBasicBlock();
48+ ge::graphStatus SaveTilingData();
49+ gert::TilingContext* context_;
50+ DualLevelGroupedMatmul::DualLevelGroupedMatmulTilingData tilingData_{};
51+ bool transposeWeight_ = false;
52+ int64_t groupListType_ = 0;
53+ int64_t outputDtype_ = 0;
54+ uint64_t ubSize_ = 0;
55+ uint64_t libApiWorkspaceSize_ = 0;
56+};
57+} // namespace optiling
58+#endif
@@ -0,0 +1,93 @@
1+// Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+// Licensed under CANN Open Software License Agreement Version 2.0.
3+#include "kernel_operator.h"
4+#include "kernel_tiling/kernel_tiling.h"
5+#include "dual_level_grouped_matmul_tiling_data.h"
6+#include "blaze/gemm/kernel/kernel_qgmm_mx.h"
7+#include "blaze/gemm/block/block_mmad_qgmm_mx.h"
8+#include "blaze/epilogue/block/block_epilogue_dual_level_scale.h"
9+ 
10+// The generated DFX metadata references this name at namespace scope.
11+using DualLevelGroupedMatmulTilingData = DualLevelGroupedMatmul::DualLevelGroupedMatmulTilingData;
12+ 
13+namespace {
14+using namespace DualLevelGroupedMatmul;
15+template <class Output, bool TransposeWeight>
16+__aicore__ inline void RunDualLevelGroupedMatmul(GM_ADDR x, GM_ADDR a0, GM_ADDR a1, GM_ADDR weight, GM_ADDR b0,
17+ GM_ADDR b1, GM_ADDR groups, GM_ADDR bias, GM_ADDR y,
18+ const DualLevelGroupedMatmulTilingData& t)
19+{
20+ if (t.version != TILING_DATA_VERSION) {
21+ return;
22+ }
23+ using Nd = asc::te::nd_ext_layout_ptn;
24+ using WeightLayout = AscendC::Std::conditional_t<TransposeWeight, asc::te::zn_layout_ptn, asc::te::nz_layout_ptn>;
25+ using Policy = Blaze::Gemm::GroupedMatmulWithScaleMx<0, false, Blaze::Gemm::KernelGroupedMmadWithDualLevelScaleMx>;
26+ using Mmad =
27+ Blaze::Gemm::Block::BlockMmad<Policy, fp4x2_e2m1_t, Nd, fp4x2_e2m1_t, WeightLayout, Output, Nd, float, Nd>;
28+ using Epilogue = Blaze::Epilogue::Block::BlockEpilogueDualLevelScale<Output>;
29+ using Kernel = Blaze::Gemm::Kernel::GemmUniversal<typename Mmad::ProblemShape, Mmad, Epilogue,
30+ Blaze::Gemm::Block::BlockSchedulerGmmSwatWithTailSplit>;
31+ typename Kernel::Params params{};
32+ params.problemShape = {t.m, t.n, t.k, 0};
33+ params.mmadParams.aGmAddr = x;
34+ params.mmadParams.bGmAddr = weight;
35+ params.mmadParams.cGmAddr = y;
36+ params.mmadParams.biasGmAddr = bias;
37+ params.mmadParams.scaleAGmAddr = a1;
38+ params.mmadParams.scaleBGmAddr = b1;
39+ params.epilogueParams.level0ScaleAGmAddr = a0;
40+ params.epilogueParams.level0ScaleBGmAddr = b0;
41+ params.groupListGmAddr = groups;
42+ auto& gmm = params.gmmParams;
43+ gmm.groupNum = t.experts;
44+ gmm.m = t.m;
45+ gmm.n = t.n;
46+ gmm.k = t.k;
47+ gmm.baseM = t.baseM;
48+ gmm.baseN = t.baseN;
49+ gmm.baseK = t.level0Size;
50+ gmm.kAL1 = t.level0Size;
51+ gmm.kBL1 = t.level0Size;
52+ gmm.scaleKAL1 = LEVEL1_SCALE_L1_WINDOW_K;
53+ gmm.scaleKBL1 = gmm.scaleKAL1;
54+ gmm.isBias = t.hasBias;
55+ gmm.groupType = 0;
56+ gmm.groupListType = t.groupListType;
57+ gmm.singleW = 1;
58+ Kernel kernel;
59+ kernel(params);
60+}
61+} // namespace
62+ 
63+extern "C" __global__ __aicore__ void dual_level_grouped_matmul(GM_ADDR x, GM_ADDR a0, GM_ADDR a1, GM_ADDR weight,
64+ GM_ADDR b0, GM_ADDR b1, GM_ADDR groups, GM_ADDR bias,
65+ GM_ADDR y, GM_ADDR workspace, GM_ADDR tiling)
66+{
67+ KERNEL_TASK_TYPE_DEFAULT(KERNEL_TYPE_MIX_AIC_1_2);
68+ REGISTER_TILING_DEFAULT(DualLevelGroupedMatmulTilingData);
69+ DualLevelGroupedMatmulTilingData td;
70+ // Read the shared fixed-width POD directly; this entry also compiles outside
71+ // the generated op-build wrapper which supplies GET_TILING_DATA_WITH_STRUCT.
72+ auto* words = reinterpret_cast<uint64_t*>(&td);
73+ auto* gmWords = reinterpret_cast<__gm__ uint64_t*>(tiling);
74+ for (uint32_t i = 0; i < sizeof(DualLevelGroupedMatmulTilingData) / sizeof(uint64_t); ++i) {
75+ words[i] = gmWords[i];
76+ }
77+ AscendC::InitSocState();
78+#define RUN_DUAL_LEVEL(Output, Trans) \
79+ RunDualLevelGroupedMatmul<Output, Trans>(x, a0, a1, weight, b0, b1, groups, bias, y, td)
80+ if (TILING_KEY_IS(DLGMM_FP16_TILING_KEY)) {
81+ RUN_DUAL_LEVEL(half, false);
82+ }
83+ if (TILING_KEY_IS(DLGMM_FP16_TRANSPOSE_TILING_KEY)) {
84+ RUN_DUAL_LEVEL(half, true);
85+ }
86+ if (TILING_KEY_IS(DLGMM_BF16_TILING_KEY)) {
87+ RUN_DUAL_LEVEL(bfloat16_t, false);
88+ }
89+ if (TILING_KEY_IS(DLGMM_BF16_TRANSPOSE_TILING_KEY)) {
90+ RUN_DUAL_LEVEL(bfloat16_t, true);
91+ }
92+#undef RUN_DUAL_LEVEL
93+}
@@ -0,0 +1,52 @@
1+// Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+// Licensed under CANN Open Software License Agreement Version 2.0.
3+#pragma once
4+#include <cstdint>
5+#include <cstddef>
6+ 
7+// TILING_KEY_IS requires keys visible to the kernel preprocessor.
8+#define DLGMM_FP16_TILING_KEY 0
9+#define DLGMM_FP16_TRANSPOSE_TILING_KEY 1
10+#define DLGMM_BF16_TILING_KEY 2
11+#define DLGMM_BF16_TRANSPOSE_TILING_KEY 3
12+ 
13+namespace DualLevelGroupedMatmul {
14+inline constexpr int64_t DEFAULT_LEVEL0_GROUP_SIZE = 512;
15+inline constexpr int64_t DEFAULT_LEVEL1_GROUP_SIZE = 32;
16+inline constexpr uint32_t LEVEL1_SCALE_L1_WINDOW_K = 4096;
17+inline constexpr int64_t MX_SCALE_PAIR = 2;
18+inline constexpr int64_t WEIGHT_NK_AXIS = 2;
19+inline constexpr uint64_t TILING_DATA_VERSION = 1;
20+inline constexpr uint64_t DEFAULT_BASE_M = 32;
21+inline constexpr uint64_t DEFAULT_BASE_N = 64;
22+inline constexpr size_t TILING_DATA_ALIGNMENT = 8;
23+inline constexpr size_t TILING_DATA_WORDS = 14;
24+inline constexpr size_t LEVEL0_SIZE_WORD = 8;
25+inline constexpr size_t OUTPUT_BF16_WORD = 13;
26+// Operator-owned Host/Kernel tiling data. Dimensions count logical elements.
27+ 
28+struct alignas(TILING_DATA_ALIGNMENT) DualLevelGroupedMatmulTilingData {
29+ uint64_t version = TILING_DATA_VERSION;
30+ int64_t m = 0;
31+ int64_t n = 0;
32+ int64_t k = 0;
33+ int64_t experts = 0;
34+ // Protocol v1 metadata; device addressing is derived from the logical shape.
35+ uint64_t weightStrideBytes = 0;
36+ // M/N for scheduling and L1 planning. BlockMmad defines its L0 limits.
37+ uint64_t baseM = DEFAULT_BASE_M;
38+ uint64_t baseN = DEFAULT_BASE_N;
39+ // Number of K elements per level0 scale group.
40+ uint64_t level0Size = DEFAULT_LEVEL0_GROUP_SIZE;
41+ uint64_t coreNum = 0;
42+ uint64_t transposeWeight = 0;
43+ uint64_t groupListType = 0;
44+ uint64_t hasBias = 0;
45+ uint64_t outputBf16 = 0;
46+};
47+ 
48+static_assert(alignof(DualLevelGroupedMatmulTilingData) == TILING_DATA_ALIGNMENT);
49+static_assert(sizeof(DualLevelGroupedMatmulTilingData) == TILING_DATA_WORDS * sizeof(uint64_t));
50+static_assert(offsetof(DualLevelGroupedMatmulTilingData, level0Size) == LEVEL0_SIZE_WORD * sizeof(uint64_t));
51+static_assert(offsetof(DualLevelGroupedMatmulTilingData, outputBf16) == OUTPUT_BF16_WORD * sizeof(uint64_t));
52+} // namespace DualLevelGroupedMatmul
@@ -0,0 +1,3 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# Licensed under CANN Open Software License Agreement Version 2.0.
3+add_subdirectory(ut)
@@ -0,0 +1,39 @@
1+# DualLevelGroupedMatmul 测试
2+ 
3+## 精度
4+ 
5+`assets/dlgmm_reference.py` 为共享 CPU reference;ACLNN 和 E2E 适配器分别处理 TensorList、NZ allocation 和 Torch 打包数据。Kernel 适配模块供两者复用,不再单独交付重复 Kernel ST。
6+ 
7+数值顺序:每 32 K 应用 level1 scale,在 512 K 段内 FP32 累加,再乘 A0×B0 并跨段累加;最终加 bias、转换 FP16/BF16。比较使用 CSV 中的 isclose 阈值,不放宽容差。
8+ 
9+ACLNN 和 Torch E2E 各有 11 条 ST,两条通路使用不同的 shape。每条通路独立覆盖权重转置与非转置、FP16/BF16 输出、有无 bias 的全部组合,以及三种分组列表类型和两种 `splitItem` 取值。用例还覆盖单行输入、多基本块、空专家、M/N/K 尾块,以及两级 scale 窗口切换。Torch E2E 同时覆盖 `torch.int8` 和 `torch.uint8` 打包输入。
10+ 
11+加载 CANN、已安装算子 vendor 和 Torch 扩展后,在 ops-test-kit 根目录运行:
12+ 
13+```bash
14+OP=/absolute/ops-transformer/experimental/gmm/dual_level_grouped_matmul
15+python3 -m ttk aclnn -i "$OP/tests/st/arch35/ttk_aclnn_dual_level_grouped_matmul_weight_nz_basic_st.csv" \
16+ --plugin "$OP/tests/assets" --devices 0 --pc 1 --seed 20261116 -o aclnn_results.csv
17+python3 "$OP/tests/st/run_e2e.py" e2e -i "$OP/tests/st/arch35/ttk_e2e_dual_level_grouped_matmul_basic_st.csv" \
18+ --plugin "$OP/tests/assets" --devices 0 --pc 1 --seed 20261116 -o e2e_results.csv
19+```
20+ 
21+vendor Torch 包通过 `CANN_TRANSFORMER_PACKAGE` 指定;标准包默认为 cann_ops_transformer。TTK 须支持 TensorList 的嵌套 stride。CPU reference 依赖 NumPy,BF16 需要 ml_dtypes,E2E 需要 Torch/TorchNPU。
22+ 
23+E2E 预处理显式将四维 weight level1 scale 转成实际 ND 存储,再恢复转置 view;不能仅凭 CSV 的 ND 标签或逻辑连续性判断设备格式。
24+ 
25+## 核心 UT
26+ 
27+Host/API UT 采用 CSV 批量驱动:用例全部定义在测试文件旁的同名 CSV 中(表头键值列,新增用例只需追加行,无需改动测试代码)。tiling 校验 tilingKey 与 tilingData 字段,infershape 按 `case_type=shape/dtype_only` 分别覆盖 shape 推导与 dtype 推导,op_api 按行调用生产 checker 校验 null/offset/stride/storage 及属性非法路径。通过仓库 build.sh 的 `--ophost --opapi -u --experimental --ops=dual_level_grouped_matmul` 运行:
28+ 
29+- `ut/op_host/test_dual_level_grouped_matmul_tiling.csv`(tiling 用例)
30+- `ut/op_host/test_dual_level_grouped_matmul_infershape.csv`(shape/dtype 用例)
31+- `ut/op_host/op_api/test_aclnn_dual_level_grouped_matmul_weight_nz.csv`(checker 用例)
32+ 
33+`ut/generate_ut_csv.py` 可按几何规则重新生成上述三张表(NZ 存储、level0/level1 分组数等均由 M/K/E/N 推导);手工改 CSV 或改脚本后重跑均可。
34+ 
35+Torch 测试覆盖 Meta 输出推导、稀疏分组以及设备侧的 scale shape、存储 dtype、视图偏移、ND/NZ 格式和默认确定性。在安装该扩展的环境运行:
36+ 
37+```bash
38+python3 -m unittest discover -s "$OP/tests/torch" -v
39+```
@@ -0,0 +1,96 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# Licensed under CANN Open Software License Agreement Version 2.0.
3+"""ACLNN TensorList/NZ adapter; all arithmetic lives in the CPU reference."""
4+ 
5+from pathlib import Path
6+from runpy import run_path
7+ 
8+_kernel = run_path(str(Path(__file__).with_name("dlgmm_kernel_golden.py")))
9+_ref = run_path(str(Path(__file__).with_name("dlgmm_reference.py")))
10+ 
11+ 
12+def _transposed(value):
13+ return (
14+ value.stride(-2) == 1
15+ if hasattr(value, "stride")
16+ else value.strides[-2] == value.itemsize
17+ )
18+ 
19+ 
20+class AclnnDualLevelGroupedMatmulTestSpec:
21+ tolerance = _ref["TOLERANCE"]
22+ compare = staticmethod(_ref["isclose_compare"])
23+ 
24+ @staticmethod
25+ def golden(
26+ x,
27+ weight,
28+ biasOptional,
29+ scaleOptional,
30+ perTokenScaleOptional,
31+ groupListOptional,
32+ xLevel0Scale,
33+ weightLevel0Scale,
34+ level0GroupSize,
35+ level1GroupSize,
36+ splitItem,
37+ groupType,
38+ groupListType,
39+ tuningConfigOptional,
40+ out,
41+ **kwargs,
42+ ):
43+ if (level0GroupSize, level1GroupSize, groupType) != (
44+ 512,
45+ 32,
46+ 0,
47+ ) or splitItem not in (2, 3):
48+ raise ValueError(
49+ "Only group sizes (512,32), splitItem=2/3, groupType=0 are supported"
50+ )
51+ for name, seq in (
52+ ("x", x),
53+ ("weight", weight),
54+ ("scaleOptional", scaleOptional),
55+ ("perTokenScaleOptional", perTokenScaleOptional),
56+ ("xLevel0Scale", xLevel0Scale),
57+ ("weightLevel0Scale", weightLevel0Scale),
58+ ("out", out),
59+ ):
60+ _kernel["_single_tensor"](seq, name)
61+ bias = _kernel["_single_tensor"](biasOptional, "biasOptional", optional=True)
62+ dtype = _kernel["_ge_output_dtype"](out[0].dtype)
63+ if groupListOptional is None:
64+ raise ValueError("groupListOptional is required")
65+ a = _ref["as_numpy"](x[0])
66+ e, k, n = weight[0].shape
67+ if tuple(out[0].shape) != (a.shape[0], n):
68+ raise ValueError("out[0] must have shape (M,N)")
69+ trans = _transposed(weight[0])
70+ rows, cols = (n, k) if trans else (k, n)
71+ storage = _ref["whole_storage"](weight[0]).reshape(
72+ e, (cols + 63) // 64, (rows + 15) // 16, 16, 64
73+ )
74+ b = _ref["nz_to_nd"](storage, (e, rows, cols))
75+ b1 = _ref["as_numpy"](scaleOptional[0])
76+ if trans:
77+ b1 = b1.swapaxes(1, 2)
78+ return _kernel["golden"](
79+ a,
80+ _ref["as_numpy"](xLevel0Scale[0]),
81+ _ref["as_numpy"](perTokenScaleOptional[0]),
82+ b,
83+ _ref["as_numpy"](weightLevel0Scale[0]),
84+ b1,
85+ _ref["as_numpy"](groupListOptional),
86+ None if bias is None else _ref["as_numpy"](bias),
87+ dtype=dtype,
88+ transpose_weight=trans,
89+ group_list_type=groupListType,
90+ tuning_config=tuningConfigOptional,
91+ )
92+ 
93+ 
94+__spec__ = {
95+ "aclnnDualLevelGroupedMatmulWeightNz": "AclnnDualLevelGroupedMatmulTestSpec"
96+}
@@ -0,0 +1,175 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# Licensed under CANN Open Software License Agreement Version 2.0.
3+"""Torch packed-byte adapter and device-side NZ preparation for TTK eager ST."""
4+ 
5+from pathlib import Path
6+from runpy import run_path
7+ 
8+_kernel = run_path(str(Path(__file__).with_name("dlgmm_kernel_golden.py")))
9+_ref = run_path(str(Path(__file__).with_name("dlgmm_reference.py")))
10+ 
11+ 
12+def _physical_weight_inputs(weight, scale):
13+ # Public transposed views pack pairs along K, not along their last (N) axis.
14+ if hasattr(weight, "stride"):
15+ public_transpose = weight.stride(-2) == 1 and weight.stride(-1) > 1
16+ else:
17+ public_transpose = (
18+ weight.strides[-2] == weight.itemsize
19+ and weight.strides[-1] > weight.itemsize
20+ )
21+ if public_transpose:
22+ return weight.swapaxes(1, 2), scale.swapaxes(1, 2), True
23+ return weight, scale, False
24+ 
25+ 
26+def _output_dtype(value):
27+ import torch
28+ 
29+ if value is None:
30+ value = torch.bfloat16
31+ if value not in (torch.float16, torch.bfloat16):
32+ raise ValueError("output_dtype must be torch.float16 or torch.bfloat16")
33+ return _kernel["_ge_output_dtype"](value)
34+ 
35+ 
36+class DualLevelGroupedMatmulTorchTestSpec:
37+ tolerance = _ref["TOLERANCE"]
38+ compare = staticmethod(_ref["isclose_compare"])
39+ 
40+ @staticmethod
41+ def npu_preprocess(
42+ x,
43+ weight,
44+ x_level0_scale,
45+ x_level1_scale,
46+ weight_level0_scale,
47+ weight_level1_scale,
48+ level0_group_size=512,
49+ level1_group_size=32,
50+ *,
51+ group_list,
52+ **kwargs,
53+ ):
54+ import torch_npu
55+ 
56+ # Restore the physical packed axis from the declared logical stride.
57+ w = _kernel["_single_tensor"](weight, "weight")
58+ b1 = _kernel["_single_tensor"](weight_level1_scale, "weight_level1_scale")
59+ physical_w, physical_b1, transposed = _physical_weight_inputs(w, b1)
60+ converted = torch_npu.npu_format_cast(physical_w, 29)
61+ weight[0] = converted.transpose(1, 2) if transposed else converted
62+ # Rank-four inputs created by the framework can use NCHW (format=0).
63+ # The public API requires actual ND storage, including for scale views.
64+ scale_nd = torch_npu.npu_format_cast(physical_b1.contiguous(), 2)
65+ weight_level1_scale[0] = scale_nd.transpose(1, 2) if transposed else scale_nd
66+ 
67+ @staticmethod
68+ def golden(
69+ x,
70+ weight,
71+ x_level0_scale,
72+ x_level1_scale,
73+ weight_level0_scale,
74+ weight_level1_scale,
75+ level0_group_size=512,
76+ level1_group_size=32,
77+ *,
78+ group_list=None,
79+ bias=None,
80+ offset=None,
81+ antiquant_scale=None,
82+ antiquant_offset=None,
83+ activation_input=None,
84+ activation_quant_scale=None,
85+ activation_quant_offset=None,
86+ split_item=3,
87+ group_type=0,
88+ group_list_type=0,
89+ act_type=0,
90+ tuning_config=None,
91+ output_dtype=None,
92+ x_dtype=None,
93+ weight_dtype=None,
94+ scale_dtype=None,
95+ per_token_scale_dtype=None,
96+ **kwargs,
97+ ):
98+ for name, value in (
99+ ("offset", offset),
100+ ("antiquant_scale", antiquant_scale),
101+ ("antiquant_offset", antiquant_offset),
102+ ("activation_input", activation_input),
103+ ("activation_quant_scale", activation_quant_scale),
104+ ("activation_quant_offset", activation_quant_offset),
105+ ):
106+ if value is not None:
107+ raise ValueError(
108+ f"{name} is not supported by dual-level MXFP4 grouped matmul."
109+ )
110+ if "scale" in kwargs or "per_token_scale" in kwargs:
111+ raise ValueError(
112+ "Use weight_level1_scale and x_level1_scale; duplicate scale names are not exposed."
113+ )
114+ if split_item not in (2, 3) or group_type != 0:
115+ raise ValueError("split_item must be 2 or 3 and group_type must be 0.")
116+ if act_type not in (None, 0):
117+ raise ValueError(
118+ "act_type currently supports only no activation (0 or None)."
119+ )
120+ # The documented default None selects FP4/E8M0. Explicit hints use
121+ # TorchNPU's named semantic types rather than opaque integer codes.
122+ hints = (
123+ ("x_dtype", x_dtype, "float4_e2m1fn_x2"),
124+ ("weight_dtype", weight_dtype, "float4_e2m1fn_x2"),
125+ ("scale_dtype", scale_dtype, "float8_e8m0fnu"),
126+ ("per_token_scale_dtype", per_token_scale_dtype, "float8_e8m0fnu"),
127+ )
128+ for name, value, semantic_name in hints:
129+ if value is None:
130+ continue
131+ import torch_npu
132+ 
133+ semantic = getattr(torch_npu, semantic_name)
134+ if value not in (None, semantic):
135+ raise ValueError(
136+ f"{name} supports only torch_npu.{semantic_name} or None."
137+ )
138+ if group_list is None:
139+ raise ValueError("group_list is required.")
140+ group_list_type = 0 if group_list_type is None else group_list_type
141+ if (level0_group_size, level1_group_size) != (512, 32):
142+ raise ValueError("Only group sizes (512,32) are supported")
143+ for name, seq in (
144+ ("x", x),
145+ ("weight", weight),
146+ ("x_level0_scale", x_level0_scale),
147+ ("x_level1_scale", x_level1_scale),
148+ ("weight_level0_scale", weight_level0_scale),
149+ ("weight_level1_scale", weight_level1_scale),
150+ ):
151+ _kernel["_single_tensor"](seq, name)
152+ bias_tensor = _kernel["_single_tensor"](bias, "bias", optional=True)
153+ dtype = _output_dtype(output_dtype)
154+ physical_w, physical_b1, transposed = _physical_weight_inputs(
155+ weight[0], weight_level1_scale[0]
156+ )
157+ return _kernel["golden"](
158+ _ref["unpack_fp4"](x[0]),
159+ _ref["as_numpy"](x_level0_scale[0]),
160+ _ref["as_numpy"](x_level1_scale[0]),
161+ _ref["unpack_fp4"](physical_w),
162+ _ref["as_numpy"](weight_level0_scale[0]),
163+ _ref["as_numpy"](physical_b1),
164+ _ref["as_numpy"](group_list),
165+ None if bias_tensor is None else _ref["as_numpy"](bias_tensor),
166+ dtype=dtype,
167+ transpose_weight=transposed,
168+ group_list_type=group_list_type,
169+ tuning_config=tuning_config,
170+ )
171+ 
172+ 
173+__spec__ = {
174+ "torch.ops.cann_ops_transformer.dual_level_grouped_matmul": "DualLevelGroupedMatmulTorchTestSpec"
175+}