aclnnMoeTokenUnpermuteWithEpGrad

📄 View Source Code

Applicable Products

  • Ascend 950PR&950DT products: Not 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 aclnnMoeTokenUnpermuteWithEp.
  • Formula:
    • When probs is not None, the formula is as follows, where $i \in {0, 1, 2, ..., num\_tokens - 1}$:

      • First, calculate unpermutedTokens:

        • When rangeOptional[0] <= sortedIndices[i] < rangeOptional[1]:

          $$ unpermutedTokens[i] = permutedTokensOptional[sortedIndices[i]-rangeOptional[0]] $$
        • Otherwise:

          $$ unpermutedTokens[i] = 0 $$
      • Then calculate:

        $$ unpermutedTokens = unpermutedTokens.reshape(-1, topkNum, hiddenSize) $$
        $$ unpermutedTokens = unpermutedTokensGrad.unsqueeze(1) * unpermutedTokens $$
        $$ probsGrad = \sum_{k=0}^{topkNum}(unpermutedTokens_{i,j,k}) $$
      • Finally, when rangeOptional[0] <= sortedIndices[i] < rangeOptional[1]:

        $$ permutedTokensGradOut[sortedIndices[i]] = ((unpermutedTokensGrad.unsqueeze(1) * probs.unsqueeze(-1)).reshape(-1, hiddenSize))[i] $$
    • When probs is None, the formula is as follows, where $i \in {0, 1, 2, ..., num\_tokens - 1}$:

      • When rangeOptional[0] <= sortedIndices[i] < rangeOptional[1]:
      $$ permutedTokensGradOut[sortedIndices[i]-rangeOptional[0]] = unpermutedTokensGrad[i] $$

Function Prototype

Each operator uses a two-phase API. You must first call the "aclnnMoeTokenUnpermuteWithEpGradGetWorkspaceSize" API to obtain the workspace size required by the computation and the executor that contains the operator computation process, and then call the "aclnnMoeTokenUnpermuteWithEpGrad" API to perform the computation.

aclnnStatus aclnnMoeTokenUnpermuteWithEpGradGetWorkspaceSize(
  const aclTensor   *unpermutedTokensGrad,
  const aclTensor   *sortedIndices,
  const aclTensor   *permutedTokensOptional,
  const aclTensor   *probsOptional,
  bool               paddedMode,
  const aclIntArray *restoreShapeOptional,
  const aclIntArray *rangeOptional,
  int64_t            topkNum,
  const aclTensor   *permutedTokensGradOut,
  const aclTensor   *probsGradOut,
  uint64_t          *workspaceSize,
  aclOpExecutor     **executor)
