aclnnMoeDistributeDispatchV2
Applicable Products
Ascend 950DT products : Supported
Atlas A3 products : Supported
Atlas A2 products : Supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Not supported
Atlas training products : Not supported
Function
Description: Quantizes token data (optional) and performs AllToAllV communication in the EP (Expert Parallelism) domain. Communication in the TP (Tensor Parallelism) domain is no longer supported in the current version. TP-related parameters are reserved parameters.
Compared with the
aclnnMoeDistributeDispatchAPI, this API has the following changes:- More detailed token information is output to help the CombineV2 series operator efficiently perform synchronization across all devices. Therefore, the
expandIdxoutput parameter with shape(BS * K,)in the original API is replaced by theassistInfoForCombineOutparameter with shape(A * 128,); - Adds the
commAlginput parameter, which replaces theHCCL_INTRA_PCIE_ENABLEandHCCL_INTRA_ROCE_ENABLEenvironment variables used to control the hierarchical algorithm.
For details, refer to the following Parameters.
- More detailed token information is output to help the CombineV2 series operator efficiently perform synchronization across all devices. Therefore, the
Formula:
- Case 1: If quantMode=0 (non-quantization scenario):
$$ allToAllXOut = AllToAllV(X)\\ expandXOut = AllToAllV(X) $$When the data type of
xisINT32,scalesOptionalis communicated along with the corresponding token:$$ allToAllDynamicScalesOut = AllToAllV(scalesOptional)\\ dynamicScalesOut = allToAllDynamicScalesOut $$- Case 2: If quantMode=1 (static quantization scenario):
$$ xFp32 = CastToFp32(X) \times scales \\ quantOut = Cast(xFp32,dstType) \\ allToAllXOut = AllToAllV(quantOut)\\ expandXOut = AllToAllV(quantOut) $$- Case 3: If quantMode=2 (pertoken dynamic quantization scenario):
$$ xFp32 = CastToFp32(X) \times scales \\ dynamicScales = dstTypeMax/Max(Abs(xFp32)) \\ quantOut = CastToInt8(xFp32 \times dynamicScales) \\ allToAllXOut = AllToAllV(quantOut) \\ allToAllDynamicScalesOut = AllToAllV(1.0/dynamicScales) \\ expandXOut = AllToAllV(quantOut) \\ dynamicScalesOut = allToAllDynamicScalesOut $$- Case 4: If quantMode=3 (pertile dynamic quantization scenario):
$$ xFp32 = CastToFp32(X) \times scales \\ dynamicScales = dstTypeMax/Max(Abs(xFp32)) \\ quantOut = CastToInt8(xFp32 \times dynamicScales) \\ allToAllXOut = AllToAllV(quantOut) \\ allToAllDynamicScalesOut = AllToAllV(1.0/dynamicScales) \\ expandXOut = AllToAllV(quantOut) \\ dynamicScalesOut = allToAllDynamicScalesOut $$- Scenario 5: If quantMode=4 (mx quantization scenario):
$$ sharedExp = Floor(log_2(max(x))) - emax \\ dynamicScales = 2^{sharedExp} \\ quantOut = CastToFp8(X / dynamicScales) \\ allToAllXOut = AllToAllV(quantOut) \\ allToAllDynamicScalesOut = AllToAllV(1.0 / dynamicScales) \\ expandXOut = AllToAllV(quantOut) \\ dynamicScalesOut = allToAllDynamicScalesOut $$where $emax$ is the exponent value of the largest normal number of the data type.
Atlas A2 products : This API must be used together withaclnnMoeDistributeCombineV2.
Atlas A3 products and Ascend 950DT products: This API must be used together withaclnnMoeDistributeCombineV2oraclnnMoeDistributeCombineAddRmsNorm.
NOTE:
aclnnMoeDistributeCombineV2andaclnnMoeDistributeCombineAddRmsNormare collectively referred to as CombineV2 series operators in subsequent documents.
Function Prototype
Each operator is a two-phase API. First, call the "aclnnMoeDistributeDispatchV2GetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation process. Then, call the "aclnnMoeDistributeDispatchV2" API to perform the computation.
aclnnStatus aclnnMoeDistributeDispatchV2GetWorkspaceSize(
const aclTensor* x,
const aclTensor* expertIds,
const aclTensor* scalesOptional,
const aclTensor* xActiveMaskOptional,
const aclTensor* expertScalesOptional,
const char* groupEp,
int64_t epWorldSize,
int64_t epRankId,
int64_t moeExpertNum,
const char* groupTp,
int64_t tpWorldSize,
int64_t tpRankId,
int64_t expertShardType,
int64_t sharedExpertNum,
int64_t sharedExpertRankNum,
int64_t quantMode,
int64_t globalBS,
int64_t expertTokenNumsType,
const char* commAlg,
aclTensor* expandXOut,
aclTensor* dynamicScalesOut,
aclTensor* assistInfoForCombineOut,
aclTensor* expertTokenNumsOut,
aclTensor* epRecvCountsOut,
aclTensor* tpRecvCountsOut,
aclTensor* expandScalesOut,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnMoeDistributeDispatchV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMoeDistributeDispatchV2GetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x Input Token data sent by the local device. Requires a 2D tensor. FLOAT16, BFLOAT16, FLOAT8_E5M2, FLOAT8_E4M3FN, HIFLOAT8, FLOAT4_E2M1, FLOAT4_E1M2, INT32 ND (BS, H)(BS = batch size, H = hidden size)- expertIds Input TopK expert indices of each token. Requires a 2D tensor. INT32 ND (BS, K)- scalesOptional Input Quantization smoothing parameter for each expert or scaling parameter for INT32 tokens. - FLOAT32, FLOAT8_E8M0 ND - √ xActiveMaskOptional Input Indicates whether tokens participate in communication. Valid data or a null pointer can be passed in.
For 1D input, a value of true indicates that the corresponding token participates in communication, and true values must precede false values. For example, {true, false, true} is invalid input;
For 2D input, a value of true indicates that the expert_ids corresponding to the current token participate in communication. If all K BOOL values of the current token are false, the token does not participate in communication. By default, all tokens participate in communication. When the number of BSs varies across devices, all tokens must be valid.BOOL ND
For 1D input, the shape is(BS,); for 2D input, the shape is(BS, K)√ expertScalesOptional Input TopK expert weights of each token. - FLOAT32 ND (BS, K)√ groupEp Input EP communication domain name (expert parallelism communication domain). String length range: [1, 128).STRING - - - epWorldSize Input EP communication domain size. - INT64 - - - epRankId Input Local device ID in the EP domain. - Value Range
[0, epWorldSize) - In the same EP communication domain, each device has a unique
epRankId.
INT64 - - - moeExpertNum Input Number of MoE experts. Must satisfy moeExpertNum % (epWorldSize - sharedExpertRankNum) = 0.INT64 - - - groupTp Input TP communication domain name (Reserved Parameter, not supported in the current version). Default Value: "" STRING - - - tpWorldSize Input TP communication domain size (reserved parameter, not supported in the current version; only 0 or 1 is supported). Default value: 0. INT64 - - - tpRankId Input Local device ID in the TP domain (reserved parameter, not supported in the current version; only 0 is supported). Default Value: 0. INT64 - - - expertShardType Input Distribution type of shared expert cards. - INT64 - - - sharedExpertNum Input Number of shared experts (a shared expert can be replicated and deployed on multiple devices). - INT64 - - - sharedExpertRankNum Input Number of shared expert cards. - INT64 - - - quantMode Input Quantization mode. - INT64 - - - globalBS Input EP domain global batch size. - If BS is the same across all devices,
globalBS = BS * epWorldSizeor 0. - If BS differs across devices,
globalBS = maxBS * epWorldSize(maxBS is the maximum BS on a single device).
INT64 - - - expertTokenNumsType Input Semantic type of the values in the output expertTokenNums.Supported values: 0: the output in expertTokenNumsis the prefix sum of the number of tokens processed by each expert. 1: the output inexpertTokenNumsis the number of tokens processed by each expert.INT64 - - √ commAlg Input Communication affinity memory layout algorithm. - STRING - - - expandXOut Output Token features expanded according to expertIds.Must be a 2D tensor. FLOAT16, BFLOAT16, INT8, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8, FLOAT4_E2M1, FLOAT4_E1M2, INT32 ND (A, H)√ dynamicScalesOut Output Scaling parameter. Must be a 1D or 2D tensor. This output is generated when quantMode is 2, 3, or 4, and is also generated when quantMode is 0 and the data type of `x` is `HIFLOAT8`, `FLOAT8_E5M2`, `FLOAT8_E4M3FN`, `FLOAT4_E2M1`, `FLOAT4_E1M2`, or `INT32`. FLOAT32, FLOAT8_E8M0 - - √ assistInfoForCombineOut Output Number of tokens sent to the same expert (corresponding to assistInfoForCombineinaclnnMoeDistributeCombineV2).Must be a 1D tensor. INT32 ND (A*128, )√ expertTokenNumsOut Output Number of tokens received by each expert. Must be a 1D tensor. INT64 ND (localExpertNum, )√ epRecvCountsOut Output Number of tokens received from each device in the EP communication domain (corresponding to epSendCountsinaclnnMoeDistributeCombineV2).Must be a 1D tensor. INT32 ND - √ tpRecvCountsOut Output Number of tokens received from each device in the TP communication domain (reserved output, not supported in the current version; pass a null pointer). INT32 ND - √ expandScalesOut Output Weight of the output tokens on the local device (corresponding to expertScalesOptionalinaclnnMoeDistributeCombineV2).- FLOAT32 ND - √ workspaceSize Output Returns the workspace size to be requested on the Device. - - - - - executor Output Returns the op executor containing the operator computation flow. - aclOpExecutor* - - - Atlas A2 products :dynamicScalesOuthas an output when quantMode is set to 2 or the data type ofxis INT32.commAlgsupports nullptr, "", "fullmesh", and "hierarchy"; "hierarchy" is recommended together with a driver of version 25.0.RC1.1 or later; nullptr and "" select the algorithm based on HCCL environment variables (not recommended); "fullmesh" transfers tokens directly over RDMA; "hierarchy" optimizes communication through two sends, cross-server and intra-server.- When
commAlgis "hierarchy", or HCCL_INTRA_PCIE_ENABLE=1 and HCCL_INTRA_ROCE_ENABLE=0, scalesOptional must be set to nullptr. When the data type ofxis INT32, only "fullmesh" is supported forcommAlg, and valid data must be passed to scalesOptional. - The settings for
xActiveMaskOptionaldepend on the value of commAlg: "fullmesh" requires a 1D Tensor with shape (BS, ), and true values must precede false values (for example, {true, false, true} is invalid); "hierarchy" is not supported in the current version, and a null pointer can be passed. expertScalesOptionalmust be a 2D Tensor with shape (BS, K).- The value of
epWorldSizedepends on the value of commAlg: "fullmesh" supports 2, 3, 4, 5, 6, 7, 8, 16, 32, 64, 128, 192, 256, and 384; "hierarchy" supports 16, 32, and 64. - The value of
moeExpertNumdepends on the value of commAlg: "fullmesh" supports (0, 1024], and "hierarchy" supports (0, 512]. groupTpis not supported in the current version. Pass an empty string.tpWorldSize,tpRankId,expertShardType,sharedExpertNum, andsharedExpertRankNumare not supported in the current version. Pass 0 for each.- The shape of
epRecvCountsOutis (moeExpertNum + 2 * globalBS * K * serverNum,) (the first moeExpertNum values are the numbers of received tokens, and the remaining values are pre-communication reduce-related information). - TP domain communication is not supported currently.
expandScalesOutmust be a 1D tensor with shape (A,).quantModesupports 0 (non-quantized) and 2 (dynamic quantization).
Atlas A3 products :dynamicScalesOuthas an output only when the value ofquantModeis 2.commAlgis not supported in the current version. Pass a null pointer.xActiveMaskOptionalmust be a 1D or 2D tensor (the 1D shape is (BS, ) and the 2D shape is (BS, K)). For 1D tensors, true must be placed before false. For 2D tensors, if all K values corresponding to a token are false, the token does not participate in communication.expertScalesOptionalis not supported in the current version. Pass a null pointer.- The value range of
epWorldSizeis [2, 768]. moeExpertNumvalue range: (0, 1024].groupTp(reserved parameter, not supported in the current version).tpWorldSize(reserved parameter, not supported in the current version; only 0 or 1 is supported).tpRankId(reserved parameter, not supported in the current version; only 0 is supported).expertShardType: Currently, only 0 is supported, indicating that shared expert cards are placed before MoE expert cards.sharedExpertNumcurrent value range: [0, 4].sharedExpertRankNumvalue range: [0, epWorldSize). If sharedExpertRankNum is 0, sharedExpertNum must be 0 or 1. If sharedExpertRankNum is not 0, sharedExpertRankNum % sharedExpertNum = 0 must be satisfied.epRecvCountsOuthas a shape of (epWorldSize * localExpertNum,).tpRecvCountsOut(reserved output, not supported in the current version; simply pass an empty pointer).- The
expandScalesOutoutput is not supported in the current version. quantModesupports 0 (non-quantized) and 2 (dynamic quantization).
Ascend 950DT products :dynamicScalesOuthas an output when quantMode is 2, 3, or 4. It also has an output when quantMode is 0 and the data type ofxisHIFLOAT8,FLOAT8_E5M2,FLOAT8_E4M3FN,FLOAT4_E2M1, orFLOAT4_E1M2.commAlgis not supported in the current version. Pass a null pointer.xActiveMaskOptionalmust be a 1D or 2D tensor (1D shape: (BS,); 2D shape: (BS, K)). In the 1D case, true must be placed before false (for example, {true, false, true} is invalid). In the 2D case, if all K values corresponding to a token are false, the token does not participate in communication.expertScalesOptionalaccepts a valid tensor or a null pointer. If a valid tensor is passed, the expertScales expert weight function is enabled. The valid tensor is a 2D tensor with shape (BS, K). If a null pointer is passed, the expertScales expert weight function is not enabled. Empty tensors are not supported.epWorldSizevalue range: [2, 1024].moeExpertNumvalue range: (0, 1024].groupTpis not supported in the current version. Pass an empty string.tpWorldSizeis not supported in the current version. Pass 0.tpRankIdis not supported in the current version. Pass 0.expertShardType: Currently, only 0 is supported, indicating that shared expert cards are placed before MoE expert cards.sharedExpertNumcurrent value range: [0, 4].sharedExpertRankNumvalue range: [0, epWorldSize). If sharedExpertRankNum is 0, sharedExpertNum must be 0 or 1. If sharedExpertRankNum is not 0, sharedExpertRankNum % sharedExpertNum = 0 must be satisfied.epRecvCountsOuthas a shape of (epWorldSize * localExpertNum,).tpRecvCountsOut: This output is not supported in the current version.expandScalesOutis a valid output when the expertScales expert weight function is enabled; otherwise, this output is invalid.quantModesupports 0 (non-quantized), 1 (static quantization), 2 (pertoken dynamic quantization), 3 (pergroup dynamic quantization), and 4 (mx dynamic quantization).
- Value Range
Return Value
aclnnStatus: return status codes. For details, see aclnn return codes.
The first-phase API performs input parameter validation and returns an error in the following scenarios:
Return Value Error Code Description ACLNN_ERR_PARAM_NULLPTR 161001 A required input or output tensor is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is out of the supported range. ACLNN_ERR_INNER_TILING_ERROR 561002 The shape of the input or output is out of the supported range. The parameter value is out of the supported range.
aclnnMoeDistributeDispatchV2
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Size of the workspace allocated on the device, obtained by calling the first-phase API aclnnMoeDistributeDispatchV2GetWorkspaceSize.executor Input Op executor that contains the operator computation flow. stream Input Specifies the Stream for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
- aclnnMoeDistributeDispatchV2 defaults to a deterministic implementation.
Driver Constraints:
- The driver versions of all nodes in the operator communication domain must be the same.
API Compatibility Constraints:
- The
aclnnMoeDistributeDispatchV2API must be used together with the CombineV2 series operator APIs. For details, see Example. - Across different product models, communication algorithms, or versions, the element values in the Tensor outputs
assistInfoForCombineOut,epRecvCountsOut,tpRecvCountsOut, andexpandScalesOutofaclnnMoeDistributeDispatchV2may differ. During use, simply pass these tensors to the corresponding parameters of the CombineV2 series operator. Other business logic of the model should not depend on these values.
- The
Parameter Consistency Constraints:
- During the API call, the parameters
groupEp,epWorldSize,moeExpertNum,groupTp,tpWorldSize,expertShardType,sharedExpertNum,sharedExpertRankNum,globalBS, andcommAlg, as well as the value ofHCCL_BUFFSIZE, must be the same on all devices, the same across different layers of the network, and the same as the corresponding parameters of the CombineV2 series operator.
- During the API call, the parameters
Product-Specific Constraints:
Atlas A3 products : In this use case, a single device contains two DIEs (referred to as "die"). Therefore, "local device" in Parameters refers to a single DIE.
Shape Variable Constraints:
| Variable | Definition And Value Range |
|---|---|
| A | Maximum number of tokens to be dispatched by the current device. The value range is as follows:
|
| H (hidden size) | Indicates the hidden size.
|
| BS | Indicates the final number of tokens output by the local device.
|
| K | Number of topK experts selected. The value range is (0 < K ≤ 16), and (0 < K ≤ moeExpertNum) must be satisfied. |
| serverNum | Indicates the number of server nodes. Only 2, 4, and 8 are supported. Atlas A2 products: this variable is used only by the shape in this use case. |
| localExpertNum | Number of experts on the local device:
|
quantMode-related constraints:
Atlas A2 products :- When
quantModeis 0, indicating the non-quantization use case:- When the data type of
xisFLOAT16orBFLOAT16, pass a null pointer for the inputscalesOptional, and the data type ofexpandXis the same as that ofx. - When the data type of
xisINT32, onlycommAlgconfigured to "fullmesh" is supported. The inputscalesOptionalmust be a 1D Tensor with the data typeFLOAT32and the shape (BS, ); the data type ofexpandXisINT32, and the data type of the outputdynamicScalesOutisFLOAT32with the shape (A, ).
- When the data type of
- When
quantModeis set to 2, it indicates a per-token dynamic quantization scenario, and the data type ofexpandXsupportsINT8.- A null pointer can be passed for the input
scalesOptional. - If valid data is passed for the input
scalesOptional, its shape is (moeExpertNum,H). - The shape of the output
dynamicScalesOutis(A, )
- A null pointer can be passed for the input
- When
Atlas A3 products :- When
quantModeis 0, indicating the non-quantization use case, pass a null pointer for the inputscalesOptional; the data type ofexpandXcan beFLOAT16orBFLOAT16. - When
quantModeis set to 2, it indicates a per-token dynamic quantization scenario, and the data type ofexpandXsupportsINT8.- A null pointer can be passed for the input
scalesOptional. - If valid data is passed for the input
scalesOptionaland there are shared expert devices, its shape is (sharedExpertNum+moeExpertNum,H). - If valid data is passed for the input
scalesOptionaland there are no shared expert devices, its shape is (moeExpertNum,H). - The shape of the output
dynamicScalesOutis(A, )
- A null pointer can be passed for the input
- When
Ascend 950DT products :- When the value of
quantModeis 0, it indicates the non-quantization use case.- When the data type of
xisFLOAT16orBFLOAT16, the data type ofexpandXcan be the same as that ofxorHIFLOAT8, and a null pointer must be passed for the inputscalesOptional. - When the data type of
xisHIFLOAT8,FLOAT8_E5M2,FLOAT8_E4M3FN,FLOAT4_E2M1, orFLOAT4_E1M2, valid data must be passed to the inputscalesOptional, and the data type ofexpandXis the same as that ofx.- If the data type of
xisHIFLOAT8, the data type ofscalesOptionalisFLOAT. - If the data type of
xisFLOAT8_E5M2orFLOAT8_E4M3FN, the data type ofscalesOptionalisFLOATorFLOAT8_E8M0. - When the data type of
xisFLOAT4_E2M1orFLOAT4_E1M2, the data type ofscalesOptionalisFLOAT8_E8M0, and H must be an even number. - The shape of
scalesOptionalis (BS,dim1), wheredim1must be less than or equal toH.
- If the data type of
- When the data type of
- When
quantModeis 1, it indicates the static quantization use case.expandXsupports the data typesINT8andHIFLOAT8.- When the data type of
expandXisINT8, the following use cases exist:- The input
scalesOptionalindicates the quantization coefficient, and the shape is (1, ); - When the input
scalesOptionalindicates the smoothing weight shared by each expert, the shape is (H,); - When the input
scalesOptionalindicates the quantization coefficient fused with the smoothing weight of each expert, the shape is (sharedExpertNum+moeExpertNum,H) if there are shared expert devices, and (moeExpertNum,H) if there are no shared expert devices.
- The input
- When the data type of
expandXisHIFLOAT8, the shape ofscalesOptionalmust be (1, ).
- When the data type of
- When
quantModeis 2, it indicates the pertoken dynamic quantization use case.expandXsupports the data typesINT8,FLOAT8_E4M3FN, andFLOAT8_E5M2.- A null pointer can be passed for the input
scalesOptional. - If valid data is passed for the input
scalesOptionaland there are shared expert devices, its shape is (sharedExpertNum+moeExpertNum,H). - If valid data is passed for the input
scalesOptionaland there are no shared expert devices, its shape is (moeExpertNum,H). - The shape of the output
dynamicScalesOutis(A, )
- A null pointer can be passed for the input
- When
quantModeis set to 3, it indicates the pergroup dynamic quantization use case. expandX supports the data typesFLOAT8_E4M3FNandFLOAT8_E5M2.- A null pointer can be passed for the input
scalesOptional. - If valid data is passed for the input
scalesOptionaland there are shared expert devices, its shape is (sharedExpertNum+moeExpertNum,H). - If valid data is passed for the input
scalesOptionaland there are no shared expert devices, its shape is (moeExpertNum,H). - The shape of the output
dynamicScalesOutis(A, Ceil(H, 128)), whereCeil(H, 128) = (H + 128 - 1) / 128
- A null pointer can be passed for the input
- When
quantModeis set to 4, it indicates the mx quantization use case.expandXsupports the data typesFLOAT8_E4M3FN,FLOAT8_E5M2,FLOAT4_E2M1, andFLOAT4_E1M2. A null pointer must be passed for the inputscalesOptional. The shape of the outputdynamicScalesOutis(A, Ceil(H, 64)), whereCeil(H, 64) = (H + 64 - 1) / 64. If the data type ofexpandXisFLOAT4_E2M1orFLOAT4_E1M2, H must be an even number.
- When the value of
Environment Variable Constraints:
HCCL_BUFFSIZE: Before calling this API, check whether the value of the
HCCL_BUFFSIZEenvironment variable is appropriate. This environment variable specifies the memory size occupied by a single communication domain, in MB. The default value is 200 MB when not configured:<!-- npu="910b" id16 --> - <term>Atlas A2 products</term>: - commAlg is "" or nullptr: the "fullmesh" or "hierarchy" formula is selected based on HCCL environment variables. - commAlg is "fullmesh": when the data type of `x` is `INT32`, the size requirement is (≥ 2 \* (BS \* epWorldSize \* min(localExpertNum, K) \* (H \* sizeof(int32) + 32B) + 2MB)); for other data types, the size requirement is (≥ 2 \* (BS \* epWorldSize \* min(localExpertNum, K) \* H \* sizeof(uint16) + 2MB)). - commAlg is "hierarchy": the size requirement is (≥ (`moeExpertNum` + `epWorldSize` / 4) \* Align512(`maxBS` \* (`H` \* 2 + 16 \* Align8 (`K`))) \* 1B + 8MB, where Align8(x) = ((x + 8 - 1) / 8) \* 8 and Align512(x) = ((x + 512 - 1) / 512) \* 512). <!-- end id16 --> <!-- npu="A3" id17 --> - <term>Atlas A3 products</term> : - In the ep communication domain: the size requirement is (≥ 2) and must satisfy (≥ 2 \* (localExpertNum \* maxBS \* epWorldSize \* Align512(Align32(2 \* H) + 64) + (K + sharedExpertNum) \* maxBS \* Align512(2 \* H))) (`localExpertNum` must use the number of local experts on the MoE expert card; `Align512(x) = ((x + 512 - 1) / 512) * 512`; `Align32(x) = ((x + 32 - 1) / 32) * 32`). Currently, the TP communication domain is not supported. <!-- end id17 --> <!-- npu="950" id18 --> - <term>Ascend 950DT products</term>: Set the size in the EP communication domain to (≥ 2) and ensure it satisfies (≥ 2 \* (localExpertNum \* maxBS \* epWorldSize \* Align512(Align32(2 \* H) + 64) + (K + sharedExpertNum) \* maxBS \* Align512(2 \* H))) (`localExpertNum` must be set to the number of local experts on the MoE expert card; `Align512(x) = ((x + 512 - 1) / 512) * 512`; `Align32(x) = ((x + 32 - 1) / 32) * 32`). The TP communication domain is not supported. <!-- end id18 -->HCCL_INTRA_PCIE_ENABLE and HCCL_INTRA_ROCE_ENABLE:
Atlas A2 products : This environment variable is no longer recommended. SetcommAlgto "hierarchy" instead.
Atlas A3 products and Ascend 950DT products: This environment variable is not supported.
Communication Domain Usage Constraints:
- The CombineV2 series operator and
aclnnMoeDistributeDispatchV2in a model support only the same EP communication domain, and no other operators are allowed in the communication domain. - TP domain communication is not supported currently.
Atlas A3 products : Nodes in a communication domain must be within one SuperPoD. Cross-SuperPoD deployment is not supported.
- The CombineV2 series operator and
Communication mode constraints:
Ascend 950DT products : Only UB Memory communication is supported.
Networking Constraints:
Atlas A2 products : For multi-node use cases, only switch networking is supported. Direct networking between two nodes is not supported.
Other Constraints:
- In the formula, "/" indicates integer division.
Example
Environment variable configuration:
# Set an environment variable before running. ## ENV_DEV_NUM description: Set this variable based on the number of devices on the current machine. For example, with 16 devices on two machines, set both machines to 16. export ENV_DEV_NUM=16Number of machines:
In a two-machine 16-NPU scenario, set the MACHINE_NUM parameter to 2, that is,
const uint32_t MACHINE_NUM = 2;No modification is required for a single-machine 16-NPU scenario.
Atlas A2 products :No need to configure the ranktable file or the environment variables RANK_TABLE_FILE and FIRST_RANK_ID.
This example supports running the A2 operator on a single-server environment with a device count of [2, 8]. Before running, set IS_TEST_A2 to true in the sample code to ensure that the A2 branch is executed. In addition, if needed, set EP_WORLD_SIZE_A2 in the sample code to the number of devices and change moeExpertNum in the launchOneThreadDispatchV2AndCombineV2_A2 function so that moeExpertNum is divisible by EP_WORLD_SIZE_A2.
The operator compilation commands are as follows. Both the moe_distribute_dispatch_v2 and moe_distribute_combine_v2 operators must be compiled, and the two operators must be executed in pairs:
bash build.sh --pkg --soc=ascend910b --ops=moe_distribute_dispatch_v2,moe_distribute_combine_v2The sample operator execution commands are as follows:
bash build.sh --run_example --ops=moe_distribute_dispatch_v2 eager cust
Atlas A3 products andAscend 950DT products :No need to configure the ranktable file or the environment variables RANK_TABLE_FILE and FIRST_RANK_ID.
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
Atlas A2 products ,Atlas A3 products , andAscend 950DT products :#include <thread> #include <iostream> #include <string> #include <cstring> #include <vector> #include <memory> #include <cstdio> #include "acl/acl.h" #include "hccl/hccl.h" #include "aclnn/opdev/fp16_t.h" #include "aclnnop/aclnn_moe_distribute_dispatch_v2.h" #include "aclnnop/aclnn_moe_distribute_combine_v2.h" #define CHECK_RET(cond, return_expr) \ do { \ if (!(cond)) { \ return_expr; \ } \ } while (0) #define LOG_PRINT(message, ...) \ do { \ printf(message, ##__VA_ARGS__); \ } while (0) struct Args { uint32_t rankId; uint32_t epRankId; HcclComm hcclEpComm; aclrtStream dispatchV2Stream; aclrtStream combineV2Stream; aclrtContext context; }; const uint32_t MACHINE_NUM = 1; const char* env_dev_num = std::getenv("ENV_DEV_NUM"); const uint32_t EP_WORLD_SIZE = 2; const uint32_t DEV_NUM = EP_WORLD_SIZE; const bool IS_TEST_A2 = false; const bool IS_TEST_A3A5 = true; const uint32_t EP_WORLD_SIZE_A2 = 8; const uint32_t DEV_NUM_A2 = EP_WORLD_SIZE_A2; int64_t GetShapeSize(const std::vector<int64_t> &shape) { int64_t shape_size = 1; for (auto i : shape) { shape_size *= i; } return shape_size; } template<typename T> int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr, aclDataType dataType, aclTensor **tensor) { auto size = GetShapeSize(shape) * sizeof(T); auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtMalloc failed. ret: %d\n", ret); return ret); ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtMemcpy failed. ret: %d\n", ret); return ret); std::vector<int64_t> strides(shape.size(), 1); for (int64_t i = shape.size() - 2; i >= 0; i--) { strides[i] = shape[i + 1] * strides[i + 1]; } *tensor = aclCreateTensor( shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND, shape.data(), shape.size(), *deviceAddr ); return 0; } void DestroyTensor(aclTensor *tensor) { if (tensor != nullptr) { aclDestroyTensor(tensor); } } void FreeDeviceAddr(void *deviceAddr) { if (deviceAddr != nullptr) { aclrtFree(deviceAddr); } } int launchOneThreadDispatchV2AndCombineV2_A3A5(Args &args) { int ret = aclrtSetCurrentContext(args.context); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtSetCurrentContext failed. ret: %d\n", ret); return ret); char hcomEpName[128] = {0}; ret = HcclGetCommName(args.hcclEpComm, hcomEpName); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclGetEpCommName failed. ret: %d\n", ret); return -1); LOG_PRINT( "[INFO] rank = %d, hcomEpName = %s, dispatchV2Stream = %p, combineV2Stream = %p, context = %p\n", args.rankId, hcomEpName, args.dispatchV2Stream, args.combineV2Stream, args.context ); // Set the use case. int64_t BS = 8; int64_t H = 7168; int64_t K = 1; int64_t expertShardType = 0; int64_t sharedExpertNum = 0; int64_t sharedExpertRankNum = 0; int64_t moeExpertNum = EP_WORLD_SIZE - sharedExpertRankNum; int64_t quantMode = 0; int64_t globalBS = BS * EP_WORLD_SIZE; int64_t expertTokenNumsType = 0; int64_t outDtype = 0; int64_t commQuantMode = 0; int64_t groupListType = 0; int64_t localExpertNum; int64_t A; if (args.epRankId < sharedExpertRankNum) { // Shared expert card. localExpertNum = 1; A = globalBS / sharedExpertRankNum; } else { // MoE expert card localExpertNum = moeExpertNum / (EP_WORLD_SIZE - sharedExpertRankNum); A = globalBS * (localExpertNum < K ? localExpertNum : K); } std::string commAlg = ""; /* Construct device-side input and output variables based on the current use case. */ // Declare device-side input and output variables. void *xDeviceAddr = nullptr; void *expertIdsDeviceAddr = nullptr; void *scalesDeviceAddr = nullptr; void *expertScalesDeviceAddr = nullptr; void *expandXDeviceAddr = nullptr; void *dynamicScalesDeviceAddr = nullptr; void *expandIdxDeviceAddr = nullptr; void *expertTokenNumsDeviceAddr = nullptr; void *epRecvCountsDeviceAddr = nullptr; void *tpRecvCountsDeviceAddr = nullptr; void *expandScalesDeviceAddr = nullptr; aclTensor *x = nullptr; aclTensor *expertIds = nullptr; aclTensor *scales = nullptr; aclTensor *expertScales = nullptr; aclTensor *expandX = nullptr; aclTensor *dynamicScales = nullptr; aclTensor *expandIdx = nullptr; aclTensor *expertTokenNums = nullptr; aclTensor *epRecvCounts = nullptr; aclTensor *tpRecvCounts = nullptr; aclTensor *expandScales = nullptr; // Define the dimensions of each variable in the current use case. std::vector<int64_t> xShape{BS, H}; std::vector<int64_t> expertIdsShape{BS, K}; std::vector<int64_t> scalesShape{(sharedExpertRankNum > 0) ? 1 + moeExpertNum : moeExpertNum, H}; std::vector<int64_t> expertScalesShape{BS, K}; std::vector<int64_t> expandXShape{A, H}; std::vector<int64_t> dynamicScalesShape{A}; std::vector<int64_t> expandIdxShape{A * 128}; std::vector<int64_t> expertTokenNumsShape{localExpertNum}; std::vector<int64_t> epRecvCountsShape{localExpertNum * EP_WORLD_SIZE}; std::vector<int64_t> tpRecvCountsShape{1}; std::vector<int64_t> expandScalesShape{A}; long long xShapeSize = GetShapeSize(xShape); long long expertIdsShapeSize = GetShapeSize(expertIdsShape); long long scalesShapeSize = GetShapeSize(scalesShape); long long expertScalesShapeSize = GetShapeSize(expertScalesShape); long long expandXShapeSize = GetShapeSize(expandXShape); long long dynamicScalesShapeSize = GetShapeSize(dynamicScalesShape); long long expandIdxShapeSize = GetShapeSize(expandIdxShape); long long expertTokenNumsShapeSize = GetShapeSize(expertTokenNumsShape); long long epRecvCountsShapeSize = GetShapeSize(epRecvCountsShape); long long tpRecvCountsShapeSize = GetShapeSize(tpRecvCountsShape); long long expandScalesShapeSize = GetShapeSize(expandScalesShape); // Construct host-side variables. std::vector<op::fp16_t> xHostData(xShapeSize, 1); std::vector<int32_t> expertIdsHostData; for (int32_t token_id = 0; token_id < expertIdsShape[0]; token_id++) { // Each token is dispatched to MoE experts {0, 1, ... k - 1}. for (int32_t k_id = 0; k_id < expertIdsShape[1]; k_id++) { expertIdsHostData.push_back(k_id); } } std::vector<float> scalesHostData(scalesShapeSize, 0); std::vector<float> expertScalesHostData(expertScalesShapeSize, 0); std::vector<op::fp16_t> expandXHostData(expandXShapeSize, 0); std::vector<float> dynamicScalesHostData(dynamicScalesShapeSize, 0); std::vector<int32_t> expandIdxHostData(expandIdxShapeSize, 0); std::vector<int64_t> expertTokenNumsHostData(expertTokenNumsShapeSize, 0); std::vector<int32_t> epRecvCountsHostData(epRecvCountsShapeSize, 0); std::vector<int32_t> tpRecvCountsHostData(tpRecvCountsShapeSize, 0); std::vector<float> expandScalesHostData(expandScalesShapeSize, 0); // Construct device-side variables. ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_BF16, &x); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(expertIdsHostData, expertIdsShape, &expertIdsDeviceAddr, aclDataType::ACL_INT32, &expertIds); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(scalesHostData, scalesShape, &scalesDeviceAddr, aclDataType::ACL_FLOAT, &scales); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(expertScalesHostData, expertScalesShape, &expertScalesDeviceAddr, aclDataType::ACL_FLOAT, &expertScales); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(expandXHostData, expandXShape, &expandXDeviceAddr, (quantMode > 0) ? aclDataType::ACL_INT8 : aclDataType::ACL_BF16, &expandX); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(dynamicScalesHostData, dynamicScalesShape, &dynamicScalesDeviceAddr, aclDataType::ACL_FLOAT, &dynamicScales); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(expandIdxHostData, expandIdxShape, &expandIdxDeviceAddr, aclDataType::ACL_INT32, &expandIdx); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(expertTokenNumsHostData, expertTokenNumsShape, &expertTokenNumsDeviceAddr, aclDataType::ACL_INT64, &expertTokenNums); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(epRecvCountsHostData, epRecvCountsShape, &epRecvCountsDeviceAddr, aclDataType::ACL_INT32, &epRecvCounts); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(tpRecvCountsHostData, tpRecvCountsShape, &tpRecvCountsDeviceAddr, aclDataType::ACL_INT32, &tpRecvCounts); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(expandScalesHostData, expandScalesShape, &expandScalesDeviceAddr, aclDataType::ACL_FLOAT, &expandScales); CHECK_RET(ret == ACL_SUCCESS, return ret); /* Declare variables required for operator execution. */ uint64_t dispatchV2WorkspaceSize = 0; aclOpExecutor *dispatchV2Executor = nullptr; void *dispatchV2WorkspaceAddr = nullptr; uint64_t combineV2WorkspaceSize = 0; aclOpExecutor *combineV2Executor = nullptr; void *combineV2WorkspaceAddr = nullptr; /* Execute the dispatchV2 and combineV2 operators in sequence. */ // Call the first-phase API of the dispatchV2 operator. ret = aclnnMoeDistributeDispatchV2GetWorkspaceSize( x, expertIds, (quantMode > 0 ? scales : nullptr), nullptr, expertScales, hcomEpName, EP_WORLD_SIZE, args.epRankId, moeExpertNum, "", 0, 0, expertShardType, sharedExpertNum, sharedExpertRankNum, quantMode, globalBS, expertTokenNumsType, commAlg.c_str(), expandX, dynamicScales, expandIdx, expertTokenNums, epRecvCounts, tpRecvCounts, expandScales, &dispatchV2WorkspaceSize, &dispatchV2Executor ); CHECK_RET( ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnMoeDistributeDispatchV2GetWorkspaceSize failed. ret = %d\n", ret); return ret ); // Allocate device memory based on the workspaceSize computed by the first-phase API of the dispatchV2 operator. if (dispatchV2WorkspaceSize > 0) { ret = aclrtMalloc(&dispatchV2WorkspaceAddr, dispatchV2WorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtMalloc failed. ret = %d\n", ret); return ret); } // Call the second-phase API of the dispatchV2 operator. ret = aclnnMoeDistributeDispatchV2(dispatchV2WorkspaceAddr, dispatchV2WorkspaceSize, dispatchV2Executor, args.dispatchV2Stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnMoeDistributeDispatchV2 failed. ret = %d\n", ret); return ret); // (boilerplate) Synchronize and wait for the task execution to complete. ret = aclrtSynchronizeStreamWithTimeout(args.dispatchV2Stream, 10000); CHECK_RET( ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtSynchronizeStreamWithTimeout failed. ret = %d\n", ret); return ret ); // Call the first-phase API of the combineV2 operator. ret = aclnnMoeDistributeCombineV2GetWorkspaceSize( expandX, expertIds, expandIdx, epRecvCounts, expertScales, tpRecvCounts, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, hcomEpName, EP_WORLD_SIZE, args.epRankId, moeExpertNum, "", 0, 0, expertShardType, sharedExpertNum, sharedExpertRankNum, globalBS, outDtype, commQuantMode, groupListType, commAlg.c_str(), x, &combineV2WorkspaceSize, &combineV2Executor); CHECK_RET( ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnMoeDistributeCombineV2GetWorkspaceSize failed. ret = %d\n", ret); return ret ); // Allocate device memory based on the workspaceSize computed by the first-phase API of the combineV2 operator. if (combineV2WorkspaceSize > 0) { ret = aclrtMalloc(&combineV2WorkspaceAddr, combineV2WorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtMalloc failed. ret = %d\n", ret); return ret); } // Call the second-phase API of the combineV2 operator. ret = aclnnMoeDistributeCombineV2(combineV2WorkspaceAddr, combineV2WorkspaceSize, combineV2Executor, args.combineV2Stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnMoeDistributeCombineV2 failed. ret = %d\n", ret); return ret); // (boilerplate) Synchronize and wait for the task execution to complete. ret = aclrtSynchronizeStreamWithTimeout(args.combineV2Stream, 10000); CHECK_RET( ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtSynchronizeStreamWithTimeout failed. ret = %d\n", ret); return ret ); LOG_PRINT("[INFO] device_%d aclnnMoeDistributeDispatchV2 and aclnnMoeDistributeCombineV2 execute successfully.\n", args.rankId); // Release device resources. if (dispatchV2WorkspaceSize > 0) { aclrtFree(dispatchV2WorkspaceAddr); } if (combineV2WorkspaceSize > 0) { aclrtFree(combineV2WorkspaceAddr); } DestroyTensor(x); DestroyTensor(expertIds); DestroyTensor(scales); DestroyTensor(expertScales); DestroyTensor(expandX); DestroyTensor(dynamicScales); DestroyTensor(expandIdx); DestroyTensor(expertTokenNums); DestroyTensor(epRecvCounts); DestroyTensor(tpRecvCounts); DestroyTensor(expandScales); FreeDeviceAddr(xDeviceAddr); FreeDeviceAddr(expertIdsDeviceAddr); FreeDeviceAddr(scalesDeviceAddr); FreeDeviceAddr(expertScalesDeviceAddr); FreeDeviceAddr(expandXDeviceAddr); FreeDeviceAddr(dynamicScalesDeviceAddr); FreeDeviceAddr(expandIdxDeviceAddr); FreeDeviceAddr(expertTokenNumsDeviceAddr); FreeDeviceAddr(epRecvCountsDeviceAddr); FreeDeviceAddr(tpRecvCountsDeviceAddr); FreeDeviceAddr(expandScalesDeviceAddr); HcclCommDestroy(args.hcclEpComm); aclrtDestroyStream(args.dispatchV2Stream); aclrtDestroyStream(args.combineV2Stream); aclrtDestroyContext(args.context); aclrtResetDevice(args.rankId); return 0; } int launchOneThreadDispatchV2AndCombineV2_A2(Args &args) { int ret = aclrtSetCurrentContext(args.context); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtSetCurrentContext failed, ret %d\n", ret); return ret); char hcomEpName[128] = {0}; ret = HcclGetCommName(args.hcclEpComm, hcomEpName); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclGetEpCommName failed, ret %d\n", ret); return -1); LOG_PRINT("[INFO] rank = %d, hcomEpName = %s, dispatchV2Stream = %p, combineV2Stream = %p, \ context = %p\n", args.rankId, hcomEpName, args.dispatchV2Stream, args.combineV2Stream, \ args.context); int64_t BS = 32; int64_t H = 7168; int64_t K = 8; int64_t expertShardType = 0; int64_t sharedExpertNum = 0; int64_t sharedExpertRankNum = 0; int64_t moeExpertNum = 256; int64_t quantMode = 0; int64_t globalBS = BS * EP_WORLD_SIZE_A2; int64_t expertTokenNumsType = 1; int64_t outDtype = 0; int64_t commQuantMode = 0; int64_t groupList_type = 1; int64_t localExpertNum; int64_t A; std::string commAlg = "fullmesh"; if (args.epRankId < sharedExpertRankNum) { localExpertNum = 1; A = globalBS / sharedExpertRankNum; } else { localExpertNum = moeExpertNum / (EP_WORLD_SIZE_A2 - sharedExpertRankNum); A = globalBS * (localExpertNum < K ? localExpertNum : K); } void *xDeviceAddr = nullptr; void *expertIdsDeviceAddr = nullptr; void *scalesDeviceAddr = nullptr; void *expertScalesDeviceAddr = nullptr; void *expandXDeviceAddr = nullptr; void *dynamicScalesDeviceAddr = nullptr; void *assistInfoForCombineDeviceAddr = nullptr; void *expertTokenNumsDeviceAddr = nullptr; void *epRecvCountsDeviceAddr = nullptr; void *tpRecvCountsDeviceAddr = nullptr; void *expandScalesDeviceAddr = nullptr; void *xOutDeviceAddr = nullptr; aclTensor *x = nullptr; aclTensor *expertIds = nullptr; aclTensor *scales = nullptr; aclTensor *xActiveMask = nullptr; aclTensor *expertScales = nullptr; aclTensor *elasticInfo = nullptr; // A3 aclTensor *expandX = nullptr; aclTensor *dynamicScales = nullptr; aclTensor *assistInfoForCombine = nullptr; // expandIdx aclTensor *expertTokenNums = nullptr; aclTensor *epRecvCounts = nullptr; aclTensor *tpRecvCounts = nullptr; aclTensor *expandScales = nullptr; aclTensor *activationScale = nullptr; // Reserved parameter. aclTensor *weightScale = nullptr; // Reserved parameter. aclTensor *groupList = nullptr; // Reserved parameter aclTensor *sharedExpertX = nullptr; // A3 aclTensor *xOut = nullptr; // Define the dimensions of variables for the current use case. std::vector<int64_t> xShape{BS, H}; std::vector<int64_t> expertIdsShape{BS, K}; std::vector<int64_t> scalesShape{moeExpertNum + 1, H}; std::vector<int64_t> expertScalesShape{BS, K}; std::vector<int64_t> expandXShape{A, H}; std::vector<int64_t> dynamicScalesShape{A}; std::vector<int64_t> assistInfoForCombineShape{A * 128}; std::vector<int64_t> expertTokenNumsShape{localExpertNum}; std::vector<int64_t> epRecvCountsShape{localExpertNum * EP_WORLD_SIZE_A2}; // No layering std::vector<int64_t> tpRecvCountsShape{1}; std::vector<int64_t> expandScalesShape{A}; std::vector<int64_t> xOutShape{BS, H}; int64_t xShapeSize = GetShapeSize(xShape); int64_t expertIdsShapeSize = GetShapeSize(expertIdsShape); int64_t scalesShapeSize = GetShapeSize(scalesShape); int64_t expertScalesShapeSize = GetShapeSize(expertScalesShape); int64_t expandXShapeSize = GetShapeSize(expandXShape); int64_t dynamicScalesShapeSize = GetShapeSize(dynamicScalesShape); int64_t assistInfoForCombineShapeSize = GetShapeSize(assistInfoForCombineShape); int64_t expertTokenNumsShapeSize = GetShapeSize(expertTokenNumsShape); int64_t epRecvCountsShapeSize = GetShapeSize(epRecvCountsShape); int64_t tpRecvCountsShapeSize = GetShapeSize(tpRecvCountsShape); int64_t expandScalesShapeSize = GetShapeSize(expandScalesShape); int64_t xOutShapeSize = GetShapeSize(xOutShape); std::vector<int16_t> xHostData(xShapeSize, 1); std::vector<int32_t> expertIdsHostData; for (int32_t token_id = 0; token_id < expertIdsShape[0]; token_id++) { for (int32_t k_id = 0; k_id < expertIdsShape[1]; k_id++) { expertIdsHostData.push_back(k_id); } } std::vector<float> scalesHostData(scalesShapeSize, 0.1); std::vector<float> expertScalesHostData(expertScalesShapeSize, 0.1); std::vector<int16_t> expandXHostData(expandXShapeSize, 0); std::vector<float> dynamicScalesHostData(dynamicScalesShapeSize, 0); std::vector<int32_t> assistInfoForCombineHostData(assistInfoForCombineShapeSize, 0); std::vector<int64_t> expertTokenNumsHostData(expertTokenNumsShapeSize, 0); std::vector<int32_t> epRecvCountsHostData(epRecvCountsShapeSize, 0); std::vector<int32_t> tpRecvCountsHostData(tpRecvCountsShapeSize, 0); std::vector<float> expandScalesHostData(expandScalesShapeSize, 0); std::vector<int16_t> xOutHostData(xOutShapeSize, 0); ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_BF16, &x); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(expertIdsHostData, expertIdsShape, &expertIdsDeviceAddr, aclDataType::ACL_INT32, &expertIds); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(scalesHostData, scalesShape, &scalesDeviceAddr, aclDataType::ACL_FLOAT, &scales); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(expertScalesHostData, expertScalesShape, &expertScalesDeviceAddr, aclDataType::ACL_FLOAT, &expertScales); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(expandXHostData, expandXShape, &expandXDeviceAddr, (quantMode > 0) ? aclDataType::ACL_INT8 : aclDataType::ACL_BF16, &expandX); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(dynamicScalesHostData, dynamicScalesShape, &dynamicScalesDeviceAddr, aclDataType::ACL_FLOAT, &dynamicScales); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(assistInfoForCombineHostData, assistInfoForCombineShape, &assistInfoForCombineDeviceAddr, aclDataType::ACL_INT32, &assistInfoForCombine); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(expertTokenNumsHostData, expertTokenNumsShape, &expertTokenNumsDeviceAddr, aclDataType::ACL_INT64, &expertTokenNums); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(epRecvCountsHostData, epRecvCountsShape, &epRecvCountsDeviceAddr, aclDataType::ACL_INT32, &epRecvCounts); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(tpRecvCountsHostData, tpRecvCountsShape, &tpRecvCountsDeviceAddr, aclDataType::ACL_INT32, &tpRecvCounts); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(expandScalesHostData, expandScalesShape, &expandScalesDeviceAddr, aclDataType::ACL_FLOAT, &expandScales); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(xOutHostData, xOutShape, &xOutDeviceAddr, aclDataType::ACL_BF16, &xOut); CHECK_RET(ret == ACL_SUCCESS, return ret); uint64_t dispatchWorkspaceSize = 0; aclOpExecutor *dispatchExecutor = nullptr; void *dispatchWorkspaceAddr = nullptr; uint64_t combineWorkspaceSize = 0; aclOpExecutor *combineExecutor = nullptr; void *combineWorkspaceAddr = nullptr; /**************************************** Call dispatch ********************************************/ // Call the first-phase API. ret = aclnnMoeDistributeDispatchV2GetWorkspaceSize(x, expertIds, (quantMode > 0 ? scales : nullptr), xActiveMask, expertScales, hcomEpName, EP_WORLD_SIZE_A2, args.epRankId, moeExpertNum, "", 0, 0, expertShardType, sharedExpertNum, sharedExpertRankNum, quantMode, globalBS, expertTokenNumsType, commAlg.c_str(), expandX, dynamicScales, assistInfoForCombine, expertTokenNums, epRecvCounts, tpRecvCounts, expandScales, &dispatchWorkspaceSize, &dispatchExecutor); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnMoeDistributeDispatchV2GetWorkspaceSize failed. ret = %d \n", ret); return ret); if (dispatchWorkspaceSize > 0) { ret = aclrtMalloc(&dispatchWorkspaceAddr, dispatchWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtMalloc workspace failed. ret = %d \n", ret); return ret); } // Call the second-phase API. ret = aclnnMoeDistributeDispatchV2(dispatchWorkspaceAddr, dispatchWorkspaceSize, dispatchExecutor, args.dispatchV2Stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnMoeDistributeDispatchV2 failed. ret = %d \n", ret); \ return ret); ret = aclrtSynchronizeStreamWithTimeout(args.dispatchV2Stream, 10000); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] dispatch aclrtSynchronizeStreamWithTimeout failed. ret = %d \n", ret); \ return ret); LOG_PRINT("[INFO] device_%d aclnnMoeDistributeDispatchV2 execute successfully.\n", args.rankId); /**************************************** Call combine ********************************************/ // Call the first-phase API. ret = aclnnMoeDistributeCombineV2GetWorkspaceSize(expandX, expertIds, assistInfoForCombine, epRecvCounts, expertScales, tpRecvCounts, xActiveMask, activationScale, weightScale, groupList, expandScales, sharedExpertX, hcomEpName, EP_WORLD_SIZE_A2, args.epRankId, moeExpertNum, "", 0, 0, expertShardType, sharedExpertNum, sharedExpertRankNum, globalBS, outDtype, commQuantMode, groupList_type, commAlg.c_str(), xOut, &combineWorkspaceSize, &combineExecutor); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnMoeDistributeCombineV2GetWorkspaceSize failed. ret = %d \n", ret); return ret); // Allocate device memory based on the workspaceSize computed by the first-phase API. if (combineWorkspaceSize > 0) { ret = aclrtMalloc(&combineWorkspaceAddr, combineWorkspaceSize, ACL_MEM_MALLOC_HUGE_FIRST); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtMalloc workspace failed. ret = %d \n", ret); return ret); } // Call the second-phase API. ret = aclnnMoeDistributeCombineV2(combineWorkspaceAddr, combineWorkspaceSize, combineExecutor, args.combineV2Stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnMoeDistributeCombineV2 failed. ret = %d \n", ret); return ret); // (Boilerplate) Synchronize and wait for the task execution to complete. ret = aclrtSynchronizeStreamWithTimeout(args.combineV2Stream, 10000); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtSynchronizeStreamWithTimeout failed. ret = %d \n", ret); return ret); LOG_PRINT("[INFO] device_%d aclnnMoeDistributeDispatchV2 and aclnnMoeDistributeCombineV2 \ execute successfully.\n", args.rankId); // Release device resources. if (dispatchWorkspaceSize > 0) { aclrtFree(dispatchWorkspaceAddr); } if (combineWorkspaceSize > 0) { aclrtFree(combineWorkspaceAddr); } DestroyTensor(x); DestroyTensor(expertIds); DestroyTensor(scales); DestroyTensor(xActiveMask); DestroyTensor(expertScales); DestroyTensor(elasticInfo); DestroyTensor(expandX); DestroyTensor(dynamicScales); DestroyTensor(assistInfoForCombine); DestroyTensor(expertTokenNums); DestroyTensor(epRecvCounts); DestroyTensor(tpRecvCounts); DestroyTensor(expandScales); DestroyTensor(activationScale); DestroyTensor(weightScale); DestroyTensor(groupList); DestroyTensor(sharedExpertX); DestroyTensor(xOut); FreeDeviceAddr(xDeviceAddr); FreeDeviceAddr(expertIdsDeviceAddr); FreeDeviceAddr(scalesDeviceAddr); FreeDeviceAddr(expertScalesDeviceAddr); FreeDeviceAddr(expandXDeviceAddr); FreeDeviceAddr(dynamicScalesDeviceAddr); FreeDeviceAddr(assistInfoForCombineDeviceAddr); FreeDeviceAddr(expertTokenNumsDeviceAddr); FreeDeviceAddr(epRecvCountsDeviceAddr); FreeDeviceAddr(tpRecvCountsDeviceAddr); FreeDeviceAddr(expandScalesDeviceAddr); FreeDeviceAddr(xOutDeviceAddr); HcclCommDestroy(args.hcclEpComm); aclrtDestroyStream(args.dispatchV2Stream); aclrtDestroyStream(args.combineV2Stream); aclrtDestroyContext(args.context); LOG_PRINT("[INFO] device_%d Destroy.\n", args.rankId); aclrtResetDevice(args.rankId); LOG_PRINT("[INFO] device_%d Reset.\n", args.rankId); return 0; } int run_example_on_A2() { int ret = aclInit(nullptr); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclInit failed, ret = %d\n", ret); return ret); aclrtStream dispatchV2Stream[DEV_NUM_A2]; aclrtStream combineV2Stream[DEV_NUM_A2]; aclrtContext context[DEV_NUM_A2]; for (uint32_t rankId = 0; rankId < DEV_NUM_A2; rankId++) { ret = aclrtSetDevice(rankId); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtSetDevice failed, ret = %d\n", ret); return ret); ret = aclrtCreateContext(&context[rankId], rankId); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtCreateContext failed, ret = %d\n", ret); return ret); ret = aclrtCreateStream(&dispatchV2Stream[rankId]); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtCreateStream failed, ret = %d\n", ret); return ret); ret = aclrtCreateStream(&combineV2Stream[rankId]); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtCreateStream failed, ret = %d\n", ret); return ret); } int32_t devicesEp[EP_WORLD_SIZE_A2]; for (int32_t epId = 0; epId < EP_WORLD_SIZE_A2; epId++) { devicesEp[epId] = epId; } HcclComm commsEp[EP_WORLD_SIZE_A2]; ret = HcclCommInitAll(EP_WORLD_SIZE_A2, devicesEp, commsEp); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclCommInitAll ep failed, ret %d\n", ret); return ret); Args args[DEV_NUM_A2]; std::vector<std::unique_ptr<std::thread>> threads(DEV_NUM_A2); for (uint32_t rankId = 0; rankId < DEV_NUM_A2; rankId++) { uint32_t epRankId = rankId; args[rankId].rankId = rankId; args[rankId].epRankId = epRankId; args[rankId].hcclEpComm = commsEp[epRankId]; args[rankId].dispatchV2Stream = dispatchV2Stream[rankId]; args[rankId].combineV2Stream = combineV2Stream[rankId]; args[rankId].context = context[rankId]; threads[rankId].reset(new (std::nothrow) std::thread(&launchOneThreadDispatchV2AndCombineV2_A2, std::ref(args[rankId]))); } for (uint32_t rankId = 0; rankId < DEV_NUM_A2; rankId++) { threads[rankId]->join(); } aclFinalize(); LOG_PRINT("[INFO] aclFinalize success\n"); return 0; } int run_example_on_A3A5() { int ret = aclInit(nullptr); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclInit failed. ret = %d\n", ret); return ret); aclrtStream dispatchV2Stream[DEV_NUM]; aclrtStream combineV2Stream[DEV_NUM]; aclrtContext context[DEV_NUM]; for (uint32_t rankId = 0; rankId < DEV_NUM; rankId++) { ret = aclrtSetDevice(rankId); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtSetDevice failed. ret = %d\n", ret); return ret); ret = aclrtCreateContext(&context[rankId], rankId); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtCreateContext failed. ret = %d\n", ret); return ret); ret = aclrtCreateStream(&dispatchV2Stream[rankId]); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtCreateStream failed. ret = %d\n", ret); return ret); ret = aclrtCreateStream(&combineV2Stream[rankId]); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtCreateStream failed. ret = %d\n", ret); return ret); } int32_t devicesEp[EP_WORLD_SIZE]; for (int32_t epId = 0; epId < EP_WORLD_SIZE; epId++) { devicesEp[epId] = epId; } // Initialize the EP communication domain. HcclComm commsEp[EP_WORLD_SIZE]; ret = HcclCommInitAll(EP_WORLD_SIZE, devicesEp, commsEp); CHECK_RET( ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclCommInitAll ep failed. ret = %d\n", ret); return ret ); Args args[DEV_NUM]; // Each thread calls its own device to execute the operator. std::vector<std::unique_ptr<std::thread>> threads(DEV_NUM); for (uint32_t rankId = 0; rankId < DEV_NUM; rankId++) { uint32_t epRankId = rankId; args[rankId].rankId = rankId; args[rankId].epRankId = epRankId; args[rankId].hcclEpComm = commsEp[epRankId]; args[rankId].dispatchV2Stream = dispatchV2Stream[rankId]; args[rankId].combineV2Stream = combineV2Stream[rankId]; args[rankId].context = context[rankId]; threads[rankId].reset(new (std::nothrow) std::thread(&launchOneThreadDispatchV2AndCombineV2_A3A5, std::ref(args[rankId]))); } for (uint32_t rankId = 0; rankId < DEV_NUM; rankId++) { threads[rankId]->join(); } aclFinalize(); LOG_PRINT("[INFO] aclFinalize success\n"); return 0; } int main(int argc, char *argv[]) { if (!env_dev_num) { LOG_PRINT("[WARNING] Please check whether environment variable ENV_DEV_NUM is set correctly.\n"); return 0; } int actual_env_dev_num = std::stoi(std::string(env_dev_num)); if (actual_env_dev_num < DEV_NUM) { LOG_PRINT("[INFO] ENV_DEV_NUM = %d is less than %d, currently not supported\n", actual_env_dev_num, DEV_NUM); return 0; } if (IS_TEST_A2) { LOG_PRINT("Example on <Atlas A2> will be executed!\n"); int ret = run_example_on_A2(); } else if (IS_TEST_A3A5) { LOG_PRINT("Example on <Atlas A3> or <Atlas A5> will be executed!\n"); int ret = run_example_on_A3A5(); } return 0; }