aclnnMoeInitRoutingV2Grad
Applicable Products
| Product | Supported |
|---|---|
| √ | |
| √ | |
| √ | |
| × | |
| × | |
| × |
Function
Description: Backward propagation of aclnnMoeInitRoutingV2, which performs weighted summation of tokens.
Formula:
Function Prototype
Each operator is divided into a two-phase API. You must first call the "aclnnMoeInitRoutingV2GradGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call the "aclnnMoeInitRoutingV2Grad" API 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 Represents the target tensor after routing. Must be a 2D or 3D tensor. The 2D shape is [B*S*K, H] for the Dropless scenario or [A, H] for the Active scenario. The 3D shape is [E, C, H] for the Drop/Pad scenario. FLOAT16, BFLOAT16, FLOAT32 ND 2 or 3 √ expandedRowIdx Input Indicates the token indices sorted by expert order. - Supports empty tensors.
- Must be a 1D tensor with shape [B*S*K].
- In Drop/Pad scenarios, element values range from [-1, E*C); in other scenarios, they range from [0, B*S*K), and all values except -1 are unique and non-repeating.
INT32 ND 1 √ topK Input The topK value. Must be greater than 0, and the size of the 0-axis of expandedRowIdx must be divisible by topK. - - - - dropPadMode Input Indicates whether it is a Drop/Pad scenario. The value is 0 or 1. - 0: Indicates a Dropless scenario.
- 1: Indicates a Drop/Pad scenario.
- - - - activeNum Input Indicates whether the scenario is an Active scenario. The value range is greater than or equal to 0. It takes effect when dropPadMode is 0. 0 indicates a non-Active scenario, and a value greater than 0 indicates an Active scenario. In an Active scenario, the size of the 0-axis of gradExpandedX must be equal to the activeNum value. - - - - out Output Represents the routing backward output. - Supports empty tensors.
- Must be a 2D tensor with shape [B*S, H].
- The data type must be consistent with the input gradExpandedX.
FLOAT16, BFLOAT16, FLOAT32 ND 2 × workspaceSize Output Returns the workspace size to be allocated on the Device side. - - - - - executor Output Returns the operator 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 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 Null pointer for the input or output tensor. ACLNN_ERR_PARAM_INVALID 161002 The data type of the input or output is not within the supported range. ACLNN_ERR_INNER_TILING_ERROR 561002 The attribute value of dropPadMode is neither 0 nor 1. topK is less than or equal to 0. activeNum is less than 0. gradExpandedX is not 2D or 3D, or when dropPadMode is 1, gradExpandedX is not 3D. When both dropPadMode and activeNum are 0, the dimension-0 sizes of gradExpandedX and expandedRowIdx are not equal. When dropPadMode is 0 and activeNum is greater than 0, the dimension-0 size of gradExpandedX is not equal to activeNum. The last-dimension sizes of out and gradExpandedX are not equal. The dimension-0 size of out is not equal to the dimension-0 size of expandedRowIdx divided by topK.
aclnnMoeInitRoutingV2Grad
Parameters:
Parameter Input/Output Description workspace Input Specifies the workspace memory address applied on the Device side. workspaceSize Input Specifies the workspace size applied on the Device side, which is obtained through the first-phase API aclnnMoeInitRoutingV2GradGetWorkspaceSize.Executor Input Operator executor that contains the operator computation flow. Stream Input Specifies the stream that executes the task. Return value
aclnnStatus: return code. For details, see aclnn Return Code.
Constraints
Deterministic computation:
- aclnnMoeInitRoutingV2Grad defaults to a deterministic implementation.
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_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 for 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 apply for 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);
// Copy the host-side data to the device-side memory by calling aclrtMemcpy.
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];
}
// Create an aclTensor by calling the aclCreateTensor API.
*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 external ACL API list.
// Set deviceId based on the actual device.
int32_t deviceId = 0;
aclrtStream stream;
auto ret = Init(deviceId, &stream);
// Handle the check based on your needs.
CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);
// 2. Construct the input and output based on 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 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);
// 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 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 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 this based on 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 based on the specific API definition.
aclDestroyTensor(gradExpandedX);
aclDestroyTensor(expandedRowIdx);
aclDestroyScalar(k);
aclDestroyScalar(dropPadMode);
aclDestroyScalar(activeNum);
aclDestroyTensor(out);
// 7. Release device resources. Modify based on the specific API definition.
aclrtFree(gradExpandedXDeviceAddr);
aclrtFree(expandedRowIdxDeviceAddr);
aclrtFree(gradXDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}