aclnnMoeFinalizeRoutingV2Grad
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 aclnnMoeFinalizeRoutingV2.
- Formula:$$ i : 0 \sim R * K - 1 $$$$ j : 0 \sim H $$(1) scalesOptional is a null pointer:$$ gradExpandedXOut[expandedRowIdx[i]][j] = gradY[i / K][j] $$(2) scalesOptional is a non-null pointer and biasOptional is a null pointer:$$ gradExpandedXOut[expandedRowIdx[i]][j] = gradY[i / K][j] * scalesOptional[i / K][i \% K] $$$$ gradScalesOut[i] = sum(expandedXOptional[expandedRowIdx[i]][j] * gradY[i / K][j]) $$(3) scalesOptional is a non-null pointer and biasOptional is a non-null pointer:$$ gradExpandedXOut[expandedRowIdx[i]][j] = gradY[i / K][j] * scalesOptional[i / K][i \% K] $$$$ gradScalesOut[i] = sum((expandedXOptional[expandedRowIdx[i]][j] + biasOptional[expertIdxOptional[i]][j]) * gradY[i / K][j]) $$Where R represents batch * sequence, H represents hidden, and K represents topK.
Function Prototype
Each operator uses a two-phase API. Call the "aclnnMoeFinalizeRoutingV2GradGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that includes the computation process of the operator, and then call the "aclnnMoeFinalizeRoutingV2Grad" API to perform the computation.
aclnnStatus aclnnMoeFinalizeRoutingV2GradGetWorkspaceSize(
const aclTensor *gradY,
const aclTensor *expandedRowIdx,
const aclTensor *expandedXOptional,
const aclTensor *scalesOptional,
const aclTensor *expertIdxOptional,
const aclTensor *biasOptional,
int64_t dropPadMode,
int64_t activeNum,
int64_t expertNum,
int64_t expertCapacity,
const aclTensor *gradExpandedXOut,
const aclTensor *gradScalesOut,
uint64_t *workspaceSize,
aclOpExecutor **executor);aclnnStatus aclnnMoeFinalizeRoutingV2Grad(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream);aclnnMoeFinalizeRoutingV2GradGetWorkspaceSize
Parameters
Parameter Input/Output Description Instruction Data Type Data Format Dim (shape) Non-contiguous Tensor gradY (aclTensor) Input Indicates the derivative of the output y of MoeFinalizeRoutingV2 forward propagation. - FLOAT16, BFLOAT16, FLOAT32 ND (R, H) √ expandedRowIdx (aclTensor) Input Indicates the indices of tokens sorted by expert order. When scalesOptional is a null pointer, K must be 1. When dropPadMode is 0, the value range is [0, R * K - 1] and no duplicate indices exist; when dropPadMode is 1, the value range is [-1, expertNum * expertCapacity - 1] and, except for -1, no other duplicate indices are allowed. INT32 ND (R * K) √ expandedXOptional (aclTensor) Input Indicates the features expanded based on expertIdx. When scalesOptional is a non-null pointer, this parameter cannot be a null pointer. Consistent with gradY. ND When dropPadMode is 0, if activeNum is greater than 0 and less than R * K, the shape is (activeNum, H); otherwise, the shape is (R * K, H).
When dropPadMode is 1: (expertNum, expertCapacity, H)√ scalesOptional (aclTensor) Input Indicates the scaling applied to features. - FLOAT16, BFLOAT16, FLOAT32 ND (R, K) √ expertIdxOptional (aclTensor) Input Indicates the index of the expert for processing each feature. When biasOptional is a non-null pointer, expertIdxOptional cannot be a null pointer. The value range is [0, E - 1], E >= 1. Duplicate indices are allowed. E represents the number of experts. INT32 ND (R, K) √ biasOptional (aclTensor) Input Indicates the offset applied to features. - Consistent with gradY. ND (E, H) √ dropPadMode (int64_t) Input Indicates different use cases. The value is 0 or 1. 0 represents the dropless use case, where expertNum and expertCapacity are not validated; 1 represents the drop use case, where expertNum and expertCapacity are validated, and values that exceed or fall short of expertCapacity for each expert are handled accordingly. - - - - activeNum (int64_t) Input Indicates the maximum number of output rows of gradExpandedXOut. When dropPadMode is 0, this parameter takes effect only when activeNum is greater than 0 and less than R * K; when dropPadMode is 1, this parameter does not take effect. - - - - expertNum (int64_t) Input Indicates the number of experts. When dropPadMode is 0, this parameter does not take effect. When dropPadMode is 1, expertNum must be equal to E if biasOptional is a non-null pointer, and must be greater than 0 if biasOptional is a null pointer. Otherwise, an error is reported. - - - - expertCapacity (int64_t) Input Indicates the number of rows that each expert can process. When dropPadMode is 0, this parameter does not take effect. When dropPadMode is 1, expertCapacity must be greater than 0; otherwise, an error is reported. - - - - gradExpandedXOut (aclTensor) Output Derivative of the MoeFinalizeRoutingV2 forward input expandedX. - Consistent with gradY. ND Consistent with expandedXOptional. × gradScalesOut (aclTensor) Output Derivative of the MoeFinalizeRoutingV2 forward input scales. This output is meaningful only when scalesOptional is not a null pointer. Consistent with scalesOptional. ND (R, K) × workspaceSize (uint64_t) Output Returns the size of the Device side-applied workspace. - - - - - executor (aclOpExecutor) Output Returns the op executor, which includes the operator computation flow. - - - - - Atlas A2 products ,Atlas A3 products :- The data type of scalesOptional must be the same as that of gradY.
Ascend 950PR&950DT products :- The data type of scalesOptional can be different from that of gradY.
Return Value
aclnnStatus: Returns a status code. For details, see Error 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 tensor of a required input or output is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data types and formats of the inputs and outputs are not within the supported range. ACLNN_ERR_INNER_NULLPTR 561103 The shapes and values of the inputs and outputs do not meet the requirements in Parameters.
aclnnMoeFinalizeRoutingV2Grad
Parameters
Parameter Input/Output Description workspace Input Device-side-applied workspace memory address. workspaceSize Input Size of the Device-side-applied workspace, obtained by calling the first-phase API aclnnMoeFinalizeRoutingV2GradGetWorkspaceSize. executor Input Op executor that includes the operator computation process. stream Input Specifies the Stream for task execution. Return Value
aclnnStatus: return status code. For details, see aclnn Error Codes.
Constraints
- Deterministic computation:
- aclnnMoeFinalizeRoutingV2Grad defaults to a deterministic implementation.
Example
The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.
#include <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_moe_finalize_routing_v2_grad.h"
#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("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);
// 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) 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 input and output, customized according to the API.
std::vector<int64_t> gradYShape = {2, 2};
std::vector<int64_t> expandedRowIdxShape = {4};
std::vector<int64_t> expandedXShape = {4, 2};
std::vector<int64_t> scalesShape = {2, 2};
std::vector<int64_t> expertIdxShape = {2, 2};
std::vector<int64_t> biasShape = {2, 2};
std::vector<int64_t> gradExpandedXShape = {4, 2};
std::vector<int64_t> gradScalesShape = {2, 2};
void* gradYDeviceAddr = nullptr;
void* expandedRowIdxDeviceAddr = nullptr;
void* expandedXDeviceAddr = nullptr;
void* scalesDeviceAddr = nullptr;
void* expertIdxDeviceAddr = nullptr;
void* biasDeviceAddr = nullptr;
void* gradExpandedXDeviceAddr = nullptr;
void* gradScalesDeviceAddr = nullptr;
aclTensor* gradY = nullptr;
aclTensor* expandedRowIdx = nullptr;
aclTensor* expandedX = nullptr;
aclTensor* scales = nullptr;
aclTensor* expertIdx = nullptr;
aclTensor* bias = nullptr;
int64_t dropPadMode = 0;
int64_t activeNum = 0;
int64_t expertNum = 0;
int64_t expertCapacity = 0;
aclTensor* gradExpandedX = nullptr;
aclTensor* gradScales = nullptr;
std::vector<float> gradYHostData = {0.3816, 0.3939, 0.8474, 0.1652};
std::vector<int> expandedRowIdxHostData = {1, 3, 0, 2};
std::vector<float> expandedXHostData = {0.6049, 0.3315, 0.4954, 0.3284, 0.7060, 0.4359, 0.6514, 0.9476};
std::vector<float> scalesHostData = {0.4708, 0.0656, 0.9652, 0.9512};
std::vector<int> expertIdxHostData = {0, 1, 0, 1};
std::vector<float> biasHostData = {0.6452, 0.1981, 0.4159, 0.9575};
std::vector<float> gradExpandedXHostData = {0, 0, 0, 0, 0, 0, 0, 0};
std::vector<float> gradScalesHostData = {0, 0, 0, 0};
ret = CreateAclTensor(gradYHostData, gradYShape, &gradYDeviceAddr, aclDataType::ACL_FLOAT, &gradY);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expandedRowIdxHostData, expandedRowIdxShape, &expandedRowIdxDeviceAddr, aclDataType::ACL_INT32,
&expandedRowIdx);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expandedXHostData, expandedXShape, &expandedXDeviceAddr, aclDataType::ACL_FLOAT, &expandedX);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(scalesHostData, scalesShape, &scalesDeviceAddr, aclDataType::ACL_FLOAT, &scales);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(expertIdxHostData, expertIdxShape, &expertIdxDeviceAddr, aclDataType::ACL_INT32, &expertIdx);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(biasHostData, biasShape, &biasDeviceAddr, aclDataType::ACL_FLOAT, &bias);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gradExpandedXHostData, gradExpandedXShape, &gradExpandedXDeviceAddr, aclDataType::ACL_FLOAT,
&gradExpandedX);
CHECK_RET(ret == ACL_SUCCESS, return ret);
ret = CreateAclTensor(gradScalesHostData, gradScalesShape, &gradScalesDeviceAddr, aclDataType::ACL_FLOAT, &gradScales);
CHECK_RET(ret == ACL_SUCCESS, return ret);
// 3. Call the CANN operator library API. Change it to the actual API name.
uint64_t workspaceSize = 0;
aclOpExecutor *executor;
// Call the first-phase API of aclnnMoeFinalizeRoutingV2Grad.
ret = aclnnMoeFinalizeRoutingV2GradGetWorkspaceSize(gradY, expandedRowIdx, expandedX, scales, expertIdx, bias,
dropPadMode, activeNum, expertNum, expertCapacity, gradExpandedX,gradScales, &workspaceSize, &executor);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeFinalizeRoutingV2GradGetWorkspaceSize 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 aclnnMoeFinalizeRoutingV2Grad.
ret = aclnnMoeFinalizeRoutingV2Grad(workspaceAddr, workspaceSize, executor, stream);
CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeFinalizeRoutingV2Grad 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 device memory to host memory. Modify it according to the specific API definition.
LOG_PRINT("gradExpandedX result is: \n");
PrintOutResult(gradExpandedXShape, &gradExpandedXDeviceAddr);
LOG_PRINT("gradScales result is: \n");
PrintOutResult(gradScalesShape, &gradScalesDeviceAddr);
// 6. Release aclTensor and aclScalar. Modify it according to the specific API definition.
aclDestroyTensor(gradY);
aclDestroyTensor(expandedRowIdx);
aclDestroyTensor(expandedX);
aclDestroyTensor(scales);
aclDestroyTensor(expertIdx);
aclDestroyTensor(bias);
aclDestroyTensor(gradExpandedX);
aclDestroyTensor(gradScales);
// 7. Release device resources.
aclrtFree(gradYDeviceAddr);
aclrtFree(expandedRowIdxDeviceAddr);
aclrtFree(expandedXDeviceAddr);
aclrtFree(scalesDeviceAddr);
aclrtFree(expertIdxDeviceAddr);
aclrtFree(biasDeviceAddr);
aclrtFree(gradExpandedXDeviceAddr);
aclrtFree(gradScalesDeviceAddr);
if (workspaceSize > 0) {
aclrtFree(workspaceAddr);
}
aclrtDestroyStream(stream);
aclrtResetDevice(deviceId);
aclFinalize();
return 0;
}