aclnnMoeTokenPermuteWithEpGrad
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: Performs backward propagation computation for aclnnMoeTokenPermuteWithEp.
Formula:
First, compute tokenGradOut:
When rangeOptional[0] <= sortedIndices[i] < rangeOptional[1]:
$$ tokenGradOut[i] = permutedTokensOutputGrad[sortedIndices[i]-rangeOptional[0]] $$Otherwise:
$$ tokenGradOut[i] = 0 $$
Then calculate:
$$ tokenGradOut = tokenGradOut.reshape(-1, numTopk, hiddenSize) $$$$ tokenGradOut = tokenGradOut.sum(dim = 1) $$
Function Prototype
Each operator uses a two-phase API. First, call the "aclnnMoeTokenPermuteWithEpGradGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process. 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:
Return value
aclnnStatus: Returns the 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 A 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.
aclnnMoeTokenPermuteWithEpGrad
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 aclnnMoeTokenPermuteWithEpGradGetWorkspaceSize. executor Input Op executor. Contains the computation flow of the operator. stream Input Specifies the Stream for task execution. Return value
aclnnStatus: Return status code. For details, see aclnn Return Code.
Constraints
Deterministic computation:
- aclnnMoeTokenPermuteWithEpGrad defaults to a deterministic implementation.
numTopk <= 512.
paddedMode being
Trueis not supported.When rangeOptional is empty, permutedProbsOutputGradOptional and probsGradOut are ignored, and the execution logic falls back to aclnnMoeTokenPermuteGrad.
Example
The sample code is as follows and is for reference only. For details about compilation and execution, 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 request 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 data from the host to the 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. For details, see the acl API manual.
// 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. Customize the construction 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. Change it to 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);
// 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 aclnnMoeTokenPermuteWithEpGrad.
ret = aclnnMoeTokenPermuteWithEpGrad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnMoeTokenPermuteWithEpGrad failed. ERROR: %d\n", ret);
return ret);
// 4. (boilerplate) Wait synchronously 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 output values and copy the results from the device side to the host side. Modify the code based on the specific API definition.
PrintOutResult(tokenOutShape, &tokenOutAddr);
PrintOutResult(probOutShape, &probOutAddr);
// 6. Release aclTensor and aclScalar. Modify the code 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;
}