aclnnMoeGatingTopKSoftmaxV2
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, if renorm=0, Softmax is first computed on the output of x, and then the topK operation is performed; if renorm=1, the topK operation is first performed on the output of x, and then Softmax is computed. yOut: when renorm=0, the topK values obtained after Softmax is computed on x; when renorm=1, the result obtained by computing topK on x first and then computing Softmax. expertIdxOut is the index result of the topK values, that is, the corresponding expert index; if finished of the corresponding row is True, the expert index is directly filled with num_expert (that is, the size of the last axis of x).
- Formula:
renorm = 0,
$$ softmaxResultOutOptional=softmax(x,axis=-1) $$$$ yOut,expertIdxOut=topK(softmaxResultOutOptional,k=k) $$renorm = 1
$$ topkOut,expertIdxOut=topK(x, k=k) $$$$ yOut = softmax(topkOut,axis=-1) $$
Function Prototype
Each operator uses a two-phase API. First call the "aclnnMoeGatingTopKSoftmaxV2GetWorkspaceSize" API to obtain the workspace size required for the computation and the executor that contains the computation flow of the operator, and then call the "aclnnMoeGatingTopKSoftmaxV2" API to execute the computation.
aclnnStatus aclnnMoeGatingTopKSoftmaxV2GetWorkspaceSize(
const aclTensor *x,
const aclTensor *finishedOptional,
int64_t k,
int64_t renorm,
bool outputSoftmaxResultFlag,
const aclTensor *yOut,
const aclTensor *expertIdxOut,
const aclTensor *softmaxResultOutOptional,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMoeGatingTopKSoftmaxV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMoeGatingTopKSoftmaxV2GetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-Contiguous Tensor x Input x in the formula, the input to be computed. Must be a 2D/3D tensor. The size of each dimension must not exceed the maximum int32 value of 2147483647. FLOAT16, BFLOAT16, FLOAT32 ND 2-3 √ finishedOptional Input finished in the formula, indicating whether the row participates in the computation. The shape is x_shape[:-1]. BOOL ND 1-2 √ k Input Value of k in topK, the number of experts. 0 <= k <= the size of the last axis of x, and k is not greater than 1024. INT64 - - - renorm Input Order of Softmax and TopK. Only 0 and 1 are supported. 0 means Softmax is calculated before TopK; 1 means the reverse order. INT64 - - - outputSoftmaxResultFlag Input Indicates whether to output the softmax result. When renorm=0, true indicates outputting the Softmax result and false indicates not outputting it. When renorm=1, this parameter does not take effect and the Softmax result is not output. BOOL - - - yOut Output topK values taken after softmax is applied to x. The non -1 axes of its shape must be consistent with the corresponding axes of x in size, and the -1 axis must have the same size as k. Must be consistent with input x. ND 2-3 x expertIdxOut Output expertIdxOut in the formula, the index result of topK values, that is, the corresponding expert index. Shape requirements are consistent with yOut. INT32 ND 2-3 x softmaxResultOutOptional Output Softmax result in the computation process. Shape requirements are consistent with x. FLOAT32 ND 2-3 x workspaceSize Output Returns the size of the workspace to be allocated on the device. - - - - - executor Output Returns the op executor, which contains 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 Required input, output, or attribute is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types and data formats of the input and output are not within the supported range. ACLNN_ERR_INNER_TILING_ERROR 561002 Shape information of multiple input tensors does not match. Shape information between input attributes and input tensors does not match. The dimension of the shape of x is not 2 or 3. The shape of x does not match that of finishedOptional. The value of k is less than 0 or greater than the size of the x-1 axis. The value of k is greater than 1024. The value of renorm is not 0 or 1. The data type of softmaxResultOutOptional is not within the supported range.
aclnnMoeGatingTopKSoftmaxV2
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 aclnnMoeGatingTopKSoftmaxV2GetWorkspaceSize. executor Input op executor, 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:
- aclnnMoeGatingTopKSoftmaxV2 defaults to a deterministic implementation.
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_gating_top_k_softmax_v2.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, 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 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 device/stream. For details, see the list of AscendCL external APIs.
// Fill in deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle check as required.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the inputs and outputs. Custom construction is required based on the API.
std::vector<int64_t> inputShape = {3, 4};
std::vector<int64_t> outShape = {3, 2};
std::vector<int64_t> expertIdOutShape = {3, 2};
std::vector<int64_t> softmaxResultOutOptionalShape = {3, 4};
void* inputAddr = nullptr;
void* outAddr = nullptr;
void* expertIdOutAddr = nullptr;
void* softmaxResultOutOptionalAddr = nullptr;
aclTensor* input = nullptr;
aclTensor* out = nullptr;
aclTensor* expertIdOut = nullptr;
aclTensor* softmaxResultOutOptional = nullptr;
std::vector<float> inputHostData = {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> outHostData = {0.1, 1.1, 2.1, 3.1, 4.1, 5.1};
std::vector<int32_t> expertIdOutHostData = {1, 1, 1, 1, 1, 1};
std::vector<float> softmaxResultOutOptionalHostData = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
// Create the expandedPermutedRows aclTensor.
ret = CreateAclTensor(inputHostData, inputShape, &inputAddr, aclDataType::ACL_FLOAT, &input);
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 expandedSrcToDstRow aclTensor.
ret = CreateAclTensor(expertIdOutHostData, expertIdOutShape, &expertIdOutAddr, aclDataType::ACL_INT32, &expertIdOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// Create softmaxResultOutOptional aclTensor.
ret = CreateAclTensor(softmaxResultOutOptionalHostData, softmaxResultOutOptionalShape, &softmaxResultOutOptionalAddr, aclDataType::ACL_FLOAT, &softmaxResultOutOptional);
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 aclnnMoeGatingTopKSoftmaxV2.
ret = aclnnMoeGatingTopKSoftmaxV2GetWorkspaceSize(input, nullptr, 2, 0, true, out, expertIdOut, softmaxResultOutOptional, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeGatingTopKSoftmaxV2GetWorkspaceSize 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 aclnnMoeGatingTopKSoftmaxV2.
ret = aclnnMoeGatingTopKSoftmaxV2(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeGatingTopKSoftmaxV2 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 value of the output, and copy the result on the device memory to the host. Modify 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 the aclTensor and aclScalar. Modify them based on the definition of the specific API.
aclDestroyTensor(input);
aclDestroyTensor(out);
aclDestroyTensor(expertIdOut);
aclDestroyTensor(softmaxResultOutOptional);
// 7. Release device resources. Modify them based on the definition of the specific API.
aclrtFree(inputAddr);
aclrtFree(outAddr);
aclrtFree(expertIdOutAddr);
aclrtFree(softmaxResultOutOptionalAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}