aclnnMoeGatingTopKV2

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

Function

  • Description: In MoE computation, Sigmoid, SoftMax, or SqrtSoftplus is computed on input x, grouped sorting is performed on the computation results, and the top k experts are selected based on the grouped sorting result. Two modes are supported:

    • TopK mode: Selects experts by performing TopK sorting on normValue
    • Hash mode: Obtains pre-computed expert indices from the tid2eid mapping table based on inputIds, skips the sorting step, and outputs them directly (newly supported by aclnnMoeGatingTopKV2)
  • Formula:

    TopK mode:

    Step 1: Normalization

    Perform normalization on input x according to normType:

    $$ normOut = \begin{cases} \text{SoftMax}(x), & normType = 0 \\ \text{Sigmoid}(x), & normType = 1 \\ \sqrt{\text{Softplus}(x)}, & normType = 2 \end{cases} $$

    Step 2: Add bias

    If bias is not empty, perform bias addition to obtain the value used for selection:

    $$ normValue = normOut + bias $$

    Otherwise, $normValue = normOut$.

    Step 3: group filtering (performed only when groupCount > 1)

    Divide normValue into groupCount groups and compute the score of each group based on groupSelectMode:

    $$ groupedValue = Reshape(normValue,\ [batch,\ groupCount,\ -1]) $$
    $$ groupScore = \begin{cases} ReduceMax(groupedValue,\ dim=-1), & groupSelectMode = 0 \\ ReduceSum(TopK(groupedValue,\ k=2,\ dim=-1),\ dim=-1), & groupSelectMode = 1 \end{cases} $$

    Select the kGroup groups with the highest scores and set the corresponding positions of the unselected groups to $-\infty$:

    $$ groupIdx = TopK(groupScore,\ k=kGroup).indices $$
    $$ normValue = Mask(groupedValue,\ groupIdx,\ fillValue=-\infty) $$

    Step 4: Top-K expert selection

    Apply Top-K to normValue to obtain the expert index. Only expertIdxOut is needed here:

    $$ y, expertIdxOut = TopK(normValue[groupIdx, :],\ k=k) $$

    Step 5: Renorm and scaling

    Obtain the corresponding k expert scores from normOut based on expertIdxOut:

    $$ gathered = normOut[\text{expertIdxOut}] $$

    Normalization is performed when normType=1 or normType=2; when normType=0, the renorm parameter effect applies, and renorm is performed when renorm=1:

    $$ if\ (normType = 1\ or\ normType = 2)\ or\ (normType = 0\ and\ renorm = 1): $$
    $$ \quad yOut = \frac{gathered}{ReduceSum(gathered,\ dim=-1) + eps} $$

    Otherwise $yOut = gathered$

    Final output:

    $$ yOut = yOut \times routedScalingFactor $$

    Step 6: Optional output

    If outFlag is True, the third output is normOut; otherwise, it is empty.

    Hash mode:

    Hash mode is enabled when inputIds and tid2eid are provided:

    Step 1: Normalization

    Normalize the input x according to normType (same as in TopK mode):

    $$ normOut = \begin{cases} SoftMax(x), & normType = 0 \\ Sigmoid(x), & normType = 1 \\ \sqrt{Softplus(x)}, & normType = 2 \end{cases} $$

    Step 2: Hash index lookup

    Obtain expert indexes from the tid2eid mapping table based on inputIds:

    $$ expertIdxOut = tid2eid[inputIds, :] $$

    The shape of tid2eid is [numKeys, k], and the shape of inputIds is [batch]. Each inputIds value corresponds to a row of k expert indexes.

    Step 3: Gather and scaling

    Obtain the corresponding k expert scores from normOut based on expertIdxOut:

    $$ gathered = normOut[expertIdxOut] $$

    Normalization is performed when normType=1 or normType=2; when normType=0, the renorm parameter effect applies, and renorm is performed when renorm=1:

    $$ if\ (normType = 1\ or\ normType = 2)\ or\ (normType = 0\ and\ renorm = 1): $$
    $$ \quad yOut = \frac{gathered}{ReduceSum(gathered,\ dim=-1) + eps} $$

    Otherwise $yOut = gathered$

    Final output:

    $$ yOut = yOut \times routedScalingFactor $$

