aclnnMoeFinalizeRoutingV2Grad

📄 View Source Code

Applicable Products

ProductSupported
Ascend 950PR/Ascend 950DT√
Atlas A3 training products/Atlas A3 inference products√
Atlas A2 training products/Atlas A2 inference products√
Atlas 200I/500 A2 inference products×
Atlas inference products×
Atlas training products×

Function

  • Description: Backward propagation of aclnnMoeFinalizeRoutingV2.

  • Formula:

    i:0∼R∗K−1i : 0 \sim R * K - 1 j:0∼Hj : 0 \sim H

    (1) scalesOptional is a null pointer:

    gradExpandedXOut[expandedRowIdx[i]][j]=gradY[i/K][j]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]gradExpandedXOut[expandedRowIdx[i]][j] = gradY[i / K][j] * scalesOptional[i / K][i \% K] gradScalesOut[i]=sum(expandedXOptional[expandedRowIdx[i]][j]∗gradY[i/K][j])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]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])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 is divided into a two-phase API. You must first call the "aclnnMoeFinalizeRoutingV2GradGetWorkspaceSize" API to obtain the workspace size required for computation and the executor that contains the operator computation process, 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 Shape Non-contiguous Tensor
    gradY (aclTensor) Input Represents the gradient of the forward output y of MoeFinalizeRoutingV2. - FLOAT16, BFLOAT16, FLOAT32 ND (R, H) √
    expandedRowIdx (aclTensor) Input Indicates the index 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] with no duplicate indices. When dropPadMode is 1, the value range is [-1, expertNum * expertCapacity - 1], and no duplicate indices other than -1 are allowed. INT32 ND (R * K) √
    expandedXOptional (aclTensor) Input. Represents the features expanded based on expertIdx. When scalesOptional is a non-null pointer, this cannot be a null pointer either. Same as gradY. N/A When dropPadMode is 0, if activeNum is greater than 0 and less than R * K, the shape is (activeNum, H); otherwise, it is (R * K, H).
    When dropPadMode is 1: (expertNum, expertCapacity, H)
    √
    scalesOptional (aclTensor) Input Indicates the scaling applied to the features. - FLOAT16, BFLOAT16, FLOAT32 ND (R, K) √
    expertIdxOptional (aclTensor) Input Indicates the index of the expert that processes each feature. When biasOptional is a non-null pointer, expertIdxOptional must also be a non-null pointer, with a value range of [0, E - 1], where E >= 1. Duplicate indices are allowed. E represents the number of experts. INT32 ND (R, K) √
    biasOptional (aclTensor) Input Indicates the offset applied to the features. - Same as gradY. ND (E, H) √
    dropPadMode (int64_t) Input Indicates the use of different scenarios. The value is 0 or 1. 0 indicates the dropless scenario, where expertNum and expertCapacity are not checked. 1 indicates the drop scenario, where expertNum and expertCapacity need to be checked, and values exceeding or falling short of expertCapacity for each expert are processed 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: if biasOptional is a non-null pointer, expertNum must equal E; if biasOptional is a null pointer, expertNum must be greater than 0. Otherwise, an error is reported. - - - -
    expertCapacity (int64_t) Input Indicates the number of rows 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 Gradient of expandedX, the forward input of MoeFinalizeRoutingV2. - Same as gradY. ND Same as expandedXOptional. ×
    gradScalesOut (aclTensor) Output Derivative of the scales input in the forward computation of MoeFinalizeRoutingV2. This output is meaningful only when scalesOptional is not a null pointer. Consistent with scalesOptional. ND (R, K) ×
    workspaceSize (uint64_t) Output Returns the workspace size to be allocated on the Device side. - - - - -
    executor (aclOpExecutor) Output Returns the operator executor, which contains the operator computation process. - - - - -
    • Atlas A2 training products/Atlas A2 inference products, Atlas A3 training products/Atlas A3 inference products:

      • The data type of scalesOptional must be the same as that of gradY.
    • Ascend 950PR/Ascend 950DT:

      • The data type of scalesOptional can be different from that of gradY.
  • 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 The tensor of a mandatory input or output is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type and format of the input and output are not within the supported range.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The shape and values of the input and output do not meet the requirements in the parameter description.

aclnnMoeFinalizeRoutingV2Grad

  • Parameters

    Parameter Input/Output Description
    workspace Input Address of the workspace memory applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained by the first-phase API aclnnMoeFinalizeRoutingV2GradGetWorkspaceSize.
    executor Input Operator executor, which 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:

    • aclnnMoeFinalizeRoutingV2Grad 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 <iostream>
#include <vector>
#include "acl/acl.h"
#include "aclnnop/aclnn_moe_finalize_routing_v2_grad.h"
#include <iostream>

#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 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 data from the host to the device memory using 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);

  // Compute the strides of a 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. See the ACL API manual.
  // Enter the actual device ID.
  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. Customize the construction based on 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. Replace with the specific 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) Synchronously wait for task execution to finish.
  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.
  LOG_PRINT("gradExpandedX result is: \n");
  PrintOutResult(gradExpandedXShape, &gradExpandedXDeviceAddr);
  LOG_PRINT("gradScales result is: \n");
  PrintOutResult(gradScalesShape, &gradScalesDeviceAddr);

  // 6. Release aclTensor and aclScalar. Modify this based on 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;
}