aclnnMoeTokenUnpermuteWithRoutingMap
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: Accumulates the permutedTokens processed by aclnnMoeTokenUnpermuteWithRoutingMap back to the original unpermutedTokens. Retrieves the input data stored in permutedTokens based on the indices stored in sortedIndices. If probs data exists, permutedTokens is multiplied by probs, and then the results are accumulated and summed to produce the output.
- Formula:$$ topK\_num= permutedTokens.size(0) // routingMapOptional.size(0) $$where
topK_numindicates the maximum number of expert slots reserved for each token. WhenpaddedModeis false, the number of experts actually selected for each token can be less than or equal totopK_num; unused slots are indicated by-1insortedIndicesand are skipped during computation.$$ numExperts = probs.size(1) $$$$ numTokens = probs.size(0) $$$$ capacity = sortedIndices.size(0) // numExperts $$(1) When probs is not None and paddedMode is true:$$ permuteProbs [i//capacity,sortedIndices[i]]=probs[i] $$$$ permutedTokens = permutedTokens * permuteProbs $$$$ unpermutedTokens= zeros(restoreShape, dtype=permutedTokens.dtype, device=permutedTokens.device) $$$$ permuteTokenId, outIndex= sortedIndices.sort(dim=-1) $$$$ unpermutedTokens[permuteTokenId[i]] += permutedTokens[outIndex[i]] $$(2) When probs is not None and paddedMode is false (T denotes the transpose operation):$$ permuteProbs = probs.T.maskedSelect(routingMap.T) $$$$ permutedTokens = permutedTokens * permuteProbs $$$$ unpermutedTokens= zeros(restoreShape, dtype=permutedTokens.dtype, device=permutedTokens.device) $$$$ if sortedIndices[i] >= 0: unpermutedTokens[i//topK\_num] += permutedTokens[sortedIndices[i]] * permuteProbs[i] $$(3) When probs is None and paddedMode is true:$$ permuteTokenId, outIndex= sortedIndices.sort(dim=-1) $$$$ unpermutedTokens[permuteTokenId[i]] += permutedTokens[outIndex[i]] $$(4) When probs is None and paddedMode is false:$$ if sortedIndices[i] >= 0: unpermutedTokens[i//topK\_num] += permutedTokens[sortedIndices[i]] $$
Function Prototype
Each operator uses a two-phase API. Call "aclnnMoeTokenUnpermuteWithRoutingMapGetWorkspaceSize" first to obtain the workspace size required for computation and the executor that contains the operator computation flow, and then call "aclnnMoeTokenUnpermuteWithRoutingMap" to execute the computation.
aclnnStatus aclnnMoeTokenUnpermuteWithRoutingMapGetWorkspaceSize(
const aclTensor *permutedTokens,
const aclTensor *sortedIndices,
const aclTensor *routingMapOptional,
const aclTensor *probsOptional,
bool paddedMode,
const aclIntArray *restoreShapeOptional,
aclTensor *unpermutedTokens,
aclTensor *outIndex,
aclTensor *permuteTokenId,
aclTensor *permuteProbs,
uint64_t *workspaceSize,
aclOpExecutor **executor);aclnnStatus aclnnMoeTokenUnpermuteWithRoutingMap(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnMoeTokenUnpermuteWithRoutingMapGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor permutedTokens (aclTensor*) Input Indicates the input token. In the shape, capacity indicates the number of tokens each expert can process. BFLOAT16, FLOAT16, FLOAT ND when paddedMode is false: (tokens_num * topK_num, hidden_size)
when paddedMode is true: (experts_num* capacity, hidden_size)√ sortedIndices (aclTensor*) Input Indicates the mapping between input and output gradients. When paddedMode is false, the index value range must be [0, tokens_num * topK_num - 1].
When paddedMode is true, the index value range is [0, tokens_num - 1].INT32 ND When paddedMode is false: (tokens_num * topK_num)
When paddedMode is true: (experts_num * capacity)√ routingMapOptional(aclTensor*) Input routingMapOptional in the Formula. Indicates whether the token at the corresponding position is processed by the corresponding expert. Not required when the input probsOptional is a null pointer. Pass a null pointer in this case.
When the data type is INT8, supported values are 0 and 1.
When the data type is bool, supported values are true and false.INT8, BOOL ND (tokens_num, experts_num) √ probsOptional (aclTensor*) Input probsOptional in the Formula. It represents the weight of the token at the corresponding position processed by the corresponding expert in the final result. The data type is the same as that of permutedTokens, or FLOAT is supported when permutedTokens is BFLOAT16. BFLOAT16, FLOAT16, FLOAT ND Same as routingMapOptional √ paddedMode (bool) Input Specifies whether padded mode is enabled. true indicates that paddedMode is enabled.
false indicates that paddedMode is disabled.- - - - restoreShapeOptional (aclIntArray*) Input Shape of unpermutedTokens. The size is 2. INT64 - - - unpermutedTokens (aclTensor*) Output Forward output, corresponding to unpermutedTokens in the Formula. - BFLOAT16, FLOAT16, FLOAT ND (tokens_num, hidden_size) √ outIndex (aclTensor*) Output Represents the output index, that is, outIndex in the Formula. When paddedMode is false, outIndex indicates the slot index, with the value range of [0, tokens_num * topK_num - 1]. -1 in sortedIndices only indicates an invalid input slot and does not change the slot index range of outIndex.
When paddedMode is true, the index value range is [0, experts_num* capacity- 1].INT32 ND When paddedMode is false: (tokens_num * topK_num)
When paddedMode is true: (experts_num* capacity)√ permuteTokenId (aclTensor*) Output permuteTokenId in the Formula. Value range of the index: [0, tokens_num - 1]. INT32 ND When paddedMode is false: (tokens_num * topK_num)
When paddedMode is true: (experts_num* capacity)√ permuteProbs (aclTensor*) Output permuteProbs in the Formula. It indicates the sorted output probs. Same as probsOptional. BFLOAT16, FLOAT16, FLOAT ND 1 √ workspaceSize (uint64_t*) Output Size of the workspace to be allocated on the Device side. - - - - - executor (aclOpExecutor**) Output Returns the op executor, which contains the computation process of the operator. - - - - - 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 Tensor of a required input or required output is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type or shape of an input or output is out of the supported range. ACLNN_ERR_INNER_NULLPTR 561103 topK_num > 512. The shape of probsOptional is out of the supported range.
aclnnMoeTokenUnpermuteWithRoutingMap
Parameters
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device side. workspaceSize Input Workspace size allocated on the Device side, obtained by the first-phase API aclnnMoeTokenUnpermuteWithRoutingMapGetWorkspaceSize. executor Input opExecutor containing the operator computation flow. stream Input Stream for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
- aclnnMoeTokenUnpermuteWithRoutingMap defaults to a non-deterministic implementation. Deterministic computation can be enabled by using aclrtCtxSetSysParamOpt.
topK_num <= 512. When paddedMode is false, each token reserves at most topK_num expert slots, and the number of 1 or true values in each row of routingMap must be less than or equal to topK_num. -1 is allowed in sortedIndices to indicate an invalid slot.
The following scenarios will be intercepted in later versions. If a warning is displayed, rectify the issue:
- paddedMode is true, and topK_num > experts_num.
- paddedMode is true, and capacity > tokens_num.
- The data type or shape of routingMap does not meet the requirements.
- The data format of the input tensor is not ND.
Example
The sample code is as follows and is for reference only. For the compilation and execution procedure, see Compile and Run Samples.
#include "acl/acl.h"
#include "aclnnop/aclnn_moe_token_unpermute_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 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 aclCreateTensor to create the 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.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle the check as required.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output according to the API definition.
std::vector<int64_t> permutedTokensShape = {2, 2};
std::vector<int64_t> sortedIndicesShape = {2};
std::vector<int64_t> routingMapOptionalShape = {2, 2};
std::vector<int64_t> probsShape = {2, 2};
std::vector<int64_t> unpermutedTokensShape = {2, 2};
std::vector<int64_t> outIndexShape = {2};
std::vector<int64_t> permuteTokenIdShape = {2};
std::vector<int64_t> permuteProbsShape = {2};
void* permutedTokensDeviceAddr = nullptr;
void* sortedIndicesDeviceAddr = nullptr;
void* routingMapOptionalDeviceAddr = nullptr;
void* probsDeviceAddr = nullptr;
void* unpermutedTokensDeviceAddr = nullptr;
void* outIndexDeviceAddr = nullptr;
void* permuteTokenIdDeviceAddr = nullptr;
void* permuteProbsDeviceAddr = nullptr;
//in
aclTensor* permutedTokens = nullptr;
aclTensor* sortedIndices = nullptr;
aclTensor* routingMapOptional = nullptr;
aclTensor* probs = nullptr;
aclTensor* unpermutedTokens = nullptr;
aclTensor* outIndex = nullptr;
aclTensor* permuteTokenId = nullptr;
aclTensor* permuteProbs = nullptr;
bool paddedMode = true;
std::vector<int64_t> restoreShapeOptionalData = {2, 2};
aclIntArray *restoreShapeOptional = aclCreateIntArray(restoreShapeOptionalData.data(), restoreShapeOptionalData.size());
// Construct the data.
std::vector<float> permutedTokensHostData = {1.0, 1.0, 1.0, 1.0};
std::vector<int> sortedIndicesHostData = {1, 1};
std::vector<char> routingMapOptionalHostData = {1, 1, 1, 1};
std::vector<float> probsHostData = {1, 1, 1, 1};
std::vector<float> unpermutedTokensHostData = {0, 0, 0, 0};
std::vector<int> outIndexHostData = {0, 0};
std::vector<int> permuteTokenIdHostData = {0, 0};
std::vector<float> permuteProbsHostData = {0, 0};
// Create the self aclTensor.
ret = CreateAclTensor(permutedTokensHostData, permutedTokensShape, &permutedTokensDeviceAddr, aclDataType::ACL_FLOAT, &permutedTokens);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(sortedIndicesHostData, sortedIndicesShape, &sortedIndicesDeviceAddr, aclDataType::ACL_INT32, &sortedIndices);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(routingMapOptionalHostData, routingMapOptionalShape, &routingMapOptionalDeviceAddr, aclDataType::ACL_INT8, &routingMapOptional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(probsHostData, probsShape, &probsDeviceAddr, aclDataType::ACL_FLOAT, &probs);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the out aclTensor.
ret = CreateAclTensor(unpermutedTokensHostData, unpermutedTokensShape, &unpermutedTokensDeviceAddr, aclDataType::ACL_FLOAT, &unpermutedTokens);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(outIndexHostData, outIndexShape, &outIndexDeviceAddr, aclDataType::ACL_INT32, &outIndex);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(permuteTokenIdHostData, permuteTokenIdShape, &permuteTokenIdDeviceAddr, aclDataType::ACL_INT32, &permuteTokenId);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(permuteProbsHostData, permuteProbsShape, &permuteProbsDeviceAddr, aclDataType::ACL_FLOAT, &permuteProbs);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Change it to a specific API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnMoeTokenUnpermuteWithRoutingMap.
ret = aclnnMoeTokenUnpermuteWithRoutingMapGetWorkspaceSize(permutedTokens, sortedIndices, routingMapOptional, probs, paddedMode, restoreShapeOptional,
unpermutedTokens, outIndex, permuteTokenId, permuteProbs, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeTokenUnpermuteWithRoutingMapGetWorkspaceSize 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 = aclnnMoeTokenUnpermuteWithRoutingMap(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeTokenUnpermuteWithRoutingMap failed. ERROR: %d\n", ret); return ret);
// 4. Boilerplate. Synchronize and 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 memory to the host. Modify it based on the specific API definition.
auto unpermutedTokensSize = GetShapeSize(unpermutedTokensShape);
std::vector<float> unpermutedTokensData(unpermutedTokensSize, 0);
ret = aclrtMemcpy(unpermutedTokensData.data(), unpermutedTokensData.size() * sizeof(unpermutedTokensData[0]), unpermutedTokensDeviceAddr, unpermutedTokensSize * 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 < unpermutedTokensSize; i++) {
LOG_PRINT("unpermutedTokensData[%ld] is: %f\n", i, unpermutedTokensData[i]);
}
// 6. Release the aclTensor and aclScalar. Modify it based on the specific API definition.
aclDestroyTensor(permutedTokens);
aclDestroyTensor(sortedIndices);
aclDestroyTensor(routingMapOptional);
aclDestroyTensor(probs);
aclDestroyTensor(unpermutedTokens);
aclDestroyTensor(outIndex);
aclDestroyTensor(permuteTokenId);
aclDestroyTensor(permuteProbs);
// 7. Release the device resources. Modify it based on the specific API definition.
aclrtFree(permutedTokensDeviceAddr);
aclrtFree(sortedIndicesDeviceAddr);
aclrtFree(routingMapOptionalDeviceAddr);
aclrtFree(probsDeviceAddr);
aclrtFree(unpermutedTokensDeviceAddr);
aclrtFree(outIndexDeviceAddr);
aclrtFree(permuteTokenIdDeviceAddr);
aclrtFree(permuteProbsDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}