aclnnMoeTokenUnpermute
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: Retrieves the input data stored in permutedTokens based on the indices stored in sortedIndices. If probs data exists, permutedTokens is multiplied by probs. Finally, cumulative summation is performed and the computation result is output.
Formula:
When probs is not None, the formula is as follows:
$$ T[k] = T[S[k]] $$$$ T[k] = T[k] * P[i][j] $$$$ O[i] = \sum_{k=i*topK}^{(i+1)*topK - 1 } T[k] $$Where $i \in {0,1,...,tokens-1}$; $j \in {0,1,...,topK-1}$; $k \in {0,1,...,tokens*topK-1}$; T denotes permutedTokens; S denotes sortedIndices; P denotes probs; O denotes out; topK denotes topK_num; tokens denotes tokens_num.
When probs is None, topK_num = 1, and the formula is as follows:
$$ T[i] = T[S[i]] $$$$ O[i] = T[i] $$Where $i \in {0,1,...,tokens-1}$; T denotes permutedTokens; S denotes sortedIndices; O denotes out; and tokens denotes tokens_num.
Function Prototype
Each operator uses a two-phase API. First call the "aclnnMoeTokenUnpermuteGetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the operator computation flow. Then call the "aclnnMoeTokenUnpermute" API to perform the computation.
aclnnStatus aclnnMoeTokenUnpermuteGetWorkspaceSize(
const aclTensor *permutedTokens,
const aclTensor *sortedIndices,
const aclTensor *probsOptional,
bool paddedMode,
const aclIntArray *restoreShapeOptional,
aclTensor *out,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMoeTokenUnpermute(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMoeTokenUnpermuteGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor permutedTokens (aclTensor) Input Input tokens, that is, T in the Formula. Shape is (tokens_num * topK_num, hidden_size), where tokens_num indicates the number of input tokens, topK_num indicates the number of experts for each token, and hidden_size indicates the length of the vector representation of each token. BFLOAT16, FLOAT16, FLOAT32 ND 2 β sortedIndices(aclTensor) Input Indicates the positions of the data to be computed in permutedTokens. - shape is (tokens_num * topK_num).
- The value range is [0, tokens_num * topK_num - 1], and there are no duplicate indices.
INT32 ND 1 β probsOptional(aclTensor) Input P in the formula. - If probs is passed, topK_num equals the second dimension of probs; if probs is not passed, topK_num=1.
- If probs is passed, topK_num equals the second dimension of probs; if probs is not passed, topK_num=1.
- shape is (tokens_num, topK_num).
BFLOAT16, FLOAT16, FLOAT32 ND 2 β paddedMode (bool) Input Indicates whether paddedMode is enabled. - If paddedMode is true, restoreShapeOptional takes effect. Otherwise, it is not processed.
- Currently, only false is supported.
BOOL - - - restoreShapeOptional (aclIntArray) Input Shape of the output when paddedMode is true. - When paddedMode is true, restoreShapeOptional takes effect, and the shape of out is represented as restoreShapeOptional.
- Currently, only nullptr is supported.
aclIntArray* - - - out (aclTensor) Output Output result. - When paddedMode=false, the shape is (tokens_num, hidden_size); when paddedMode=true, the shape is the same as restoreShapeOptional.
- The data type is the same as permutedTokens.
BFLOAT16, FLOAT16, FLOAT32 ND 2 Γ workspaceSize (uint64_t) Output Returns the workspace size to be allocated on the Device. - - - - - executor (aclOpExecutor) Output Returns the op executor containing the operator computation flow. - - - - - Return value
aclnnStatus: Return 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 mandatory input, mandatory output, or mandatory attribute passed in is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of the inputs and outputs are out of the supported range. ACLNN_ERR_INNER_TILING_ERROR 561002 The shape information of multiple input tensors does not match. The shape information between input attributes and input tensors does not match.
aclnnMoeTokenUnpermute
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device. workspaceSize Input Workspace size allocated on the Device, obtained by the first-phase API aclnnMoeTokenUnpermuteGetWorkspaceSize.executor Input Op executor containing 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:
- aclnnMoeTokenUnpermute defaults to a deterministic implementation.
Atlas A2 products ,Atlas A3 products : topK_num <= 512.
Ascend 950PR&950DT products : When this API is called, the framework internally calls aclnnMoeFinalizeRoutingV2. If a parameter error message is displayed, refer to the following parameter mapping:- The permutedTokens input is equivalent to the expandedX input of the aclnnMoeFinalizeRoutingV2 API.
- The sortedIndices input is equivalent to the expandedRowIdx input of the aclnnMoeFinalizeRoutingV2 API.
- The probsOptional input is equivalent to the scalesOptional input of the aclnnMoeFinalizeRoutingV2 API.
- The paddedMode input is equivalent to the dropPadMode input of the aclnnMoeFinalizeRoutingV2 API.
- The out output is equivalent to the out output of the aclnnMoeFinalizeRoutingV2 API.
- |
Atlas inference products :- The supported data types for permutedTokens and probsOptional are FLOAT16 and FLOAT32.
- topK_num <= 512.
- hidden_size is a multiple of 128 and less than 10240.
Example
The 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_unpermute.h"
#include <iostream>
#include <vector>
#include <cstdio>
#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 shapeSize = 1;
for (auto i : shape) {
shapeSize *= i;
}
return shapeSize;
}
void PrintOutResult(std::vector<int64_t> &shape, void **deviceAddr) {
auto size = GetShapeSize(shape);
std::vector<float> resultData(size, 0);
auto ret = aclrtMemcpy(
resultData.data(), resultData.size() * sizeof(resultData[0]), *deviceAddr,
size * sizeof(resultData[0]), ACL_MEMCPY_DEVICE_TO_HOST);
CHECK_RET(
ret == ACL_SUCCESS,
LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret);
return );
for (int64_t i = 0; i < size; i++) {
LOG_PRINT("mean result[%ld] is: %f\n", i, resultData[i]);
}
}
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 device 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 data from the host to 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) Device/stream initialization, see the acl API reference.
// Fill in deviceId according to your actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("Init acl failed. ERROR: %d\n", ret);
return ret);
// 2. Construct the inputs and outputs. Customize the construction according to the API.
std::vector<float> permutedTokensData = {1, 2, 3, 4};
std::vector<int64_t> permutedTokensShape = {2, 2};
void *permutedTokensAddr = nullptr;
aclTensor *permutedTokens = nullptr;
ret = CreateAclTensor(permutedTokensData, permutedTokensShape,
&permutedTokensAddr, aclDataType::ACL_FLOAT,
&permutedTokens);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<int> sortedIndicesData = {0,1};
std::vector<int64_t> sortedIndicesShape = {2};
void *sortedIndicesAddr = nullptr;
aclTensor *sortedIndices = nullptr;
ret =
CreateAclTensor(sortedIndicesData, sortedIndicesShape, &sortedIndicesAddr,
aclDataType::ACL_INT32, &sortedIndices);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> probsOptionalData = {1, 1};
std::vector<int64_t> probsOptionalShape = {1, 2};
void *probsOptionalAddr = nullptr;
aclTensor *probsOptional = nullptr;
ret =
CreateAclTensor(probsOptionalData, probsOptionalShape, &probsOptionalAddr,
aclDataType::ACL_FLOAT, &probsOptional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> outData = {0, 0};
std::vector<int64_t> outShape = {1, 2};
void *outAddr = nullptr;
aclTensor *out = nullptr;
ret = CreateAclTensor(outData, outShape, &outAddr, aclDataType::ACL_FLOAT,
&out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Change Api to the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor *executor;
// Call the first-phase API of aclnnMoeTokenUnpermute.
ret = aclnnMoeTokenUnpermuteGetWorkspaceSize(permutedTokens, sortedIndices,
probsOptional, false, nullptr,
out, &workspaceSize, &executor);
CHECK_RET(
ret == ACL_SUCCESS,
LOG_PRINT("aclnnMoeTokenUnpermuteGetWorkspaceSize 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 aclnnMoeTokenUnpermute.
ret = aclnnMoeTokenUnpermute(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnMoeTokenUnpermute failed. ERROR: %d\n", ret);
return ret);
// 4. (boilerplate) Synchronize and wait for the task to finish.
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 the code according to the specific API definition.
PrintOutResult(outShape, &outAddr);
// 6. Release aclTensor and aclScalar. Modify the code according to the specific API definition.
aclDestroyTensor(permutedTokens);
aclDestroyTensor(sortedIndices);
aclDestroyTensor(probsOptional);
aclDestroyTensor(out);
// 7. Release device resources.
aclrtFree(permutedTokensAddr);
aclrtFree(sortedIndicesAddr);
aclrtFree(probsOptionalAddr);
aclrtFree(outAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}