aclnnMoeGatingTopK
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: In MoE computation, Sigmoid, SoftMax, or SqrtSoftplus is applied to input x. Grouped sorting is performed on the computation results. Then, the top k experts are selected based on the grouped sorting result.
Formula:
Step 1: Normalization
Perform normalization on input x according to normType:
Step 2: Add bias
If bias is not empty, perform bias addition to obtain the value used for selection:
Otherwise, $normValue = normOut$.
Step 3: group filtering (performed only when groupCount > 1)
Divide normValue into groupCount groups and compute the score of each group based on groupSelectMode:
Select the kGroup groups with the highest scores and set the corresponding positions of the unselected groups to $-\infty$:
Step 4: Top-K expert selection
Apply Top-K to normValue to obtain the expert index. Only expertIdxOut is needed here:
Step 5: Renorm and scaling
Obtain the corresponding k expert scores from normOut based on expertIdxOut:
Normalization is performed when normType=1 or normType=2; when normType=0, the renorm parameter effect applies, and renorm is performed when renorm=1:
Otherwise $yOut = gathered$
Final output:
Step 6: Optional output
If outFlag is True, the third output is normOut; otherwise, it is empty.
Function Prototype
Each operator is split into a two-phase API. You must first call the "aclnnMoeGatingTopKGetWorkspaceSize" API to obtain the workspace size required for calculation and the executor that includes calculation processes of the operator, and then call the "aclnnMoeGatingTopK" API to perform the calculation.
aclnnStatus aclnnMoeGatingTopKGetWorkspaceSize(
const aclTensor *x,
const aclTensor *biasOptional,
int64_t k,
int64_t kGroup,
int64_t groupCount,
int64_t groupSelectMode,
int64_t renorm,
int64_t normType,
bool outFlag,
double routedScalingFactor,
double eps,
const aclTensor *yOut,
const aclTensor *expertIdxOut,
const aclTensor *outOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMoeGatingTopK(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMoeGatingTopKGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x Input Input tensor to be computed, corresponding to x in the formula. None FLOAT16, BFLOAT16, FLOAT32 ND 2 √ biasOptional Input bias value computed with input x, corresponding to `bias` in the formula. Shape equals the last dimension of x. FLOAT16, BFLOAT16, FLOAT32 ND 1 √ k Input k value for topk, corresponding to `k` in the formula. None INT64 - - - kGroup Input Number of groups selected after group sorting, corresponding to `kGroup` in the formula. None INT64 - - - groupCount Input Total number of groups, corresponding to `groupCount` in the formula. None INT64 - - - groupSelectMode Input Group sorting method. None INT64 - - - renorm Input renorm flag. None INT64 - - - normType Input Type of the norm function. None INT64 - - - outFlag Input Specifies whether to output the norm operation result. None BOOL - - - routedScalingFactor Input Scaling factor routedScalingFactor used to compute yOut, corresponding to `routedScalingFactor` in the formula. None DOUBLE - - - eps Input The eps coefficient used to compute yOut, corresponding to `eps` in the formula. None DOUBLE - - - yOut Output The result computed after applying norm and grouped sorting topk to x, corresponding to `yOut` in the formula. The data type must be the same as that of x. FLOAT16, BFLOAT16, FLOAT32 ND 2 - expertIdxOut Output Indices of x after norm, group sorting, and topk, corresponding to `expertIdxOut` in the formula. The shape must be the same as that of yOut. INT32 ND 2 - outOut Output Output of the norm computation, corresponding to `normOut` in the formula. The shape must be the same as that of x. FLOAT32 ND 2 - workspaceSize Output Returns the workspace size to be requested on the Device. - - - - - 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 The input and output tensors are null pointers. ACLNN_ERR_PARAM_INVALID 161002 The data types of the input and output are out of the supported range. ACLNN_ERR_INNER_NULLPTR 561103 The shape of x does not meet requirements.
The shapes of x and biasOptional do not match.
The value of k is not in the range of 1 to x_shape[-1] / groupCount * kGroup.
The value of kGroup is not in the range of 1 to groupCount.
The total number of experts in each group after 32-alignment exceeds 2048.
The value of the input parameter does not meet requirements.
aclnnMoeGatingTopK
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address applied for on the Device. workspaceSize Input Workspace size applied for on the Device, obtained by the first-phase API aclnnMoeGatingTopKGetWorkspaceSize. executor Input Op executor that contains the operator computation flow. stream Input Stream where the task is executed. Return value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
- Deterministic computation:
- aclnnMoeGatingTopK defaults to a deterministic implementation.
- Input shape constraints:
- The last dimension of x (i.e., the number of experts) must not exceed 2048.
- Input value range restrictions:
- Requires 1 <= k <= x_shape[-1] / groupCount * kGroup.
- Requires 1 <= kGroup <= groupCount, and the value of kGroup * x_shape[-1] / groupCount must be greater than or equal to k.
- Requires groupCount > 0, x_shape[-1] must be divisible by groupCount and the quotient must be greater than groupSelectMode, and the result of the quotient aligned to 32 elements multiplied by groupCount must not exceed 2048.
- Other constraints:
- The value of groupSelectMode is 0 or 1. 0 indicates use of the maximum value for sorting groups. 1 indicates use of the sum value of topk2 for sorting groups.
- The value of normType is 0, 1, or 2. 0 indicates the Softmax function, 1 indicates the Sigmoid function, and 2 indicates the SqrtSoftplus function.
Atlas A3 products ,Atlas A2 products : When normType is 2, groupCount must be 1
- When the value of normType is 1 or 2, the renorm parameter effect does not apply; when the value of normType is 0, the renorm parameter effect applies. The value of renorm is 0 or 1, where 0 indicates no renorm and 1 indicates renorm.
- outFlag takes values true and false, where true indicates output and false indicates no output.
- Empty tensors and scalar tensors are not supported for input.
Example
The following sample code is for reference only. For details about the compilation and execution, see Compile and Run Samples.
#include "acl/acl.h"
#include "aclnnop/aclnn_moe_gating_top_k.h"
#include <iostream>
#include <vector>
#include <random>
#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;
}
std::vector<float> GenerateRandomFloats(int64_t count) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float> dist(0.0f, 10.0f);
std::vector<float> result(count);
for (auto& num : result) {
num = dist(gen);
}
return result;
}
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-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);
// Compute 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) Initialize the device/stream. For details, see the AscendCL API list.
// Set deviceId based on the actual device in use.
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 input and output. Custom construction is required based on the API.
std::vector<int64_t> inputShape = {3, 256};
std::vector<int64_t> biasShape = {256};
std::vector<int64_t> outShape = {3, 8};
std::vector<int64_t> expertIdOutShape = {3, 8};
std::vector<int64_t> normOutShape = {3, 256};
void* inputAddr = nullptr;
void* biasAddr = nullptr;
void* outAddr = nullptr;
void* expertIdOutAddr = nullptr;
void* normOutAddr = nullptr;
aclTensor* input = nullptr;
aclTensor* bias = nullptr;
aclTensor* out = nullptr;
aclTensor* expertIdOut = nullptr;
aclTensor* normOut = nullptr;
std::vector<float> inputHostData = GenerateRandomFloats(GetShapeSize(inputShape));
std::vector<float> biasHostData = GenerateRandomFloats(GetShapeSize(biasShape));
std::vector<float> outHostData(GetShapeSize(outShape));
std::vector<int32_t> expertIdOutHostData(GetShapeSize(expertIdOutShape));
std::vector<float> normOutHostData(GetShapeSize(normOutShape));
// Create the expandedPermutedRows aclTensor.
ret = CreateAclTensor(inputHostData, inputShape, &inputAddr, aclDataType::ACL_FLOAT, &input);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the expandedPermutedRows aclTensor.
ret = CreateAclTensor(biasHostData, biasShape, &biasAddr, aclDataType::ACL_FLOAT, &bias);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the expertForSourceRow aclTensor.
ret = CreateAclTensor(outHostData, outShape, &outAddr, aclDataType::ACL_FLOAT, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the expandedSrcToDstRow aclTensor.
ret = CreateAclTensor(expertIdOutHostData, expertIdOutShape, &expertIdOutAddr, aclDataType::ACL_INT32, &expertIdOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create the expandedSrcToDstRow aclTensor.
ret = CreateAclTensor(normOutHostData, normOutShape, &normOutAddr, aclDataType::ACL_FLOAT, &normOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Change it to the specific operator API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnMoeGatingTopK.
ret = aclnnMoeGatingTopKGetWorkspaceSize(input, bias, 8, 4, 8, 1, 0, 1, false, 1, 1, out, expertIdOut, normOut, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeGatingTopKGetWorkspaceSize 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 aclnnMoeGatingTopK.
ret = aclnnMoeGatingTopK(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeGatingTopK failed. ERROR: %d\n", ret); return ret);
// 4. (Boilerplate) Synchronize and 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 value and copy the result from device memory to host memory. Change it based on the definition of the specific API.
auto size = GetShapeSize(outShape);
std::vector<float> resultData(size, 0.0f);
ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
outAddr, 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, which need to be modified based on the specific API definition.
aclDestroyTensor(input);
aclDestroyTensor(bias);
aclDestroyTensor(out);
aclDestroyTensor(expertIdOut);
aclDestroyTensor(normOut);
// 7. Release device resources, which need to be modified based on the specific API definition.
aclrtFree(inputAddr);
aclrtFree(biasAddr);
aclrtFree(outAddr);
aclrtFree(normOutAddr);
aclrtFree(expertIdOutAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}