Function Prototype

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

aclnnStatus aclnnMoeGatingTopKV2GetWorkspaceSize(
  const aclTensor *x,
  const aclTensor *biasOptional,
  const aclTensor *inputIdsOptional,
  const aclTensor *tid2eidOptional,
  int64_t          k,
  int64_t          kGroup,
  int64_t          groupCount,
  int64_t          groupSelectMode,
  int64_t          renorm,
  int64_t          normType,
  bool             outFlag,
  double           routedScalingFactor,
  double           eps,
  const aclTensor *yOut,
  const aclTensor *expertIdxOut,
  const aclTensor *outOut,
  uint64_t        *workspaceSize,
  aclOpExecutor  **executor)
aclnnStatus aclnnMoeGatingTopKV2(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnMoeGatingTopKV2GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x Input Input parameter to be computed, corresponding to x in the corresponding formula. None FLOAT16, BFLOAT16, FLOAT32 ND 2 √
    biasOptional Input Bias value computed together with input x, corresponding to bias in the corresponding formula. The shape value is equal to the last dimension of x. FLOAT16, BFLOAT16, FLOAT32 ND 1 √
    inputIdsOptional Input Input index in Hash mode, used to look up the expert index from tid2eid. Corresponds to inputIds in the corresponding formula. The shape is [batch], equal to the first dimension of x. Required only in Hash mode. INT32, INT64 ND 1 √
    tid2eidOptional Input Hash mapping table that stores precomputed expert indices. It corresponds to tid2eid in the corresponding formula. The shape is [numKeys, k], where numKeys is the number of rows in the mapping table, and k is equal to parameter k. Required only in Hash mode. INT32, INT64 ND 2 √
    k Input Value of k for topk, which is k in the corresponding formula. None INT64 - - -
    kGroup Input Number of groups selected after group sorting, corresponding to kGroup in the formula. None INT64 - - -
    groupCount Input Total number of groups, corresponding to groupCount in the formula. None INT64 - - -
    groupSelectMode Input Group sorting mode. None INT64 - - -
    renorm Input renorm flag. None INT64 - - -
    normType Input Type of the norm function. None INT64 - - -
    outFlag Input Indicates whether to output the result of the norm operation. None BOOL - - -
    routedScalingFactor Input The routedScalingFactor coefficient used to compute yOut, corresponding to routedScalingFactor in the formula. None DOUBLE - - -
    eps Input eps coefficient used for computing yOut, corresponding to eps in the formula. None DOUBLE - - -
    yOut Output Result of computing norm, group sorting, and topk on x, corresponding to yOut in the corresponding formula. Data type must be the same as that of x. FLOAT16, BFLOAT16, FLOAT32 ND 2 -
    expertIdxOut Output Index of x after norm and group sorting topk, corresponding to expertIdxOut in the formula. Shape requirement: same as yOut. INT32 ND 2 -
    outOut Output Output of the norm computation, i.e., normOut in the corresponding formula. The shape must be the same as that of x. FLOAT32 ND 2 -
    workspaceSize Output Size of the workspace to be allocated on the device. - - - - -
    executor Output Returns the op executor that contains the operator computation flow. - - - - -
  • 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 compute input or compute output is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data types of the input and output are not within the supported range.
    ACLNN_ERR_INNER_NULLPTR 561103 The shape of x does not meet the requirement.
    The shapes of x and biasOptional mismatch.
    The value of k is not in the range of 1 to x_shape[-1] / groupCount * kGroup.
    The value of kGroup is not in the range of 1 to groupCount.
    The total number of experts per group exceeds 2048 after alignment to 32.
    The value of a calculation input parameter does not meet the requirement.
    In Hash mode, k exceeds 64.
    In Hash mode, the shape of tid2eid mismatches.
    In Hash mode, the shape of inputIds mismatches.
    In Hash mode, the non-simplified path is not supported.

aclnnMoeGatingTopKV2

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the device.
    workspaceSize Input Workspace size allocated on the device, obtained by the first-phase API aclnnMoeGatingTopKV2GetWorkspaceSizeV2.
    executor Input Op executor, which contains the operator computation flow.
    stream Input Stream on which the task is executed.
  • Return value

    aclnnStatus: return status code. For details, see aclnn Return Codes.

Constraints

  • Deterministic computation:
    • aclnnMoeGatingTopKV2 defaults to a deterministic implementation.
  • Input shape constraints:
    • The last dimension of x (i.e., the number of experts) must not exceed 2048.
  • Input value range restrictions:
    • Requires 1 <= k <= x_shape[-1] / groupCount * kGroup.
    • Requires 1 <= kGroup <= groupCount, and the value of kGroup * x_shape[-1] / groupCount must be greater than or equal to k.
    • Requires groupCount > 0, x_shape[-1] must be divisible by groupCount and the quotient must be greater than groupSelectMode, and the result of the quotient aligned to 32 elements multiplied by groupCount must not exceed 2048.
  • Other constraints:
    • groupSelectMode takes values 0 and 1. 0 indicates sorting groups by the maximum value, and 1 indicates sorting groups by the sum of topk2 values.
    • The value of normType is 0, 1, or 2. 0 indicates the Softmax function, 1 indicates the Sigmoid function, and 2 indicates the SqrtSoftplus function.
    • Atlas A3 products, Atlas A2 products: when the value of normType is 2, groupCount is required to be 1
    • When the value of normType is 1 or 2, the renorm parameter effect does not apply; when the value of normType is 0, the renorm parameter effect applies. The value of renorm is 0 or 1, where 0 indicates no renorm and 1 indicates renorm.
    • outFlag takes values true and false, where true indicates output and false indicates no output.
  • Hash mode constraints:
    • The Hash mode requires both inputIdsOptional and tid2eidOptional to be provided; otherwise, the TopK mode is used.
    • The Hash mode supports only the simplified path (kGroup == groupCount or groupCount == expertCount).
    • In the Hash mode, k must not be greater than 64.
    • The shape of tid2eid must be [numKeys, k], where numKeys is the total number of rows in the mapping table and k is equal to parameter k.
    • The shape of inputIds must be [batch], which is equal to the first dimension of x.
    • Each value in inputIds must be in the range [0, numKeys-1].
    • The data types of inputIdsOptional and tid2eidOptional support the combination of INT32 and INT64.

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_gating_top_k_v2.h"
#include <iostream>
#include <vector>
#include <random>

#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;
}

