aclnnMoeTokenPermuteWithRoutingMapGrad
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: Backward propagation of aclnnMoeTokenPermuteWithRoutingMap.
- Formula:$$ permuteTokenId, outIndex= sortedIndices.sort(dim=-1) $$$$ capacity = permutedTokensOutputGrad.size(0) / numExperts $$
- When probs is not None:
$$ probsGradOutOptional = zeros(tokens_num, numExperts) $$- When dropPaddedMode is true:
$$ probsGradOutOptional [sortedIndices[i], i/capacity] = permutedProbsOutputGradOptional[i] $$- When dropPaddedMode is false:
$$ probsGradOutOptional = maskedscatter(probsGradOutOptional,routingMapOptional, permutedProbsOutputGradOptional) $$- probs is None:
$$ tokenGradOut= zeros(restoreShapeOptional, dtype=permutedTokens.dtype, device=permutedTokens.device) $$$$ tokenGradOut[permuteTokenId[i]] += permutedTokens[outIndex[i]] $$
Function Prototype
Each operator uses a two-phase API. First, call "aclnnMoeTokenPermuteWithRoutingMapGradGetWorkspaceSize" to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call "aclnnMoeTokenPermuteWithRoutingMapGrad" to perform the computation.
aclnnStatus aclnnMoeTokenPermuteWithRoutingMapGradGetWorkspaceSize(
const aclTensor *permutedTokensOutputGrad,
const aclTensor *permutedProbsOutputGradOptional,
const aclTensor *sortedIndices,
const aclTensor *routingMapOptional,
int64_t experts_num,
int64_t tokens_num,
bool dropAndPad,
aclTensor *tokenGradOut,
aclTensor *probsGradOutOptional,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMoeTokenPermuteWithRoutingMapGrad(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
const aclrtStream stream)aclnnMoeTokenPermuteWithRoutingMapGradGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor permutedTokensOutputGrad Input Gradient of the forward output permutedTokens. Supports 2D dimensions. Empty tensors are not supported. topK_num indicates each token's upper limit on the quantity of experts that can be selected. capacity indicates each expert's quantity of selected tokens. BFLOAT16, FLOAT16, FLOAT32 ND • Non-dropAndPad mode: (tokens_num * topK_num, hidden_size)
• dropAndPad mode: (experts_num * capacity, hidden_size)√ permutedProbsOutputGradOptional Optional input Gradient of the forward output permutedProbs. • If not specified, probsGradOutOptional does not need to be computed;
• The shape is a 1D dimension. topK_num indicates each token's upper limit of the quantity of selected experts, and capacity indicates the quantity of tokens selected by each expert.
• The data type must be the same as that of permutedTokensOutputGrad, or FLOAT is supported when permutedTokensOutputGrad is BFLOAT16.BFLOAT16, FLOAT16, FLOAT32 ND • Non-dropAndPad mode: (tokens_num * topK_num)
• dropAndPad mode: (experts_num * capacity)√ sortedIndices Input Sorted indices. In non-dropAndPad mode, the value range of the index is [0, tokens_num * topK_num - 1] or -1. -1 indicates an invalid slot that does not participate in the computation. topK_num indicates each token's upper limit of the quantity of selected experts. In dropAndPad mode, the value range of the index is [0, experts_num * capacity - 1]. capacity indicates the quantity of tokens selected by each expert. INT32 ND • Non-dropAndPad mode: (tokens_num * topK_num,)
• dropAndPad mode: (experts_num * capacity)√ routingMapOptional Optional input Represents the mapping from tokens to experts. Requires the shape to be a 2D tensor. In the non-dropAndPad mode, each row must contain no more than topK true or 1 values. INT8, bool (when the data type is INT8, supported values are 0 and 1; when the data type is bool, supported values are true and false) ND (tokens_num, experts_num) √ experts_num Input Indicates the quantity of experts participating in the computation. - - - - - tokens_num Input Indicates the number of tokens involved in the operation. - - - - - dropAndPad Input - true indicates that dropPaddedMode is enabled, and false indicates that dropPaddedMode is disabled. bool - - - tokenGradOut Output Gradient of the input permutedTokens. Required to be a 2D tensor. BFLOAT16, FLOAT16, FLOAT32 ND (tokens_num, hidden_size) × probsGradOutOptional Optional output Gradient of the forward operator input probs. Supports 2D shape. Same as permutedProbsOutputGradOptional ND (tokens_num, experts_num) × workspaceSize Output Returns the size of the workspace to be requested 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 The required input, output, or attribute passed in is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 1.The data type and data format of inputs and outputs are not in the supported range.
2.The Shape of inputs and outputs is not in the supported range.
aclnnMoeTokenPermuteWithRoutingMapGrad
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 through the first-phase API aclnnMoeTokenPermuteWithRoutingMapGradGetWorkspaceSize. executor Input op executor that contains the operator computation flow. stream Input Stream for executing tasks. Return value
Returns an aclnnStatus status code. For details, see aclnn Return Codes.
Constraints
Deterministic computation:
- aclnnMoeTokenPermuteWithRoutingMapGrad defaults to a non-deterministic implementation. Deterministic computation can be enabled through aclrtCtxSetSysParamOpt.
For non-dropPaddedMode use cases, topK_num <= 512
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include "aclnnop/aclnn_moe_token_permute_with_routing_map_grad.h"
#include <iostream>
#include <vector>
#include <sys/stat.h>
#include <fstream>
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>
#include <cassert>
#include <iomanip>
#include <unistd.h>
#include "acl/acl.h"
#include "aclnn/acl_meta.h"
#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;
}
template <typename T>
bool WriteFile(const std::string &filePath, int64_t size, std::vector<T>& hostData)
{
int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
if (fd < 0) {
LOG_PRINT("Open file failed. path = %s", filePath.c_str());
return false;
}
size_t writeSize = write(fd, reinterpret_cast<char*>(hostData.data()), size * sizeof(T));
(void)close(fd);
if (writeSize != size * sizeof(T)) {
LOG_PRINT("Write file Failed.");
return false;
}
return true;
}
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 < 10; i++) {
LOG_PRINT("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 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 data from the host 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 aclCreateTensor 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 acl API manual.
// Fill in 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 as required by the API.
int64_t num_token = 4096;
int64_t hidden_size = 7168;
int64_t num_expert = 256;
int64_t num_capacity = 16;
std::vector<float> permuted_output_grad_Data(num_expert * num_capacity * hidden_size, 0);
std::vector<int64_t> permuted_output_grad_Shape = {num_expert * num_capacity, hidden_size};
void* permuted_output_grad_Addr = nullptr;
aclTensor* permuted_output_grad = nullptr;
ret = CreateAclTensor(permuted_output_grad_Data, permuted_output_grad_Shape, &permuted_output_grad_Addr,
aclDataType::ACL_FLOAT, &permuted_output_grad);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> permutedProbsOutputGradOptional(num_expert * num_capacity, 0.1);
std::vector<int64_t> permutedProbsOutputGradOptionalShape = {num_expert * num_capacity};
void* permutedProbsOutputGrad_Addr = nullptr;
aclTensor* ppermutedProbsOutputGrad = nullptr;
ret = CreateAclTensor(permutedProbsOutputGradOptional, permutedProbsOutputGradOptionalShape,
&permutedProbsOutputGrad_Addr, aclDataType::ACL_FLOAT, &ppermutedProbsOutputGrad);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<int> sortedIndicesData(num_expert * num_capacity, 0);
std::vector<int64_t> sortedIndicesShape = {num_expert * num_capacity};
void* sortedIndicesAddr = nullptr;
aclTensor* sortedIndices = nullptr;
ret = CreateAclTensor(sortedIndicesData, sortedIndicesShape, &sortedIndicesAddr, aclDataType::ACL_INT32,
&sortedIndices);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<char> routingMapOptionalData(num_token * num_expert, 1);
std::vector<int64_t> routingMapOptionalShape = {num_token , num_expert};
void* routingMapOptionalAddr = nullptr;
aclTensor* proutingMapOptional = nullptr;
ret = CreateAclTensor(routingMapOptionalData, routingMapOptionalShape, &routingMapOptionalAddr,
aclDataType::ACL_INT8, &proutingMapOptional);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> outData(num_token * hidden_size, 0.0f);
std::vector<int64_t> outShape = {num_token, hidden_size};
// std::vector<int64_t> outShape = {num_token};
void* outAddr = nullptr;
aclTensor* out = nullptr;
ret = CreateAclTensor(outData, outShape, &outAddr, aclDataType::ACL_FLOAT, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
std::vector<float> outData2(num_token * num_expert, 0.0f);
std::vector<int64_t> outShape2 = {num_token, num_expert};
void* outAddr2 = nullptr;
aclTensor* out2 = nullptr;
ret = CreateAclTensor(outData2, outShape2, &outAddr2, aclDataType::ACL_FLOAT, &out2);
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 aclnnMoeTokenPermuteWithRoutingMapGrad.
ret = aclnnMoeTokenPermuteWithRoutingMapGradGetWorkspaceSize(permuted_output_grad, ppermutedProbsOutputGrad, sortedIndices, proutingMapOptional, num_expert, num_token, true,
out, out2, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS,
LOG_PRINT("aclnnMoeTokenPermuteWithRoutingMapGradGetWorkspaceSize failed. ERROR: %d\n", ret);
return ret);
// Allocate device memory based on the workspaceSize computed 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 aclnnMoeTokenPermuteWithRoutingMapGrad.
ret = aclnnMoeTokenPermuteWithRoutingMapGrad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeTokenPermuteWithRoutingMapGrad failed. ERROR: %d\n", ret);
return ret);
// 4. (boilerplate) Synchronize and 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 output value and copy the result from the device memory to the host memory. The code must be modified based on the specific API definition.
PrintOutResult(outShape, &outAddr);
PrintOutResult(outShape2, &outAddr2);
// 6. Release aclTensor and aclScalar. The code must be modified based on the specific API definition.
aclDestroyTensor(permuted_output_grad);
aclDestroyTensor(sortedIndices);
aclDestroyTensor(out);
// 7. Release device resources.
aclrtFree(permuted_output_grad_Addr);
aclrtFree(sortedIndicesAddr);
aclrtFree(outAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}