aclnnMoeInitRoutingV2
Applicable Products
Ascend 950PR&950DT products : Supported
Atlas A3 products : Supported
Atlas A2 products : Supported
Atlas 200I/500 A2 inference products : Not supported
Atlas inference products : Supported
Atlas training products : Not supported
Function
Description: This operator corresponds to the Routing computation in MoE (Mixture of Experts). It takes the computation result of the aclnnMoeGatingTopKSoftmax operator as input, and outputs the Routing matrix expandedXOut and other results for subsequent computation. This API has the following function changes compared with aclnnMoeInitRouting. Select an appropriate API as required:
- A Drop mode is newly added. In Drop mode, the count of tokens to be processed by each expert in the output is aligned to expertCapacity. Tokens exceeding expertCapacity are dropped, and the insufficient part is padded with 0.
- Newly added optional output expertTokensCountOrCumsumOut in Dropless mode, which outputs the cumulative token count (Cumsum) or the token count (Count) that each expert needs to process.
- Newly added optional output expertTokensBeforeCapacityOut in Drop mode, which outputs the count of tokens each expert should process before Drop.
- Removed the rowIdx input.
NOTE: Routing computation is a step in the MoE model. An MoE model mainly consists of a group of expert models and a gating model. During computation, the input data first goes through the gating network (including the MoeGatingTopKSoftmax operator) to derive the k experts with the highest weights for each data element. The result is then fed into the MoeInitRouting operator to generate the Routing matrix. Each expert then processes its corresponding data based on the Routing matrix and produces the output. Finally, the outputs of all experts are weighted and summed to form the final prediction result.
Formula:
1.Flatten expertIdx with input shape [numRows, k] or [numRows] into one row for sorting, and derive the sorted result sortedExpertIdx and the corresponding indices sortedRowIdx. Here, numRows is the token count, and k indicates the k experts with the highest weights for each token element. When expertIdx is one-dimensional, set k to 1:
$$ sortedExpertIdx, sortedRowIdx=keyValueSort(\text{flatten}(expertIdx)) $$2.Perform position mapping based on sortedRowIdx to obtain expandedRowIdxOut:
$$ expandedRowIdxOut[sortedRowIdx[i]]=i $$3.Arrange tokens in expert order according to sortedRowIdx. When dropPadMode is 1, count alignment is performed to align the token count processed by each expert to expertCapacity. Tokens exceeding expertCapacity are dropped, and tokens fewer than expertCapacity are filled with 0. Derive expandedXOut:
$$ expandedXOut[expandedRowIdxOut[i]]=x[i//k] $$4.Obtain the histogram result of each expert in sortedExpertIdx, and then perform Cumsum to derive expertTokensCountOrCumsumOut:
$$ expertTokensCountOrCumsumOut[i]=Cumsum(Histogram(sortedExpertIdx)) $$5.Obtain the histogram result of each expert in sortedExpertIdx to derive expertTokensBeforeCapacityOut:
$$ expertTokensBeforeCapacityOut[i]=Histogram(sortedExpertIdx) $$
Function Prototype
Each operator uses a two-phase API. First, call the "aclnnMoeInitRoutingV2GetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation flow. Then, call the "aclnnMoeInitRoutingV2" API to perform computation.
aclnnStatus aclnnMoeInitRoutingV2GetWorkspaceSize(
const aclTensor *x,
const aclTensor *expertIdx,
int64_t activeNum,
int64_t expertCapacity,
int64_t expertNum,
int64_t dropPadMode,
int64_t expertTokensCountOrCumsumFlag,
bool expertTokensBeforeCapacityFlag,
const aclTensor *expandedXOut,
const aclTensor *expandedRowIdxOut,
const aclTensor *expertTokensCountOrCumsumOut,
const aclTensor *expertTokensBeforeCapacityOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMoeInitRoutingV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMoeInitRoutingV2GetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x Input Input of MoE, that is, the token feature input. - Supports empty tensors.
- Must be a 2D tensor with shape [numRows, h]. numRows indicates the number of tokens, and h indicates the length of each token.
FLOAT16, BFLOAT16, FLOAT32 ND 2 √ expertIdx Input Indices of the k experts that process each token. - Supports empty tensors.
- In Drop/Pad use cases, or in non-Drop/Pad use cases where expertTokensCountOrCumsumOut need to be output, the value range must be [0, expertNum - 1]. In other use cases, the value must be greater than or equal to 0.
INT32, INT64 ND 1 or 2 √ activeNum Input Indicates whether it is an Active use case. This parameter takes effect in non-Drop/Pad use cases where dropPadMode is 0. The value is greater than or equal to 0. The value 0 indicates the Dropless use case, and a value greater than 0 indicates the Active use case. The total number of tokens processed jointly by all experts must not exceed activeNum. - - - - expertCapacity Input Indicates the number of tokens each expert can process. The value range is greater than or equal to 0. In Drop/Pad use cases, the value range is (0, numRows]. In this case, each expert drops the tokens exceeding capacity and pads all-0 tokens when the token count is below the capacity threshold. This attribute value is ignored in other use cases. - - - - expertNum Input Indicates the total number of experts. The value range is greater than or equal to 0. In Drop/Pad scenarios, or when expertTokensCountOrCumsumFlag is greater than 0 and expertTokensCountOrCumsumOut needs to be output, expertNum must be greater than 0. - - - - dropPadMode Input Indicates whether it is the Drop/Pad use case. The value is 0 or 1. - 0: indicates the non-Drop/Pad use case. In this use case, expertCapacity is not checked.
- 1: indicates the Drop/Pad use case. expertNum and expertCapacity need to be checked. In this mode, the output aligns the count of tokens to be processed by each expert to expertCapacity. Tokens exceeding expertCapacity are dropped, and the insufficient ones are filled with 0.
- - - - expertTokensCountOrCumsumFlag Input Controls whether to output expertTokensCountOrCumsumOut. The value is 0, 1, or 2. - 0: indicates that expertTokensCountOrCumsumOut is not output.
- 1: indicates that the output value is the cumulative count of tokens processed by each expert.
- 2: indicates that the output value is the count of tokens processed by each expert.
- - - - expertTokensBeforeCapacityFlag Input Controls whether to output expertTokensBeforeCapacityOut. The value is false or true - false: indicates that expertTokensBeforeCapacityOut is not output.
- true: indicates that expertTokensBeforeCapacityOut is output, and the value is the count of tokens processed by each expert before dropping.
- - - - expandedXOut Output Features expanded based on expertIdx. - Supports empty tensors.
- The data type must be the same as x.
- In the Dropless/Active use case, must be a 2D tensor. The shape is [numRows * k, h] in the Dropless use case and [min(activeNum, numRows * k), h] in the Active use case.
In the Drop/Pad use case, must be a 3D tensor with the shape [expertNum, expertCapacity, h].
FLOAT16, BFLOAT16, FLOAT32 ND 2 or 3 × expandedRowIdxOut Output Index mapping relationship between expandedXOut and x. - Supports empty tensors.
- The requirement is a 1D tensor with shape [numRows*k].
INT32 ND 1 × expertTokensCountOrCumsumOut Output Outputs the statistics of the token count processed by each expert and the cumulative value. - Supports empty tensors
- Whether to output is controlled by the expertTokensCountOrCumsumFlag parameter. The value is output only in non-Drop/Pad use cases. The requirement is a 1D tensor with shape [expertNum].
INT32 ND 1 × expertTokensBeforeCapacityOut Output Outputs the statistics of the token count processed by each expert before drop. - Supports empty tensor
- Whether to output it is controlled by the expertTokensBeforeCapacityFlag parameter. The value is output only in Drop/Pad scenarios. The requirement is a 1D tensor with shape [expertNum].
INT32 ND 1 × workspaceSize Output Returns the workspace size that the user needs to allocate on the Device side. - - - - - executor Output Returns the op executor, which contains the operator computation process. - - - - - Atlas A2 products ,Atlas A3 products : The input expertIdx supports the INT32 data type. The requirement is a 2D shape [numRows, k].
Ascend 950PR&950DT products : The input expertIdx supports the INT32 or INT64 data type. The requirement is a 2D shape [numRows, k] or a 1D shape [numRows]. A 1D shape indicates k=1.
- |
Atlas inference products : The input expertIdx supports the INT32 data type. The requirement is a 2D shape [numRows, k], and dropPadMode supports only 0. The size of the last dimension of input x must be divisible by 32.
Return value
aclnnStatus: Return status code. 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 The compute input and required compute output are null pointers. ACLNN_ERR_PARAM_INVALID 161002 The data type and format of the compute input and output are not in the supported range. ACLNN_ERR_INNER_NULLPTR 561103 When expertTokensCountOrCumsumOut needs to be output, expertNum is equal to 0. The shape dimensions of x and expertIdx are not equal to 2, and the first dimensions are not equal. On | Atlas inference products , the size of the tail axis of input x is not divisible by 32The value of activeNum, expertNum, or expertCapacity is less than 0. The value of dropPadMode, expertTokensCountOrCumsumFlag, or expertTokensBeforeCapacityFlag is not in the value range. When dropPadMode is equal to 1, expertCapacity and expertNum are equal to 0.
aclnnMoeInitRoutingV2
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address applied for on the Device side. workspaceSize Input Workspace size applied for on the Device side, obtained by the first-phase API aclnnMoeInitRoutingV2GetWorkspaceSize.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:
- aclnnMoeInitRoutingV2 defaults to a deterministic implementation.
Example
The sample code is as follows and is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include "acl/acl.h"
#include "aclnnop/aclnn_moe_init_routing_v2.h"
#include <iostream>
#include <vector>
#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 side.
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 host-side data to the device-side 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 the aclCreateTensor API 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, device/stream initialization. For details, see the list of ACL external APIs.
// Fill in deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle the check as needed.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the inputs and outputs based on the API definition.
std::vector<int64_t> xShape = {3, 4};
std::vector<int64_t> idxShape = {3, 2};
std::vector<int64_t> expandedXOutShape = {3, 2, 4};
std::vector<int64_t> idxOutShape = {6};
std::vector<int64_t> expertTokenOutShape = {3};
void* xDeviceAddr = nullptr;
void* expertIdxDeviceAddr = nullptr;
void* expandedXOutDeviceAddr = nullptr;
void* expandedRowIdxOutDeviceAddr = nullptr;
void* expertTokenBeforeCapacityOutDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* expertIdx = nullptr;
int64_t activeNum = 0;
int64_t expertCapacity = 2;
int64_t expertNum = 3;
int64_t dropPadMode = 1;
int64_t expertTokensCountOrCumsumFlag = 0;
bool expertTokensBeforeCapacityFlag = true;
aclTensor* expandedXOut = nullptr;
aclTensor* expandedRowIdxOut = nullptr;
aclTensor* expertTokensBeforeCapacityOut = nullptr;
std::vector<float> xHostData = {0.1, 0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3, 0.3};
std::vector<int> expertIdxHostData = {1, 2, 0, 1, 0, 2};
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};
std::vector<int> expertTokensBeforeCapacityOutHostData = {0, 0, 0};
// Create the self aclTensor.
ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expertIdxHostData, idxShape, &expertIdxDeviceAddr, aclDataType::ACL_INT32, &expertIdx);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create out aclTensor.
ret = CreateAclTensor(expandedXOutHostData, expandedXOutShape, &expandedXOutDeviceAddr, aclDataType::ACL_FLOAT, &expandedXOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expandedRowIdxOutHostData, idxOutShape, &expandedRowIdxOutDeviceAddr, aclDataType::ACL_INT32, &expandedRowIdxOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expertTokensBeforeCapacityOutHostData, expertTokenOutShape, &expertTokenBeforeCapacityOutDeviceAddr, aclDataType::ACL_INT32, &expertTokensBeforeCapacityOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API, and replace it with the specific API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnMoeInitRoutingV2.
ret = aclnnMoeInitRoutingV2GetWorkspaceSize(x, expertIdx, activeNum, expertCapacity, expertNum, dropPadMode, expertTokensCountOrCumsumFlag, expertTokensBeforeCapacityFlag, expandedXOut, expandedRowIdxOut, nullptr, expertTokensBeforeCapacityOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeInitRoutingV2GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
// Allocate device memory based on the workspaceSize calculated 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 aclnnMoeInitRoutingV2.
ret = aclnnMoeInitRoutingV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeInitRoutingV2 failed. ERROR: %d\n", ret); return ret);
// 4. Boilerplate: synchronously wait for the task execution 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 the device side to the host side. Modify it according to the specific API definition.
auto expandedXOutSize = GetShapeSize(expandedXOutShape);
std::vector<float> expandedXOutData(expandedXOutSize, 0);
ret = aclrtMemcpy(expandedXOutData.data(), expandedXOutData.size() * sizeof(expandedXOutData[0]), expandedXOutDeviceAddr, expandedXOutSize * 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 < expandedXOutSize; i++) {
LOG_PRINT("expandedXOutData[%ld] is: %f\n", i, expandedXOutData[i]);
}
auto expandedRowIdxOutSize = GetShapeSize(idxOutShape);
std::vector<int> expandedRowIdxOutData(expandedRowIdxOutSize, 0);
ret = aclrtMemcpy(expandedRowIdxOutData.data(), expandedRowIdxOutData.size() * sizeof(expandedRowIdxOutData[0]), expandedRowIdxOutDeviceAddr, expandedRowIdxOutSize * 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 < expandedRowIdxOutSize; i++) {
LOG_PRINT("expandedRowIdxOutData[%ld] is: %d\n", i, expandedRowIdxOutData[i]);
}
auto expertTokensBeforeCapacityOutSize = GetShapeSize(expertTokenOutShape);
std::vector<int> expertTokenIdxOutData(expertTokensBeforeCapacityOutSize, 0);
ret = aclrtMemcpy(expertTokenIdxOutData.data(), expertTokenIdxOutData.size() * sizeof(expertTokenIdxOutData[0]), expertTokenBeforeCapacityOutDeviceAddr, expertTokensBeforeCapacityOutSize * 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 < expertTokensBeforeCapacityOutSize; i++) {
LOG_PRINT("expertTokenIdxOutData[%ld] is: %d\n", i, expertTokenIdxOutData[i]);
}
// 6. Release the aclTensor and aclScalar. Modify it according to the specific API definition.
aclDestroyTensor(x);
aclDestroyTensor(expertIdx);
aclDestroyTensor(expandedXOut);
aclDestroyTensor(expandedRowIdxOut);
aclDestroyTensor(expertTokensBeforeCapacityOut);
// 7. Release device resources. Modify it according to the specific API definition.
aclrtFree(xDeviceAddr);
aclrtFree(expertIdxDeviceAddr);
aclrtFree(expandedXOutDeviceAddr);
aclrtFree(expandedRowIdxOutDeviceAddr);
aclrtFree(expertTokenBeforeCapacityOutDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}