aclnnMoeTokenPermuteWithRoutingMap
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: MoE permute computation. Passes token and expert labels as the routingMap, and sorts tokens and optional probsOptional after broadcasting based on the routingMap.
Formula:
tokens_num is the size of dimension 0 of routingMap, expert_num is the size of dimension 1 of routingMap when dropAndPad is
false$$ expertIndex=arange(tokens\_num).expand(expert\_num,-1) $$$$ sortedIndicesFirst=expertIndex.masked\_select(routingMap.T) $$$$ sortedIndicesOut=argsort(sortedIndicesFirst) $$$$ topK = numOutTokens // tokens\_num $$$$ outToken = topK * tokens\_num $$$$ permuteTokensOut[sortedIndicesOut[i]]=tokens[i//topK] $$If probs is not none
$$ permuteProbsOutOptional=probsOptional.T.masked\_select(routingMap.T) $$When dropAndPad is
true$$ capacity = numOutTokens // expert\_num $$$$ outToken = capacity * expert\_num $$$$ sortedIndicesOut = argsort[routingMap.T,dim=-1](:, :capacity) $$$$ permutedTokensOut = tokens.index\_select(0, sortedIndicesOut) $$If probs is not none
$$ probs\_T\_1D = probsOptional.T.view(-1) $$$$ indices\_dim0 = arange(expert\_num).view(expert\_num, 1) $$$$ indices\_dim1 = sortedIndicesOut.view(expert\_num, capacity) $$$$ indices\_1D = (indices\_dim0 * tokens\_num + indices\_dim1).view(-1) $$$$ permuteProbsOutOptional = probs\_T\_1D.index\_select(0, indices\_1D) $$
Function Prototype
Each operator uses a two-phase API. Call the "aclnnMoeTokenPermuteWithRoutingMapGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the operator computation process. Then call the "aclnnMoeTokenPermuteWithRoutingMap" API to perform computation.
aclnnStatus aclnnMoeTokenPermuteWithRoutingMapGetWorkspaceSize(
const aclTensor *tokens,
const aclTensor *routingMap,
const aclTensor *probsOptional,
int64_t numOutTokens,
bool dropAndPad,
aclTensor *permuteTokensOut,
aclTensor *permuteProbsOutOptional,
aclTensor *sortedIndicesOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMoeTokenPermuteWithRoutingMap(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMoeTokenPermuteWithRoutingMapGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor tokens Input Input token features. - Empty tensors are supported.
- Must be a 2D tensor with shape (tokens_num, hidden_size).
BFLOAT16, FLOAT16, FLOAT ND 2 √ routingMap Input The mapping from token to expert. - Supports empty tensors.
- Requires a 2D shape of (tokens_num, experts_num).
- Supports 0 and 1 when the data type is INT8, and true and false when the data type is BOOL.
- In modes other than dropAndPad, each row must contain fewer than topK true or 1 values.
INT8, BOOL ND 2 √ probsOptional Input Optional input probsOptional. - Supports empty tensors.
- The number of elements is the same as routingMap.
- If probsOptional is empty, optional output permuteProbsOutOptional is empty.
- The data type of probsOptional can differ from that of tokens only when the data type of probsOptional is FLOAT and the data type of tokens is BFLOAT16. In other use cases, the data type of probsOptional must be the same as that of tokens.
BFLOAT16, FLOAT16, FLOAT ND 2 √ numOutTokens Input Number of valid output tokens. Used as topK and capacity in the formula. The value ranges from 0 to tokens_num * experts_num, both inclusive. - - - - dropAndPad Input Specifies whether to enable the dropAndPad mode. Value options: false and true. - false: indicates the non-dropAndPad mode.
- true: indicates the dropAndPad mode.
- - - - permuteTokensOut Output Tokens expanded, sorted, and filtered based on indices. - Supports empty tensors.
- Must be a 2D tensor with shape (outToken, hidden_size).
- Same data type as tokens.
BFLOAT16, FLOAT16, FLOAT ND 2 √ permuteProbsOutOptional Output probsOptional sorted and filtered based on indices. - Supports empty tensors.
- The shape is (outToken).
- Data type is the same as probsOptional.
BFLOAT16, FLOAT16, FLOAT ND 1 √ sortedIndicesOut Output Mapping between permuteTokensOut and tokens. - Supports empty tensors.
- Must be a 1D tensor with shape (outToken).
INT32 ND 1 √ workspaceSize Output Returns the workspace size to be allocated on the Device. - - - - - executor Output Returns the op executor containing the operator computation process. - - - - - Return value
aclnnStatus: Returns the 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 input or output tensor is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output tensor is not in the supported range. The input or output shape is invalid. numOutTokens < 0 or numOutTokens > tokens_num * experts_num ACLNN_ERR_INNER_NULLPTR 561103 The internal pointer is null.
aclnnMoeTokenPermuteWithRoutingMap
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 the first-phase API aclnnMoeTokenPermuteWithRoutingMapGetWorkspaceSize.executor Input Operator executor that contains the operator computation process. stream Input Stream for executing tasks. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
- aclnnMoeTokenPermuteWithRoutingMap defaults to a deterministic implementation.
When pad mode is true, tokens_num must be less than
16777215. When pad mode is false, the number of 1 or true values in each row of routingMap must be less than topK and less than512, and topK * tokens_num must be less than16777215.
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_token_permute_with_routing_map.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 for 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 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 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 for device/stream initialization. For details, see the list of ACL external APIs.
// Set 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 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* indicesDeviceAddr = nullptr;
void* expandedXOutDeviceAddr = nullptr;
void* sortedIndicesOutDeviceAddr = nullptr;
aclTensor* x = nullptr;
aclTensor* indices = nullptr;
int64_t numTokenOut = 6;
bool padMode = false;
aclTensor* expandedXOut = nullptr;
aclTensor* sortedIndicesOut = 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<uint8_t> indicesHostData = {1, 1, 1, 1, 1, 1};
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> sortedIndicesOutHostData = {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(indicesHostData, idxShape, &indicesDeviceAddr, aclDataType::ACL_INT8, &indices);
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(sortedIndicesOutHostData, idxOutShape, &sortedIndicesOutDeviceAddr, aclDataType::ACL_INT32, &sortedIndicesOut);
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 aclnnMoeTokenPermuteWithRoutingMap.
ret = aclnnMoeTokenPermuteWithRoutingMapGetWorkspaceSize(x, indices, nullptr, numTokenOut, padMode, expandedXOut, nullptr, sortedIndicesOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeTokenPermuteWithRoutingMapGetWorkspaceSize 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);
}
ret = aclnnMoeTokenPermuteWithRoutingMap(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeTokenPermuteWithRoutingMap 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 device memory to the host side. Modify it according to 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 sortedIndicesSize = GetShapeSize(idxOutShape);
std::vector<int> sortedIndicesData(sortedIndicesSize, 0);
ret = aclrtMemcpy(sortedIndicesData.data(), sortedIndicesData.size() * sizeof(sortedIndicesData[0]), sortedIndicesOutDeviceAddr, sortedIndicesSize * 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 < sortedIndicesSize; i++) {
LOG_PRINT("sortedIndicesData[%ld] is: %d\n", i, sortedIndicesData[i]);
}
// 6. Release aclTensor and aclScalar. Modify it according to the specific API definition.
aclDestroyTensor(x);
aclDestroyTensor(indices);
aclDestroyTensor(expandedXOut);
aclDestroyTensor(sortedIndicesOut);
// 7. Release device resources. Modify it according to the specific API definition.
aclrtFree(xDeviceAddr);
aclrtFree(indicesDeviceAddr);
aclrtFree(expandedXOutDeviceAddr);
aclrtFree(sortedIndicesOutDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}