aclnnStatus aclnnMoeTokenUnpermuteWithEpGrad(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnMoeTokenUnpermuteWithEpGradGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    unpermutedTokensGrad (aclTensor) Input unpermutedTokensGrad in the formula, the gradient of the forward output unpermutedTokens. tokens_num indicates the number of tokens, and hidden_size indicates the dimension size of tokens. BFLOAT16, FLOAT16, FLOAT32 ND (tokens_num, hidden_size) √
    sortedIndices (aclTensor) Input sortedIndices in the formula. Value range [0, tokens_num * topkNum - 1]. INT32 ND (tokens_num * topkNum) √
    permutedTokensOptional (aclTensor) Input permutedTokensOptional in the formula. Requires topkNum <= 512. Same as unpermutedTokensGrad. ND (tokens_num * topkNum, hidden_size) √
    probsOptional (aclTensor) Input probsOptional in the formula. If probs is provided, topkNum equals the second dimension of probs. If probs is not provided, topkNum=1. BFLOAT16, FLOAT16, FLOAT32 ND (tokens_num, topkNum) √
    paddedMode (bool) Input true indicates that paddedMode is enabled, and false indicates that paddedMode is disabled. paddedMode indicates the padded mode. Currently, only false is supported. - - - -
    restoreShapeOptional (aclIntArray) Input restoreShapeOptional in the formula. Takes effect only when paddedMode is true. Otherwise, no operation is performed on it. Currently, only nullptr is supported. - - - -
    rangeOptional (aclIntArray) Input rangeOptional in the formula. Valid range for EP splitting. The start position represented by rangeOptional[0] must be less than the end position represented by rangeOptional[1]. Takes no effect when empty. - - - -
    topkNum (int64_t) Input topkNum in the formula. Number of experts selected for each token. - - - - -
    permutedTokensGradOut (aclTensor) Output Gradient of permutedTokens, which is permutedTokensGradOut in the formula. - Same as unpermutedTokensGrad. ND (tokens_num * topkNum, hidden_size) ×
    probsGradOut (aclTensor) Output probsGradOut in the formula, the gradient of probs. (tokens_num, topkNum) Same as probsOptional. ND (tokens_num, topkNum) ×
    workspaceSize (uint64_t) Output Returns the workspace size to be applied for on the Device. - - - - -
    executor (aclOpExecutor) Output Returns the op executor that contains the operator computation 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 required input or required output tensor is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type or data format of the input or output is out of the supported range.
    ACLNN_ERR_INNER_TILING_ERROR 561002 topkNum > 512.
    The shape of the input or output does not meet the requirement.
    rangeOptional[1] < rangeOptional[0].

aclnnMoeTokenUnpermuteWithEpGrad

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Workspace size allocated on the Device, obtained from the first-phase API aclnnMoeTokenUnpermuteWithEpGradGetWorkspaceSize.
    executor Input Op executor, which contains the operator computation flow.
    stream Input Stream for executing the task.
  • Return Value

    aclnnStatus: Return status code. For details, see Error Codes.

Constraints

  • Deterministic computation:
    • aclnnMoeTokenUnpermuteWithEpGrad 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_token_unpermute_with_ep_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("mean result[%ld] is: %f\n", i, resultData[i]);
  }
}

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 allocate 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);
  // Call aclrtMemcpy to copy host-side data to device-side 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 the aclCreateTensor API 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 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 inputs and outputs as required by the API.
  std::vector<int64_t> permutedTokensShape = {3, 2};
  std::vector<int64_t> unpermutedTokensGradShape = {1, 2};
  std::vector<int64_t> probsShape = {1, 3};
  std::vector<int64_t> sortedIndicesShape = {3};
  std::vector<int64_t> permutedTokensGradShape = {3, 2};
  std::vector<int64_t> probsGradShape = {1, 3};
  void* permutedTokensDeviceAddr = nullptr;
  void* unpermutedTokensGradDeviceAddr = nullptr;
  void* probsDeviceAddr = nullptr;
  void* sortedIndicesDeviceAddr = nullptr;
  void* permutedTokensGradDeviceAddr = nullptr;
  void* probsGradDeviceAddr = nullptr;

  aclTensor* permutedTokens = nullptr;
  aclTensor* unpermutedTokensGrad = nullptr;
  aclTensor* probs = nullptr;
  aclTensor* sortedIndices = nullptr;
  bool paddedMode = false;
  aclTensor *permutedTokensGrad = nullptr;
  aclTensor *probsGrad = nullptr;

  std::vector<float> permutedTokensHostData = {1, 1, 1, 1, 1, 1};
  std::vector<float> unpermutedTokensGradHostData = {1, 1};
  std::vector<float> probsHostData = {1, 1, 1};
  std::vector<int> sortedIndicesHostData = {0, 1, 2};
  std::vector<float> permutedTokensGradHostData = {0, 0, 0, 0, 0, 0};
  std::vector<float> probsGradHostData = {0, 0, 0};

  ret = CreateAclTensor(permutedTokensHostData, permutedTokensShape,
                        &permutedTokensDeviceAddr, aclDataType::ACL_FLOAT,
                        &permutedTokens);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(unpermutedTokensGradHostData, unpermutedTokensGradShape, &unpermutedTokensGradDeviceAddr,
                      aclDataType::ACL_FLOAT, &unpermutedTokensGrad);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(probsHostData, probsShape, &probsDeviceAddr,
                      aclDataType::ACL_FLOAT, &probs);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(sortedIndicesHostData, sortedIndicesShape, &sortedIndicesDeviceAddr,
                      aclDataType::ACL_INT32, &sortedIndices);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  ret = CreateAclTensor(permutedTokensGradHostData, permutedTokensGradShape, &permutedTokensGradDeviceAddr, aclDataType::ACL_FLOAT,
                        &permutedTokensGrad);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  ret = CreateAclTensor(probsGradHostData, probsGradShape, &probsGradDeviceAddr, aclDataType::ACL_FLOAT,
                        &probsGrad);
  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 aclnnMoeTokenUnpermuteWithEpGrad.
  ret = aclnnMoeTokenUnpermuteWithEpGradGetWorkspaceSize(unpermutedTokensGrad, sortedIndices,permutedTokens, probs, paddedMode, nullptr, nullptr, 3, permutedTokensGrad, probsGrad, &workspaceSize, &executor);
  CHECK_RET(
      ret == ACL_SUCCESS,
      LOG_PRINT("aclnnMoeTokenUnpermuteWithEpGradGetWorkspaceSize 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 aclnnMoeTokenUnpermuteWithEpGrad.
  ret = aclnnMoeTokenUnpermuteWithEpGrad(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS,
            LOG_PRINT("aclnnMoeTokenUnpermuteWithEpGrad 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 API definition.
  PrintOutResult(permutedTokensGradShape, &permutedTokensGradDeviceAddr);
  PrintOutResult(probsGradShape, &probsGradDeviceAddr);

  // 6. Release aclTensor and aclScalar. Modify it according to the API definition.
  aclDestroyTensor(permutedTokens);
  aclDestroyTensor(unpermutedTokensGrad);
  aclDestroyTensor(sortedIndices);
  aclDestroyTensor(probs);
  aclDestroyTensor(permutedTokensGrad);
  aclDestroyTensor(probsGrad);

  // 7. Release device resources.
  aclrtFree(permutedTokensDeviceAddr);
  aclrtFree(unpermutedTokensGradDeviceAddr);
  aclrtFree(probsDeviceAddr);
  aclrtFree(sortedIndicesDeviceAddr);
  aclrtFree(permutedTokensGradDeviceAddr);
  aclrtFree(probsGradDeviceAddr);

  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();

  return 0;
}