aclnnMoeFinalizeRoutingV3

📄 View Source Code

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: Supported
  • Atlas training products: Not supported

Function

  • Description: In MoE computation, performs the final processing to merge the outputs of the MoE FFN. This API has the following changes compared with V2 API aclnnMoeFinalizeRoutingV2. Select an appropriate API as required:
    1. While retaining the original V2 functions, adds computation for zero-computation experts, copy experts, and constant experts. The formula is changed as follows.
  • Formula:
$$ \begin{aligned} &\mathrm{expertId} = \mathrm{expertIdx}[i,k] \\ &\text{if } \mathrm{expertId} \in \mathrm{zero\_expert\_range}:\\&\quad \text{skip}; \\&\text{elif } \mathrm{expertId} \in \mathrm{copy\_expert\_range}: \\ &\quad x = x[i] \\ &\quad \mathrm{out}(i, j) = x1_{i, j} + x2_{i, j} + \sum_{k=1}^{K}\mathrm{scales}_{i,k} \cdot \left(x + \mathrm{bias}_{mathrm{expertId},j}\right) \\ &\text{elif } \mathrm{expertId} \in \mathrm{constant\_expert\_range}: \\&\quad x = \alpha_1 \cdot x[i] + \alpha_2 \cdot v \\ &\quad \mathrm{out}(i, j) = x1_{i, j} + x2_{i, j} + \sum_{k=1}^{K}\mathrm{scales}_{i,k} \cdot \left(x + \mathrm{bias}_mathrm{expertId},j\right) \\ &\text{else}: \\ &\quad \mathrm{out}(i, j) = x1_{i, j} + x2_{i, j} + \sum_{k=0}^{K}\mathrm{scales}_{i,k} \cdot\big(\mathrm{expandedX}_{\mathrm{expandedRowIdx}_{i\cdot K+k},j} + \mathrm{bias}_{\mathrm{expertid}_{i\cdot K+k},j}\big) \end{aligned} $$

Function Prototype

Each operator uses a two-phase API. Call "aclnnMoeFinalizeRoutingV3GetWorkspaceSize" first to obtain the workspace size required for computation and the executor that contains the operator computation process, and then call "aclnnMoeFinalizeRoutingV3" to perform the computation.

aclnnStatus aclnnMoeFinalizeRoutingV3GetWorkspaceSize(
    const aclTensor *expandedX,
    const aclTensor *expandedRowIdx,
    const aclTensor *x1Optional,
    const aclTensor *x2Optional,
    const aclTensor *biasOptional,
    const aclTensor *scalesOptional,
    const aclTensor *expertIdxOptional,
    const aclTensor *xOptional,
    const aclTensor *alpha1Optional,
    const aclTensor *alpha2Optional,
    const aclTensor *vOptional,
    int64_t           dropPadMode,
    const aclIntArray *zeroExpertRange,
    const aclIntArray *copyExpertRange,
    const aclIntArray *constantExpertRange,
    const aclTensor *out,
    uint64_t        *workspaceSize,
    aclOpExecutor  **executor)
