aclnnMoeInitRouting
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 : Not supported
Atlas training products : Not supported
Function
- Description: Performs MoE routing computation based on the result of aclnnMoeGatingTopKSoftmax.
- Formula:
expertIdx with the input shape [NUM_ROWS, K] is flattened into one row for sorting, where NUM_ROWS is the number of input tokens and K is the number of experts selected by each token. sortedRowIdx is the sorted result of rowIdx.$$ expandedExpertIdxOut,sortedRowIdx=keyValueSort(expertIdx,rowIdx) $$$$ expandedRowIdxOut[sortedRowIdx[i]]=i $$$$ expandedXOut[i]=x[sortedRowIdx[i]\%NUM_ROWS] $$
Function Prototype
Each operator uses a two-phase API. Call "aclnnMoeInitRoutingGetWorkspaceSize" first to obtain the workspace size required for computation and the executor that contains the operator computing flow, and then call "aclnnMoeInitRouting" to execute the computation.
aclnnStatus aclnnMoeInitRoutingGetWorkspaceSize(
const aclTensor *x,
const aclTensor *rowIdx,
const aclTensor *expertIdx,
int64_t activeNum,
const aclTensor *expandedXOut,
const aclTensor *expandedRowIdxOut,
const aclTensor *expandedExpertIdxOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMoeInitRouting(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMoeInitRoutingGetWorkspaceSize
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. - FLOAT16, BFLOAT16, FLOAT32 ND The shape is (NUM_ROWS, H). √ rowIdx Input Indicates the original row index corresponding to each position. rowIdx values start from 0 and increase along dimension 1. INT32 ND The shape must be the same as that of expertIdx. √ expertIdx Input K processing experts corresponding to each row of features. - INT32 ND Shape is (NUM_ROWS, K) √ activeNum Input Specifies the maximum total number of rows to process. The value must be greater than or equal to 0. Only these rows in expandedXOut are valid. - INT64 - - - expandedXOut Output Features expanded based on expertIdx. - Same as x ND The shape is (min(NUM_ROWS, activeNum) * K, H) x expandedRowIdxOut Output Mapping between expandedX and x. - INT32 ND Shape: (NUM_ROWS*K, ) x expandedExpertIdxOut Output Sorted result of expertIdx. - INT32 ND shape is (NUM_ROWS*K, ) x workspaceSize Output Returns the size of the workspace to be allocated on the Device. - - - - - executor Output Returns the op executor, which contains the operator computation process. - - - - - 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 Input and output tensors are null pointers. ACLNN_ERR_PARAM_INVALID 161002 The data types of input and output tensors are not within the supported range. ACLNN_ERR_INNER_TILING_ERROR 561002 The number of dimensions of the shape of x is not 2. The shape of rowIdx is not 2, or the shapes of rowIdx and expertIdx are not equal. The value of activeNum is less than 0. The shape of expandedXOut is not (min(num_rows, activeNum) * K, H). The shapes of expandedRowIdxOut and expandedExpertIdxOut are not equal, and neither is (num_rows * K, ).
aclnnMoeInitRouting
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the device. workspaceSize Input Workspace size allocated on the device, obtained by calling the first-phase API aclnnMoeInitRoutingGetWorkspaceSize.executor Input Op executor that contains the operator computation process. stream Input Stream for executing tasks. Return value
aclnnStatus: Return status code. For details, see aclnn_return_code.
Constraints
- Deterministic computation:
- aclnnMoeInitRouting defaults to a deterministic implementation.
- The values of elements in expertIdx must be greater than -2**24 and not greater than 2**24; otherwise, precision issues may occur.
Example
The following sample code 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.h"
#include <iostream>
#include <cstdio>
#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: initialize resources.
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 device-side memory.
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 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. Refer to the list of ACL public APIs.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle check as needed.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the inputs and outputs according to the API definition.
std::vector<int64_t> xShape = {3, 4};
std::vector<int64_t> idxShape = {3, 2};
std::vector<int64_t> expandedXOutShape = {6, 4};
std::vector<int64_t> idxOutShape = {6};
void* xDeviceAddr = nullptr;
void* rowIdxDeviceAddr = nullptr;
void* expertIdxDeviceAddr = nullptr;
void* expandedXOutDeviceAddr = nullptr;
void* expandedRowIdxOutDeviceAddr = nullptr;
void* expandedExpertIdxOutDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* rowIdx = nullptr;
aclTensor* expertIdx = nullptr;
int64_t activeNum = 3;
aclTensor* expandedXOut = nullptr;
aclTensor* expandedRowIdxOut = nullptr;
aclTensor* expandedExpertIdxOut = 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<int> rowIdxHostData = {0, 3, 1, 4, 2, 5};
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> expandedExpertIdxOutHostData = {0, 0, 0, 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(rowIdxHostData, idxShape, &rowIdxDeviceAddr, aclDataType::ACL_INT32, &rowIdx);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expertIdxHostData, idxShape, &expertIdxDeviceAddr, aclDataType::ACL_INT32, &expertIdx);
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, idxOutShape, &expandedRowIdxOutDeviceAddr, aclDataType::ACL_INT32, &expandedRowIdxOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expandedExpertIdxOutHostData, idxOutShape, &expandedExpertIdxOutDeviceAddr, aclDataType::ACL_INT32, &expandedExpertIdxOut);
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 aclnnMoeInitRouting.
ret = aclnnMoeInitRoutingGetWorkspaceSize(x, rowIdx, expertIdx, activeNum, expandedXOut, expandedRowIdxOut, expandedExpertIdxOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeInitRoutingGetWorkspaceSize 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 aclnnMoeInitRouting.
ret = aclnnMoeInitRouting(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeInitRouting failed. ERROR: %d\n", ret); return ret);
// 4. Boilerplate: synchronously wait 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 values and copy the results from the device side to the host side. 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(idxOutShape);
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 expandedExpertIdxSize = GetShapeSize(idxOutShape);
std::vector<int> expandedExpertIdxData(expandedExpertIdxSize, 0);
ret = aclrtMemcpy(expandedExpertIdxData.data(), expandedExpertIdxData.size() * sizeof(expandedExpertIdxData[0]), expandedExpertIdxOutDeviceAddr, expandedExpertIdxSize * 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 < expandedExpertIdxSize; i++) {
LOG_PRINT("expandedExpertIdxData[%ld] is: %d\n", i, expandedExpertIdxData[i]);
}
// 6. Release aclTensor and aclScalar. Modify the code based on the specific API definition.
aclDestroyTensor(x);
aclDestroyTensor(rowIdx);
aclDestroyTensor(expertIdx);
aclDestroyTensor(expandedXOut);
aclDestroyTensor(expandedRowIdxOut);
aclDestroyTensor(expandedExpertIdxOut);
// 7. Release device resources. Modify the code based on the specific API definition.
aclrtFree(xDeviceAddr);
aclrtFree(rowIdxDeviceAddr);
aclrtFree(expertIdxDeviceAddr);
aclrtFree(expandedXOutDeviceAddr);
aclrtFree(expandedRowIdxOutDeviceAddr);
aclrtFree(expandedExpertIdxOutDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}