aclnnMoeInitRoutingV2Grad
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 aclnnMoeInitRoutingV2. Computes the weighted sum of tokens.
- Formula:$$ gradX_i=\sum_{t=0}^{topK}gradExpandedX[expandedRowIdx[i * topK + t]] $$
Function Prototype
Each operator uses a two-phase API. Call "aclnnMoeInitRoutingV2GradGetWorkspaceSize" first to obtain the workspace size required for the computation and the executor that contains the operator computation process, and then call "aclnnMoeInitRoutingV2Grad" to perform the computation.
aclnnStatus aclnnMoeInitRoutingV2GradGetWorkspaceSize(
const aclTensor *gradExpandedX,
const aclTensor *expandedRowIdx,
int64_t topK,
int64_t dropPadMode,
int64_t activeNum,
const aclTensor *out,
uint64_t *workspaceSize,
aclOpExecutor **executor)aclnnStatus aclnnMoeInitRoutingV2Grad(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMoeInitRoutingV2GradGetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor gradExpandedX Input Indicates the target tensor after routing. Must be a 2D/3D tensor. The 2D shape is [B*S*K, H] in the Dropless scenario or [A, H] in the Active scenario, and the 3D shape is [E, C, H] in the Drop/Pad scenario. FLOAT16, BFLOAT16, FLOAT32 ND 2 or 3 √ expandedRowIdx Input Indicates the index of tokens sorted by expert order. - Supports empty tensor.
- Must be a 1D tensor with shape [B*S*K].
- Element values range from [-1, E*C) in Drop/Pad scenarios and [0, B*S*K) in other scenarios, and are unique except for -1.
INT32 ND 1 √ topK Input topK value. Must be greater than 0, and the size of axis 0 of expandedRowIdx must be divisible by topK. - - - - dropPadMode Input Indicates whether it is the Drop/Pad scenario. The value is 0 or 1. - 0: indicates the Dropless scenario.
- 1: indicates the Drop/Pad scenario.
- - - - activeNum Input Indicates whether this is an Active scenario. Value range: greater than or equal to 0. This parameter takes effect when dropPadMode is 0. 0 indicates a non-Active scenario, and a value greater than 0 indicates an Active scenario. In the Active scenario, the size of dimension 0 of gradExpandedX must be equal to activeNum. - - - - out Output Indicates the backward output of Routing. - Empty tensors are supported.
- Must be a 2D tensor with shape [B*S, H].
- The data type must be the same as that of input gradExpandedX.
FLOAT16, BFLOAT16, FLOAT32 ND 2 × workspaceSize Output Indicates the workspace size to be requested on the Device. - - - - - executor Output Returns the op executor, which contains the operator computation flow. - - - - - Shape symbol description:
- B: batch size
- S: number of tokens.
- H: hidden size, i.e., the sequence length of each token.
- K: topK, i.e., the number of experts that process each token.
- A: activeNum value.
- E: number of experts.
- C: expert capacity, which indicates the capacity threshold for the number of tokens an expert can process.
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 type of the input or output is not in the supported range. ACLNN_ERR_INNER_NULLPTR 561103 The value of dropPadMode is not 0 or 1. topK is less than or equal to 0. activeNum is less than 0. gradExpandedX is not 2D/3D, or gradExpandedX is not 3D when dropPadMode is 1. When both dropPadMode and activeNum are 0, the size of dim 0 of gradExpandedX is not equal to that of expandedRowIdx. When dropPadMode is 0 and activeNum is greater than 0, the size of dim 0 of gradExpandedX is not equal to activeNum. The size of the last dim of out is not equal to that of gradExpandedX. The size of dim 0 of out is not equal to the size of dim 0 of expandedRowIdx divided by topK.
aclnnMoeInitRoutingV2Grad
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 calling the first-phase API aclnnMoeInitRoutingV2GradGetWorkspaceSize.executor Input Op executor that contains the operator computation flow. stream Input Stream for task execution. Return value
aclnnStatus: return value, which is a status code. For details, see aclnn return codes.
Constraints
- Deterministic computation:
- aclnnMoeInitRoutingV2Grad defaults to a deterministic implementation.
Example
The following is sample code for reference only. For details about compilation and execution, see Compile and Run Samples.
#include "acl/acl.h"
#include "aclnnop/aclnn_moe_init_routing_v2_grad.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 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 host data 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);
// 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 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 the device/stream. For details, see the ACL external API list.
// Set deviceId based on the actual device.
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 inputs and outputs according to the API definition.
std::vector<int64_t> gradExpandedXShape = {4, 2};
std::vector<int64_t> expandedRowIdxShape = {4};
std::vector<int64_t> gradXShape = {2, 2};
void* gradExpandedXDeviceAddr = nullptr;
void* expandedRowIdxDeviceAddr = nullptr;
void* gradXDeviceAddr = nullptr;
aclTensor* gradExpandedX = nullptr;
aclTensor* expandedRowIdx = nullptr;
aclScalar* k = nullptr;
aclScalar* dropPadMode = nullptr;
aclScalar* activeNum = nullptr;
aclTensor* expertIdx = nullptr;
aclTensor* out = nullptr;
std::vector<float> gradExpandedXHostData = {0.1, 0.1, 0.3, 0.3, 0.2, 0.2, 0.4, 0.4};
std::vector<int32_t> expandedRowIdxHostData = {2, 0, 1, 3};
std::vector<float> gradXOutHostData = {0, 0, 0, 0};
int32_t kValue = 2;
int32_t dropPadModeValue = 0;
int32_t activeNumValue = 0;
// Create the input aclTensor.
ret = CreateAclTensor(gradExpandedXHostData, gradExpandedXShape, &gradExpandedXDeviceAddr, aclDataType::ACL_FLOAT, &gradExpandedX);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expandedRowIdxHostData, expandedRowIdxShape, &expandedRowIdxDeviceAddr, aclDataType::ACL_INT32, &expandedRowIdx);
CHECK_RET(ret == ACL_SUCCESS, return ret);
k = aclCreateScalar(&kValue, aclDataType::ACL_INT32);
CHECK_RET(k != nullptr, return ret);
dropPadMode = aclCreateScalar(&dropPadModeValue, aclDataType::ACL_INT32);
CHECK_RET(dropPadMode != nullptr, return ret);
activeNum = aclCreateScalar(&activeNumValue, aclDataType::ACL_INT32);
CHECK_RET(activeNum != nullptr, return ret);
// Create the output aclTensor.
ret = CreateAclTensor(gradXOutHostData, gradXShape, &gradXDeviceAddr, aclDataType::ACL_FLOAT, &out);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Replace it with the specific API.
uint64_t workspaceSize = 0;
aclOpExecutor* executor;
// Call the first-phase API of aclnnMoeInitRoutingV2Grad.
ret = aclnnMoeInitRoutingV2GradGetWorkspaceSize(gradExpandedX, expandedRowIdx, kValue, dropPadModeValue, activeNumValue, out, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeInitRoutingV2GradGetWorkspaceSize 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 aclnnMoeInitRoutingV2Grad.
ret = aclnnMoeInitRoutingV2Grad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeInitRoutingV2Grad 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 output value and copy the result from device memory to host memory. Modify it according to the specific API definition.
auto gradXSize = GetShapeSize(gradXShape);
std::vector<float> gradXData(gradXSize, 0);
ret = aclrtMemcpy(gradXData.data(), gradXData.size() * sizeof(gradXData[0]), gradXDeviceAddr, gradXSize * 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 < gradXSize; i++) {
LOG_PRINT("gradXData[%ld] is: %f\n", i, gradXData[i]);
}
// 6. Release aclTensor and aclScalar. Modify it according to the specific API definition.
aclDestroyTensor(gradExpandedX);
aclDestroyTensor(expandedRowIdx);
aclDestroyScalar(k);
aclDestroyScalar(dropPadMode);
aclDestroyScalar(activeNum);
aclDestroyTensor(out);
// 7. Release device resources. Modify it according to the specific API definition.
aclrtFree(gradExpandedXDeviceAddr);
aclrtFree(expandedRowIdxDeviceAddr);
aclrtFree(gradXDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}