aclnnMoeTokenPermuteWithEpGrad
Applicable Products
| Product | Supported |
|---|---|
| × | |
| √ | |
| √ | |
| × | |
| × | |
| × |
Function
Description: Performs backward propagation computation for aclnnMoeTokenPermuteWithEp.
Formula:
First, compute tokenGradOut:
When rangeOptional[0] <= sortedIndices[i] < rangeOptional[1]:
Otherwise:
Then calculate:
Function Prototype
Each operator is divided into a two-phase API. You must first call the "aclnnMoeTokenPermuteWithEpGradGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnMoeTokenPermuteWithEpGrad" API to perform the computation.
aclnnStatus aclnnMoeTokenPermuteWithEpGradGetWorkspaceSize(
const aclTensor *permutedTokensOutputGrad,
const aclTensor *sortedIndices,
const aclTensor *permutedProbsOutputGradOptional,
int64_t numTopk,
const aclIntArray *rangeOptional,
bool paddedMode,
const aclTensor *tokenGradOut,
const aclTensor *probsGradOut,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMoeTokenPermuteWithEpGrad(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMoeTokenPermuteWithEpGradGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor permutedTokensOutputGrad Input Represents the gradient of the forward output permutedTokens. The shape supports 2D dimensions. Empty tensors are not supported. topK_num is the value of numTopk. BFLOAT16, FLOAT16, FLOAT32 ND ((rangeOptional[1] - rangeOptional[0])* topK_num,hidden_size) √ sortedIndices Input Indicates the mapping relationship between the forward output permuteTokensOut and the forward input tokens. The shape supports 1D, where num_tokens is the number of original tokens. Empty tensors are not supported. INT32 ND (num_tokens * topK_num) √ permutedProbsOutputGradOptional Optional input. Gradient of the forward output permutedProbs. - The shape supports 1D, where topK_num is the value of numTopk.
- Corresponds to the computed output probsGradOut. If empty, probsGradOut is not output.
BFLOAT16, FLOAT16, FLOAT32 ND ((rangeOptional[1] - rangeOptional[0]) * topK_num) √ numTopk Input. Number of selected experts. - INT64 - - - rangeOptional Input Valid range of EP sharding, with a size of 2. When empty, permutedProbsOutputGradOptional and probsGradOut are ignored, and the logic falls back to aclnnMoeTokenPermuteGrad. - - - - paddedMode Input - true: enables paddedMode.
false: disables paddedMode.
Currently, only false is supported.bool - - - tokenGradOut Output Gradient of the output token. Must be a 2D tensor. BFLOAT16, FLOAT16, FLOAT32 ND (num_tokens, hidden_size) - probsGradOut Output Outputs the gradient of probs. The shape supports 2D dimensions. BFLOAT16, FLOAT16, FLOAT32 ND (num_tokens, topK_num) - workspaceSize Output Size of the workspace to be requested on the Device side. - - - - - executor Output Returns the operator executor, which contains the operator computation process. - - - - - Return value
aclnnStatus: return 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 passed mandatory input, mandatory output, or mandatory attribute is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of the input and output is not within the supported range.
aclnnMoeTokenPermuteWithEpGrad
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address applied for on the Device side. workspaceSize Input Workspace size applied for on the Device side, obtained from the first-phase API aclnnMoeTokenPermuteWithEpGradGetWorkspaceSize. executor Input Operator executor, which contains the operator computation flow. stream Input Specifies the stream for task execution. Return value
aclnnStatus: return code. For details, see aclnn Return Code.
Constraints
Deterministic computation:
- aclnnMoeTokenPermuteWithEpGrad defaults to a deterministic implementation.
numTopk <= 512.
paddedMode set to
Trueis not supported.When rangeOptional is empty, permutedProbsOutputGradOptional and probsGradOut are ignored, and the execution logic falls back to aclnnMoeTokenPermuteGrad.
Example
The following provides example code for reference only. For details about compilation and running, see Compile and Run Samples.
#include "acl/acl.h"
#include "aclnnop/aclnn_moe_token_permute_with_ep_grad.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 CreateAclIntArray(const std::vector<T>& hostData, void** deviceAddr, aclIntArray** intArray) {
auto size = GetShapeSize(hostData) * sizeof(T);
// Call aclrtMalloc to allocate memory on the device.
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 the data on the host to the memory on the device.
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);
// Call aclCreateIntArray to create an aclIntArray.
*intArray = aclCreateIntArray(hostData.data(), hostData.size());
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 data from the host side 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 a 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. See the ACL API Reference.
// Set deviceId based on the 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. Custom construction is required based on the API.
int64_t num_topk = 2;
std::vector<float> permuted_token_output_grad_Data = {2, 2, 1, 1, 3, 3, 2, 2};
std::vector<float> permuted_prob_output_grad_Data = {0.2, 0.5, 0.4, 0.4};
std::vector<int64_t> permuted_token_output_grad_Shape = {8, 2};
std::vector<int64_t> permuted_prob_output_grad_Shape = {8};
void *permuted_token_output_grad_Addr = nullptr;
void *permuted_prob_output_grad_Addr = nullptr;
aclTensor *permuted_token_output_grad = nullptr;
aclTensor *permuted_prob_output_grad = nullptr;
ret = CreateAclTensor(permuted_token_output_grad_Data, permuted_token_output_grad_Shape,
&permuted_token_output_grad_Addr, aclDataType::ACL_FLOAT,
&permuted_token_output_grad);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(permuted_prob_output_grad_Data, permuted_prob_output_grad_Shape,
&permuted_prob_output_grad_Addr, aclDataType::ACL_FLOAT,
&permuted_prob_output_grad);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<int> sortedIndicesData = {2, 0, 4, 1, 5, 3};
std::vector<int64_t> sortedIndicesShape = {6};
void *sortedIndicesAddr = nullptr;
aclTensor *sortedIndices = nullptr;
ret = CreateAclTensor(sortedIndicesData, sortedIndicesShape, &sortedIndicesAddr,
aclDataType::ACL_INT32, &sortedIndices);
CHECK_RET(ret == ACL_SUCCESS, return ret);
void* rangeDeviceAddr = nullptr;
aclIntArray* range = nullptr;
std::vector<int64_t> rangeHostData = {1, 5};
ret = CreateAclIntArray(rangeHostData, &rangeDeviceAddr, &range);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> tokenOutData = {0, 0, 0, 0, 0, 0};
std::vector<int64_t> tokenOutShape = {3, 2};
void *tokenOutAddr = nullptr;
aclTensor *tokenOut = nullptr;
ret = CreateAclTensor(tokenOutData, tokenOutShape, &tokenOutAddr, aclDataType::ACL_FLOAT,
&tokenOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> probOutData = {0, 0, 0, 0, 0, 0};
std::vector<int64_t> probOutShape = {3, 2};
void *probOutAddr = nullptr;
aclTensor *probOut = nullptr;
ret = CreateAclTensor(probOutData, probOutShape, &probOutAddr, aclDataType::ACL_FLOAT,
&probOut);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace it with the specific API name.
uint64_t workspaceSize = 0;
aclOpExecutor *executor;
// Call the first-phase API of aclnnMoeTokenPermuteWithEpGrad.
ret = aclnnMoeTokenPermuteWithEpGradGetWorkspaceSize(permuted_token_output_grad, sortedIndices, permuted_prob_output_grad,
num_topk, range, false,
tokenOut, probOut, &workspaceSize, &executor);
CHECK_RET(
ret == ACL_SUCCESS,
LOG_PRINT("aclnnMoeTokenPermuteWithEpGradGetWorkspaceSize failed. ERROR: %d\n",
ret);
return ret);
// Apply for 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 aclnnMoeTokenPermuteWithEpGrad.
ret = aclnnMoeTokenPermuteWithEpGrad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnMoeTokenPermuteWithEpGrad failed. ERROR: %d\n", ret);
return ret);
// 4. (Boilerplate) Synchronize and wait for 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 memory. Modify based on the specific API definition.
PrintOutResult(tokenOutShape, &tokenOutAddr);
PrintOutResult(probOutShape, &probOutAddr);
// 6. Release aclTensor and aclScalar. Modify based on the specific API definition.
aclDestroyTensor(permuted_token_output_grad);
aclDestroyTensor(permuted_prob_output_grad);
aclDestroyTensor(sortedIndices);
aclDestroyTensor(tokenOut);
aclDestroyTensor(probOut);
// 7. Release device resources.
aclrtFree(permuted_token_output_grad_Addr);
aclrtFree(permuted_prob_output_grad_Addr);
aclrtFree(sortedIndicesAddr);
aclrtFree(tokenOutAddr);
aclrtFree(probOutAddr);
aclrtFree(rangeDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}