std::vector<float> GenerateRandomFloats(int64_t count) {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<float> dist(0.0f, 10.0f);

    std::vector<float> result(count);
    for (auto& num : result) {
        num = dist(gen);
    }
    return result;
}
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 memory on the device.
  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 data to the 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);
  // 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) Device/stream initialization. For details, see the list of AscendCL external APIs.
  // Set deviceId based on the actual device.
  int32_t deviceId = 0;
  aclrtStream stream;
  auto ret = Init(deviceId, &stream);
  // Handle the check as needed.
  CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return ret);

  // 2. Construct the inputs and outputs. Custom construction is required based on the API.
  std::vector<int64_t> inputShape = {3, 256};
  std::vector<int64_t> biasShape = {256};
  std::vector<int64_t> inputIdsShape = {3};
  std::vector<int64_t> tid2eidShape = {3, 2};
  std::vector<int64_t> outShape = {3, 2};
  std::vector<int64_t> expertIdOutShape = {3, 2};
  std::vector<int64_t> normOutShape = {3, 256};

  void* inputAddr = nullptr;
  void* biasAddr = nullptr;
  void* inputIdsAddr = nullptr;
  void* tid2eidAddr = nullptr;
  void* outAddr = nullptr;
  void* expertIdOutAddr = nullptr;
  void* normOutAddr = nullptr;

  aclTensor* input = nullptr;
  aclTensor* bias = nullptr;
  aclTensor* inputIds = nullptr;
  aclTensor* tid2eid = nullptr;
  aclTensor* out = nullptr;
  aclTensor* expertIdOut = nullptr;
  aclTensor* normOut = nullptr;

  std::vector<float> inputHostData = GenerateRandomFloats(GetShapeSize(inputShape));
  std::vector<float> biasHostData = GenerateRandomFloats(GetShapeSize(biasShape));
  std::vector<int32_t> inputIdsHostData = {0, 2, 1};
  std::vector<int32_t> tid2eidHostData = {
    10, 42,
    33, 127,
    5,  88
  };
  std::vector<float> outHostData(GetShapeSize(outShape));
  std::vector<int32_t> expertIdOutHostData(GetShapeSize(expertIdOutShape));
  std::vector<float> normOutHostData(GetShapeSize(normOutShape));

  // Create the input aclTensor.
  ret = CreateAclTensor(inputHostData, inputShape, &inputAddr, aclDataType::ACL_FLOAT, &input);
  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 inputIds aclTensor.
  ret = CreateAclTensor(inputIdsHostData, inputIdsShape, &inputIdsAddr, aclDataType::ACL_INT32, &inputIds);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the tid2eid aclTensor.
  ret = CreateAclTensor(tid2eidHostData, tid2eidShape, &tid2eidAddr, aclDataType::ACL_INT32, &tid2eid);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the out aclTensor.
  ret = CreateAclTensor(outHostData, outShape, &outAddr, aclDataType::ACL_FLOAT, &out);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the expertIdOut aclTensor.
  ret = CreateAclTensor(expertIdOutHostData, expertIdOutShape, &expertIdOutAddr, aclDataType::ACL_INT32, &expertIdOut);
  CHECK_RET(ret == ACL_SUCCESS, return ret);
  // Create the normOut aclTensor.
  ret = CreateAclTensor(normOutHostData, normOutShape, &normOutAddr, aclDataType::ACL_FLOAT, &normOut);
  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 aclnnMoeGatingTopKV2.
  ret = aclnnMoeGatingTopKV2GetWorkspaceSize(input, bias, inputIds, tid2eid, 2, 1, 1, 1, 0, 1, false, 1.0, 1e-20, out, expertIdOut, normOut, &workspaceSize, &executor);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeGatingTopKV2GetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
  // Allocate device memory based on 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 aclnnMoeGatingTopKV2.
  ret = aclnnMoeGatingTopKV2(workspaceAddr, workspaceSize, executor, stream);
  CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeGatingTopKV2 failed. ERROR: %d\n", ret); return ret);

  // 4. (Boilerplate) Synchronize and wait for 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 result from device memory to host memory. Modify as required by the specific API definition.
  auto size = GetShapeSize(outShape);
  std::vector<float> resultData(size, 0.0f);
  ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]),
                    outAddr, 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 as required by the specific API definition.
  aclDestroyTensor(input);
  aclDestroyTensor(bias);
  aclDestroyTensor(inputIds);
  aclDestroyTensor(tid2eid);
  aclDestroyTensor(out);
  aclDestroyTensor(expertIdOut);
  aclDestroyTensor(normOut);

  // 7. Release device resources. Modify as required by the specific API definition.
  aclrtFree(inputAddr);
  aclrtFree(biasAddr);
  aclrtFree(inputIdsAddr);
  aclrtFree(tid2eidAddr);
  aclrtFree(outAddr);
  aclrtFree(normOutAddr);
  aclrtFree(expertIdOutAddr);
  if (workspaceSize > 0) {
    aclrtFree(workspaceAddr);
  }
  aclrtDestroyStream(stream);
  aclrtResetDevice(deviceId);
  aclFinalize();
  return 0;
}