Merged
feat(moe): 新增 MergeChunk 算子及 ACLNN 接口 #17055
feat(moe): 新增 MergeChunk 算子及 ACLNN 接口 #17055
Merged
TiMoAdd on 4 days ago
Total: 27 files changed+2137-0
@@ -0,0 +1,19 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# -----------------------------------------------------------------------------------------------------------
10+ 
11+file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*)
12+if(NOT ENABLE_TEST AND NOT BENCHMARK)
13+ list(REMOVE_ITEM CURRENT_DIRS tests)
14+endif()
15+foreach(SUB_DIR ${CURRENT_DIRS})
16+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt")
17+ add_subdirectory(${SUB_DIR})
18+ endif()
19+endforeach()
@@ -0,0 +1,50 @@
1+# MergeChunk
kdy18482276080
kdy18482276080kdy184822760802 days ago

【review】文档的格式改成和库上算子一致

likedislike
2+ 
3+## 产品支持情况
4+ 
5+| 产品 | 是否支持 |
6+| --- | --- |
7+| <term>Ascend 950PR&950DT系列产品</term> | × |
8+| <term>Atlas A3系列产品</term> | √ |
9+| <term>Atlas A2系列产品</term> | √ |
10+| <term>Atlas 200I/500 A2推理产品</term> | × |
11+| <term>Atlas推理系列产品</term> | × |
12+| <term>Atlas训练系列产品</term> | × |
13+| <term>Kirin X90处理器系列产品</term> | × |
14+| <term>Kirin 9030处理器系列产品</term> | × |
15+ 
16+## 功能说明
17+ 
18+MergeChunk 对每一路 token 数据独立执行按专家合并。每个 chunk 的输入行已按专家编号分段。对同一专家,算子按 chunk 的输入顺序拼接各段,保留段内的行序;再按专家编号依次输出。同一个 chunk 的各路输入共用一份专家计数,各 chunk 的计数按专家相加,得到各路输出共用的一份计数。
19+ 
20+设数据路数为 `R`,每路的 chunk 数为 `C`。对第 `r` 路(`0 ≤ r < R`)的专家 `e`,`X_{r,c,e}` 表示该专家在第 `c` 个 chunk 中的行段,`g_{c,e}` 表示该段的行数。合并后的行段和计数分别为
21+ 
22+$$
23+Y_{r,e}=\operatorname{Concat}_{\mathrm{rows}}(X_{r,0,e},\ldots,X_{r,C-1,e}),\qquad
24+G_e=\sum_{c=0}^{C-1}g_{c,e}.
25+$$
26+ 
27+## 参数说明
28+ 
29+| 参数名 | 输入/输出/属性 | 描述 | 数据类型 | 数据格式 |
30+| --- | --- | --- | --- | --- |
31+| input_chunks | 输入 | 各路、各 chunk 的 token 数据,列表长度为 `R × C`。 | FLOAT16、BFLOAT16 | ND |
32+| group_list_chunk | 输入 | 每个 chunk 一份专家计数,各路共用,列表长度为 `C`。 | INT32 | ND |
33+| num_paths | 属性 | 数据路数 `R`。 | INT64 | - |
34+| num_chunks | 属性 | 每路的 chunk 数 `C`。 | INT64 | - |
35+| out_chunks | 输出 | 每路一个合并结果,列表长度为 `R`。 | FLOAT16、BFLOAT16 | ND |
36+| out_group_list | 输出 | 各专家合并后的 token 数。 | INT32 | ND |
37+ 
38+## 约束说明
39+ 
40+- 当前版本仅支持两路数据、每路两个 chunk(`R = C = 2`)。
41+- 输入列表先按数据路排列,每路内按 chunk 顺序排列。第 `r` 路、第 `c` 个 chunk 的形状为 `[t_c, h_r]`,其中 `t_c > 0`。同一 chunk 在各路中的行数和专家分段一致。同一路内各 chunk 的宽度相同,不同路的宽度可以不同。
42+- 每份计数是长度为 `E` 的一维 Tensor,`1 ≤ E ≤ 1024`。调用方须确保各项非负且每份计数之和等于对应的 `t_c`。
43+- 所有数据 Tensor 统一使用 FLOAT16 或 BFLOAT16。`h_r` 是 16 的倍数,范围为 `[16, 90112]`。设 `T` 为每路所有 chunk 的 token 行数之和,每路输出形状为 `[T, h_r]`,`T × h_r` 不超过 INT32 最大值。
44+- 所有 Tensor 均为连续 ND 格式,位于同一设备。各输出缓冲区相互独立,与输入缓冲区无重叠。
45+ 
46+## 调用说明
47+ 
48+| 调用方式 | 调用样例 | 说明 |
49+| --- | --- | --- |
50+| aclnn | [test_aclnn_merge_chunk.cpp](examples/test_aclnn_merge_chunk.cpp) | [aclnnMergeChunk](docs/aclnnMergeChunk.md) |
@@ -0,0 +1,52 @@
1+# MergeChunk
2+ 
3+English | [简体中文](./README.md)
4+ 
5+## Product Support Status
6+ 
7+| Product | Supported |
8+| --- | --- |
9+| <term>Ascend 950PR&950DT products</term> | × |
10+| <term>Atlas A3 products</term> | √ |
11+| <term>Atlas A2 products</term> | √ |
12+| <term>Atlas 200I/500 A2 inference products</term> | × |
13+| <term>Atlas inference products</term> | × |
14+| <term>Atlas training products</term> | × |
15+| <term>Kirin X90 processor products</term> | × |
16+| <term>Kirin 9030 processor products</term> | × |
17+ 
18+## Function Description
19+ 
20+MergeChunk merges token rows by expert independently for each data path. Rows within each input chunk are already grouped by expert. For each expert, the operator concatenates its segments in input chunk order, preserving row order within each segment. Each path outputs the resulting segments in expert order. All paths share one expert count vector per chunk. Summing these vectors across chunks gives one count vector shared by all outputs.
21+ 
22+Let `R` be the number of paths and `C` the number of chunks per path. For expert `e` on path `r` (`0 ≤ r < R`), `X_{r,c,e}` denotes its row segment in chunk `c`, and `g_{c,e}` denotes the number of rows in that segment. The merged segment and count are
23+ 
24+$$
25+Y_{r,e}=\operatorname{Concat}_{\mathrm{rows}}(X_{r,0,e},\ldots,X_{r,C-1,e}),\qquad
26+G_e=\sum_{c=0}^{C-1}g_{c,e}.
27+$$
28+ 
29+## Parameter Description
30+ 
31+| Parameter Name | Input/Output/Attribute | Description | Data Type | Data Format |
32+| --- | --- | --- | --- | --- |
33+| input_chunks | Input | Token data for each path and chunk. List length: `R × C`. | FLOAT16, BFLOAT16 | ND |
34+| group_list_chunk | Input | One expert count tensor per chunk, shared by all paths. List length: `C`. | INT32 | ND |
35+| num_paths | Attribute | Number of data paths (`R`). | INT64 | - |
36+| num_chunks | Attribute | Number of chunks per path (`C`). | INT64 | - |
37+| out_chunks | Output | One merged tensor per path. List length: `R`. | FLOAT16, BFLOAT16 | ND |
38+| out_group_list | Output | Merged token count per expert. | INT32 | ND |
39+ 
40+## Constraints
41+ 
42+- This version requires two paths and two chunks per path (`R = C = 2`).
43+- Order input tensors by path, then by chunk within each path. Chunk `c` of path `r` has shape `[t_c, h_r]`, where `t_c > 0`. All paths share the row count and expert partition for each chunk. Width must match within a path and may differ between paths.
44+- Each count tensor is a vector of length `E`, with `1 ≤ E ≤ 1024`. The caller must supply nonnegative counts that sum to `t_c` for each chunk.
45+- Use the same data type, FLOAT16 or BFLOAT16, for all token data tensors. Each `h_r` must be a multiple of 16 in `[16, 90112]`. Let `T` be the sum of the chunk row counts for one path. Each output has shape `[T, h_r]`, and `T × h_r` must fit in INT32.
46+- All tensors must be contiguous, use ND format and reside on the same device. Output buffers must be mutually disjoint and must not overlap any input buffer.
47+ 
48+## Calling Instructions
49+ 
50+| Calling Method | Example | Description |
51+| --- | --- | --- |
52+| aclnn | [test_aclnn_merge_chunk.cpp](examples/test_aclnn_merge_chunk.cpp) | [aclnnMergeChunk](docs/aclnnMergeChunk_en.md) |
@@ -0,0 +1,103 @@
1+# aclnnMergeChunk
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+MergeChunk 对每一路 token 数据独立执行按专家合并。每个 chunk 的输入行已按专家编号分段。对同一专家,算子按 chunk 的输入顺序拼接各段,保留段内的行序;再按专家编号依次输出。同一个 chunk 的各路输入共用一份专家计数,各 chunk 的计数按专家相加,得到各路输出共用的一份计数。
27+ 
28+设数据路数为 `R`,每路的 chunk 数为 `C`。对第 `r` 路(`0 ≤ r < R`)的专家 `e`,`X_{r,c,e}` 表示该专家在第 `c` 个 chunk 中的行段,`g_{c,e}` 表示该段的行数。合并后的行段和计数分别为
29+ 
30+$$
31+Y_{r,e}=\operatorname{Concat}_{\mathrm{rows}}(X_{r,0,e},\ldots,X_{r,C-1,e}),\qquad
32+G_e=\sum_{c=0}^{C-1}g_{c,e}.
33+$$
34+ 
35+## 函数原型
36+ 
37+本接口采用[两段式调用](../../../docs/zh/context/two_phase_api.md)。先调用 `aclnnMergeChunkGetWorkspaceSize` 获取 workspace 大小和执行器,再调用 `aclnnMergeChunk` 提交计算任务。
38+ 
39+```cpp
40+aclnnStatus aclnnMergeChunkGetWorkspaceSize(
41+ const aclTensorList *inputChunks,
42+ const aclTensorList *groupListChunk,
43+ int64_t numPaths,
44+ int64_t numChunks,
45+ const aclTensorList *outChunks,
46+ const aclTensor *outGroupList,
47+ uint64_t *workspaceSize,
48+ aclOpExecutor **executor);
49+```
50+ 
51+```cpp
52+aclnnStatus aclnnMergeChunk(
53+ void *workspace,
54+ uint64_t workspaceSize,
55+ aclOpExecutor *executor,
56+ aclrtStream stream);
57+```
58+ 
59+## aclnnMergeChunkGetWorkspaceSize
60+ 
61+**参数说明**
62+ 
63+| 参数名 | 输入/输出 | 描述 | 使用说明 | 数据类型 | 数据格式 | 维度(shape) | 非连续 Tensor |
64+| --- | --- | --- | --- | --- | --- | --- | --- |
65+| `inputChunks` (`const aclTensorList*`) | 输入 | 各路、各 chunk 的 token 数据,列表长度为 `R × C`。 | 第 `r * C + c` 项对应第 `r` 路、第 `c` 块。 | FLOAT16、BFLOAT16 | ND | `[t_c, h_r]` | × |
66+| `groupListChunk` (`const aclTensorList*`) | 输入 | 每个 chunk 一份专家计数,各路共用,列表长度为 `C`。 | 第 `c` 项中,下标 `e` 对应专家 `e` 的 token 数。 | INT32 | ND | `[E]` | × |
67+| `numPaths` (`int64_t`) | 输入 | 数据路数 `R`。 | 必选。 | INT64 | - | - | - |
68+| `numChunks` (`int64_t`) | 输入 | 每路的 chunk 数 `C`。 | 必选。 | INT64 | - | - | - |
69+| `outChunks` (`const aclTensorList*`) | 输出 | 每路一个合并结果,列表长度为 `R`。 | 调用方按路序提供输出 Tensor,第 `r` 项对应第 `r` 路。 | FLOAT16、BFLOAT16 | ND | `[T, h_r]` | × |
70+| `outGroupList` (`const aclTensor*`) | 输出 | 各专家合并后的 token 数。 | 调用方提供长度为 `E` 的输出 Tensor。 | INT32 | ND | `[E]` | × |
71+| `workspaceSize` (`uint64_t*`) | 输出 | 所需 workspace 字节数。 | 用于准备第二阶段所需的设备内存。 | - | - | - | - |
72+| `executor` (`aclOpExecutor**`) | 输出 | 算子执行器。 | 传给第二阶段接口。 | - | - | - | - |
73+ 
74+**返回值**
75+ 
76+返回 `aclnnStatus`,详见[aclnn 返回码](../../../docs/zh/context/aclnn_return_code.md)。当路数或 chunk 数超出当前支持范围,或列表长度与参数不匹配时,返回 `ACLNN_ERR_PARAM_INVALID`。
77+ 
78+## aclnnMergeChunk
79+ 
80+**参数说明**
81+ 
82+| 参数名 | 输入/输出 | 描述 | 使用说明 | 数据类型 | 数据格式 | 维度(shape) | 非连续 Tensor |
83+| --- | --- | --- | --- | --- | --- | --- | --- |
84+| `workspace` (`void*`) | 输入 | 设备侧临时内存。 | 大小为 0 时可传空指针。 | - | - | - | - |
85+| `workspaceSize` (`uint64_t`) | 输入 | 临时内存字节数。 | 使用第一阶段返回值。 | - | - | - | - |
86+| `executor` (`aclOpExecutor*`) | 输入 | 算子执行器。 | 使用第一阶段返回的执行器。 | - | - | - | - |
87+| `stream` (`aclrtStream`) | 输入 | 执行任务的流。 | 读取输出前须等待任务完成。 | - | - | - | - |
88+ 
89+**返回值**
90+ 
91+返回 `aclnnStatus`,详见[aclnn 返回码](../../../docs/zh/context/aclnn_return_code.md)。
92+ 
93+## 约束说明
94+ 
95+- 当前版本仅支持两路数据、每路两个 chunk(`R = C = 2`)。
96+- 输入列表先按数据路排列,每路内按 chunk 顺序排列。第 `r` 路、第 `c` 个 chunk 的形状为 `[t_c, h_r]`,其中 `t_c > 0`。同一 chunk 在各路中的行数和专家分段一致。同一路内各 chunk 的宽度相同,不同路的宽度可以不同。
97+- 每份计数是长度为 `E` 的一维 Tensor,`1 ≤ E ≤ 1024`。调用方须确保各项非负且每份计数之和等于对应的 `t_c`。
98+- 所有数据 Tensor 统一使用 FLOAT16 或 BFLOAT16。`h_r` 是 16 的倍数,范围为 `[16, 90112]`。设 `T` 为每路所有 chunk 的 token 行数之和,每路输出形状为 `[T, h_r]`,`T × h_r` 不超过 INT32 最大值。
99+- 所有 Tensor 均为连续 ND 格式,位于同一设备。各输出缓冲区相互独立,与输入缓冲区无重叠。
100+ 
101+## 调用示例
102+ 
103+完整的 C++ 调用及输出校验见[test_aclnn_merge_chunk.cpp](../examples/test_aclnn_merge_chunk.cpp)。
@@ -0,0 +1,103 @@
1+# aclnnMergeChunk
2+ 
3+## Applicable Products
4+ 
5+<!-- npu="950" id1 -->
6+- <term>Ascend 950PR&950DT products</term>: Not supported
7+<!-- end id1 -->
8+<!-- npu="A3" id2 -->
9+- <term>Atlas A3 products</term>: Supported
10+<!-- end id2 -->
11+<!-- npu="910b" id3 -->
12+- <term>Atlas A2 products</term>: Supported
13+<!-- end id3 -->
14+<!-- npu="310b" id4 -->
15+- <term>Atlas 200I/500 A2 inference products</term>: Not supported
16+<!-- end id4 -->
17+<!-- npu="310p" id5 -->
18+- <term>Atlas inference products</term>: Not supported
19+<!-- end id5 -->
20+<!-- npu="910" id6 -->
21+- <term>Atlas training products</term>: Not supported
22+<!-- end id6 -->
23+ 
24+## Function
25+ 
26+MergeChunk merges token rows by expert independently for each data path. Rows within each input chunk are already grouped by expert. For each expert, the operator concatenates its segments in input chunk order, preserving row order within each segment. Each path outputs the resulting segments in expert order. All paths share one expert count vector per chunk. Summing these vectors across chunks gives one count vector shared by all outputs.
27+ 
28+Let `R` be the number of paths and `C` the number of chunks per path. For expert `e` on path `r` (`0 ≤ r < R`), `X_{r,c,e}` denotes its row segment in chunk `c`, and `g_{c,e}` denotes the number of rows in that segment. The merged segment and count are
29+ 
30+$$
31+Y_{r,e}=\operatorname{Concat}_{\mathrm{rows}}(X_{r,0,e},\ldots,X_{r,C-1,e}),\qquad
32+G_e=\sum_{c=0}^{C-1}g_{c,e}.
33+$$
34+ 
35+## Function Prototypes
36+ 
37+Use the [two-stage API](../../../docs/en/context/two_phase_api.md). Call `aclnnMergeChunkGetWorkspaceSize` to obtain the workspace size and executor, then call `aclnnMergeChunk` to submit the operation.
38+ 
39+```cpp
40+aclnnStatus aclnnMergeChunkGetWorkspaceSize(
41+ const aclTensorList *inputChunks,
42+ const aclTensorList *groupListChunk,
43+ int64_t numPaths,
44+ int64_t numChunks,
45+ const aclTensorList *outChunks,
46+ const aclTensor *outGroupList,
47+ uint64_t *workspaceSize,
48+ aclOpExecutor **executor);
49+```
50+ 
51+```cpp
52+aclnnStatus aclnnMergeChunk(
53+ void *workspace,
54+ uint64_t workspaceSize,
55+ aclOpExecutor *executor,
56+ aclrtStream stream);
57+```
58+ 
59+## aclnnMergeChunkGetWorkspaceSize
60+ 
61+**Parameters**
62+ 
63+| Parameter | Input/Output | Description | Usage | Data Type | Format | Shape | Non-contiguous Tensor |
64+| --- | --- | --- | --- | --- | --- | --- | --- |
65+| `inputChunks` (`const aclTensorList*`) | Input | Token data for each path and chunk. List length: `R × C`. | Item `r * C + c` is chunk `c` of path `r`. | FLOAT16, BFLOAT16 | ND | `[t_c, h_r]` | × |
66+| `groupListChunk` (`const aclTensorList*`) | Input | One expert count tensor per chunk, shared by all paths. List length: `C`. | In item `c`, entry `e` gives the token count for expert `e`. | INT32 | ND | `[E]` | × |
67+| `numPaths` (`int64_t`) | Input | Number of data paths (`R`). | Required. | INT64 | - | - | - |
68+| `numChunks` (`int64_t`) | Input | Number of chunks per path (`C`). | Required. | INT64 | - | - | - |
69+| `outChunks` (`const aclTensorList*`) | Output | One merged tensor per path. List length: `R`. | Provide output tensors in path order. Item `r` corresponds to path `r`. | FLOAT16, BFLOAT16 | ND | `[T, h_r]` | × |
70+| `outGroupList` (`const aclTensor*`) | Output | Merged token count per expert. | Provide an output tensor of length `E`. | INT32 | ND | `[E]` | × |
71+| `workspaceSize` (`uint64_t*`) | Output | Required workspace size in bytes. | Use the returned size to allocate device memory for the second call. | - | - | - | - |
72+| `executor` (`aclOpExecutor**`) | Output | Operator executor. | Pass the returned executor to the second call. | - | - | - | - |
73+ 
74+**Return Value**
75+ 
76+Returns `aclnnStatus`. See [aclnn return codes](../../../docs/en/context/aclnn_return_code.md). Returns `ACLNN_ERR_PARAM_INVALID` if the path or chunk count is unsupported or a list length does not match the supplied counts.
77+ 
78+## aclnnMergeChunk
79+ 
80+**Parameters**
81+ 
82+| Parameter | Input/Output | Description | Usage | Data Type | Format | Shape | Non-contiguous Tensor |
83+| --- | --- | --- | --- | --- | --- | --- | --- |
84+| `workspace` (`void*`) | Input | Temporary device memory. | May be null if the required size is zero. | - | - | - | - |
85+| `workspaceSize` (`uint64_t`) | Input | Workspace size in bytes. | Use the size returned by the first call. | - | - | - | - |
86+| `executor` (`aclOpExecutor*`) | Input | Operator executor. | Use the executor returned by the first call. | - | - | - | - |
87+| `stream` (`aclrtStream`) | Input | Execution stream. | Wait for completion before reading the outputs. | - | - | - | - |
88+ 
89+**Return Value**
90+ 
91+Returns `aclnnStatus`. See [aclnn return codes](../../../docs/en/context/aclnn_return_code.md).
92+ 
93+## Constraints
94+ 
95+- This version requires two paths and two chunks per path (`R = C = 2`).
96+- Order input tensors by path, then by chunk within each path. Chunk `c` of path `r` has shape `[t_c, h_r]`, where `t_c > 0`. All paths share the row count and expert partition for each chunk. Width must match within a path and may differ between paths.
97+- Each count tensor is a vector of length `E`, with `1 ≤ E ≤ 1024`. The caller must supply nonnegative counts that sum to `t_c` for each chunk.
98+- Use the same data type, FLOAT16 or BFLOAT16, for all token data tensors. Each `h_r` must be a multiple of 16 in `[16, 90112]`. Let `T` be the sum of the chunk row counts for one path. Each output has shape `[T, h_r]`, and `T × h_r` must fit in INT32.
99+- All tensors must be contiguous, use ND format and reside on the same device. Output buffers must be mutually disjoint and must not overlap any input buffer.
100+ 
101+## Example
102+ 
103+For a complete C++ call and output check, see [test_aclnn_merge_chunk.cpp](../examples/test_aclnn_merge_chunk.cpp).
@@ -0,0 +1,190 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include <algorithm>
12+#include <array>
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_merge_chunk.h"
21+ 
22+namespace {
23+using DevicePtr = std::unique_ptr<void, decltype(&aclrtFree)>;
24+using TensorPtr = std::unique_ptr<aclTensor, decltype(&aclDestroyTensor)>;
25+using TensorListPtr = std::unique_ptr<aclTensorList, decltype(&aclDestroyTensorList)>;
26+ 
27+void Check(int status, const char* operation)
28+{
29+ if (status != 0) {
30+ throw std::runtime_error(std::string(operation) + " failed: " + std::to_string(status));
31+ }
32+}
33+ 
34+struct Runtime {
35+ bool initialized = false;
36+ bool deviceSet = false;
37+ aclrtStream stream = nullptr;
38+ 
39+ ~Runtime()
40+ {
41+ if (stream != nullptr) {
42+ aclrtDestroyStream(stream);
43+ }
44+ if (deviceSet) {
45+ aclrtResetDevice(0);
46+ }
47+ if (initialized) {
48+ aclFinalize();
49+ }
50+ }
51+};
52+ 
53+DevicePtr Allocate(size_t bytes)
54+{
55+ void* address = nullptr;
56+ if (bytes != 0) {
57+ Check(aclrtMalloc(&address, bytes, ACL_MEM_MALLOC_NORMAL_ONLY), "aclrtMalloc");
58+ }
59+ return DevicePtr(address, aclrtFree);
60+}
61+ 
62+struct Tensor {
63+ DevicePtr storage;
64+ TensorPtr descriptor;
65+ 
66+ Tensor(const std::vector<int64_t>& shape, aclDataType dtype, size_t bytes, const void* values = nullptr)
67+ : storage(Allocate(bytes)),
68+ descriptor(nullptr, aclDestroyTensor)
69+ {
70+ std::vector<int64_t> strides(shape.size(), 1);
71+ for (size_t i = shape.size(); i > 1; --i) {
72+ strides[i - 2] = strides[i - 1] * shape[i - 1];
73+ }
74+ descriptor.reset(aclCreateTensor(shape.data(), shape.size(), dtype, strides.data(), 0, ACL_FORMAT_ND,
75+ shape.data(), shape.size(), storage.get()));
76+ if (!descriptor) {
77+ throw std::runtime_error("aclCreateTensor failed");
78+ }
79+ if (values != nullptr) {
80+ Check(aclrtMemcpy(storage.get(), bytes, values, bytes, ACL_MEMCPY_HOST_TO_DEVICE), "upload");
81+ }
82+ }
83+};
84+ 
85+TensorListPtr MakeList(std::initializer_list<Tensor*> tensors)
86+{
87+ std::vector<const aclTensor*> descriptors;
88+ for (auto* tensor : tensors) {
89+ descriptors.push_back(tensor->descriptor.get());
90+ }
91+ TensorListPtr list(aclCreateTensorList(descriptors.data(), descriptors.size()), aclDestroyTensorList);
92+ if (!list) {
93+ throw std::runtime_error("aclCreateTensorList failed");
94+ }
95+ for (auto* tensor : tensors) {
96+ tensor->descriptor.release();
97+ }
98+ return list;
99+}
100+ 
101+constexpr size_t PATHS = 2;
102+constexpr size_t CHUNKS = 2;
103+constexpr size_t EXPERTS = 2;
104+constexpr size_t ROWS_PER_CHUNK = 2;
105+constexpr size_t OUTPUT_ROWS = CHUNKS * ROWS_PER_CHUNK;
106+constexpr size_t WIDTH = 16;
107+using TokenRows = std::array<aclFloat16, ROWS_PER_CHUNK * WIDTH>;
108+ 
109+TokenRows Tokens(float first, float second)
110+{
111+ TokenRows rows;
112+ std::fill_n(rows.begin(), WIDTH, aclFloatToFloat16(first));
113+ std::fill_n(rows.begin() + WIDTH, WIDTH, aclFloatToFloat16(second));
114+ return rows;
115+}
116+ 
117+void Run(aclrtStream stream)
118+{
119+ const auto first = Tokens(1, 2);
120+ const auto second = Tokens(3, 4);
121+ const std::array<int32_t, EXPERTS> counts{1, 1};
122+ std::array<aclFloat16, OUTPUT_ROWS * WIDTH> tokens{};
123+ std::array<int32_t, EXPERTS> outCounts{};
124+ Tensor chunk0({ROWS_PER_CHUNK, WIDTH}, ACL_FLOAT16, sizeof(first), first.data());
125+ Tensor chunk1({ROWS_PER_CHUNK, WIDTH}, ACL_FLOAT16, sizeof(second), second.data());
126+ const auto third = Tokens(5, 6);
127+ const auto fourth = Tokens(7, 8);
128+ Tensor chunk2({ROWS_PER_CHUNK, WIDTH}, ACL_FLOAT16, sizeof(third), third.data());
129+ Tensor chunk3({ROWS_PER_CHUNK, WIDTH}, ACL_FLOAT16, sizeof(fourth), fourth.data());
130+ Tensor counts0({EXPERTS}, ACL_INT32, sizeof(counts), counts.data());
131+ Tensor counts1({EXPERTS}, ACL_INT32, sizeof(counts), counts.data());
132+ Tensor merged({OUTPUT_ROWS, WIDTH}, ACL_FLOAT16, sizeof(tokens));
133+ Tensor mergedSecond({OUTPUT_ROWS, WIDTH}, ACL_FLOAT16, sizeof(tokens));
134+ Tensor mergedCounts({EXPERTS}, ACL_INT32, sizeof(outCounts));
135+ 
136+ auto inputs = MakeList({&chunk0, &chunk1, &chunk2, &chunk3});
137+ auto groupLists = MakeList({&counts0, &counts1});
138+ auto outputs = MakeList({&merged, &mergedSecond});
139+ uint64_t workspaceSize = 0;
140+ aclOpExecutor* executor = nullptr;
141+ Check(aclnnMergeChunkGetWorkspaceSize(inputs.get(), groupLists.get(), PATHS, CHUNKS, outputs.get(),
142+ mergedCounts.descriptor.get(), &workspaceSize, &executor),
143+ "aclnnMergeChunkGetWorkspaceSize");
144+ auto workspace = Allocate(workspaceSize);
145+ Check(aclnnMergeChunk(workspace.get(), workspaceSize, executor, stream), "aclnnMergeChunk");
146+ Check(aclrtSynchronizeStream(stream), "aclrtSynchronizeStream");
147+ 
148+ Check(aclrtMemcpy(tokens.data(), sizeof(tokens), merged.storage.get(), sizeof(tokens), ACL_MEMCPY_DEVICE_TO_HOST),
149+ "download tokens");
150+ Check(aclrtMemcpy(outCounts.data(), sizeof(outCounts), mergedCounts.storage.get(), sizeof(outCounts),
151+ ACL_MEMCPY_DEVICE_TO_HOST),
152+ "download counts");
153+ const std::array<float, OUTPUT_ROWS> expected{1, 3, 2, 4};
154+ for (size_t i = 0; i < tokens.size(); ++i) {
155+ if (tokens[i] != aclFloatToFloat16(expected[i / WIDTH])) {
156+ throw std::runtime_error("unexpected token order");
157+ }
158+ }
159+ Check(aclrtMemcpy(tokens.data(), sizeof(tokens), mergedSecond.storage.get(), sizeof(tokens),
160+ ACL_MEMCPY_DEVICE_TO_HOST),
161+ "download second path");
162+ const std::array<float, OUTPUT_ROWS> expectedSecond{5, 7, 6, 8};
163+ for (size_t i = 0; i < tokens.size(); ++i) {
164+ if (tokens[i] != aclFloatToFloat16(expectedSecond[i / WIDTH])) {
165+ throw std::runtime_error("unexpected token order in second path");
166+ }
167+ }
168+ if (outCounts != std::array<int32_t, EXPERTS>{counts[0] + counts[0], counts[1] + counts[1]}) {
169+ throw std::runtime_error("unexpected expert counts");
170+ }
171+}
172+} // namespace
173+ 
174+int main()
175+{
176+ Runtime runtime;
177+ try {
178+ Check(aclInit(nullptr), "aclInit");
179+ runtime.initialized = true;
180+ Check(aclrtSetDevice(0), "aclrtSetDevice");
181+ runtime.deviceSet = true;
182+ Check(aclrtCreateStream(&runtime.stream), "aclrtCreateStream");
183+ Run(runtime.stream);
184+ std::cout << "MergeChunk example passed" << std::endl;
185+ return 0;
186+ } catch (const std::exception& error) {
187+ std::cerr << error.what() << std::endl;
188+ return 1;
189+ }
190+}
@@ -0,0 +1,22 @@
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+add_op_to_compiled_list()
12+ 
13+if(BUILD_OPEN_PROJECT)
14+ target_sources(op_host_aclnnExc PRIVATE merge_chunk_def.cpp)
15+endif()
16+ 
17+add_ops_compile_options(OP_NAME MergeChunk
18+ OPTIONS --cce-auto-sync=off -Wno-deprecated-declarations -Werror)
19+ 
20+if(NOT BUILD_OPS_RTY_KERNEL)
21+ add_modules_sources(OPTYPE merge_chunk ACLNNTYPE aclnn_exclude)
22+endif()
@@ -0,0 +1,52 @@
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 "register/op_def_registry.h"
12+ 
13+namespace ops {
14+class MergeChunk : public OpDef {
15+public:
16+ explicit MergeChunk(const char* name) : OpDef(name)
17+ {
18+ this->Input("input_chunks")
19+ .ParamType(DYNAMIC)
20+ .DataType({ge::DT_FLOAT16, ge::DT_BF16})
21+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
22+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
23+ this->Input("group_list_chunk")
24+ .ParamType(DYNAMIC)
25+ .DataType({ge::DT_INT32, ge::DT_INT32})
26+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
27+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
28+ this->Output("out_chunks")
29+ .ParamType(DYNAMIC)
30+ .DataType({ge::DT_FLOAT16, ge::DT_BF16})
31+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
32+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
33+ this->Output("out_group_list")
34+ .ParamType(REQUIRED)
35+ .DataType({ge::DT_INT32, ge::DT_INT32})
36+ .Format({ge::FORMAT_ND, ge::FORMAT_ND})
37+ .UnknownShapeFormat({ge::FORMAT_ND, ge::FORMAT_ND});
38+ this->Attr("num_paths").AttrType(REQUIRED).Int();
39+ this->Attr("num_chunks").AttrType(REQUIRED).Int();
40+ OpAICoreConfig config;
41+ config.DynamicShapeSupportFlag(true)
42+ .DynamicRankSupportFlag(false)
43+ .ExtendCfgInfo("prebuildPattern.value", "Opaque")
44+ .ExtendCfgInfo("coreType.value", "AiCore")
45+ .ExtendCfgInfo("aclnnSupport.value", "aclnn_only")
46+ .ExtendCfgInfo("jitCompile.flag", "false");
47+ this->AICore().AddConfig("ascend910b", config);
48+ this->AICore().AddConfig("ascend910_93", config);
49+ }
50+};
51+OP_ADD(MergeChunk);
52+} // namespace ops
@@ -0,0 +1,64 @@
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 "log/log.h"
12+#include "register/op_impl_registry.h"
13+#include "merge_chunk_shape.h"
14+ 
15+namespace ops {
16+namespace {
17+ge::graphStatus InferShapeMergeChunk(gert::InferShapeContext* context)
18+{
19+ int64_t paths = 0;
20+ int64_t chunks = 0;
21+ if (!MergeChunkSupport::ReadListDimensions(context, paths, chunks) ||
22+ context->GetComputeNodeOutputNum() != static_cast<size_t>(paths + 1)) {
23+ return ge::GRAPH_FAILED;
24+ }
25+ MergeChunkSupport::InferredLayout layout;
26+ const auto* error = MergeChunkSupport::InferLayout(
27+ [context](size_t i) { return context->GetDynamicInputShape(MergeChunkSupport::DATA_INDEX, i); },
28+ [context](size_t i) { return context->GetDynamicInputShape(MergeChunkSupport::COUNTS_INDEX, i); }, layout);
29+ if (error != nullptr) {
30+ OP_LOGE(context, "%s", error);
31+ return ge::GRAPH_FAILED;
32+ }
33+ for (int64_t path = 0; path < paths; ++path) {
34+ auto* shape = context->GetOutputShape(path);
35+ OP_CHECK_NULL_WITH_CONTEXT(context, shape);
36+ *shape = gert::Shape({layout.totalRows, layout.hidden[path]});
37+ }
38+ auto* counts = context->GetOutputShape(paths);
39+ OP_CHECK_NULL_WITH_CONTEXT(context, counts);
40+ *counts = gert::Shape({layout.experts});
41+ return ge::GRAPH_SUCCESS;
42+}
43+ 
44+ge::graphStatus InferDataTypeMergeChunk(gert::InferDataTypeContext* context)
45+{
46+ int64_t paths = 0;
47+ int64_t chunks = 0;
48+ if (!MergeChunkSupport::ReadListDimensions(context, paths, chunks) ||
49+ context->GetComputeNodeOutputNum() != static_cast<size_t>(paths + 1)) {
50+ return ge::GRAPH_FAILED;
51+ }
52+ const auto type = context->GetDynamicInputDataType(MergeChunkSupport::DATA_INDEX, 0);
53+ if (type != ge::DT_FLOAT16 && type != ge::DT_BF16) {
54+ return ge::GRAPH_FAILED;
55+ }
56+ for (int64_t path = 0; path < paths; ++path) {
57+ context->SetOutputDataType(path, type);
58+ }
59+ context->SetOutputDataType(paths, ge::DT_INT32);
60+ return ge::GRAPH_SUCCESS;
61+}
62+} // namespace
63+IMPL_OP_INFERSHAPE(MergeChunk).InferShape(InferShapeMergeChunk).InferDataType(InferDataTypeMergeChunk);
64+} // namespace ops
@@ -0,0 +1,170 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef MERGE_CHUNK_SHAPE_H_
12+#define MERGE_CHUNK_SHAPE_H_
13+ 
14+#include <array>
15+#include <cstddef>
16+#include <limits>
17+ 
18+#include "../op_kernel/merge_chunk_limits.h"
19+ 
20+namespace MergeChunkSupport {
21+constexpr size_t DATA_INDEX = 0;
22+constexpr size_t COUNTS_INDEX = 1;
23+constexpr size_t PATHS_ATTR_INDEX = 0;
24+constexpr size_t CHUNKS_ATTR_INDEX = 1;
25+ 
26+struct Layout {
27+ uint32_t paths = 0;
28+ uint32_t chunks = 0;
29+ uint32_t experts = 0;
30+ uint32_t totalRows = 0;
31+ std::array<uint32_t, SUPPORTED_CHUNKS> chunkRows{};
32+ std::array<uint32_t, SUPPORTED_PATHS> hidden{};
33+};
34+ 
35+inline bool ValidListDimensions(int64_t paths, int64_t chunks)
36+{
37+ return paths == SUPPORTED_PATHS && chunks == SUPPORTED_CHUNKS;
38+}
39+ 
40+template <typename DataShape, typename CountShape>
41+const char* ReadLayout(int64_t paths, int64_t chunks, DataShape dataShape, CountShape countShape, Layout& layout)
42+{
43+ if (!ValidListDimensions(paths, chunks)) {
44+ return "num_paths and num_chunks must both equal 2";
45+ }
46+ layout.paths = static_cast<uint32_t>(paths);
47+ layout.chunks = static_cast<uint32_t>(chunks);
48+ int64_t totalRows = 0;
49+ for (uint32_t chunk = 0; chunk < layout.chunks; ++chunk) {
50+ const auto* count = countShape(chunk);
51+ const auto* data = dataShape(chunk);
52+ if (count == nullptr || count->GetDimNum() != 1 || data == nullptr || data->GetDimNum() != TOKEN_RANK) {
53+ return "Each count tensor must have rank 1 and each data tensor must have rank 2";
54+ }
55+ const auto experts = count->GetDim(0);
56+ if (experts <= 0 || experts > MAX_EXPERTS || (chunk != 0 && experts != layout.experts)) {
57+ return "Expert counts must be positive, bounded and consistent across chunks";
58+ }
59+ layout.experts = static_cast<uint32_t>(experts);
60+ const auto rows = data->GetDim(0);
61+ if (rows <= 0 || rows > std::numeric_limits<int32_t>::max() - totalRows) {
62+ return "Chunk row counts must be positive and their sum must fit in int32";
63+ }
64+ layout.chunkRows[chunk] = static_cast<uint32_t>(rows);
65+ totalRows += rows;
66+ }
67+ layout.totalRows = static_cast<uint32_t>(totalRows);
68+ for (uint32_t path = 0; path < layout.paths; ++path) {
69+ const uint32_t start = path * layout.chunks;
70+ const auto* first = dataShape(start);
71+ if (first == nullptr || first->GetDimNum() != TOKEN_RANK) {
72+ return "Missing rank-2 tensor for a data path";
73+ }
74+ const auto hidden = first->GetDim(1);
75+ if (hidden <= 0 || hidden % HIDDEN_ALIGNMENT != 0 || hidden > TOKEN_BUFFER_BYTES / ELEMENT_BYTES ||
76+ hidden > std::numeric_limits<int32_t>::max() / totalRows) {
77+ return "Feature width must be 16-aligned, fit in UB and keep element offsets within int32";
78+ }
79+ layout.hidden[path] = static_cast<uint32_t>(hidden);
80+ for (uint32_t chunk = 0; chunk < layout.chunks; ++chunk) {
81+ const auto* entry = dataShape(start + chunk);
82+ if (entry == nullptr || entry->GetDimNum() != TOKEN_RANK || entry->GetDim(0) != layout.chunkRows[chunk] ||
83+ entry->GetDim(1) != hidden) {
84+ return "Token rows must agree within a chunk and feature widths must agree within a path";
85+ }
86+ }
87+ }
88+ if (dataShape(layout.paths * layout.chunks) != nullptr || countShape(layout.chunks) != nullptr) {
89+ return "Input tensor list lengths do not match num_paths and num_chunks";
90+ }
91+ return nullptr;
92+}
93+ 
94+// Inference can refine an unknown dimension from its matching tensor. Runtime
95+// validation in ReadLayout requires every individual input dimension to be concrete.
96+constexpr int64_t UNKNOWN_DIM = -1;
97+struct InferredLayout {
98+ int64_t totalRows = UNKNOWN_DIM;
99+ int64_t experts = UNKNOWN_DIM;
100+ std::array<int64_t, SUPPORTED_PATHS> hidden{};
101+};
102+ 
103+inline bool MergeDimension(int64_t value, int64_t& merged)
104+{
105+ if (value == UNKNOWN_DIM) {
106+ return true;
107+ }
108+ if (value <= 0 || (merged != UNKNOWN_DIM && merged != value)) {
109+ return false;
110+ }
111+ merged = value;
112+ return true;
113+}
114+ 
115+template <typename DataShape, typename CountShape>
116+const char* InferLayout(DataShape dataShape, CountShape countShape, InferredLayout& result)
117+{
118+ constexpr int64_t maxElements = std::numeric_limits<int32_t>::max();
119+ std::array<int64_t, SUPPORTED_CHUNKS> rows;
120+ rows.fill(UNKNOWN_DIM);
121+ result.hidden.fill(UNKNOWN_DIM);
122+ result.experts = UNKNOWN_DIM;
123+ for (size_t chunk = 0; chunk < SUPPORTED_CHUNKS; ++chunk) {
124+ const auto* counts = countShape(chunk);
125+ if (counts == nullptr || counts->GetDimNum() != 1 || !MergeDimension(counts->GetDim(0), result.experts) ||
126+ result.experts > MAX_EXPERTS) {
127+ return "Invalid expert count shape";
128+ }
129+ for (size_t path = 0; path < SUPPORTED_PATHS; ++path) {
130+ const auto* data = dataShape(path * SUPPORTED_CHUNKS + chunk);
131+ if (data == nullptr || data->GetDimNum() != TOKEN_RANK || !MergeDimension(data->GetDim(0), rows[chunk]) ||
132+ rows[chunk] > maxElements || !MergeDimension(data->GetDim(1), result.hidden[path])) {
133+ return "Incompatible token tensor shapes";
134+ }
135+ }
136+ }
137+ if (dataShape(SUPPORTED_PATHS * SUPPORTED_CHUNKS) != nullptr || countShape(SUPPORTED_CHUNKS) != nullptr) {
138+ return "Unexpected input tensor list length";
139+ }
140+ result.totalRows = rows[0] == UNKNOWN_DIM || rows[1] == UNKNOWN_DIM ? UNKNOWN_DIM : rows[0] + rows[1];
141+ if (result.totalRows > maxElements) {
142+ return "Combined row count exceeds int32";
143+ }
144+ for (auto width : result.hidden) {
145+ if (width != UNKNOWN_DIM && (width % HIDDEN_ALIGNMENT != 0 || width > TOKEN_BUFFER_BYTES / ELEMENT_BYTES ||
146+ (result.totalRows != UNKNOWN_DIM && width > maxElements / result.totalRows))) {
147+ return "Invalid feature width or combined tensor size";
148+ }
149+ }
150+ return nullptr;
151+}
152+ 
153+template <typename Context>
154+bool ReadListDimensions(Context* context, int64_t& paths, int64_t& chunks)
155+{
156+ if (context == nullptr || context->GetAttrs() == nullptr) {
157+ return false;
158+ }
159+ const auto* attrs = context->GetAttrs();
160+ const auto* pathAttr = attrs->GetInt(PATHS_ATTR_INDEX);
161+ const auto* chunkAttr = attrs->GetInt(CHUNKS_ATTR_INDEX);
162+ if (pathAttr == nullptr || chunkAttr == nullptr) {
163+ return false;
164+ }
165+ paths = *pathAttr;
166+ chunks = *chunkAttr;
167+ return ValidListDimensions(paths, chunks);
168+}
169+} // namespace MergeChunkSupport
170+#endif
@@ -0,0 +1,116 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include <algorithm>
12+ 
13+#include "log/log.h"
14+#include "register/op_impl_registry.h"
15+#include "tiling/platform/platform_ascendc.h"
16+#include "merge_chunk_shape.h"
17+#include "merge_chunk_tiling.h"
18+ 
19+namespace optiling {
20+namespace {
21+struct MergeChunkCompileInfo {
22+ uint32_t cores = 0;
23+ uint64_t ubBytes = 0;
24+};
25+ 
26+ge::graphStatus ParseMergeChunk(gert::TilingParseContext* context)
27+{
28+ auto* info = context->GetCompiledInfo<MergeChunkCompileInfo>();
29+ auto* platformInfo = context->GetPlatformInfo();
30+ OP_CHECK_NULL_WITH_CONTEXT(context, info);
31+ OP_CHECK_NULL_WITH_CONTEXT(context, platformInfo);
32+ platform_ascendc::PlatformAscendC platform(platformInfo);
33+ info->cores = platform.GetCoreNumAiv();
34+ platform.GetCoreMemSize(platform_ascendc::CoreMemType::UB, info->ubBytes);
35+ return ge::GRAPH_SUCCESS;
36+}
37+ 
38+const gert::Shape* GetLogicalShape(const gert::TilingContext* context, size_t index, size_t item)
39+{
40+ const auto* shape = context->GetDynamicInputShape(index, item);
41+ return shape == nullptr ? nullptr : &shape->GetOriginShape();
42+}
43+ 
44+ge::graphStatus ReadTilingLayout(gert::TilingContext* context, MergeChunkSupport::Layout& layout)
45+{
46+ int64_t paths = 0;
47+ int64_t chunks = 0;
48+ if (!MergeChunkSupport::ReadListDimensions(context, paths, chunks)) {
49+ return ge::GRAPH_FAILED;
50+ }
51+ const auto* error = MergeChunkSupport::ReadLayout(
52+ paths, chunks, [context](size_t i) { return GetLogicalShape(context, MergeChunkSupport::DATA_INDEX, i); },
53+ [context](size_t i) { return GetLogicalShape(context, MergeChunkSupport::COUNTS_INDEX, i); }, layout);
54+ if (error != nullptr) {
55+ OP_LOGE(context, "%s", error);
56+ return ge::GRAPH_FAILED;
57+ }
58+ return ge::GRAPH_SUCCESS;
59+}
60+ 
61+ge::graphStatus SetSplit(gert::TilingContext* context, MergeChunkSupport::Layout& layout, MergeChunkTilingData& data)
62+{
63+ const auto* info = context->GetCompileInfo<MergeChunkCompileInfo>();
64+ OP_CHECK_NULL_WITH_CONTEXT(context, info);
65+ const auto longestChunk = *std::max_element(layout.chunkRows.begin(), layout.chunkRows.end());
66+ const uint32_t cores = std::min(info->cores, longestChunk);
67+ if (cores == 0 || info->ubBytes < MergeChunkSupport::TOTAL_BUFFER_BYTES) {
68+ OP_LOGE(context, "MergeChunk requires an AIV core and at least %u bytes of UB.",
69+ MergeChunkSupport::TOTAL_BUFFER_BYTES);
70+ return ge::GRAPH_FAILED;
71+ }
72+ std::array<uint32_t, MergeChunkSupport::SUPPORTED_CHUNKS> rowsPerCore{}, extraCores{};
73+ std::array<uint32_t, MergeChunkSupport::SUPPORTED_PATHS> rowsPerTile{};
74+ for (uint32_t chunk = 0; chunk < layout.chunks; ++chunk) {
75+ rowsPerCore[chunk] = layout.chunkRows[chunk] / cores;
76+ extraCores[chunk] = layout.chunkRows[chunk] % cores;
77+ }
78+ for (uint32_t path = 0; path < layout.paths; ++path) {
79+ rowsPerTile[path] =
80+ MergeChunkSupport::TOKEN_BUFFER_BYTES / (layout.hidden[path] * MergeChunkSupport::ELEMENT_BYTES);
81+ }
82+ data.set_paths(layout.paths);
83+ data.set_chunks(layout.chunks);
84+ data.set_experts(layout.experts);
85+ data.set_rowsPerCore(rowsPerCore.data());
86+ data.set_extraCores(extraCores.data());
87+ data.set_hidden(layout.hidden.data());
88+ data.set_rowsPerTile(rowsPerTile.data());
89+ context->SetBlockDim(cores);
90+ context->SetTilingKey(0);
91+ return ge::GRAPH_SUCCESS;
92+}
93+ 
94+ge::graphStatus TilingMergeChunk(gert::TilingContext* context)
95+{
96+ MergeChunkSupport::Layout layout;
97+ MergeChunkTilingData data;
98+ if (ReadTilingLayout(context, layout) != ge::GRAPH_SUCCESS ||
99+ SetSplit(context, layout, data) != ge::GRAPH_SUCCESS) {
100+ return ge::GRAPH_FAILED;
101+ }
102+ auto* raw = context->GetRawTilingData();
103+ auto* workspace = context->GetWorkspaceSizes(1);
104+ OP_CHECK_NULL_WITH_CONTEXT(context, raw);
105+ OP_CHECK_NULL_WITH_CONTEXT(context, workspace);
106+ if (raw->GetData() == nullptr || raw->GetCapacity() < data.GetDataSize()) {
107+ return ge::GRAPH_FAILED;
108+ }
109+ data.SaveToBuffer(raw->GetData(), raw->GetCapacity());
110+ raw->SetDataSize(data.GetDataSize());
111+ workspace[0] = 0;
112+ return ge::GRAPH_SUCCESS;
113+}
114+} // namespace
115+IMPL_OP_OPTILING(MergeChunk).Tiling(TilingMergeChunk).TilingParse<MergeChunkCompileInfo>(ParseMergeChunk);
116+} // namespace optiling
@@ -0,0 +1,30 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef MERGE_CHUNK_HOST_TILING_H_
12+#define MERGE_CHUNK_HOST_TILING_H_
13+ 
14+#include "register/tilingdata_base.h"
15+#include "../op_kernel/merge_chunk_limits.h"
16+ 
17+namespace optiling {
18+BEGIN_TILING_DATA_DEF(MergeChunkTilingData)
19+TILING_DATA_FIELD_DEF(uint32_t, paths);
20+TILING_DATA_FIELD_DEF(uint32_t, chunks);
21+TILING_DATA_FIELD_DEF(uint32_t, experts);
22+TILING_DATA_FIELD_DEF_ARR(uint32_t, MergeChunkSupport::SUPPORTED_CHUNKS, rowsPerCore);
23+TILING_DATA_FIELD_DEF_ARR(uint32_t, MergeChunkSupport::SUPPORTED_CHUNKS, extraCores);
24+TILING_DATA_FIELD_DEF_ARR(uint32_t, MergeChunkSupport::SUPPORTED_PATHS, hidden);
25+TILING_DATA_FIELD_DEF_ARR(uint32_t, MergeChunkSupport::SUPPORTED_PATHS, rowsPerTile);
26+END_TILING_DATA_DEF;
27+REGISTER_TILING_DATA_CLASS(MergeChunk, MergeChunkTilingData)
28+} // namespace optiling
29+ 
30+#endif
@@ -0,0 +1,126 @@
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 "aclnn_merge_chunk.h"
12+#include "merge_chunk.h"
13+#include "../merge_chunk_shape.h"
14+#include "opdev/make_op_executor.h"
15+#include "opdev/op_dfx.h"
16+#include "opdev/tensor_view_utils.h"
17+ 
18+using namespace op;
19+ 
20+namespace {
21+aclnnStatus CheckTensor(const aclTensor* tensor, DataType type)
22+{
23+ if (tensor == nullptr) {
24+ return ACLNN_ERR_PARAM_NULLPTR;
25+ }
26+ if (tensor->GetDataType() != type || tensor->GetStorageFormat() != Format::FORMAT_ND || !IsContiguous(tensor)) {
27+ return ACLNN_ERR_PARAM_INVALID;
28+ }
29+ return ACLNN_SUCCESS;
30+}
31+ 
32+aclnnStatus CheckList(const aclTensorList* tensors, DataType type)
33+{
34+ for (size_t i = 0; i < tensors->Size(); ++i) {
35+ const auto status = CheckTensor((*tensors)[i], type);
36+ if (status != ACLNN_SUCCESS) {
37+ return status;
38+ }
39+ }
40+ return ACLNN_SUCCESS;
41+}
42+ 
43+aclnnStatus CheckParams(const aclTensorList* input, const aclTensorList* counts, int64_t paths, int64_t chunks,
44+ const aclTensorList* output, const aclTensor* outCounts)
45+{
46+ if (input == nullptr || counts == nullptr || output == nullptr || outCounts == nullptr) {
47+ return ACLNN_ERR_PARAM_NULLPTR;
48+ }
49+ if (!MergeChunkSupport::ValidListDimensions(paths, chunks) ||
50+ input->Size() != static_cast<size_t>(paths * chunks) || counts->Size() != static_cast<size_t>(chunks) ||
51+ output->Size() != static_cast<size_t>(paths)) {
52+ return ACLNN_ERR_PARAM_INVALID;
53+ }
54+ if ((*input)[0] == nullptr) {
55+ return ACLNN_ERR_PARAM_NULLPTR;
56+ }
57+ const auto dtype = (*input)[0]->GetDataType();
58+ if (dtype != DataType::DT_FLOAT16 && dtype != DataType::DT_BF16) {
59+ return ACLNN_ERR_PARAM_INVALID;
60+ }
61+ for (const auto status : {CheckList(input, dtype), CheckList(counts, DataType::DT_INT32), CheckList(output, dtype),
62+ CheckTensor(outCounts, DataType::DT_INT32)}) {
63+ if (status != ACLNN_SUCCESS) {
64+ return status;
65+ }
66+ }
67+ MergeChunkSupport::Layout layout;
68+ if (MergeChunkSupport::ReadLayout(
69+ paths, chunks, [input](size_t i) { return i < input->Size() ? &(*input)[i]->GetViewShape() : nullptr; },
70+ [counts](size_t i) { return i < counts->Size() ? &(*counts)[i]->GetViewShape() : nullptr; },
71+ layout) != nullptr) {
72+ return ACLNN_ERR_PARAM_INVALID;
73+ }
74+ for (size_t path = 0; path < layout.paths; ++path) {
75+ const auto& shape = (*output)[path]->GetViewShape();
76+ if (shape.GetDimNum() != MergeChunkSupport::TOKEN_RANK || shape.GetDim(0) != layout.totalRows ||
77+ shape.GetDim(1) != layout.hidden[path]) {
78+ return ACLNN_ERR_PARAM_INVALID;
79+ }
80+ }
81+ const auto& countShape = outCounts->GetViewShape();
82+ return countShape.GetDimNum() == 1 && countShape.GetDim(0) == layout.experts ? ACLNN_SUCCESS :
83+ ACLNN_ERR_PARAM_INVALID;
84+}
85+} // namespace
86+ 
87+extern "C" aclnnStatus aclnnMergeChunkGetWorkspaceSize(const aclTensorList* inputChunks,
88+ const aclTensorList* groupListChunk, int64_t numPaths,
89+ int64_t numChunks, const aclTensorList* outChunks,
90+ const aclTensor* outGroupList, uint64_t* workspaceSize,
91+ aclOpExecutor** executor)
92+{
93+ if (workspaceSize == nullptr || executor == nullptr) {
94+ return ACLNN_ERR_PARAM_NULLPTR;
95+ }
96+ *workspaceSize = 0;
97+ *executor = nullptr;
98+ const auto status = CheckParams(inputChunks, groupListChunk, numPaths, numChunks, outChunks, outGroupList);
99+ if (status != ACLNN_SUCCESS) {
100+ return status;
101+ }
102+ L2_DFX_PHASE_1(aclnnMergeChunk, DFX_IN(inputChunks, groupListChunk, numPaths, numChunks),
103+ DFX_OUT(outChunks, outGroupList));
104+ auto owner = CREATE_EXECUTOR();
105+ if (owner.get() == nullptr) {
106+ return ACLNN_ERR_INNER_CREATE_EXECUTOR;
107+ }
108+ const auto launchStatus =
109+ l0op::LaunchMergeChunk(inputChunks, groupListChunk, numPaths, numChunks, outChunks, outGroupList, owner.get());
110+ if (launchStatus != ACLNN_SUCCESS) {
111+ return launchStatus;
112+ }
113+ *workspaceSize = owner->GetWorkspaceSize();
114+ owner.ReleaseTo(executor);
115+ return ACLNN_SUCCESS;
116+}
117+ 
118+extern "C" aclnnStatus aclnnMergeChunk(void* workspace, uint64_t workspaceSize, aclOpExecutor* executor,
119+ aclrtStream stream)
120+{
121+ if (executor == nullptr || (workspaceSize != 0 && workspace == nullptr)) {
122+ return ACLNN_ERR_PARAM_NULLPTR;
123+ }
124+ L2_DFX_PHASE_2(aclnnMergeChunk);
125+ return CommonOpExecutorRun(workspace, workspaceSize, executor, stream);
126+}
@@ -0,0 +1,53 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef ACLNN_MERGE_CHUNK_H_
12+#define ACLNN_MERGE_CHUNK_H_
13+ 
14+#include "aclnn/aclnn_base.h"
15+ 
16+#ifdef __cplusplus
17+extern "C" {
18+#endif
19+ 
20+/**
21+ * @brief aclnnMergeChunk 的第一段接口,校验参数,计算所需的 workspace 大小并返回执行器。
22+ * @param [in] inputChunks: 各路的 token 数据,列表长度为 numPaths × numChunks。第 r 路的第 c 个 chunk
23+ * 位于下标 r * numChunks + c(下标从 0 开始)。各 Tensor 的行按专家编号分段,数据类型统一为 FLOAT16 或 BFLOAT16。
24+ * @param [in] groupListChunk: 每个 chunk 一份一维 INT32 计数,列表长度为 numChunks。第 c 项的第 e 个元素
25+ * 表示该 chunk 中专家 e 的 token 数,同一 chunk 的所有数据路共用这份计数。
26+ * @param [in] numPaths: 数据路数,当前版本仅支持 2。
27+ * @param [in] numChunks: 每路的 chunk 数,当前版本仅支持 2。
28+ * @param [out] outChunks: 调用方提供的输出 Tensor 列表,长度为 numPaths。第 r 项保存第 r 路按专家合并的
29+ * token 数据,行数为该路各 chunk 的行数之和,列数和数据类型与该路输入一致。
30+ * @param [out] outGroupList: 调用方提供的一维 INT32 输出 Tensor,第 e 个元素为各 chunk 中专家 e 的 token 数之和。
31+ * @param [out] workspaceSize: 返回第二段接口所需的设备侧 workspace 大小,单位为字节。
32+ * @param [out] executor: 返回供第二段接口使用的算子执行器。
33+ * @return aclnnStatus: 接口返回的状态码。
34+ */
35+__attribute__((visibility("default"))) aclnnStatus aclnnMergeChunkGetWorkspaceSize(
tang-lei01
tang-lei01tang-lei012 days ago

缺少参数的资料说明

likedislike
36+ const aclTensorList* inputChunks, const aclTensorList* groupListChunk, int64_t numPaths, int64_t numChunks,
37+ const aclTensorList* outChunks, const aclTensor* outGroupList, uint64_t* workspaceSize, aclOpExecutor** executor);
38+ 
39+/**
40+ * @brief aclnnMergeChunk 的第二段接口,将按专家合并各路 token 数据的任务提交到指定的 stream。
41+ * @param [in] workspace: 调用方申请的设备侧 workspace 起始地址,workspaceSize 为 0 时可传 nullptr。
42+ * @param [in] workspaceSize: 第一段接口返回的 workspace 大小,单位为字节。
43+ * @param [in] executor: 第一段接口返回的算子执行器。
44+ * @param [in] stream: 执行计算任务的 ACL Stream。
45+ * @return aclnnStatus: 接口返回的状态码。
46+ */
47+__attribute__((visibility("default"))) aclnnStatus aclnnMergeChunk(void* workspace, uint64_t workspaceSize,
48+ aclOpExecutor* executor, aclrtStream stream);
49+ 
50+#ifdef __cplusplus
51+}
52+#endif
53+#endif
@@ -0,0 +1,25 @@
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 "merge_chunk.h"
12+#include "opdev/make_op_executor.h"
13+ 
14+using namespace op;
15+ 
16+namespace l0op {
17+OP_TYPE_REGISTER(MergeChunk);
18+ 
19+aclnnStatus LaunchMergeChunk(const aclTensorList* input, const aclTensorList* counts, int64_t paths, int64_t chunks,
20+ const aclTensorList* output, const aclTensor* outCounts, aclOpExecutor* executor)
21+{
22+ return ADD_TO_LAUNCHER_LIST_AICORE(MergeChunk, OP_INPUT(input, counts), OP_OUTPUT(output, outCounts),
23+ OP_ATTR(paths, chunks));
24+}
25+} // namespace l0op
@@ -0,0 +1,21 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef OP_API_INC_LEVEL0_MERGE_CHUNK_H_
12+#define OP_API_INC_LEVEL0_MERGE_CHUNK_H_
13+ 
14+#include "opdev/op_executor.h"
15+ 
16+namespace l0op {
17+aclnnStatus LaunchMergeChunk(const aclTensorList* input, const aclTensorList* counts, int64_t paths, int64_t chunks,
18+ const aclTensorList* output, const aclTensor* outCounts, aclOpExecutor* executor);
19+} // namespace l0op
20+ 
21+#endif // OP_API_INC_LEVEL0_MERGE_CHUNK_H_
@@ -0,0 +1,30 @@
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 "merge_chunk_impl.h"
12+#include "kernel_operator_list_tensor_intf.h"
13+ 
14+extern "C" __global__ __aicore__ void merge_chunk(GM_ADDR inputChunks, GM_ADDR groupListChunk, GM_ADDR outChunks,
15+ GM_ADDR outGroupList, GM_ADDR workspace, GM_ADDR tiling)
16+{
17+ if (g_coreType == AscendC::AIC) {
18+ return;
19+ }
20+ GET_TILING_DATA(data, tiling);
21+ AscendC::ListTensorDesc inputs(reinterpret_cast<__gm__ void*>(inputChunks));
22+ AscendC::ListTensorDesc counts(reinterpret_cast<__gm__ void*>(groupListChunk));
23+ AscendC::ListTensorDesc outputs(reinterpret_cast<__gm__ void*>(outChunks));
24+ AscendC::TPipe pipe;
25+ // Token rows are copied bit for bit for both FLOAT16 and BFLOAT16.
26+ MergeChunkSupport::KernelMergeChunk<uint16_t, decltype(data)> kernel(data, pipe);
27+ kernel.Process(inputs.GetDataPtr<uint8_t>(0), inputs.GetDataPtr<uint8_t>(1), inputs.GetDataPtr<uint8_t>(2),
28+ inputs.GetDataPtr<uint8_t>(3), counts.GetDataPtr<uint8_t>(0), counts.GetDataPtr<uint8_t>(1),
29+ outputs.GetDataPtr<uint8_t>(0), outputs.GetDataPtr<uint8_t>(1), outGroupList);
30+}
@@ -0,0 +1,259 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+/*!
12+ * \file merge_chunk_impl.h
13+ * \brief MergeChunk two-path, two-chunk kernel
14+ */
15+#ifndef MERGE_CHUNK_IMPL_H_
16+#define MERGE_CHUNK_IMPL_H_
17+ 
18+#include "kernel_operator.h"
19+#include "merge_chunk_limits.h"
20+ 
21+using namespace AscendC;
22+ 
23+namespace MergeChunkSupport {
24+ 
25+template <typename T, typename Tiling>
26+class KernelMergeChunk {
27+public:
28+ __aicore__ KernelMergeChunk(const Tiling& tiling, TPipe& pipe)
29+ : tiling_(tiling),
30+ pipe_(pipe)
31+ {}
32+ 
33+ __aicore__ void Process(GM_ADDR in1c1, GM_ADDR in1c2, GM_ADDR in2c1, GM_ADDR in2c2, GM_ADDR glc1, GM_ADDR glc2,
34+ GM_ADDR out1, GM_ADDR out2, GM_ADDR gl)
35+ {
36+ if (g_coreType == AIC) {
37+ return;
lccchh
lccchhlccchh4 days ago

【建议修复】
问题分类:非法计数的错误反馈
对应位置:moe/merge_chunk/op_kernel/merge_chunk_impl.h:43
问题:PrepareExpertOffsets 检查到负计数或计数和与 chunk 行数不符时,各核直接退出,未写数据与计数输出。Torch 入口用 at::empty 创建两类输出,调用方可拿到含未定义值的 Tensor,无法区分校验失败和正常结果。
建议的修改方法:为计数值非法的情况提供可观察、可测试的失败行为,例如通过现有的设备侧错误状态上报。增加负计数和计数和不匹配的用例,验证调用方能识别失败。

likedislike
38+ }
39+ 
40+ Init(in1c1, in1c2, in2c1, in2c2, glc1, glc2, out1, out2, gl);
41+ LoadGroupList();
42+ if (!ValidCounts(glc1_, 0) || !ValidCounts(glc2_, 1)) {
43+ return;
44+ }
45+ ProcessToken<true>(in1c1Gm_, 0, out1Gm_);
46+ ProcessToken<false>(in1c2Gm_, 0, out1Gm_);
47+ ProcessToken<true>(in2c1Gm_, 1, out2Gm_);
48+ ProcessToken<false>(in2c2Gm_, 1, out2Gm_);
49+ ProcessGroupList();
50+ }
51+ 
52+ __aicore__ void LoadGroupList()
53+ {
54+ const int maxExpert = COUNT_BUFFER_BYTES / sizeof(int32_t);
55+ glc1_ = ub_.GetWithOffset<int32_t>(maxExpert, TOKEN_BUFFER_BYTES);
56+ glc2_ = ub_.GetWithOffset<int32_t>(maxExpert, TOKEN_BUFFER_BYTES + COUNT_BUFFER_BYTES);
57+ DataCopyPad(glc1_, glc1Gm_,
58+ {static_cast<uint16_t>(1), static_cast<uint32_t>(tiling_.experts * sizeof(int32_t)),
59+ /*srcStride*/ 0, /*dstStride*/ 0, 0},
60+ {false, 0, 0, 0});
61+ DataCopyPad(glc2_, glc2Gm_,
62+ {static_cast<uint16_t>(1), static_cast<uint32_t>(tiling_.experts * sizeof(int32_t)),
63+ /*srcStride*/ 0, /*dstStride*/ 0, 0},
64+ {false, 0, 0, 0});
65+ SetFlag<HardEvent::MTE2_S>(eventIdMte2ToS);
66+ WaitFlag<HardEvent::MTE2_S>(eventIdMte2ToS);
67+ }
68+ 
69+ __aicore__ bool ValidCounts(LocalTensor<int32_t>& counts, uint32_t chunk)
70+ {
71+ uint32_t remaining = tiling_.rowsPerCore[chunk] * GetBlockNum() + tiling_.extraCores[chunk];
72+ for (uint32_t expert = 0; expert < tiling_.experts; ++expert) {
73+ const int32_t count = counts.GetValue(expert);
74+ if (count < 0 || static_cast<uint32_t>(count) > remaining) {
75+ return false;
76+ }
77+ remaining -= static_cast<uint32_t>(count);
78+ }
79+ return remaining == 0;
80+ }
81+ 
82+ __aicore__ void ProcessGroupList()
83+ {
84+ if (blockIdx_ == 0) {
85+ pipe_barrier(PIPE_ALL);
86+ Add(glc1_, glc1_, glc2_, tiling_.experts);
87+ SetFlag<HardEvent::V_MTE3>(eventIdVToMte3);
88+ WaitFlag<HardEvent::V_MTE3>(eventIdVToMte3);
89+ DataCopyPad(glGm_, glc1_,
90+ {static_cast<uint16_t>(1), static_cast<uint32_t>(tiling_.experts * sizeof(int32_t)),
91+ /*srcStride*/ 0, /*dstStride*/ 0, 0});
92+ }
93+ }
94+ 
95+ template <bool isFirstChunk>
96+ __aicore__ void ProcessToken(const GlobalTensor<T>& input, uint32_t path, GlobalTensor<T>& out)
97+ {
98+ const uint32_t chunk = isFirstChunk ? 0 : 1;
99+ const uint32_t extra = tiling_.extraCores[chunk];
100+ const uint32_t base = tiling_.rowsPerCore[chunk];
101+ curToken_ = base + (blockIdx_ < extra ? 1 : 0);
102+ curTokenOffset_ = blockIdx_ * base + (blockIdx_ < extra ? blockIdx_ : extra);
103+ if (curToken_ == 0) {
104+ return;
105+ }
106+ 
107+ const int hidden = tiling_.hidden[path];
108+ const int maxToken = tiling_.rowsPerTile[path];
109+ input_ = ub_.GetWithOffset<T>(maxToken * hidden, 0);
110+ 
111+ int loop = (curToken_ + maxToken - 1) / maxToken;
112+ int tailToken = curToken_ - (loop - 1) * maxToken;
113+ 
114+ SetFlag<HardEvent::MTE3_MTE2>(eventIdMte3ToMte2);
115+ for (int i = 0; i < loop; ++i) {
116+ int curChunkToken = (i == loop - 1) ? tailToken : maxToken;
117+ int curChunkOffset = i * maxToken;
118+ ProcessChunk<isFirstChunk>(input, curChunkToken, curChunkOffset, hidden, out);
119+ }
120+ WaitFlag<HardEvent::MTE3_MTE2>(eventIdMte3ToMte2);
121+ }
122+ 
123+ template <bool isFirstChunk>
124+ __aicore__ void ProcessChunk(const GlobalTensor<T>& input, int curChunkToken, int curChunkOffset, int hidden,
125+ GlobalTensor<T>& out)
126+ {
127+ WaitFlag<HardEvent::MTE3_MTE2>(eventIdMte3ToMte2);
128+ 
129+ int chunkStart = curTokenOffset_ + curChunkOffset;
130+ int chunkEnd = chunkStart + curChunkToken;
131+ DataCopyPad(input_, input[chunkStart * hidden],
132+ {static_cast<uint16_t>(1), static_cast<uint32_t>(curChunkToken * hidden * sizeof(T)),
133+ /*srcStride*/ 0, /*dstStride*/ 0, 0},
134+ {false, 0, 0, 0});
135+ SetFlag<HardEvent::MTE2_S>(eventIdMte2ToS);
136+ WaitFlag<HardEvent::MTE2_S>(eventIdMte2ToS);
137+ SetFlag<HardEvent::MTE2_MTE3>(eventIdMte2ToMte3);
138+ WaitFlag<HardEvent::MTE2_MTE3>(eventIdMte2ToMte3);
139+ 
140+ int sumTokenC1 = 0;
141+ int sumTokenC2 = 0;
142+ int sumToken = 0;
143+ for (uint32_t curExpert = 0; curExpert < tiling_.experts; ++curExpert) {
144+ int tokenCurExpertC1 = glc1_.GetValue(curExpert);
145+ int tokenCurExpertC2 = glc2_.GetValue(curExpert);
146+ 
147+ int curExpertStartPos;
148+ int curExpertEndPos;
149+ if (isFirstChunk) {
150+ curExpertStartPos = sumTokenC1;
151+ curExpertEndPos = curExpertStartPos + tokenCurExpertC1;
152+ } else {
153+ curExpertStartPos = sumTokenC2;
154+ curExpertEndPos = curExpertStartPos + tokenCurExpertC2;
155+ }
156+ 
157+ if (curExpertEndPos <= chunkStart) { // 当前专家未到达本chunk
158+ // update intermediate status
159+ sumTokenC1 += tokenCurExpertC1;
160+ sumTokenC2 += tokenCurExpertC2;
161+ sumToken += (tokenCurExpertC1 + tokenCurExpertC2);
162+ continue;
163+ } else if (curExpertStartPos >= chunkEnd) { // 当前专家已经路过了本chunk
164+ break;
165+ }
166+ 
167+ if (curExpertEndPos == curExpertStartPos) { // 当前专家token为0
168+ // update intermediate status
169+ sumTokenC1 += tokenCurExpertC1;
170+ sumTokenC2 += tokenCurExpertC2;
171+ sumToken += (tokenCurExpertC1 + tokenCurExpertC2);
172+ continue;
173+ }
174+ 
175+ int validStart = curExpertStartPos >= chunkStart ? curExpertStartPos : chunkStart;
176+ int validEnd = curExpertEndPos <= chunkEnd ? curExpertEndPos : chunkEnd;
177+ int validTokenNum = validEnd - validStart;
178+ int startOffsetInExpert = chunkStart <= curExpertStartPos ? 0 : chunkStart - curExpertStartPos;
179+ int startOffsetInChunk = chunkStart <= curExpertStartPos ? curExpertStartPos - chunkStart : 0;
180+ 
181+ int outOffset;
182+ if (isFirstChunk) {
183+ outOffset = sumToken + startOffsetInExpert;
184+ } else {
185+ outOffset = sumToken + tokenCurExpertC1 + startOffsetInExpert;
186+ }
187+ DataCopyPad(out[outOffset * hidden], input_[startOffsetInChunk * hidden],
188+ {static_cast<uint16_t>(1), static_cast<uint32_t>(validTokenNum * hidden * sizeof(T)),
189+ /*srcStride*/ 0, /*dstStride*/ 0, 0});
190+ 
191+ // update intermediate status
192+ sumTokenC1 += tokenCurExpertC1;
193+ sumTokenC2 += tokenCurExpertC2;
194+ sumToken += (tokenCurExpertC1 + tokenCurExpertC2);
195+ }
196+ SetFlag<HardEvent::MTE3_MTE2>(eventIdMte3ToMte2);
197+ }
198+ 
199+ __aicore__ void Init(GM_ADDR in1c1, GM_ADDR in1c2, GM_ADDR in2c1, GM_ADDR in2c2, GM_ADDR glc1, GM_ADDR glc2,
200+ GM_ADDR out1, GM_ADDR out2, GM_ADDR gl)
201+ {
202+ // get block id
203+ blockIdx_ = GetBlockIdx();
204+ 
205+ // gm init
206+ in1c1Gm_.SetGlobalBuffer((__gm__ T*)in1c1);
207+ in1c2Gm_.SetGlobalBuffer((__gm__ T*)in1c2);
208+ out1Gm_.SetGlobalBuffer((__gm__ T*)out1);
209+ 
210+ in2c1Gm_.SetGlobalBuffer((__gm__ T*)in2c1);
211+ in2c2Gm_.SetGlobalBuffer((__gm__ T*)in2c2);
212+ out2Gm_.SetGlobalBuffer((__gm__ T*)out2);
213+ 
214+ glc1Gm_.SetGlobalBuffer((__gm__ int32_t*)glc1);
215+ glc2Gm_.SetGlobalBuffer((__gm__ int32_t*)glc2);
216+ glGm_.SetGlobalBuffer((__gm__ int32_t*)gl);
217+ 
218+ // alloc ub buf: token buffer + two group-list buffers
219+ pipe_.InitBuffer(ub_, TOTAL_BUFFER_BYTES);
220+ }
221+ 
222+private:
223+ const Tiling& tiling_;
224+ 
225+ // gm tensors
226+ GlobalTensor<T> in1c1Gm_;
227+ GlobalTensor<T> in1c2Gm_;
228+ GlobalTensor<T> out1Gm_;
229+ 
230+ GlobalTensor<T> in2c1Gm_;
231+ GlobalTensor<T> in2c2Gm_;
232+ GlobalTensor<T> out2Gm_;
233+ 
234+ GlobalTensor<int32_t> glc1Gm_;
235+ GlobalTensor<int32_t> glc2Gm_;
236+ GlobalTensor<int32_t> glGm_;
237+ 
238+ // ub tensors
239+ TPipe& pipe_;
240+ TBuf<> ub_;
241+ LocalTensor<T> input_;
242+ LocalTensor<int32_t> glc1_;
243+ LocalTensor<int32_t> glc2_;
244+ 
245+ // core info
246+ uint32_t blockIdx_ = 0;
247+ int curToken_;
248+ int curTokenOffset_;
249+ 
250+ // sync event
251+ event_t eventIdMte2ToS = static_cast<event_t>(GetTPipePtr()->FetchEventID<HardEvent::MTE2_S>());
252+ event_t eventIdMte2ToMte3 = static_cast<event_t>(GetTPipePtr()->FetchEventID<HardEvent::MTE2_MTE3>());
253+ event_t eventIdMte3ToMte2 = static_cast<event_t>(GetTPipePtr()->FetchEventID<HardEvent::MTE3_MTE2>());
254+ event_t eventIdVToMte3 = static_cast<event_t>(GetTPipePtr()->FetchEventID<HardEvent::V_MTE3>());
255+};
256+ 
257+} // namespace MergeChunkSupport
258+ 
259+#endif // MERGE_CHUNK_IMPL_H_
@@ -0,0 +1,28 @@
1+/**
2+ * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#ifndef MERGE_CHUNK_LIMITS_H_
12+#define MERGE_CHUNK_LIMITS_H_
13+ 
14+#include <stdint.h>
15+ 
16+namespace MergeChunkSupport {
17+constexpr uint32_t SUPPORTED_PATHS = 2;
18+constexpr uint32_t SUPPORTED_CHUNKS = 2;
19+constexpr uint32_t TOKEN_RANK = 2;
20+constexpr uint32_t MAX_EXPERTS = 1024;
21+constexpr uint32_t ELEMENT_BYTES = 2;
22+constexpr uint32_t HIDDEN_ALIGNMENT = 16;
23+constexpr uint32_t COUNT_BUFFER_BYTES = MAX_EXPERTS * sizeof(int32_t);
24+constexpr uint32_t TOKEN_BUFFER_BYTES = 176 * 1024;
25+constexpr uint32_t TOTAL_BUFFER_BYTES = TOKEN_BUFFER_BYTES + 2 * COUNT_BUFFER_BYTES;
26+} // namespace MergeChunkSupport
27+ 
28+#endif
@@ -0,0 +1,16 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# -----------------------------------------------------------------------------------------------------------
10+ 
11+file(GLOB CURRENT_SOURCE_DIRS LIST_DIRECTORIES true ${CMAKE_CURRENT_SOURCE_DIR}/*)
12+foreach(SUB_DIR ${CURRENT_SOURCE_DIRS})
13+ if(EXISTS "${SUB_DIR}/CMakeLists.txt")
14+ add_subdirectory(${SUB_DIR})
15+ endif()
16+endforeach()
@@ -0,0 +1,285 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+ 
9+import ctypes
10+import os
11+from pathlib import Path
12+ 
13+import numpy as np
14+ 
15+ACL_FLOAT = 0
16+ACL_FLOAT16 = 1
17+ACL_INT32 = 3
18+ACL_INT64 = 9
19+ACL_BF16 = 27
20+ACL_FORMAT_ND = 2
21+ 
22+ACL_MEM_MALLOC_HUGE_FIRST = 0
23+ACL_MEMCPY_HOST_TO_DEVICE = 1
24+ACL_MEMCPY_DEVICE_TO_HOST = 2
25+ 
26+DTYPE_TO_ACL = {
27+ np.float32: ACL_FLOAT,
28+ np.float16: ACL_FLOAT16,
29+ np.uint16: ACL_BF16,
30+ np.int32: ACL_INT32,
31+ np.int64: ACL_INT64,
32+}
33+ 
34+C_INT64_P = ctypes.POINTER(ctypes.c_int64)
35+C_VOID_P_P = ctypes.POINTER(ctypes.c_void_p)
36+ 
37+ 
38+def _first_existing(paths):
39+ for path in paths:
40+ if path and Path(path).is_file():
41+ return Path(path)
42+ return None
43+ 
44+ 
45+def _cann_lib_dirs():
46+ roots = [
47+ os.environ.get("ASCEND_HOME_PATH"),
48+ os.environ.get("ASCEND_TOOLKIT_HOME"),
49+ "/usr/local/Ascend/ascend-toolkit/latest",
50+ "/usr/local/Ascend/cann-8.5.0",
51+ "/usr/local/Ascend/latest",
52+ ]
53+ dirs = []
54+ for root in roots:
55+ if not root:
56+ continue
57+ for sub in ("lib64", "lib", "runtime/lib64"):
58+ path = Path(root) / sub
59+ if path.is_dir() and path not in dirs:
60+ dirs.append(path)
61+ for item in os.environ.get("LD_LIBRARY_PATH", "").split(":"):
62+ path = Path(item)
63+ if item and path.is_dir() and path not in dirs:
64+ dirs.append(path)
65+ return dirs
66+ 
67+ 
68+def _custom_opapi_candidates():
69+ candidates = []
70+ explicit = os.environ.get("CUSTOM_OPAPI_LIB")
71+ if explicit:
72+ candidates.append(Path(explicit))
73+ 
74+ for root in os.environ.get("ASCEND_CUSTOM_OPP_PATH", "").split(":"):
75+ if root:
76+ candidates.append(Path(root) / "op_api" / "lib" / "libcust_opapi.so")
77+ 
78+ repo_root = Path(__file__).resolve().parents[5]
79+ for root in (repo_root / "build_out", repo_root / "output", repo_root / "build"):
80+ if not root.is_dir():
81+ continue
82+ for path in root.rglob("libcust_opapi.so"):
83+ candidates.append(path)
84+ 
85+ for lib_dir in _cann_lib_dirs():
86+ opp_root = lib_dir.parent / "opp" / "vendors"
87+ if opp_root.is_dir():
88+ for path in opp_root.glob("*/op_api/lib/libcust_opapi.so"):
89+ candidates.append(path)
90+ return candidates
91+ 
92+ 
93+def _load_library(name, extra_dirs=None):
94+ dirs = list(extra_dirs or []) + _cann_lib_dirs()
95+ for directory in dirs:
96+ path = Path(directory) / name
97+ if path.is_file():
98+ return ctypes.CDLL(str(path), mode=ctypes.RTLD_GLOBAL)
99+ return ctypes.CDLL(name, mode=ctypes.RTLD_GLOBAL)
100+ 
101+ 
102+class AclnnTensor:
103+ def __init__(self, runtime, array):
104+ self.runtime = runtime
105+ self.host = np.ascontiguousarray(array)
106+ self.shape = list(self.host.shape)
107+ self.strides = [1] * len(self.shape)
108+ for index in range(len(self.shape) - 2, -1, -1):
109+ self.strides[index] = self.shape[index + 1] * self.strides[index + 1]
110+ self.nbytes = int(self.host.nbytes)
111+ self.device = runtime.malloc(self.nbytes) if self.nbytes else ctypes.c_void_p()
112+ if self.nbytes:
113+ runtime.h2d(self.device, self.host)
114+ 
115+ self._shape = (ctypes.c_int64 * len(self.shape))(*self.shape)
116+ self._strides = (ctypes.c_int64 * len(self.strides))(*self.strides)
117+ self._storage = (ctypes.c_int64 * len(self.shape))(*self.shape)
118+ acl_dtype = DTYPE_TO_ACL[self.host.dtype.type]
119+ self.ptr = runtime.nnopbase.aclCreateTensor(
120+ ctypes.cast(self._shape, C_INT64_P),
121+ len(self.shape),
122+ acl_dtype,
123+ ctypes.cast(self._strides, C_INT64_P),
124+ 0,
125+ ACL_FORMAT_ND,
126+ ctypes.cast(self._storage, C_INT64_P),
127+ len(self.shape),
128+ self.device,
129+ )
130+ if not self.ptr:
131+ raise RuntimeError("aclCreateTensor failed")
132+ 
133+ def copy_back(self, dtype, shape):
134+ output = np.empty(shape, dtype=dtype)
135+ if output.nbytes:
136+ self.runtime.d2h(output, self.device)
137+ return output
138+ 
139+ def close(self):
140+ if getattr(self, "ptr", None):
141+ self.runtime.nnopbase.aclDestroyTensor(self.ptr)
142+ self.ptr = None
143+ if getattr(self, "device", None):
144+ self.runtime.free(self.device)
145+ self.device = None
146+ 
147+ 
148+class AclnnRuntime:
149+ _instance = None
150+ 
151+ @classmethod
152+ def instance(cls):
153+ if cls._instance is None:
154+ cls._instance = cls()
155+ return cls._instance
156+ 
157+ def __init__(self):
158+ self.acl = _load_library("libascendcl.so")
159+ self.nnopbase = _load_library("libnnopbase.so")
160+ opapi = _first_existing(_custom_opapi_candidates())
161+ self.opapi_path = str(opapi) if opapi else None
162+ self.opapi = _load_library(
163+ "libcust_opapi.so", [opapi.parent] if opapi else None
164+ )
165+ 
166+ self.acl.aclInit.argtypes = [ctypes.c_char_p]
167+ self.acl.aclInit.restype = ctypes.c_int
168+ self.acl.aclrtSetDevice.argtypes = [ctypes.c_int32]
169+ self.acl.aclrtSetDevice.restype = ctypes.c_int
170+ self.acl.aclrtCreateStream.argtypes = [C_VOID_P_P]
171+ self.acl.aclrtCreateStream.restype = ctypes.c_int
172+ self.acl.aclrtSynchronizeStream.argtypes = [ctypes.c_void_p]
173+ self.acl.aclrtSynchronizeStream.restype = ctypes.c_int
174+ self.acl.aclrtMalloc.argtypes = [C_VOID_P_P, ctypes.c_size_t, ctypes.c_int32]
175+ self.acl.aclrtMalloc.restype = ctypes.c_int
176+ self.acl.aclrtFree.argtypes = [ctypes.c_void_p]
177+ self.acl.aclrtFree.restype = ctypes.c_int
178+ self.acl.aclrtMemcpy.argtypes = [
179+ ctypes.c_void_p,
180+ ctypes.c_size_t,
181+ ctypes.c_void_p,
182+ ctypes.c_size_t,
183+ ctypes.c_int32,
184+ ]
185+ self.acl.aclrtMemcpy.restype = ctypes.c_int
186+ 
187+ self.nnopbase.aclCreateTensor.argtypes = [
188+ C_INT64_P,
189+ ctypes.c_uint64,
190+ ctypes.c_int32,
191+ C_INT64_P,
192+ ctypes.c_int64,
193+ ctypes.c_int32,
194+ C_INT64_P,
195+ ctypes.c_uint64,
196+ ctypes.c_void_p,
197+ ]
198+ self.nnopbase.aclCreateTensor.restype = ctypes.c_void_p
199+ self.nnopbase.aclDestroyTensor.argtypes = [ctypes.c_void_p]
200+ self.nnopbase.aclDestroyTensor.restype = ctypes.c_int
201+ 
202+ if self.acl.aclInit(None) not in (0, 100002, 500000):
203+ raise RuntimeError("aclInit failed")
204+ if self.acl.aclrtSetDevice(0) not in (0, 100002, 500000, 107001):
205+ raise RuntimeError("aclrtSetDevice failed")
206+ self.stream = ctypes.c_void_p()
207+ if self.acl.aclrtCreateStream(ctypes.byref(self.stream)) != 0:
208+ raise RuntimeError("aclrtCreateStream failed")
209+ 
210+ def malloc(self, size):
211+ device = ctypes.c_void_p()
212+ if (
213+ self.acl.aclrtMalloc(ctypes.byref(device), size, ACL_MEM_MALLOC_HUGE_FIRST)
214+ != 0
215+ ):
216+ raise RuntimeError("aclrtMalloc failed")
217+ return device
218+ 
219+ def free(self, device):
220+ if device:
221+ self.acl.aclrtFree(device)
222+ 
223+ def h2d(self, device, array):
224+ size = int(array.nbytes)
225+ source = array.ctypes.data_as(ctypes.c_void_p)
226+ if (
227+ self.acl.aclrtMemcpy(device, size, source, size, ACL_MEMCPY_HOST_TO_DEVICE)
228+ != 0
229+ ):
230+ raise RuntimeError("aclrtMemcpy H2D failed")
231+ 
232+ def d2h(self, array, device):
233+ size = int(array.nbytes)
234+ target = array.ctypes.data_as(ctypes.c_void_p)
235+ if (
236+ self.acl.aclrtMemcpy(target, size, device, size, ACL_MEMCPY_DEVICE_TO_HOST)
237+ != 0
238+ ):
239+ raise RuntimeError("aclrtMemcpy D2H failed")
240+ 
241+ def sync(self):
242+ self.acl.aclrtSynchronizeStream(self.stream)
243+ 
244+ def tensor(self, array):
245+ return AclnnTensor(self, array)
246+ 
247+ def set_opapi(self, name, argtypes):
248+ try:
249+ function = getattr(self.opapi, name)
250+ except AttributeError as lookup_error:
251+ last_error = lookup_error
252+ for candidate in _custom_opapi_candidates():
253+ if not candidate.is_file():
254+ continue
255+ try:
256+ library = ctypes.CDLL(str(candidate), mode=ctypes.RTLD_GLOBAL)
257+ function = getattr(library, name)
258+ except (OSError, AttributeError) as candidate_error:
259+ last_error = candidate_error
260+ continue
261+ self.opapi = library
262+ self.opapi_path = str(candidate)
263+ break
264+ else:
265+ raise RuntimeError(
266+ f"{name} not found in libcust_opapi.so; build and install the operator package first"
267+ ) from last_error
268+ function.restype = ctypes.c_int
269+ function.argtypes = argtypes
270+ return function
271+ 
272+ def get_workspace(self, function, *args):
273+ workspace_size = ctypes.c_uint64(0)
274+ executor = ctypes.c_void_p()
275+ ret = function(*args, ctypes.byref(workspace_size), ctypes.byref(executor))
276+ return ret, workspace_size.value, executor
277+ 
278+ def execute(self, function, workspace_size, executor):
279+ workspace = self.malloc(workspace_size) if workspace_size else ctypes.c_void_p()
280+ try:
281+ ret = function(workspace, workspace_size, executor, self.stream)
282+ self.sync()
283+ return ret
284+ finally:
285+ self.free(workspace)
@@ -0,0 +1,33 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+ 
9+import ctypes
10+import os
11+import sys
12+from pathlib import Path
13+ 
14+ 
15+def _preload_runtime_libraries():
16+ candidates = [
17+ Path(sys.prefix) / "lib" / "libstdc++.so.6",
18+ Path(sys.executable).resolve().parents[1] / "lib" / "libstdc++.so.6",
19+ ]
20+ for library in candidates:
21+ if library.exists():
22+ ctypes.CDLL(str(library), mode=ctypes.RTLD_GLOBAL)
23+ break
24+ 
25+ lib_dirs = [str(path) for path in candidates if path.exists()]
26+ if lib_dirs:
27+ current = os.environ.get("LD_LIBRARY_PATH", "")
28+ os.environ["LD_LIBRARY_PATH"] = ":".join(
29+ lib_dirs + ([current] if current else [])
30+ )
31+ 
32+ 
33+_preload_runtime_libraries()
@@ -0,0 +1,6 @@
1+[pytest]
2+testpaths = .
3+python_files = test_*.py
4+addopts = -ra -p no:torchtyping
5+markers =
6+ ci: CI test cases
@@ -0,0 +1,147 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
2+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
3+# CANN Open Software License Agreement Version 2.0 (the "License").
4+# Please refer to the License for details. You may not use this file except in compliance with the License.
5+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
6+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
7+# See LICENSE in the root of the software repository for the full text of the License.
8+ 
9+import ctypes
10+from contextlib import ExitStack
11+ 
12+import numpy as np
13+import pytest
14+ 
15+from aclnn_utils import AclnnRuntime, C_VOID_P_P
16+ 
17+ 
18+def make_list(runtime, stack, members):
19+ lib = runtime.nnopbase
20+ lib.aclCreateTensorList.argtypes = [C_VOID_P_P, ctypes.c_uint64]
21+ lib.aclCreateTensorList.restype = ctypes.c_void_p
22+ lib.aclDestroyTensorList.argtypes = [ctypes.c_void_p]
23+ lib.aclDestroyTensorList.restype = ctypes.c_int
24+ pointers = (ctypes.c_void_p * len(members))(*(member.ptr for member in members))
25+ descriptor = lib.aclCreateTensorList(pointers, len(members))
26+ assert descriptor
27+ stack.callback(lib.aclDestroyTensorList, descriptor)
28+ for member in members:
29+ member.ptr = None # The list owns the descriptors, but not their buffers.
30+ return descriptor
31+ 
32+ 
33+def golden(inputs, counts, widths):
34+ starts = [np.cumsum([0, *row.tolist()]) for row in counts]
35+ return [
36+ np.concatenate(
37+ [
38+ inputs[path * len(counts) + c][
39+ starts[c][expert] : starts[c][expert + 1]
40+ ]
41+ for expert in range(len(counts[0]))
42+ for c in range(len(counts))
43+ ],
44+ axis=0,
45+ )
46+ for path in range(len(widths))
47+ ], np.sum(counts, axis=0, dtype=np.int32)
48+ 
49+ 
50+@pytest.mark.ci
51+@pytest.mark.parametrize("precision", ["fp16", "bf16"])
52+@pytest.mark.parametrize(
53+ "widths, counts",
54+ [
55+ ([16], [[1, 0, 2]]),
56+ ([16], [[1], [2]]),
57+ ([16, 48], [[3]]),
58+ ([16, 32], [[0, 1, 0, 3], [3, 0, 2, 0]]),
59+ ([16, 32], [[1, 2, 1], [2, 1, 1]]),
60+ ([16, 32, 64], [[1, 2, 1], [2, 1, 1]]),
61+ ([16, 32], [[1, 2, 1], [2, 1, 1], [0, 1, 1]]),
62+ ([16, 32, 64], [[1, 2, 1], [2, 1, 1], [0, 1, 1]]),
63+ ([16384, 32], [[157, 0, 164], [0, 8, 2]]),
64+ ([16] * 32, [[1, 1, 0]]),
65+ ([16], [[1, 0, 1]] * 32),
66+ ([16] * 32, [[1, 0, 1]] * 32),
67+ ([90112, 16], [[1] + [0] * 1022 + [1], [0] * 1023 + [1]]),
68+ ],
69+)
70+def test_merge_chunk(widths, counts, precision):
71+ runtime = AclnnRuntime.instance()
72+ get_workspace = runtime.set_opapi(
73+ "aclnnMergeChunkGetWorkspaceSize",
74+ [
75+ ctypes.c_void_p,
76+ ctypes.c_void_p,
77+ ctypes.c_int64,
78+ ctypes.c_int64,
79+ ctypes.c_void_p,
80+ ctypes.c_void_p,
81+ ctypes.POINTER(ctypes.c_uint64),
82+ C_VOID_P_P,
83+ ],
84+ )
85+ launch = runtime.set_opapi(
86+ "aclnnMergeChunk",
87+ [ctypes.c_void_p, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_void_p],
88+ )
89+ counts = [np.asarray(row, dtype=np.int32) for row in counts]
90+ rng = np.random.default_rng(42)
91+ 
92+ def sample(shape):
93+ if precision == "bf16":
94+ # Compare exact BF16 payload bits using the helper's uint16 backing storage.
95+ return rng.integers(0x3C00, 0x4100, size=shape, dtype=np.uint16)
96+ return rng.standard_normal(shape).astype(np.float16)
97+ 
98+ host = [sample((int(row.sum()), width)) for width in widths for row in counts]
99+ expected, merged_counts = golden(host, counts, widths)
100+ 
101+ with ExitStack() as stack:
102+ 
103+ def allocate(array):
104+ tensor = runtime.tensor(array)
105+ stack.callback(tensor.close)
106+ return tensor
107+ 
108+ inputs = [allocate(x) for x in host]
109+ group_lists = [allocate(x) for x in counts]
110+ outputs = [allocate(np.zeros_like(x)) for x in expected]
111+ out_counts = allocate(np.zeros_like(merged_counts))
112+ acl_input = make_list(runtime, stack, inputs)
113+ acl_counts = make_list(runtime, stack, group_lists)
114+ acl_output = make_list(runtime, stack, outputs)
115+ bad, _, _ = runtime.get_workspace(
116+ get_workspace,
117+ acl_input,
118+ acl_counts,
119+ len(widths) + 1,
120+ len(counts),
121+ acl_output,
122+ out_counts.ptr,
123+ )
124+ assert bad == 161002
125+ 
126+ status, workspace, executor = runtime.get_workspace(
127+ get_workspace,
128+ acl_input,
129+ acl_counts,
130+ len(widths),
131+ len(counts),
132+ acl_output,
133+ out_counts.ptr,
134+ )
135+ if (len(widths), len(counts)) != (2, 2):
136+ assert status == 161002 and workspace == 0 and not executor
137+ return
138+ assert status == 0, f"GetWorkspaceSize failed: {status}"
139+ assert runtime.execute(launch, workspace, executor) == 0
140+ for actual, want in zip(outputs, expected):
141+ np.testing.assert_array_equal(
142+ actual.copy_back(want.dtype, want.shape), want
143+ )
144+ np.testing.assert_array_equal(
145+ out_counts.copy_back(merged_counts.dtype, merged_counts.shape),
146+ merged_counts,
147+ )
@@ -0,0 +1,11 @@
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+add_subdirectory(op_host)
@@ -0,0 +1,13 @@
1+# -----------------------------------------------------------------------------------------------------------
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
3+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+# CANN Open Software License Agreement Version 2.0 (the "License").
5+# Please refer to the License for details. You may not use this file except in compliance with the License.
6+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+# See LICENSE in the root of the software repository for the full text of the License.
9+# -----------------------------------------------------------------------------------------------------------
10+ 
11+if(UT_TEST_ALL OR OP_HOST_UT)
12+ add_modules_ut_sources(UT_NAME ${OP_INFERSHAPE_MODULE_NAME} MODE PRIVATE DIR ${CMAKE_CURRENT_SOURCE_DIR})
13+endif()
@@ -0,0 +1,113 @@
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 <array>
12+#include <vector>
13+#include <gtest/gtest.h>
14+#include "exe_graph/runtime/shape.h"
15+#include "../../../op_host/merge_chunk_shape.h"
16+ 
17+namespace {
18+using MergeChunkSupport::Layout;
19+using MergeChunkSupport::ReadLayout;
20+using MergeChunkSupport::SUPPORTED_CHUNKS;
21+using MergeChunkSupport::SUPPORTED_PATHS;
22+constexpr int64_t FIRST_ROWS = 4;
23+constexpr int64_t SECOND_ROWS = 3;
24+constexpr int64_t FIRST_WIDTH = 16;
25+constexpr int64_t SECOND_WIDTH = 32;
26+constexpr int64_t EXPERTS = 3;
27+ 
28+class MergeChunkLayoutTest : public testing::Test {
29+protected:
30+ const char* Read(Layout& layout, int64_t paths = SUPPORTED_PATHS, int64_t chunks = SUPPORTED_CHUNKS)
31+ {
32+ return ReadLayout(
33+ paths, chunks, [this](size_t i) { return i < data.size() ? &data[i] : nullptr; },
34+ [this](size_t i) { return i < counts.size() ? &counts[i] : nullptr; }, layout);
35+ }
36+ 
37+ const char* Infer(MergeChunkSupport::InferredLayout& result)
38+ {
39+ return MergeChunkSupport::InferLayout([this](size_t i) { return i < data.size() ? &data[i] : nullptr; },
40+ [this](size_t i) { return i < counts.size() ? &counts[i] : nullptr; },
41+ result);
42+ }
43+ 
44+ std::vector<gert::Shape> data{
45+ {FIRST_ROWS, FIRST_WIDTH}, {SECOND_ROWS, FIRST_WIDTH}, {FIRST_ROWS, SECOND_WIDTH}, {SECOND_ROWS, SECOND_WIDTH}};
46+ std::array<gert::Shape, SUPPORTED_CHUNKS> counts{{{EXPERTS}, {EXPERTS}}};
47+};
48+ 
49+TEST_F(MergeChunkLayoutTest, ReadsTwoPathsAndTwoChunks)
50+{
51+ Layout layout;
52+ ASSERT_EQ(Read(layout), nullptr);
53+ EXPECT_EQ(layout.paths, SUPPORTED_PATHS);
54+ EXPECT_EQ(layout.chunks, SUPPORTED_CHUNKS);
55+ EXPECT_EQ(layout.experts, EXPERTS);
56+ EXPECT_EQ(layout.totalRows, FIRST_ROWS + SECOND_ROWS);
57+ EXPECT_EQ(layout.chunkRows[0], FIRST_ROWS);
58+ EXPECT_EQ(layout.chunkRows[1], SECOND_ROWS);
59+ EXPECT_EQ(layout.hidden[0], FIRST_WIDTH);
60+ EXPECT_EQ(layout.hidden[1], SECOND_WIDTH);
61+}
62+ 
63+TEST_F(MergeChunkLayoutTest, RejectsMismatchedRowsAcrossPaths)
64+{
65+ Layout layout;
66+ data[SUPPORTED_CHUNKS + 1].SetDim(0, SECOND_ROWS - 1);
67+ EXPECT_NE(Read(layout), nullptr);
68+}
69+ 
70+TEST_F(MergeChunkLayoutTest, RejectsMismatchedExpertCountsAcrossChunks)
71+{
72+ Layout layout;
73+ counts[1].SetDim(0, EXPERTS + 1);
74+ EXPECT_NE(Read(layout), nullptr);
75+}
76+ 
77+TEST_F(MergeChunkLayoutTest, RejectsAnIncorrectListLength)
78+{
79+ Layout layout;
80+ data.pop_back();
81+ EXPECT_NE(Read(layout), nullptr);
82+}
83+TEST_F(MergeChunkLayoutTest, PropagatesUnknownDimensionsOnlyDuringInference)
84+{
85+ data = {{-1, -1}, {SECOND_ROWS, -1}, {-1, SECOND_WIDTH}, {SECOND_ROWS, SECOND_WIDTH}};
86+ counts = {{{-1}, {-1}}};
87+ MergeChunkSupport::InferredLayout inferred;
88+ ASSERT_EQ(Infer(inferred), nullptr);
89+ EXPECT_EQ(inferred.totalRows, -1);
90+ EXPECT_EQ(inferred.hidden[0], -1);
91+ EXPECT_EQ(inferred.hidden[1], SECOND_WIDTH);
92+ EXPECT_EQ(inferred.experts, -1);
93+ Layout runtime;
94+ EXPECT_NE(Read(runtime), nullptr);
95+ data[SUPPORTED_CHUNKS].SetDim(0, FIRST_ROWS);
96+ data[1].SetDim(1, FIRST_WIDTH);
97+ counts[1].SetDim(0, EXPERTS);
98+ ASSERT_EQ(Infer(inferred), nullptr);
99+ EXPECT_EQ(inferred.totalRows, FIRST_ROWS + SECOND_ROWS);
100+ EXPECT_EQ(inferred.hidden[0], FIRST_WIDTH);
101+ EXPECT_EQ(inferred.experts, EXPERTS);
102+}
103+ 
104+TEST_F(MergeChunkLayoutTest, RejectsInvalidKnownWidthsDuringInference)
105+{
106+ MergeChunkSupport::InferredLayout inferred;
107+ for (const auto width : {0, 17, 90128}) {
108+ data[2].SetDim(1, -1);
109+ data[3].SetDim(1, width);
110+ EXPECT_NE(Infer(inferred), nullptr);
111+ }
112+}
113+} // namespace