aclnnMoeInitRoutingV4
Applicable Products
Ascend 950PR&950DT products : Supported
Atlas A3 products : Not supported
Atlas A2 products : Not supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Not supported
Atlas training products : Not supported
Function
Description: MoE routing computation. Performs routing processing based on the computation result of aclnnMoeGatingTopKSoftmaxV2. Supports non-quantized, static quantization, and dynamic quantization modes. This API provides the following function changes over the V3 API aclnnMoeInitRoutingV3. Choose a proper API based on actual requirements:
- active_num is changed from an attribute to an optional input, allowing its value to be dynamically passed in graph mode.
- Optional input topkWeight and optional output expandedTopkWeightOut are added. topkWeight can be rearranged based on the sorted index so that expandedTopkWeightOut and expandedXOut are in one-to-one correspondence. topkWeight and expandedTopkWeightOut must be passed in together or not at all.
Formula:
1.Sort the input expertIdx to obtain the sorted result sortedExpertIdx and the corresponding index sortedRowIdx:
$$ sortedExpertIdx, sortedRowIdx=keyValueSort(expertIdx,rowIdx) $$2.Perform position mapping based on sortedRowIdx to obtain expandedRowIdxOut:
When rowIdxType is 1, output scatter indices
$$ expandedRowIdxOut[i]=sortedRowIdx[i] $$When rowIdxType is 0, output gather indices
$$ expandedRowIdxOut[sortedRowIdx[i]]=i $$
3.Compute the histogram result for each expert in sortedExpertIdx to obtain expertTokensCountOrCumsumOutOptional:
$$ expertTokensCountOrCumsumOutOptional[i]=Histogram(sortedExpertIdx) $$4.If quantMode is not -1, compute the quantization result:
- Static quantization
$$ quantResult=round((x∗scaleOptional)+offsetOptional) $$- Dynamic quant:
If scale is not passed in:
$$ dynamicQuantScaleOutOptional = row\_max(abs(x)) / 127 $$$$ quantResult = round(x / dynamicQuantScaleOutOptional) $$If scale is passed in:
$$ dynamicQuantScaleOutOptional = row\_max(abs(x * scaleOptional)) / 127 $$$$ quantResult = round(x / dynamicQuantScaleOutOptional) $$When quantMode is 13, dynamic quantization uses a symmetric quantization range of [-8, 7]. The denominator in the scale calculation is 7. Every two INT4 values in the quantization result are packed into 1 byte along the H dimension.
5.If the active expert range is the full expert range, token index movement follows the Scatter index; otherwise, token index movement follows the Gather index. When dropPadMode is 1, the number of tokens to be processed by each expert is aligned to expertCapacity. Tokens exceeding expertCapacity are dropped, and the insufficient ones are padded with 0. expandedXOut is obtained:
Non-quantized scenario
- Index movement by Scatter index
$$ expandedXOut[i]=x[scatterRowIdx[i] // K] $$- Index movement by Gather index
$$ expandedXOut[gatherRowIdx[i]]=x[i // K] $$quantization scenario
- Index movement by Scatter index
$$ expandedXOut[i]=quantResult[scatterRowIdx[i] // K] $$- Index movement by Gather index
$$ expandedXOut[gatherRowIdx[i]]=quantResult[i // K] $$
6.If the input topkWeight is passed in, rearrange topkWeight according to the sorted indices, so that expandedTopkWeightOut and expandedXOut are in one-to-one correspondence:
Dropless scenario (dropPadMode=0)
$$ expandedTopkWeightOut[i] = topkWeight[sortedRowIdx[i]], \quad 0 \le i < effectiveNum $$where effectiveNum is:
$$ effectiveNum = \min(activeNum, availableIdxNum) $$DropPad scenario (dropPadMode=1)
$$ expandedTopkWeightOut[dstIdx] = topkWeight[globalSortIdx], \quad dstIdx \ne -1 $$where globalSortIdx is the position of expertIdx in the flatten layout (that is, globalSortIdx = rowIdx * K + colIdx, corresponding to topkWeight[rowIdx, colIdx]), dstIdx is the destination index at the corresponding position in expandedRowIdxOut, and the unallocated expert capacity positions in expandedTopkWeightOut are filled with 0.
7.expandedRowIdxOut has availableIdxNum valid elements, which is calculated as the number of elements in expertIdx within the range of activeExpertRangeOptional
$$ availableIdxNum = |\{x\in expertIdx| expert\_start \le x<expert\_end \ \}| $$
Function Prototype
Each operator uses a two-phase API. First call the "aclnnMoeInitRoutingV4GetWorkspaceSize" API to obtain the input parameters, calculate the required workspace size, and obtain the executor that contains the operator computation process. Then call the "aclnnMoeInitRoutingV4" API to execute the computation.
aclnnStatus aclnnMoeInitRoutingV4GetWorkspaceSize(
const aclTensor *x,
const aclTensor *expertIdx,
const aclTensor *scaleOptional,
const aclTensor *offsetOptional,
const aclTensor *activeNumOptional,
const aclTensor *topkWeightOptional,
int64_t expertCapacity,
int64_t expertNum,
int64_t dropPadMode,
int64_t expertTokensNumType,
bool expertTokensNumFlag,
int64_t quantMode,
const aclIntArray *activeExpertRangeOptional,
int64_t rowIdxType,
const aclTensor *expandedXOut,
const aclTensor *expandedRowIdxOut,
const aclTensor *expertTokensCountOrCumsumOut,
const aclTensor *expandedScaleOut,
const aclTensor *expandedTopkWeightOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMoeInitRoutingV4(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMoeInitRoutingV4GetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x (aclTensor) Input Input to MOE, that is, the token feature input. The shape is (NUM_ROWS, H). - quantMode=-1: FLOAT16, BFLOAT16, FLOAT32, INT8, HIFLOAT8, FLOAT4_E2M1, FLOAT8_E4M3FN, and FLOAT8_E5M2 are supported;
- quantMode=0 and 1: FLOAT16, BFLOAT16, and FLOAT32 are supported;
- quantMode=2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 14, 15, 16, and 17: FLOAT16 and BFLOAT16 are supported;
- quantMode=13: FLOAT32 and BFLOAT16 are supported;
ND 2 - expertIdx (aclTensor) Input K processing experts corresponding to each row of features. The expert ID of each element cannot exceed the number of experts. The shape is (NUM_ROWS, K). INT32 ND 2 - scaleOptional (aclTensor) Input Indicates the parameter used to calculate the quantization result. - If this input is not specified, scale is not used in the computation;
- Optional input in the non-quantization scenario. If specified, it must be a 1D tensor with shape (NUM_ROWS,) and data type FLOAT32. When the data type of input x is FLOAT4_E2M1, FLOAT8_E4M3FN, or FLOAT8_E5M2, it must be a 3D tensor with shape (NUM_ROWS, CeilDiv(H, 64), 2) and data type FLOAT8_E8M0;
- Mandatory input in the static quantization scenario. It must be a 1D tensor with shape [1, ];
- Optional input in the INT8 dynamic quantization scenario (quantMode is 1). If specified, it must be a 2D tensor with shape (expertEnd-expertStart, H). Optional input in the INT4 dynamic quantization scenario (quantMode is 13). If specified, it must be a tensor with shape (1, H), indicating a smooth scale broadcast along the H dimension.
- Not required in the MXFP8 quantization scenario (quantMode is 2 or 3).
- Not required in the HIF8 direct conversion and HIF8 PERTOKEN quantization scenarios (quantMode is 6 or 8).
- Mandatory input in the HIF8 PERTENSOR quantization scenario (quantMode is 7). It must be a 1D tensor with shape [1, ].
- Not required in the MXFP4 quantization scenario (quantMode is 9).
- Not required in the FP8 PerGroup quantization scenario (quantMode is 4, 5, 14, or 15).
- Not required in the FP8 PerBlock quantization scenario (quantMode is 11 or 12).
- Not required in the MXFP8 RoundScale+Amax quantization scenario (quantMode is 16 or 17).
FLOAT32, FLOAT8_E8M0 ND 1-3 - offsetOptional (aclTensor) Input Represents the offset value used to compute the quant result. - Not input in the non-quantized field;
- Required input in the static quantization scenario. The input requirements are a 1D tensor with shape [1, ];
- Not input in dynamic quantization (quantMode is 1), MXFP8 quantization (quantMode is 2 or 3), HIF8 quantization (quantMode is 6, 7, or 8), MXFP4 quantization (quantMode is 9), FP8 PerGroup quantization (quantMode is 4, 5, 14, or 15), FP8 PerBlock quantization (quantMode is 11 or 12), INT4 dynamic quantization (quantMode is 13), or the MXFP8 RoundScale+Amax quantization scenario (quantMode is 16 or 17).
FLOAT32 ND - - activeNumOptional (aclTensor) Input Specifies the maximum total number of rows to process. The output expandedXOut is valid for only this number of rows. - Optional input. If not provided, activeNum defaults to NUM_ROWS*K;
- If provided, it is a scalar Tensor of shape () or (1,) and data type INT64, with a value greater than or equal to 0. 0 indicates the Dropless use case, and a value greater than 0 indicates the Active use case, which constrains the total number of tokens jointly processed by all experts.
INT64 ND 0-1 - topkWeightOptional (aclTensor) Input Routing weights of topk experts, used to reorder by sorted index for one-to-one correspondence with expandedXOut. - Optional input. If not provided, expandedTopkWeightOut is not output;
- Input shape is (NUM_ROWS, K), and the data type only supports FLOAT32.
FLOAT32 ND 2 - expertCapacity (int64_t) Input Indicates the number of tokens that each expert can process. In the Dropless use case, only its value is validated and this parameter is not used; in the DropPad use case, the value range is (0, NUM_ROWS]. INT64 - - - expertNum (int64_t) Input Indicates the number of experts. If expertTokensNumType is key_value, the value range is [1, 5120]; otherwise, the value range is [1, 10240]. INT64 - - - dropPadMode (int64_t) Input Indicates whether the DropPad use case is used. The value is 0 or 1
0: Dropless use case, in which expertCapacity is not checked;
1: DropPad use case;INT64 - - - expertTokensNumType (int64_t) Input Indicates different histogram modes. Value is 0, 1, or 2
0: cumsum mode;
1: count mode;
2: key_value mode;INT64 - - - expertTokensNumFlag (bool) Input Indicates whether to output expertTokensCountOrCumsumOut. The value is false or true. BOOL - - - quantMode (int64_t) Input Indicates different quantization scenarios. The value is 0, 1, -1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17
0: static quantization scenario;
1: dynamic quantization scenario, expandedXOut is quantized to INT8;
-1: non-quantized scenario;
2: MXFP8 quantization scenario, expandedXOut is quantized to FLOAT8_E5M2;
3: MXFP8 quantization scenario, expandedXOut is quantized to FLOAT8_E4M3FN;
4: FP8 PerGroup quantization scenario (GroupSize=128, RoundScale), expandedXOut is quantized to FLOAT8_E5M2;
5: FP8 PerGroup quantization scenario (GroupSize=128, RoundScale), expandedXOut is quantized to FLOAT8_E4M3FN;
6: HIF8 direct conversion quantization scenario, expandedXOut is quantized to HIFLOAT8;
7: HIF8 PERTENSOR quantization scenario, expandedXOut is quantized to HIFLOAT8 in pertensor mode;
8: HIF8 PERTOKEN quantization scenario, expandedXOut is quantized to HIFLOAT8 in pertoken mode;
9: MXFP4 quantization scenario, expandedXOut is quantized to FLOAT4_E2M1;
11: FP8 PerBlock quantization scenario (BlockSize=128), expandedXOut is quantized to FLOAT8_E5M2, expandedScaleOut is in FLOAT32 3D layout;
12: FP8 PerBlock quantization scenario (BlockSize=128), expandedXOut is quantized to FLOAT8_E4M3FN, expandedScaleOut is in FLOAT32 3D layout;
13: INT4 dynamic quantization scenario, expandedXOut is quantized to INT4;
14: FP8 PerGroup quantization scenario (GroupSize=128, RoundScale+Amax), expandedXOut is quantized to FLOAT8_E5M2;
15: FP8 PerGroup quantization scenario (GroupSize=128, RoundScale+Amax), expandedXOut is quantized to FLOAT8_E4M3FN;
16: MXFP8 RoundScale+Amax quantization scenario, expandedXOut is quantized to FLOAT8_E5M2;
17: MXFP8 RoundScale+Amax quantization scenario, expandedXOut is quantized to FLOAT8_E4M3FN;INT64 - - - activeExpertRangeOptional(aclIntArray) Input Indicates the range of active experts. The length is 2. The array values are [expertStart, expertEnd], left-closed and right-open. The values must be greater than or equal to 0, and expertEnd must not be greater than expertNum. In Drop/Pad scenarios, expertStart is 0 and expertEnd is expertNum. INT64 - - - rowIdxType (int64_t) Input Indicates the index type used by expandedRowIdxOut. Value is 0 or 1
0: gather-type index
1: scatter-type indexINT64 - - - expandedXOut(aclTensor) Output Features expanded based on expertIdx. - In Dropless scenarios, the shape is [NUM_ROWS * K, H].
- In Active scenarios, the shape is [min(activeNum, NUM_ROWS * K), H].
- In Drop/Pad scenarios, the tensor must be 3D, with the shape [expertNum, expertCapacity, H].
- In non-quantized scenarios, the data type is the same as that of x. In quantization scenarios, the supported data types are INT8 when quantMode is 0 or 1; INT4 when quantMode is 13 and the data type of x is FLOAT32 or BFLOAT16; FLOAT8_E5M2 when quantMode is 2, 4, 14, or 16; FLOAT8_E4M3FN when quantMode is 3, 5, 15, or 17; HIFLOAT8 when quantMode is 6, 7, or 8; FLOAT4_E2M1 when quantMode is 9; and FLOAT8_E5M2 and FLOAT8_E4M3FN respectively when quantMode is 11 or 12.
FLOAT16, BFLOAT16, FLOAT32, INT8, INT4, FLOAT8_E5M2, FLOAT8_E4M3FN, HIFLOAT8, FLOAT4_E2M1 ND 2 - expandedRowIdxOut(aclTensor) Output Index mapping between expandedXOut and x. The output shape is (NUM_ROWS*K, ). The first availableIdxNum elements are valid data, and the rest are invalid data determined by rowIdxType: - When rowIdxType is 0, invalid data is filled with -1
- When rowIdxType is 1, invalid data is not initialized
INT32 ND 1 - expertTokensCountOrCumsumOut (aclTensor) Output Statistics or cumulative value of the number of tokens processed by each expert. - When expertTokensNumFlag is false, the output is an empty tensor.
- When expertTokensNumType is 0, the output indicates the prefix sum of the total number of tokens processed by experts within activeExpertRangeOptional after sorting. The output shape is [expertEnd-expertStart].
- When expertTokensNumType is 1, the output indicates the total number of tokens processed by experts within activeExpertRangeOptional. The output shape is [expertEnd-expertStart].
- When expertTokensNumType is 2, the output indicates the experts with a non-zero total number of tokens within activeExpertRangeOptional and the total number of tokens processed by these experts. The output shape is [expertNum, 2].
INT64 ND 1-2 - expandedScaleOut(aclTensor) Output Intermediate value of scaleOptional in different quantization processes. The output shape is the product of all dimensions of the expandedXOut shape except the last dimension. - In non-quantized fields, when scaleOptional is input, the shape is [NUM_ROWS*K]. The first availableIdxNum elements are valid data, and the output is of the FLOAT32 type. When the data type of input x is FLOAT4_E2M1, FLOAT8_E4M3FN, or FLOAT8_E5M2 and scaleOptional is input, the shape of expandedScaleOut is [NUM_ROWS*K, CeilDiv(H, 64), 2], and the output is of the FLOAT8_E8M0 type. In Drop/Pad scenarios, the output is a 1D tensor with the shape [expertNum * expertCapacity] and the FLOAT32 type.
- In dynamic quantization scenarios, when scaleOptional is input, the first availableIdxNum elements are valid data.
- In static quantization scenarios (quantMode is 0), HIF8 direct conversion quantization scenarios (quantMode is 6), and HIF8 PERTENSOR quantization scenarios (quantMode is 7), expandedScaleOut is not output.
- In MXFP8 quantization scenarios (quantMode is 2, 3, 16, or 17), the output is of the FLOAT8_E8M0 type, with the shape [NUM_ROWS*K, M], where M=CeilAlign(CeilDiv(H,32),2). The first availableIdxNum rows of NUM_ROWS*K are valid data.
- In the scenario where data is quantized to HIFLOAT8 through direct conversion, expandedScaleOut is not output.
- In the scenario where data is quantized to HIFLOAT8 in PERTENSOR mode, expandedScaleOut is not output.
- In the scenario where data is quantized to HIFLOAT8 in PERTOKEN mode, the output is of the FLOAT32 type, with the shape [NUM_ROWS*K].
- In MXFP4 quantization scenarios, the output is of the FLOAT8_E8M0 type, with the shape [NUM_ROWS*K, M, 2], where M=CeilDiv(H, 64). The first availableIdxNum rows of NUM_ROWS*K are valid data.
- In FP8 PerGroup quantization scenarios (quantMode is 4, 5, 14, or 15), the output is of the FLOAT32 type, with the shape [NUM_ROWS*K, CeilDiv(H, 128)]. The first availableIdxNum rows of NUM_ROWS*K are valid data.
- In FP8 PerBlock quantization scenarios (quantMode is 11 or 12), the output is of the FLOAT32 type, with the shape [NUM_ROWS*K, CeilDiv(H,256), 2]. The first availableIdxNum rows of NUM_ROWS*K are valid data.
FLOAT32, FLOAT8_E8M0 ND 1-3 - expandedTopkWeightOut (aclTensor) Output Routing weights reordered by sorted index, in one-to-one correspondence with expandedXOut. - Optional output; must be output together with the topkWeight input;
- In Dropless use cases, the shape is [min(activeNum, NUM_ROWS*K), 1]. The first effectiveNum elements are valid data, and the remaining elements are uninitialized. effectiveNum=min(activeNum, availableIdxNum);
- In DropPad use cases, the shape is [expertNum*expertCapacity, 1]. Positions with allocated capacity are valid data, and positions without allocated capacity are filled with 0;
- Only the data type FLOAT32 is supported.
FLOAT32 ND 2 - workspaceSize (uint64_t) Output Size of the workspace that the user needs to request on the Device. - - - - - executor (aclOpExecutor) Output Returns the op executor, which contains the operator computation process. - - - - - Return Value
aclnnStatus: Returns a status code. For details, see aclnn return code.
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 The compute input or compute output is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of the input and output are not in the supported range. ACLNN_ERR_INNER_TILING_ERROR 561002 The shapes of the input and output tensors are not in the supported range.
The input attributes are not in the supported range.
aclnnMoeInitRoutingV4
Parameters:
Parameter Input/Output Description workspace Input Memory address of the workspace allocated on the Device side. workspaceSize Input Size of the workspace allocated on the Device side, obtained by the first-phase API aclnnMoeInitRoutingV4GetWorkspaceSize. executor Input Op executor, which 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:
- aclnnMoeInitRoutingV4 defaults to a deterministic implementation.
The performance template is supported on the following products. Additional admission conditions must be met; otherwise, the generic template is used:
- Products that support the performance template:
Ascend 950PR&950DT products : Supported
- Admission conditions of the performance template:
Performance template type Admission conditions Full-load performance template When the operator input shape is small, the multi-core synchronization time between operations accounts for a high proportion and becomes a performance bottleneck. Therefore, a performance template is added for this specialized use case. In this template, data movement in, sorting, and computation are completed in the same kernel. The following conditions must be met: - Attribute requirements: dropPadMode=0; the non-quantized scenario also supports dropPadMode=1, in which case quantMode=-1, rowIdxType=0, and activeExpertRange=[0, expertNum].
- Products that support the performance template:
Special constraints for DropPad mode (when dropPadMode=1):
- quantMode supports only -1 (non-quantization).
- rowIdxType supports only 0 (gather index).
- activeExpertRangeOptional must be [0, expertNum].
For the MXFP4/INT4 dynamic quantization scenario where quantMode is 9 or 13, and the non-quantized passthrough scenario where quantMode is -1 and the data type of x is FLOAT4_E2M1, H must be an even number. The INT4 dynamic quantization scenario where quantMode is 13 must also meet the following requirements: the data type of x is FLOAT32 or BFLOAT16, dropPadMode is 0, and offsetOptional is not input.
Empty tensor processing:
Ascend 950PR&950DT products : When NUM_ROWS=0 or K=0, there are no routing elements. The empty tensor processing path is used, and the expert count is 0. The output shape must still meet the constraints of the corresponding mode.Ascend 950PR&950DT products : When NUM_ROWS*K>0 and H=0, the normal routing flow is still followed, generating expandedRowIdxOut and expertTokensCountOrCumsumOut.
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_moe_init_routing_v4.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)
int64_t GetShapeSize(const std::vector<int64_t> &shape)
{
int64_t shape_size = 1;
for (auto i : shape) {
shape_size *= i;
}
return shape_size;
}
int Init(int32_t deviceId, aclrtStream *stream)
{
// Boilerplate: resource initialization
auto ret = aclInit(nullptr);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
ret = aclrtSetDevice(deviceId);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
ret = aclrtCreateStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
return 0;
}
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);
// Call aclrtMalloc to allocate memory on the device.
auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
// Call aclrtMemcpy to copy data from the host to the device memory.
ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
// Calculate the strides of the contiguous tensor.
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];
}
// Call aclCreateTensor to create an aclTensor.
*tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
shape.data(), shape.size(), *deviceAddr);
return 0;
}
int main()
{
// 1. Boilerplate: initialize the device/stream. For details, see the ACL API list.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle the return value check as needed.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output based on the API definition.
std::vector<int64_t> xShape = {3, 2};
std::vector<int64_t> expertIdxShape = {3, 4};
std::vector<int64_t> scaleShape = {3};
std::vector<int64_t> offsetShape = {1};
std::vector<int64_t> activeNumShape = {};
std::vector<int64_t> topkWeightShape = {3, 4};
std::vector<int64_t> expandedXOutShape = {12, 2};
std::vector<int64_t> expandedRowIdxOutShape = {12};
std::vector<int64_t> expertTokensCountOrCumsumOutOptionalShape = {4};
std::vector<int64_t> expandedScaleOutOptionalShape = {12};
std::vector<int64_t> expandedTopkWeightOutShape = {12, 1};
std::vector<int64_t> activeExpertRangeArray = {0, 4};
void *xDeviceAddr = nullptr;
void *expertIdxDeviceAddr = nullptr;
void *scaleDeviceAddr = nullptr;
void *offsetDeviceAddr = nullptr;
void *activeNumDeviceAddr = nullptr;
void *topkWeightDeviceAddr = nullptr;
void *expandedXOutDeviceAddr = nullptr;
void *expandedRowIdxOutDeviceAddr = nullptr;
void *expertTokensCountOrCumsumOutOptionalDeviceAddr = nullptr;
void *expandedScaleOutOptionalDeviceAddr = nullptr;
void *expandedTopkWeightOutDeviceAddr = nullptr;
aclTensor *x = nullptr;
aclTensor *expertIdx = nullptr;
aclTensor *scale = nullptr;
aclTensor *offset = nullptr;
aclTensor *activeNumOptional = nullptr;
aclTensor *topkWeightOptional = nullptr;
int64_t expertCapacity = 4;
int64_t expertNum = 256;
int64_t dropPadMode = 0;
int64_t expertTokensNumType = 1;
bool expertTokensNumFlag = true;
int64_t quantMode = -1;
aclIntArray *activeExpertRange = aclCreateIntArray(activeExpertRangeArray.data(), activeExpertRangeArray.size());
int64_t rowIdxType = 1;
aclTensor *expandedXOut = nullptr;
aclTensor *expandedRowIdxOut = nullptr;
aclTensor *expertTokensCountOrCumsumOutOptional = nullptr;
aclTensor *expandedScaleOutOptional = nullptr;
aclTensor *expandedTopkWeightOut = nullptr;
std::vector<float> xHostData = {0.1, 0.1, 0.2, 0.2, 0.3, 0.3};
std::vector<int> expertIdxHostData = {1, 2, 0, 3, 0, 2, 1, 3, 0, 1, 3, 2};
std::vector<float> scaleHostData = {0.3423, 0.1652, 0.2652};
std::vector<float> offsetHostData = {1.8369};
std::vector<int64_t> activeNumHostData = {12};
std::vector<float> topkWeightHostData = {0.5, 0.3, 0.2, 0.1, 0.4, 0.6, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65};
std::vector<float> expandedXOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
std::vector<int> expandedRowIdxOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
std::vector<int64_t> expertTokensCountOrCumsumOutOptionalHostData = {0, 0, 0, 0};
std::vector<float> expandedScaleOutOptionalHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
std::vector<float> expandedTopkWeightOutHostData(expandedTopkWeightOutShape[0] * expandedTopkWeightOutShape[1],
0.0f);
// Create the self aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expertIdxHostData, expertIdxShape, &expertIdxDeviceAddr, aclDataType::ACL_INT32, &expertIdx);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scale);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(offsetHostData, offsetShape, &offsetDeviceAddr, aclDataType::ACL_FLOAT, &offset);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(activeNumHostData, activeNumShape, &activeNumDeviceAddr, aclDataType::ACL_INT64,
&activeNumOptional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(topkWeightHostData, topkWeightShape, &topkWeightDeviceAddr, aclDataType::ACL_FLOAT,
&topkWeightOptional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the out aclTensor.
ret = CreateAclTensor(expandedXOutHostData, expandedXOutShape, &expandedXOutDeviceAddr, aclDataType::ACL_FLOAT,
&expandedXOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expandedRowIdxOutHostData, expandedRowIdxOutShape, &expandedRowIdxOutDeviceAddr,
aclDataType::ACL_INT32, &expandedRowIdxOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expertTokensCountOrCumsumOutOptionalHostData, expertTokensCountOrCumsumOutOptionalShape,
&expertTokensCountOrCumsumOutOptionalDeviceAddr, aclDataType::ACL_INT64,
&expertTokensCountOrCumsumOutOptional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expandedScaleOutOptionalHostData, expandedScaleOutOptionalShape,
&expandedScaleOutOptionalDeviceAddr, aclDataType::ACL_FLOAT, &expandedScaleOutOptional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expandedTopkWeightOutHostData, expandedTopkWeightOutShape, &expandedTopkWeightOutDeviceAddr,
aclDataType::ACL_FLOAT, &expandedTopkWeightOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace it with the specific API.
uint64_t workspaceSize = 0;
aclOpExecutor *executor;
// Call the first-phase API of aclnnMoeInitRoutingV4.
ret = aclnnMoeInitRoutingV4GetWorkspaceSize(
x, expertIdx, scale, offset, activeNumOptional, topkWeightOptional, expertCapacity, expertNum, dropPadMode,
expertTokensNumType, expertTokensNumFlag, quantMode, activeExpertRange, rowIdxType, expandedXOut,
expandedRowIdxOut, expertTokensCountOrCumsumOutOptional, expandedScaleOutOptional, expandedTopkWeightOut,
&workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeInitRoutingV4GetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory based on the workspaceSize computed by the first-phase API.
void *workspaceAddr = nullptr;
if (workspaceSize > 0) {
ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret;);
}
// Call the second-phase API of aclnnMoeInitRoutingV4.
ret = aclnnMoeInitRoutingV4(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeInitRoutingV4 failed. ERROR: %d\n", ret); return ret);
// 4. Boilerplate: wait synchronously for the task to complete.
ret = aclrtSynchronizeStream(stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
// 5. Obtain the output value and copy the result from device memory to host memory. Modify the code based on the specific API definition.
auto expandedXSize = GetShapeSize(expandedXOutShape);
std::vector<float> expandedXData(expandedXSize, 0);
ret = aclrtMemcpy(expandedXData.data(), expandedXData.size() * sizeof(expandedXData[0]), expandedXOutDeviceAddr,
expandedXSize * sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < expandedXSize; i++) {
LOG_PRINT("expandedXData[%ld] is: %f\n", i, expandedXData[i]);
}
auto expandedRowIdxSize = GetShapeSize(expandedRowIdxOutShape);
std::vector<int> expandedRowIdxData(expandedRowIdxSize, 0);
ret = aclrtMemcpy(expandedRowIdxData.data(), expandedRowIdxData.size() * sizeof(expandedRowIdxData[0]),
expandedRowIdxOutDeviceAddr, expandedRowIdxSize * sizeof(int32_t), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < expandedRowIdxSize; i++) {
LOG_PRINT("expandedRowIdxData[%ld] is: %d\n", i, expandedRowIdxData[i]);
}
auto expertTokensCountSize = GetShapeSize(expertTokensCountOrCumsumOutOptionalShape);
std::vector<int64_t> expertTokensCountData(expertTokensCountSize, 0);
ret = aclrtMemcpy(expertTokensCountData.data(), expertTokensCountData.size() * sizeof(expertTokensCountData[0]),
expertTokensCountOrCumsumOutOptionalDeviceAddr, expertTokensCountSize * sizeof(int64_t),
ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < expertTokensCountSize; i++) {
LOG_PRINT("expertTokensCountData[%ld] is: %ld\n", i, expertTokensCountData[i]);
}
auto expandedScaleSize = GetShapeSize(expandedScaleOutOptionalShape);
std::vector<float> expandedScaleData(expandedScaleSize, 0);
ret = aclrtMemcpy(expandedScaleData.data(), expandedScaleData.size() * sizeof(expandedScaleData[0]),
expandedScaleOutOptionalDeviceAddr, expandedScaleSize * sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < expandedScaleSize; i++) {
LOG_PRINT("expandedScaleData[%ld] is: %f\n", i, expandedScaleData[i]);
}
auto expandedTopkWeightSize = GetShapeSize(expandedTopkWeightOutShape);
std::vector<float> expandedTopkWeightData(expandedTopkWeightSize, 0);
ret =
aclrtMemcpy(expandedTopkWeightData.data(), expandedTopkWeightData.size() * sizeof(expandedTopkWeightData[0]),
expandedTopkWeightOutDeviceAddr, expandedTopkWeightSize * sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return ret);
for (int64_t i = 0; i < expandedTopkWeightSize; i++) {
LOG_PRINT("expandedTopkWeightData[%ld] is: %f\n", i, expandedTopkWeightData[i]);
}
// 6. Release aclTensor and aclScalar. Modify the code based on the specific API definition.
aclDestroyTensor(x);
aclDestroyTensor(expertIdx);
aclDestroyTensor(scale);
aclDestroyTensor(offset);
aclDestroyTensor(activeNumOptional);
aclDestroyTensor(topkWeightOptional);
aclDestroyTensor(expandedXOut);
aclDestroyTensor(expandedRowIdxOut);
aclDestroyTensor(expertTokensCountOrCumsumOutOptional);
aclDestroyTensor(expandedScaleOutOptional);
aclDestroyTensor(expandedTopkWeightOut);
aclDestroyIntArray(activeExpertRange);
// 7. Release device resources. Modify the code based on the specific API definition.
aclrtFree(xDeviceAddr);
aclrtFree(expertIdxDeviceAddr);
aclrtFree(scaleDeviceAddr);
aclrtFree(offsetDeviceAddr);
aclrtFree(activeNumDeviceAddr);
aclrtFree(topkWeightDeviceAddr);
aclrtFree(expandedXOutDeviceAddr);
aclrtFree(expandedRowIdxOutDeviceAddr);
aclrtFree(expertTokensCountOrCumsumOutOptionalDeviceAddr);
aclrtFree(expandedScaleOutOptionalDeviceAddr);
aclrtFree(expandedTopkWeightOutDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}