aclnnMoeFinalizeRoutingV4

📄 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, this API performs the final processing of merging the MoE FFN outputs. Compared with the V3 API aclnnMoeFinalizeRoutingV3, this API adds the attribute k to support a custom top-K value when scalesOptional is null.
  • 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 "aclnnMoeFinalizeRoutingV4GetWorkspaceSize" first to obtain the workspace size required for the computation and the executor that contains the computation process, and then call "aclnnMoeFinalizeRoutingV4" to execute the computation.

aclnnStatus aclnnMoeFinalizeRoutingV4GetWorkspaceSize(
    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,
    int64_t           k,
    const aclTensor *out,
    uint64_t        *workspaceSize,
    aclOpExecutor  **executor)
aclnnStatus aclnnMoeFinalizeRoutingV4(
    void          *workspace,
    uint64_t       workspaceSize,
    aclOpExecutor *executor,
    aclrtStream    stream)

aclnnMoeFinalizeRoutingV4GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    expandedX(aclTensor*) Input expandedX in the formula, FFN output of MoE. - FLOAT16, BFLOAT16, FLOAT32 ND drop less use case: (NUM_ROWS * K, H),
    drop pad use case: (E, C, H).
    √
    expandedRowIdx(aclTensor*) Input expandedRowIdx in the formula. - INT32 ND (NUM_ROWS * K) √
    x1Optional(aclTensor*) Input x1 in the formula, representing the first shared expert. - Same as expandedX. ND Same as out. √
    x2Optional(aclTensor*) Input x2 in the formula, indicating the second shared expert. - Same as expandedX. ND Same as out. √
    biasOptional(aclTensor*) Input The bias in the formula, indicating the bias value. - Same as expandedX. ND (E, H) √
    scalesOptional(aclTensor*) Input The scales in the formula. - FLOAT16, BFLOAT16, FLOAT32 ND (NUM_ROWS, K) √
    expertIdxOptional(aclTensor*) Input The expertIdx in the formula. Values in the Tensor are in the range [0, E-1]. INT32 ND (NUM_ROWS, K) √
    xOptional(aclTensor*) Input x in the formula. - Same as expandedX. ND (NUM_ROWS, H) √
    alpha1Optional(aclTensor*) Input a1 in the formula. - Same as expandedX. ND (constantExpertEnd - constantExpertStart, H) √
    alpha2Optional(aclTensor*) Input a2 in the formula. - Same as expandedX. ND (constantExpertEnd - constantExpertStart, H) √
    vOptional(aclTensor*) Input v in the formula. - Same as 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. Specifies the range of the zero expert. The values in the array are [zeroExpertStart, zeroExpertEnd], left-closed and right-open. Each value must be greater than 0, zeroExpertEnd must be greater than zeroExpertStart, and zeroExpertEnd must not exceed the maximum value of expertIdxOptional. Value range: same as expertIdxOptional - 2 - -
    copyExpertRange(aclIntArray*) Input Optional parameter. Specifies the range of copy experts. The array contains [copyExpertStart, copyExpertEnd], which is left-closed and right-open. The values must be greater than 0, copyExpertEnd must be greater than copyExpertStart, and copyExpertEnd must not exceed the maximum value of expertIdxOptional. Value range same as expertIdxOptional - 2 - -
    constantExpertRange(aclIntArray*) Input Optional parameter. Specifies the range of constant experts. 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. Same as the value range of expertIdxOptional - 2 - -
    k(int64_t) Input Optional parameter, with a default value of 1. Indicates the number of top-K experts selected for each token. If scalesOptional is not empty and k > 1, k must be consistent with the second dimension of the shape of scalesOptional. If scalesOptional is empty, k is used to infer the output shape. - - - -
    out(aclTensor*) Output Output in the formula. - Same as expandedX. ND (NUM_ROWS, H) ×
    workspaceSize(uint64_t) Output Size of the workspace to be requested on the Device. - - - - -
    executor(aclOpExecutor**) Output Returns the op executor, which contains the operator computation flow. - - - - -
    • Atlas A2 products and 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: Returns the 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 A required input, required output, or required attribute is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type, data format, or dimension of the input or output is not within the supported range.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The shapes of multiple input tensors do not match.
    The shape of the input attribute does not match that of the input tensor.

aclnnMoeFinalizeRoutingV4

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the Device.
    workspaceSize Input Size of the workspace memory requested on the Device, obtained by calling the first-phase API aclnnMoeFinalizeRoutingV4GetWorkspaceSize.
    executor Input Op executor, containing 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:

    • aclnnMoeFinalizeRoutingV4 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. If scalesOptional does not exist, K is determined by the attribute k and defaults to 1. If scalesOptional exists and k (k > 1) is explicitly passed in, the system validates that k is consistent with the second dimension of the scalesOptional shape.

  6. When biasOptional exists, expertIdxOptional must also exist.

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

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

Example

Sample code is as follows. It 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_v4.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: 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 request 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);
    // 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 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) Device/stream initialization. See the acl API reference.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  // Process the check as required.
  CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. Construct the inputs and outputs. Customize the construction based on 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;
  int64_t k = 2;
  // Create the expandedX aclTensor.
  ret = CreateAclTensor(expandedXHostData, expandedXShape, &expandedXAddr,
                        aclDataType::ACL_FLOAT, &expandedX);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the x1 aclTensor.
  ret = CreateAclTensor(x1HostData, x1Shape, &x1Addr, aclDataType::ACL_FLOAT, &x1);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the x2Optional aclTensor.
  ret = CreateAclTensor(x2OptionalHostData, x2OptionalShape, &x2OptionalAddr, aclDataType::ACL_FLOAT, &x2Optional);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the bias aclTensor.
  ret = CreateAclTensor(biasHostData, biasShape, &biasAddr, aclDataType::ACL_FLOAT, &bias);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the totalWeightOut aclTensor.
  ret = CreateAclTensor(scalesHostData, scalesShape, &scalesDeviceAddr, aclDataType::ACL_FLOAT, &scales);
  CHECK_RET(ret == ACL_SUCCESS, return ret);

  // Create the expandedExpertIdx aclTensor.
  ret = CreateAclTensor(expandedExpertIdxHostData, expandedExpertIdxShape, &expandedExpertIdxAddr,
                        aclDataType::ACL_INT32, &expandedExpertIdx);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the expandedRowIdx aclTensor.
  ret = CreateAclTensor(expandedRowIdxHostData, expandedRowIdxShape, &expandedRowIdxAddr,
                        aclDataType::ACL_INT32, &expandedRowIdx);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the 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, and change it to the specific operator API.
  uint64_t workspaceSize = 0;
  aclOpExecutor* executor;

  // Call the first-phase API of aclnnMoeFinalizeRoutingV4.
  ret = aclnnMoeFinalizeRoutingV4GetWorkspaceSize(expandedX, expandedRowIdx, x1, x2Optional, bias, scales,
                                                  expandedExpertIdx, nullptr, nullptr, nullptr, nullptr,
                                                  dropPadMode, nullptr, nullptr, nullptr, k, out, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeFinalizeRoutingV4GetWorkspaceSize 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 aclnnMoeFinalizeRoutingV4.
  ret = aclnnMoeFinalizeRoutingV4(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeFinalizeRoutingV4 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 values, and copy the results from device memory to the Host. 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;
}