aclnnStatus aclnnMoeFinalizeRoutingV3(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnMoeFinalizeRoutingV3GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    expandedX(aclTensor*) Input expandedX in the formula, the FFN output of MoE. - FLOAT16, BFLOAT16, FLOAT32 ND drop less scenario: (NUM_ROWS * K, H),
    drop pad scenario: (E, C, H).
    √
    expandedRowIdx(aclTensor*) Input expandedRowIdx in the formula. - INT32 ND (NUM_ROWS * K) √
    x1Optional(aclTensor*) Input x1 in the formula, indicating the first shared expert. - Consistent with expandedX. ND Consistent with out. √
    x2Optional(aclTensor*) Input x2 in the formula, indicating the second shared expert. - Consistent with expandedX. ND Consistent with out. √
    biasOptional(aclTensor*) Input The bias in the formula, indicating a bias value. - Consistent with expandedX. ND (E, H) √
    scalesOptional(aclTensor*) Input scales in the formula. - FLOAT16, BFLOAT16, FLOAT32 ND (NUM_ROWS, K) √
    expertIdxOptional(aclTensor*) Input expertIdx in the formula. The value range of values in the Tensor is [0, E-1]. INT32 ND (NUM_ROWS, K) √
    xOptional(aclTensor*) Input x in the formula. - Consistent with expandedX. ND (NUM_ROWS, H) √
    alpha1Optional(aclTensor*) Input a1 in the formula. - Consistent with expandedX. ND (constantExpertEnd - constantExpertStart, H) √
    alpha2Optional(aclTensor*) Input a2 in the formula. - Consistent with expandedX. ND (constantExpertEnd - constantExpertStart, H) √
    vOptional(aclTensor*) Input v in the formula. - Consistent with expandedX. ND (constantExpertEnd - constantExpertStart, H) √
    dropPadMode(int64_t) Input Optional parameter. Default value: 0. Indicates whether the drop mode is supported and the arrangement of expandedRowIdx. The value range is [0, 3]. - - - -
    zeroExpertRange(aclIntArray*) Input Optional parameter. Indicates the range of the zero expert. The array value is [zeroExpertStart, zeroExpertEnd], left-closed and right-open. The value must be greater than 0, and zeroExpertEnd must be greater than zeroExpertStart and must not exceed the maximum value of expertIdxOptional. Value range: consistent with expertIdxOptional - 2 -
    copyExpertRange(aclIntArray*) Input Optional parameter. Indicates the range of copy experts. The values in the array are [copyExpertStart, copyExpertEnd], which is left-closed and right-open. Each value must be greater than 0, copyExpertEnd must be greater than copyExpertStart, and copyExpertEnd must not exceed the maximum value of expertIdxOptional. The value range is consistent with that of expertIdxOptional. - 2 -
    constantExpertRange(aclIntArray*) Input Optional parameter. Indicates the range of the constant expert. The array values are [constantExpertStart, constantExpertEnd], left-closed and right-open. The values must be greater than 0, constantExpertEnd must be greater than constantExpertStart, and constantExpertEnd must not exceed the maximum value of expertIdxOptional. Value range consistent with expertIdxOptional - 2 -
    out(aclTensor*) Output The output in the formula. - Consistent with expandedX. ND (NUM_ROWS, H) ×
    workspaceSize(uint64_t) Output Returns the workspace size to be allocated on the Device. - - - - -
    executor(aclOpExecutor**) Output Returns the op executor, which contains the operator computation process. - - - - -
    • Atlas A2 products, Atlas A3 products:
      • expandedX must be a 2D or 3D tensor. Supported data types are FLOAT16, BFLOAT16, and FLOAT32. Both drop-less and drop-pad scenarios are supported.
      • scalesOptional: In mixed-precision mode, when expandedX is BFLOAT16, scalesOptional can be FLOAT32; in non-mixed-precision mode, the data type must be consistent with that of expandedX.
    • Ascend 950PR&950DT products:
      • expandedX must be a 2D or 3D tensor. Supported data types are FLOAT16, BFLOAT16, and FLOAT32. Both drop-less and drop-pad scenarios are supported.
      • The data type of scalesOptional can differ from that of expandedX.
    • Atlas inference products:
      • expandedX must be a 2D tensor. Supported data types are FLOAT16 and FLOAT32. The last axis H must be 32-aligned.
      • x1Optional, x2Optional, biasOptional, and expertIdxOptional only support passing nullptr.
      • Only dropPadMode set to 2 is supported.
      • The data type of scalesOptional supports FLOAT16 and FLOAT32, and must be consistent with expandedX.
  • Return value

    aclnnStatus: Return status 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 required input, output, or attribute is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types, data formats, or dimensions of inputs and outputs are not within the supported range.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The shape information of multiple input tensors does not match.
    The shape information does not match between input attributes and input tensors.

aclnnMoeFinalizeRoutingV3

  • Parameters:

    Parameter Input/Output Description
    workspace Input Address of the workspace memory allocated on the Device.
    workspaceSize Input Size of the workspace memory allocated on the Device, obtained by the first-phase API aclnnMoeFinalizeRoutingV3GetWorkspaceSize.
    executor Input op executor, which contains the operator computation flow.
    stream Input Stream for task execution.
  • Return Value

    aclnnStatus: return status code. For details, see aclnn return codes.

Constraints

  1. Deterministic computation:

    • aclnnMoeFinalizeRoutingV3 defaults to a deterministic implementation.
  2. NUM_ROWS: Indicates the number of rows;

    • K: Indicates that K experts are selected from the total E experts;
    • H: Indicates the hidden size, i.e., the sequence length of each token, which is the number of columns.
    • E: Indicates the expert num, i.e., the number of experts. E must be greater than or equal to K.
    • C: Indicates the expert capacity, i.e., the capacity threshold for the number of tokens an expert can process.
  3. expandedRowIdx: When the dropPadMode parameter value is 0 or 2, the value range of the tensor is [0, NUM_ROWS * K - 1]; when the dropPadMode parameter value is 1 or 3, the value range of the tensor is [-1, E * C - 1].

  4. When the x1Optional parameter is not input, the x2Optional parameter cannot be input either.

  5. When scalesOptional does not exist, K is 1.

  6. When biasOptional exists, expertIdxOptional must also exist.

  7. The values and meanings of dropPadMode are as follows:

    • 0: drop less scenario, expandedRowIdx is arranged by column (corresponding to the output format of aclnnMoeInitRouting).
    • 1: drop pad scenario, expandedRowIdx is arranged by column (corresponding to the output format of aclnnMoeInitRouting).
    • 2: In the drop less scenario, expandedRowIdx is arranged by row (corresponding to the output format of aclnnMoeInitRoutingV2).
    • 3: In the drop pad scenario, expandedRowIdx is arranged by row (corresponding to the output format of aclnnMoeInitRoutingV2).
  8. The expert ranges of zeroExpertRange, copyExpertRange, and constantExpertRange cannot overlap.

Example

The following sample code is for reference only. For details about compilation and execution, see Compile and Run Samples.

#include "acl/acl.h"
#include "aclnnop/aclnn_moe_finalize_routing_v3.h"
#include <iostream>
#include <vector>
#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 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 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 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);
  // Handle check according to your needs.
  CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. Construct the input and output as required by the API.
  std::vector<int64_t> expandedXShape = {3 * 2, 4};
  std::vector<int64_t> x1Shape = {3, 4};
  std::vector<int64_t> x2OptionalShape = {3, 4};
  std::vector<int64_t> biasShape = {2, 4};
  std::vector<int64_t> scalesShape = {3, 2};
  std::vector<int64_t> expandedExpertIdxShape = {3, 2};
  std::vector<int64_t> expandedRowIdxShape = {3 * 2};
  std::vector<int64_t> outShape = {3, 4};
  void* expandedXAddr = nullptr;
  void* x1Addr = nullptr;
  void* x2OptionalAddr = nullptr;
  void* biasAddr = nullptr;
  void* scalesDeviceAddr = nullptr;
  void* expandedExpertIdxAddr = nullptr;
  void* expandedRowIdxAddr = nullptr;
  void* outDeviceAddr = nullptr;

  aclTensor* expandedX = nullptr;
  aclTensor* x1 = nullptr;
  aclTensor* x2Optional = nullptr;
  aclTensor* bias = nullptr;
  aclTensor* scales = nullptr;
  aclTensor* expandedExpertIdx = nullptr;
  aclTensor* expandedRowIdx = nullptr;
  aclTensor* out = nullptr;
  std::vector<float> expandedXHostData = {0.1, 1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1, 11.1,
                                                     0.1, 1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1, 11.1};
  std::vector<float> x1HostData = {0.2, 1.2, 2.2, 3.2, 4.2, 5.2, 6.2, 7.2, 8.2, 9.2, 10.2, 11.2};
  std::vector<float> x2OptionalHostData = {0.2, 1.2, 2.2, 3.2, 4.2, 5.2, 6.2, 7.2, 8.2, 9.2, 10.2, 11.2};
  std::vector<float> biasHostData = {0.2, 0.4, 0.2, 0.4, 0.2, 0.4, 0.2, 0.4};
  std::vector<float> scalesHostData = {1.3, 1.6, 1.2, 1.8, 1.2, 2.3};
  std::vector<int32_t> expandedExpertIdxHostData = {0, 1, 0, 1, 0, 1};
  std::vector<int32_t> expandedRowIdxHostData = {2, 1, 4, 3, 0, 5};
  std::vector<float> outHostData(12, 0.0f);
  int64_t dropPadMode = 0;
  // Create expandedX aclTensor.
  ret = CreateAclTensor(expandedXHostData, expandedXShape, &expandedXAddr,
                        aclDataType::ACL_FLOAT, &expandedX);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create x1 aclTensor.
  ret = CreateAclTensor(x1HostData, x1Shape, &x1Addr, aclDataType::ACL_FLOAT, &x1);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create x2Optional aclTensor.
  ret = CreateAclTensor(x2OptionalHostData, x2OptionalShape, &x2OptionalAddr, aclDataType::ACL_FLOAT, &x2Optional);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create bias aclTensor.
  ret = CreateAclTensor(biasHostData, biasShape, &biasAddr, aclDataType::ACL_FLOAT, &bias);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create scales aclTensor.
  ret = CreateAclTensor(scalesHostData, scalesShape, &scalesDeviceAddr, aclDataType::ACL_FLOAT, &scales);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create expandedExpertIdx aclTensor.
  ret = CreateAclTensor(expandedExpertIdxHostData, expandedExpertIdxShape, &expandedExpertIdxAddr,
                        aclDataType::ACL_INT32, &expandedExpertIdx);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create expandedRowIdx aclTensor.
  ret = CreateAclTensor(expandedRowIdxHostData, expandedRowIdxShape, &expandedRowIdxAddr,
                        aclDataType::ACL_INT32, &expandedRowIdx);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create Out aclTensor.
  ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // 3. Call the CANN operator library API. Modify it to the specific operator API.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  // Call the first-phase API of aclnnMoeFinalizeRoutingV3.
  ret = aclnnMoeFinalizeRoutingV3GetWorkspaceSize(expandedX, expandedRowIdx, x1, x2Optional, bias, scales,
                                                  expandedExpertIdx, nullptr, nullptr, nullptr, nullptr,
                                                  dropPadMode, nullptr, nullptr, nullptr, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeFinalizeRoutingV3GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Allocate device memory using the workspaceSize computed 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 aclnnMoeFinalizeRoutingV3.
  ret = aclnnMoeFinalizeRoutingV3(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeFinalizeRoutingV3 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 on the device side to the Host side. Modify it based on the specific API definition.
  auto size = GetShapeSize(outShape);
  std::vector<float> resultData(size, 0.0f);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
                    outDeviceAddr, size * 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 < size; i++) {
      LOG_PRINT("result[%ld] is: %f\n", i, resultData[i]);
  }

  // 6. Release aclTensor and aclScalar. Modify it based on the specific API definition.
  aclDestroyTensor(expandedX);
  aclDestroyTensor(x1);
  aclDestroyTensor(x2Optional);
  aclDestroyTensor(bias);
  aclDestroyTensor(scales);
  aclDestroyTensor(expandedExpertIdx);
  aclDestroyTensor(expandedRowIdx);
  aclDestroyTensor(out);

  // 7. Release device resources. Modify it based on the specific API definition.
  aclrtFree(expandedXAddr);
  aclrtFree(x1Addr);
  aclrtFree(x2OptionalAddr);
  aclrtFree(biasAddr);
  aclrtFree(scalesDeviceAddr);
  aclrtFree(expandedExpertIdxAddr);
  aclrtFree(expandedRowIdxAddr);
  aclrtFree(outDeviceAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}