aclnnMoeFinalizeRouting
Applicable Products
Ascend 950PR&950DT products : Not 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: In MoE computation, it finally processes and merges the output results of the MoE FFN.
- Formula:$$ expertid=expandedExpertIdx[i,k] $$$$ out(i,j)=x1_{i,j}+x2Optional_{i,j}+\sum_{k=0}^{K}(scales_{i,k}*(expandedX_{expandedRowIdx_{i+k*num_rows},j}+bias_{expertid,j})) $$
Function Prototype
Each operator uses a two-phase API. First, call the "aclnnMoeFinalizeRoutingGetWorkspaceSize" API to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the "aclnnMoeFinalizeRouting" API to perform the computation.
aclnnStatus aclnnMoeFinalizeRoutingGetWorkspaceSize(
const aclTensor* expandedX,
const aclTensor* x1,
const aclTensor* x2Optional,
const aclTensor* bias,
const aclTensor* scales,
const aclTensor* expandedRowIdx,
const aclTensor* expandedExpertIdx,
const aclTensor* out,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnMoeFinalizeRouting(
void* workspace,
uint64_t workspaceSize,
aclOpExecutor* executor,
aclrtStream stream)aclnnMoeFinalizeRoutingGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor expandedX Input expandedX in the formula, the FFN output of MoE. Must be a 2D tensor. FLOAT16, BFLOAT16, FLOAT32 ND (NUM_ROWS * K, H)
NUM_ROWS: number of rows
K: K experts selected from the total E experts
H: number of columns√ x1 Input x1 in the formula. Must be a 2D tensor. Same as expandedX ND Same as out √ x2Optional Input x2Optional in the formula. Must be a 2D tensor. Same as expandedX ND Same as out √ bias Input The bias in the formula. Requires a 2D tensor. Same as expandedX ND (E, H)
E indicates the total number of experts, and H indicates the number of columns.√ scales Input Scales in the formula. Must be a 2D tensor. Same as expandedX ND (NUM_ROWS, K) √ expandedRowIdx Input expandedRowIdx in the formula. Must be a 1D tensor.
The values in the tensor are in the range of [0, NUM_ROWS * K-1].INT32 ND (NUM_ROWS * K) √ expandedExpertIdx Input expandedExpertIdx in the formula. Must be a 2D tensor.
Values in the tensor are in the range [0, E-1], where E is the total number of experts.INT32 ND (NUM_ROWS, K) √ out Output Output in the formula. Must be a 2D tensor. Same as expandedX. ND (NUM_ROWS, H) × workspaceSize Output Returns the workspace size to be allocated on the Device side. - - - - - executor Output Returns the op executor containing the operator computation flow. - - - - - 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 expandedX, x1, x2Optional, bias, scales, expandedRowIdx, or expandedExpertIdx is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types of expandedX, x1, x2Optional, bias, scales, expandedRowIdx, and expandedExpertIdx are out of the supported range. The shapes of expandedX, x1, x2Optional, bias, scales, expandedRowIdx, and expandedExpertIdx are out of the supported range.
aclnnMoeFinalizeRouting
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 aclnnMoeFinalizeRoutingGetWorkspaceSize. executor Input Executor of the op, containing the operator computation process. stream Input Stream used for task execution. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation:
- aclnnMoeFinalizeRouting defaults to a deterministic implementation.
Example
The following sample code is for reference only. For details about how to compile and run, see Compile and Run Samples.
#include "acl/acl.h"
#include "aclnnop/aclnn_moe_finalize_routing.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 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 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 data 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 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 ACL API guide.
// 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 as required by the API.
std::vector<int64_t> expandedXShape = {3 * 2, 4};
std::vector<int64_t> x1Shape = {3, 4};
std::vector<int64_t> x2OptionalShape = {3, 4};
std::vector<int64_t> biasShape = {2, 4};
std::vector<int64_t> scalesShape = {3, 2};
std::vector<int64_t> expandedExpertIdxShape = {3, 2};
std::vector<int64_t> expandedRowIdxShape = {3 * 2};
std::vector<int64_t> outShape = {3, 4};
void* expandedXAddr = nullptr;
void* x1Addr = nullptr;
void* x2OptionalAddr = nullptr;
void* biasAddr = nullptr;
void* scalesDeviceAddr = nullptr;
void* expandedExpertIdxAddr = nullptr;
void* expandedRowIdxAddr = nullptr;
void* outDeviceAddr = nullptr;
aclTensor* expandedX = nullptr;
aclTensor* x1 = nullptr;
aclTensor* x2Optional = nullptr;
aclTensor* bias = nullptr;
aclTensor* scales = nullptr;
aclTensor* expandedExpertIdx = nullptr;
aclTensor* expandedRowIdx = nullptr;
aclTensor* out = nullptr;
std::vector<float> expandedXHostData = {0.1, 1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1, 11.1,
0.1, 1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1, 11.1};
std::vector<float> x1HostData = {0.2, 1.2, 2.2, 3.2, 4.2, 5.2, 6.2, 7.2, 8.2, 9.2, 10.2, 11.2};
std::vector<float> x2OptionalHostData = {0.2, 1.2, 2.2, 3.2, 4.2, 5.2, 6.2, 7.2, 8.2, 9.2, 10.2, 11.2};
std::vector<float> biasHostData = {0.2, 0.4, 0.2, 0.4, 0.2, 0.4, 0.2, 0.4};
std::vector<float> scalesHostData = {1.3, 1.6, 1.2, 1.8, 1.2, 2.3};
std::vector<int32_t> expandedExpertIdxHostData = {0, 1, 0, 1, 0, 1};
std::vector<int32_t> expandedRowIdxHostData = {2, 1, 4, 3, 0, 5};
std::vector<float> outHostData(12, 0.0f);
// Create the expandedX aclTensor.
ret = CreateAclTensor(expandedXHostData, expandedXShape, &expandedXAddr,
aclDataType::ACL_FLOAT, &expandedX);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the x1 aclTensor.
ret = CreateAclTensor(x1HostData, x1Shape, &x1Addr, aclDataType::ACL_FLOAT, &x1);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the x2Optional aclTensor.
ret = CreateAclTensor(x2OptionalHostData, x2OptionalShape, &x2OptionalAddr, aclDataType::ACL_FLOAT, &x2Optional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the bias aclTensor.
ret = CreateAclTensor(biasHostData, biasShape, &biasAddr, aclDataType::ACL_FLOAT, &bias);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the scale aclTensor.
ret = CreateAclTensor(scalesHostData, scalesShape, &scalesDeviceAddr, aclDataType::ACL_FLOAT, &scales);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the expandedExpertIdx aclTensor.
ret = CreateAclTensor(expandedExpertIdxHostData, expandedExpertIdxShape, &expandedExpertIdxAddr,
aclDataType::ACL_INT32, &expandedExpertIdx);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the expandedRowIdx aclTensor.
ret = CreateAclTensor(expandedRowIdxHostData, expandedRowIdxShape, &expandedRowIdxAddr,
aclDataType::ACL_INT32, &expandedRowIdx);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the Out aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace it with the specific operator API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnMoeFinalizeRouting.
ret = aclnnMoeFinalizeRoutingGetWorkspaceSize(expandedX, x1, x2Optional, bias, scales,
expandedRowIdx, expandedExpertIdx, out, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeFinalizeRoutingGetWorkspaceSize 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 aclnnMoeFinalizeRouting.
ret = aclnnMoeFinalizeRouting(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeFinalizeRouting failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Wait for task execution to complete synchronously.
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 as required by the specific API definition.
auto size = GetShapeSize(outShape);
std::vector<float> resultData(size, 0.0f);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
outDeviceAddr, size * 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 < size; i++) {
LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
}
// 6. Release aclTensor and aclScalar. Modify as required by the specific API definition.
aclDestroyTensor(expandedX);
aclDestroyTensor(x1);
aclDestroyTensor(x2Optional);
aclDestroyTensor(bias);
aclDestroyTensor(scales);
aclDestroyTensor(expandedExpertIdx);
aclDestroyTensor(expandedRowIdx);
aclDestroyTensor(out);
// 7. Release device resources. Modify as required by the specific API definition.
aclrtFree(expandedXAddr);
aclrtFree(x1Addr);
aclrtFree(x2OptionalAddr);
aclrtFree(biasAddr);
aclrtFree(scalesDeviceAddr);
aclrtFree(expandedExpertIdxAddr);
aclrtFree(expandedRowIdxAddr);
aclrtFree(outDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}