aclnnMoeInitRoutingV3

📄 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: MoE routing computation. Performs routing based on the computation result of aclnnMoeGatingTopKSoftmaxV2. Supports non-quantized, static quantization, and dynamic quantization modes. Compared with the V2 API aclnnMoeInitRoutingV2, this API has the following changes. Select an appropriate API based on actual requirements:

    1. Adds dynamic and static quantization. Supports int8 quantization output for expandX and adds multiple FP8/FP4/INT4/HIFLOAT8 quantization modes.
    2. Adds the activeExpertRangeOptional parameter to filter expertId within the valid range.
    3. Deletes attribute expertTokensBeforeCapacityFlag and output expertTokensBeforeCapacityOut, and adds output expertTokensCountOrCumsumOut.
    4. Is compatible with the original V2 output modes and adds support for the key_value output format: the original attributes expertTokensBeforeCapacityFlag(bool) and expertTokensCountOrCumsumFlag(int) are redefined as expertsTokensNumFlag(bool) and expertTokensNumType(int), respectively. For details about the output format mapping, see the following table:
    5. DropPadMode expertsTokensNumFlag expertTokensNumType Output Format Description
      0 true 0 cumsum mode: expertTokensCountOrCumsumOut indicates the prefix sum histogram of token counts processed by each expert after sorting.
      0 true 1 count mode. expertTokensCountOrCumsumOut indicates a separate count histogram of tokens processed by each expert after sorting.
      0 true 2 key_value mode. The output shape is [expert_num, 2], indicating each expert and the cumulative count of non-zero tokens processed by that expert.
      1 true 1 The output mode is count mode.
      Not enabled false Not enabled expertTokensCountOrCumsumOut is not output.
  • Formula:

    1.Sort the input expertIdx to obtain the sorted result sortedExpertIdx and the corresponding index sortedRowIdx:

    $$ sortedExpertIdx, sortedRowIdx=keyValueSort(expertIdx,rowIdx) $$

    2.Perform position mapping based on sortedRowIdx to obtain expandedRowIdxOut:

    • When rowIdxType equals 1, output the scatter index

      $$ expandedRowIdxOut[i]=sortedRowIdx[i] $$
    • When rowIdxType equals 0, the gather index is output

      $$ expandedRowIdxOut[sortedRowIdx[i]]=i $$

    3.Compute the histogram result for each expert in sortedExpertIdx to obtain expertTokensCountOrCumsumOutOptional:

    $$ expertTokensCountOrCumsumOutOptional[i]=Histogram(sortedExpertIdx) $$

    4.If quantMode does not equal -1, calculate the quantization result:

    • Static quantization
    $$ quantResult=round((x∗scaleOptional)+offsetOptional) $$
    • Dynamic quant:
      • If scale is not passed in:

        $$ dynamicQuantScaleOutOptional = row\_max(abs(x)) / 127 $$
        $$ quantResult = round(x / dynamicQuantScaleOutOptional) $$
      • If scale is passed in:

        $$ dynamicQuantScaleOutOptional = row\_max(abs(x * scaleOptional)) / 127 $$
        $$ quantResult = round(x / dynamicQuantScaleOutOptional) $$
      • When quantMode is 13, dynamic quantization uses a symmetric quantization range of [-8, 7]. The denominator in the scale calculation is 7. Every two INT4 values in the quantization result are packed into 1 byte along the H dimension.

    5.If the active expert range is the full expert range, token index movement follows the Scatter index; otherwise, token index movement follows the Gather index. When dropPadMode is 1, the number of tokens to be processed by each expert is aligned to expertCapacity. Tokens exceeding expertCapacity are dropped, and the insufficient ones are padded with 0. expandedXOut is obtained:

    • Non-quantized scenario

      • Index movement by Scatter index
      $$ expandedXOut[i]=x[scatterRowIdx[i] // K] $$
      • Index movement by Gather index
      $$ expandedXOut[gatherRowIdx[i]]=x[i // K] $$
    • Quantization scenario

      • Index movement by Scatter index
      $$ expandedXOut[i]=quantResult[scatterRowIdx[i] // K] $$
      • Index movement by Gather index
      $$ expandedXOut[gatherRowIdx[i]]=quantResult[i // K] $$

    6.The number of valid elements in expandedRowIdxOut is availableIdxNum. It is calculated as the number of elements in expertIdx that are within the range specified by activeExpertRangeOptional. -1 is not within the range either, indicating an invalid expert that does not participate in routing calculation:

    $$ availableIdxNum = |\{x\in expertIdx| expert\_start \le x<expert\_end \ \}| $$

Function Prototype

Each operator uses a two-phase API. Call "aclnnMoeInitRoutingV3GetWorkspaceSize" first to obtain the input parameters, calculate the required workspace size, and obtain the executor that contains the operator computation process. Then call "aclnnMoeInitRoutingV3" to perform the computation.

aclnnStatus aclnnMoeInitRoutingV3GetWorkspaceSize(
  const aclTensor   *x,
  const aclTensor   *expertIdx,
  const aclTensor   *scaleOptional,
  const aclTensor   *offsetOptional,
  int64_t            activeNum,
  int64_t            expertCapacity,
  int64_t            expertNum,
  int64_t            dropPadMode,
  int64_t            expertTokensNumType,
  bool               expertTokensNumFlag,
  int64_t            quantMode,
  const aclIntArray *activeExpertRangeOptional,
  int64_t            rowIdxType,
  const aclTensor   *expandedXOut,
  const aclTensor   *expandedRowIdxOut,
  const aclTensor   *expertTokensCountOrCumsumOut,
  const aclTensor   *expandedScaleOut,
  uint64_t          *workspaceSize,
  aclOpExecutor    **executor)
aclnnStatus aclnnMoeInitRoutingV3(
  void          *workspace,
  uint64_t       workspaceSize,
  aclOpExecutor *executor,
  aclrtStream    stream)

aclnnMoeInitRoutingV3GetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    x (aclTensor) Input Input of MoE, that is, the token feature input.
    • shape is (NUM_ROWS, H);
    • For the MXFP4/INT4 dynamic quantization scenario where quantMode is 9 or 13, and the non-quantized pass-through scenario where quantMode is -1 and the data type of x is FLOAT4_E2M1, H must be an even number.
    • quantMode=-1: supports FLOAT16, BFLOAT16, FLOAT32, INT8, HIFLOAT8, FLOAT4_E2M1, FLOAT8_E4M3FN, and FLOAT8_E5M2;
    • quantMode=0, 1: supports FLOAT16, BFLOAT16, and FLOAT32;
    • quantMode=2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 14, 15, 16, and 17: supports FLOAT16 and BFLOAT16;
    • quantMode=13: supports FLOAT32 and BFLOAT16;
    ND 2 -
    expertIdx (aclTensor) Input K experts for processing each row of features. The expert ID of each element cannot exceed the number of experts. -1 indicates an invalid expert (this position does not participate in routing and is filtered out). The shape is (NUM_ROWS, K). INT32 ND 2 -
    scaleOptional (aclTensor) Input Represents the parameter used to compute the quantization result.
    • If not input, scale is not used in the computation;
    • Optional in the non-quantized field. If input, it must be a 1D tensor with shape (NUM_ROWS,) and data type FLOAT32. When the data type of input x is FLOAT4_E2M1, FLOAT8_E4M3FN, or FLOAT8_E5M2, it must be a 3D tensor with shape (NUM_ROWS, CeilDiv(H, 64), 2) and data type FLOAT8_E8M0;
    • Mandatory in the static quantization scenario. The input requirements are a 1D tensor with shape [1, ];
    • Optional in the INT8 dynamic quantization scenario (quantMode is 1). If input, it must be a 2D tensor with shape (expertEnd-expertStart, H). Optional in the INT4 dynamic quantization scenario (quantMode is 13). If input, it must have shape (1, H), representing the smooth scale broadcast along the H dimension.
    • Not input in the MXFP8 quantization scenario (quantMode is 2 or 3).
    • Not input in the HIF8 direct conversion and HIF8 PERTOKEN quantization scenarios (quantMode is 6 or 8).
    • Mandatory in the HIF8 PERTENSOR quantization scenario (quantMode is 7). The input requirements are a 1D tensor with shape [1, ].
    • Not input in the MXFP4 quantization scenario (quantMode is 9).
    • Not input in the FP8 PerGroup quantization scenarios (quantMode is 4, 5, 14, or 15).
    • Not input in the FP8 PerBlock quantization scenarios (quantMode is 11 or 12).
    • Not input in the MXFP8 RoundScale+Amax quantization scenarios (quantMode is 16 or 17).
    FLOAT32, FLOAT8_E8M0 ND 1-3 -
    offsetOptional (aclTensor) Input Offset value used for computing the quant result.
    • Not required in non-quantized scenarios;
    • Required in static quantization scenarios; input requirements: a 1D Tensor with shape [1, ];
    • Not required in dynamic quantization (quantMode is 1), MXFP8 quantization (quantMode is 2 or 3), HIF8 quantization (quantMode is 6, 7, or 8), MXFP4 quantization (quantMode is 9), FP8 PerGroup quantization (quantMode is 4, 5, 14, or 15), FP8 PerBlock quantization (quantMode is 11 or 12), INT4 dynamic quantization (quantMode is 13), or MXFP8 RoundScale+Amax quantization scenarios (quantMode is 16 or 17).
    FLOAT32 ND - -
    activeNum (int64_t) Input Indicates the maximum total number of rows to process. The specific behavior depends on the product. Atlas A2 products and Atlas A3 products: when dropPadMode=0, activeNum supports values greater than or equal to -1. -1 and 0 indicate no limit on the number of rows to process; if the value is greater than 0, at most min(activeNum, NUM_ROWS*K) rows are processed. Ascend 950PR&950DT products: this attribute is not used to limit the number of rows to process and accepts only -1, 0, or NUM_ROWS*K. INT64 - - -
    expertCapacity (int64_t) Input Indicates the number of tokens that each expert can process. In Dropless scenarios, this parameter is not used. In DropPad scenarios, the input must be validated and the value range is (0, NUM_ROWS]. INT64 - - -
    expertNum (int64_t) Input Indicates the number of experts. When expertTokensNumType is key_value mode, the value range is [1, 5120]; for other modes, the value range is [1, 10240]. INT64 - - -
    dropPadMode (int64_t) Input Indicates whether it is a DropPad scenario. The value is 0 or 1
    0: Dropless scenario;
    1: DropPad scenario;
    INT64 - - -
    expertTokensNumType (int64_t) Input Indicates different histogram modes. Value options are 0, 1, and 2
    0: cumsum mode;
    1: count mode;
    2: key_value mode;
    INT64 - - -
    expertTokensNumFlag (bool) Input Indicates whether to output expertTokensCountOrCumsumOut. Value: false or true BOOL - - -
    quantMode (int64_t) Input Indicates different quantization scenarios. Values are 0, 1, -1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17 (support status varies by product, see the description after the table)
    0: static quantization scenario;
    1: dynamic quantization scenario, expandedXOut is quantized to INT8;
    -1: non-quantization scenario;
    2: MXFP8 quantization scenario, expandedXOut is quantized to FLOAT8_E5M2;
    3: MXFP8 quantization scenario, expandedXOut is quantized to FLOAT8_E4M3FN;
    4: FP8 PerGroup quantization scenario (GroupSize=128, RoundScale), expandedXOut is quantized to FLOAT8_E5M2;
    5: FP8 PerGroup quantization scenario (GroupSize=128, RoundScale), expandedXOut is quantized to FLOAT8_E4M3FN;
    6: HIF8 direct conversion quantization scenario, expandedXOut is quantized to HIFLOAT8;
    7: HIF8 PERTENSOR quantization scenario, expandedXOut is quantized to HIFLOAT8 in pertensor mode;
    8: HIF8 PERTOKEN quantization scenario, expandedXOut is quantized to HIFLOAT8 in pertoken mode;
    9: MXFP4 quantization scenario, expandedXOut is quantized to FLOAT4_E2M1;
    11: FP8 PerBlock quantization scenario (BlockSize=128), expandedXOut is quantized to FLOAT8_E5M2, and expandedScaleOut is a FLOAT32 3D layout;
    12: FP8 PerBlock quantization scenario (BlockSize=128), expandedXOut is quantized to FLOAT8_E4M3FN, and expandedScaleOut is a FLOAT32 3D layout;
    13: INT4 dynamic quantization scenario, expandedXOut is quantized to INT4;
    14: FP8 PerGroup quantization scenario (GroupSize=128, RoundScale+Amax), expandedXOut is quantized to FLOAT8_E5M2;
    15: FP8 PerGroup quantization scenario (GroupSize=128, RoundScale+Amax), expandedXOut is quantized to FLOAT8_E4M3FN;
    16: MXFP8 RoundScale+Amax quantization scenario, expandedXOut is quantized to FLOAT8_E5M2;
    17: MXFP8 RoundScale+Amax quantization scenario, expandedXOut is quantized to FLOAT8_E4M3FN;
    INT64 - - -
    activeExpertRangeOptional(aclIntArray) Input Indicates the range of active experts. The length is 2, and the array values are [expertStart, expertEnd] in a left-closed, right-open interval. Values must be greater than or equal to 0, and expertEnd must not be greater than expertNum; in Drop/Pad scenarios, expertStart is 0 and expertEnd is expertNum. INT64 - - -
    rowIdxType (int64_t) Input Indicates the index type used by expandedRowIdxOut. Value: 0 or 1.
    0: gather-type index.
    1: scatter-type index.
    INT64 - - -
    expandedXOut (aclTensor) Output Features expanded based on expertIdx.
    • In the Dropless scenario, the shape is [NUM_ROWS * K, H].
    • In the Active scenario, the shape is [min(activeNum, NUM_ROWS * K), H].
    • In the Drop/Pad scenario, a 3D tensor is required, with the shape [expertNum, expertCapacity, H].
    • In the non-quantized scenario, the data type is the same as x. In the quantization scenario, when quantMode is 0 or 1, the data type is INT8; when quantMode is 2, 4, 14, or 16, the data type is FLOAT8_E5M2; when quantMode is 3, 5, 15, or 17, the data type is FLOAT8_E4M3FN; when quantMode is 6, 7, or 8, the data type is HIFLOAT8; when quantMode is 9, the data type is FLOAT4_E2M1; when quantMode is 11 or 12, the data types are FLOAT8_E5M2 and FLOAT8_E4M3FN respectively; when quantMode is 13 and the data type of x is FLOAT32 or BFLOAT16, the data type is INT4.
    FLOAT16, BFLOAT16, FLOAT32, INT8, INT4, FLOAT8_E5M2, FLOAT8_E4M3FN, HIFLOAT8, FLOAT4_E2M1 ND 2 -
    expandedRowIdxOut (aclTensor) Output Index mapping between expandedXOut and x. The output shape is (NUM_ROWS*K, ). The first availableIdxNum elements are valid data, and the invalid data for the remaining elements is determined by rowIdxType:
    • When rowIdxType is 0, invalid data is filled with -1.
    • When rowIdxType is 1, invalid data is not initialized.
    INT32 ND 1 -
    expertTokensCountOrCumsumOut (aclTensor) Output Outputs statistics or cumulative values of the number of tokens processed by each expert.
    • When expertTokensNumType is 0, indicates the prefix sum of the total number of tokens processed by each expert within activeExpertRangeOptional after sorting.
    • When expertTokensNumType is 1, indicates the total number of tokens processed by each expert within activeExpertRangeOptional.
    • When expertTokensNumType is 2, indicates experts whose total number of tokens is non-zero within activeExpertRangeOptional, as well as the total number of tokens processed by each of these experts.
    • When expertTokensNumType is 0 or 1, the output shape is [expertEnd-expertStart]; when expertTokensNumType is 2, the output shape is [expertNum, 2].
    INT64 ND 1-2 -
    expandedScaleOut (aclTensor) Output Outputs intermediate values of scaleOptional in different quantization processes. The output shape is the product of all dimensions of the shape of expandedXOut except the last dimension.
    • In the non-quantization scenario, if scaleOptional is input, the shape is [NUM_ROWS*K], the first availableIdxNum elements are valid data, and the output data type is FLOAT32. If the data type of input x is FLOAT4_E2M1, FLOAT8_E4M3FN, or FLOAT8_E5M2 and scaleOptional is input, the shape of expandedScaleOut is [NUM_ROWS*K, CeilDiv(H, 64), 2] and the output data type is FLOAT8_E8M0. In the Drop/Pad scenario, the output is a 1D Tensor with shape [expertNum * expertCapacity] and the output data type is FLOAT32.
    • In the dynamic quantization scenario, if scaleOptional is input, the first availableIdxNum elements are valid data.
    • Not output in the static quantization scenario.
    • In the MXFP8 quantization scenario (quantMode is 2 or 3), the output data type is FLOAT8_E8M0 and the shape is [NUM_ROWS*K, M], where M=CeilAlign(CeilDiv(H,32),2), and the first availableIdxNum rows of NUM_ROWS*K are valid data.
    • In the MXFP8 RoundScale+Amax quantization scenario (quantMode is 16 or 17), the output data type is FLOAT8_E8M0 and the shape is [NUM_ROWS*K, M], where M=CeilAlign(CeilDiv(H,32),2), and the first availableIdxNum rows of NUM_ROWS*K are valid data.
    • In the scenario of quantizing to HIFLOAT8 by direct conversion, expandedScaleOut is not output.
    • In the scenario of quantizing to HIFLOAT8 in PERTENSOR mode, expandedScaleOut is not output.
    • In the scenario of quantizing to HIFLOAT8 in PERTOKEN mode, the output data type is FLOAT32 and the shape is [NUM_ROWS*K].
    • In the MXFP4 quantization scenario, the output data type is FLOAT8_E8M0 and the shape is [NUM_ROWS*K, M, 2], where M=CeilDiv(H, 64), and the first availableIdxNum rows of NUM_ROWS*K are valid data.
    • In the FP8 PerGroup quantization scenario (quantMode is 4, 5, 14, or 15), the output data type is FLOAT32 and the shape is [NUM_ROWS*K, CeilDiv(H,128)], and the first availableIdxNum rows of NUM_ROWS*K are valid data.
    • In the FP8 PerBlock quantization scenario (quantMode is 11 or 12), the output data type is FLOAT32 and the shape is [NUM_ROWS*K, CeilDiv(H,256), 2], and the first availableIdxNum rows of NUM_ROWS*K are valid data.
    FLOAT32, FLOAT8_E8M0 ND 1-3 -
    workspaceSize (uint64_t) Output Returns the size of the workspace to be requested by the user on the Device. - - - - -
    executor (aclOpExecutor) Output Returns the op executor containing 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 calculation input and calculation output are null pointers.
    ACLNN_ERR_PARAM_NULLPTR 161002 The data types of the input and output are not within the supported range.
    ACLNN_ERR_INNER_TILING_ERROR 561002 The shape of the input or output Tensor is not within the supported range.
    The attributes of the input are not within the supported range.
  • Differences in product support status

    • Differences in quantMode support status:

      • Atlas A2 products and Atlas A3 products: Supported values are -1, 0, and 1. When quantMode=-1, x supports only FLOAT16, BFLOAT16, FLOAT32, and INT8.
      • Ascend 950PR&950DT products: Supported values are -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, and 17.
    • Ascend 950PR&950DT products support only the following parameter values:
      • The activeNum parameter is not used. The supported values are -1, 0, or NUM_ROWS*K.
      • In the Dropless scenario, expertCapacity is not used; in the DropPad scenario, it must be validated, and the value range is (0, NUM_ROWS].
      • dropPadMode supports the values 0 and 1. The DropPad mode (dropPadMode=1) has the following additional constraints:
        • rowIdxType supports only the value 0 (gather index).
        • activeExpertRangeOptional must be [0, expertNum].
        • expertTokensNumType supports only the value 1 (count mode).
        • In DropPad mode, quantMode supports only -1 (non-quantization), and the data type supports only FLOAT16, BFLOAT16, FLOAT32, INT8, and HIFLOAT8.
        • expandedXOut must be a 3D Tensor with the shape [expertNum, expertCapacity, H].
      • expertTokensNumType only supports taking the values 0, 1, and 2.
      • expertTokensNumFlag only supports taking the value true.
    • Ascend 950PR&950DT products support the INT4 dynamic quantization scenario where quantMode is 13. All of the following conditions must be met:
      • The data type of x is FLOAT32 or BFLOAT16, and the data type of expandedXOut is INT4.
      • H must be even, so that every two INT4 values along the H dimension are packed into 1 byte; NUM_ROWS is not required to be even.
      • activeNum equals NUM_ROWS*K.
      • scaleOptional is not input, or its shape is (1, H) and its data type is FLOAT32, indicating that the smooth scale is broadcast along the H dimension to the experts within the range of activeExpertRangeOptional; offsetOptional is not input.
      • When the value of expertTokensNumType is 0 or 1, the shape of expertTokensCountOrCumsumOut is [expertEnd-expertStart]; when the value of expertTokensNumType is 2, the shape of expertTokensCountOrCumsumOut is [expertNum, 2].

aclnnMoeInitRoutingV3

  • Parameters:

    Parameter Input/Output Description
    workspace Input Memory address of the workspace allocated on the Device.
    workspaceSize Input Workspace size allocated on the Device, obtained by the first-phase API aclnnMoeInitRoutingV3GetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream that executes tasks.
  • Return value

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

Constraints

  • Deterministic computation:

    • aclnnMoeInitRoutingV3 defaults to a deterministic implementation.
  • The operator supports multiple performance templates on the following products. Each template requires meeting additional admission conditions; otherwise, the generic template is used:

    • Products that support the performance template:

      • Atlas A2 products
      • Atlas A3 products
    • Admission conditions of the performance template:

      Performance Template Type Admission Conditions
      Low-Latency Performance Template All the following conditions must be met:
      • The input shapes of x, expertIdx, and scaleOptional must be (1, 7168), (1, 8), and (256, 7168) respectively.
      • x data type requirement: BFLOAT16.
      • Attribute requirements: activeExpertRangeOptional=[0, 256], quantMode=1, expertTokensNumType=2, expertNum=256
      Large-Batch Performance Template All the following conditions must be met:
      • The value range of NUM_ROWS is [384, 8192], and K=8.
      • Attribute requirements: expertNum=256, expertEnd-expertStart<=32, quantMode=-1, rowIdxType=1, expertTokensNumType=1

      Full-Load Performance Template
      In scenarios where the operator input shapes are small, multi-core synchronization between operations takes a high proportion of time and becomes the performance bottleneck. Therefore, a performance template is added for this specific scenario. In this template, copy-in, sorting, and computation are all completed within the same kernel. The following conditions must be met:
      • Attribute requirements: dropPadMode=0. Ascend 950PR&950DT products also support dropPadMode=1 in non-quantized scenarios, where quantMode=-1, rowIdxType=0, activeExpertRange=[0, expertNum]
  • Empty tensor processing:

    • Atlas A2 products, Atlas A3 products: When NUM_ROWS=0, the empty tensor processing path is used.
    • Ascend 950PR&950DT products: When NUM_ROWS=0 or K=0, there are no routing elements, the empty tensor processing path is used, and the expert count is 0. The output shapes must still meet the constraints of the corresponding mode.
    • Ascend 950PR&950DT products: When NUM_ROWS*K>0 and H=0, the normal routing process is still used to generate expandedRowIdxOut and expertTokensCountOrCumsumOut.
  • Input values of inf/-inf/nan are not supported.

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_init_routing_v3.h"

#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 code. 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 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 code. Device/stream initialization. For details, see the acl external API list.
    // Set deviceId based on the actual device.
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    // Handle 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 based on the API definition.
    std::vector<int64_t> xShape = {3, 2};
    std::vector<int64_t> expertIdxShape = {3, 4};
    std::vector<int64_t> scaleShape = {3};
    std::vector<int64_t> offsetShape = {1};

    std::vector<int64_t> expandedXOutShape = {12, 2};
    std::vector<int64_t> expandedRowIdxOutShape = {12};
    std::vector<int64_t> expertTokensCountOrCumsumOutOptionalShape = {4};
    std::vector<int64_t> expandedScaleOutOptionalShape = {12};

    std::vector<int64_t> activeExpertRangeArray = {0, 4};

    void *xDeviceAddr = nullptr;
    void *expertIdxDeviceAddr = nullptr;
    void *scaleDeviceAddr = nullptr;
    void *offsetDeviceAddr = nullptr;

    void *expandedXOutDeviceAddr = nullptr;
    void *expandedRowIdxOutDeviceAddr = nullptr;
    void *expertTokensCountOrCumsumOutOptionalDeviceAddr = nullptr;
    void *expandedScaleOutOptionalDeviceAddr = nullptr;

    aclTensor *x = nullptr;
    aclTensor *expertIdx = nullptr;
    aclTensor *scale = nullptr;
    aclTensor *offset = nullptr;

    int64_t activeNum = 12;
    int64_t expertCapacity = 0;
    int64_t expertNum = 256;
    int64_t dropPadMode = 0;
    int64_t expertTokensNumType = 1;
    bool expertTokensNumFlag = true;
    int64_t quantMode = -1;
    aclIntArray *activeExpertRange = aclCreateIntArray(activeExpertRangeArray.data(), activeExpertRangeArray.size());
    int64_t rowIdxType = 1;

    aclTensor *expandedXOut = nullptr;
    aclTensor *expandedRowIdxOut = nullptr;
    aclTensor *expertTokensCountOrCumsumOutOptional = nullptr;
    aclTensor *expandedScaleOutOptional = nullptr;

    std::vector<float> xHostData = {0.1, 0.1, 0.2, 0.2, 0.3, 0.3};
    std::vector<int> expertIdxHostData = {1, 2, 0, 3, 0, 2, 1, 3, 0, 1, 3, 2};
    std::vector<float> scaleHostData = {0.3423, 0.1652, 0.2652};
    std::vector<float> offsetHostData = {1.8369};

    std::vector<float> expandedXOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    std::vector<int> expandedRowIdxOutHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    std::vector<int64_t> expertTokensCountOrCumsumOutOptionalHostData = {0, 0, 0, 0};
    std::vector<float> expandedScaleOutOptionalHostData = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    // Create the self aclTensor.
    ret = CreateAclTensor(xHostData, xShape, &xDeviceAddr, aclDataType::ACL_FLOAT, &x);
    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(scaleHostData, scaleShape, &scaleDeviceAddr, aclDataType::ACL_FLOAT, &scale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(offsetHostData, offsetShape, &offsetDeviceAddr, aclDataType::ACL_FLOAT, &offset);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // Create the out aclTensor.
    ret = CreateAclTensor(expandedXOutHostData, expandedXOutShape, &expandedXOutDeviceAddr, aclDataType::ACL_FLOAT,
                          &expandedXOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(expandedRowIdxOutHostData, expandedRowIdxOutShape, &expandedRowIdxOutDeviceAddr,
                          aclDataType::ACL_INT32, &expandedRowIdxOut);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(expertTokensCountOrCumsumOutOptionalHostData, expertTokensCountOrCumsumOutOptionalShape,
                          &expertTokensCountOrCumsumOutOptionalDeviceAddr, aclDataType::ACL_INT64,
                          &expertTokensCountOrCumsumOutOptional);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(expandedScaleOutOptionalHostData, expandedScaleOutOptionalShape,
                          &expandedScaleOutOptionalDeviceAddr, aclDataType::ACL_FLOAT, &expandedScaleOutOptional);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    // 3. Call the CANN operator library API and replace it with the actual API.
    uint64_t workspaceSize = 0;
    aclOpExecutor *executor;
    // Call the first-phase API of aclnnMoeInitRoutingV3.
    ret = aclnnMoeInitRoutingV3GetWorkspaceSize(
        x, expertIdx, scale, offset, activeNum, expertCapacity, expertNum, dropPadMode, expertTokensNumType,
        expertTokensNumFlag, quantMode, activeExpertRange, rowIdxType, expandedXOut, expandedRowIdxOut,
        expertTokensCountOrCumsumOutOptional, expandedScaleOutOptional, &workspaceSize, &executor);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeInitRoutingV3GetWorkspaceSize 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 aclnnMoeInitRoutingV3.
    ret = aclnnMoeInitRoutingV3(workspaceAddr, workspaceSize, executor, stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnMoeInitRoutingV3 failed. ERROR: %d\n", ret); return ret);
    // 4. Boilerplate: synchronize and wait for the task 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 as defined in the API.
    auto expandedXSize = GetShapeSize(expandedXOutShape);
    std::vector<float> expandedXData(expandedXSize, 0);
    ret = aclrtMemcpy(expandedXData.data(), expandedXData.size() * sizeof(expandedXData[0]), expandedXOutDeviceAddr,
                      expandedXSize * 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 < expandedXSize; i++) {
        LOG_PRINT("expandedXData[%ld] is: %f\n", i, expandedXData[i]);
    }
    auto expandedRowIdxSize = GetShapeSize(expandedRowIdxOutShape);
    std::vector<int> expandedRowIdxData(expandedRowIdxSize, 0);
    ret = aclrtMemcpy(expandedRowIdxData.data(), expandedRowIdxData.size() * sizeof(expandedRowIdxData[0]),
                      expandedRowIdxOutDeviceAddr, expandedRowIdxSize * sizeof(int32_t), 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 < expandedRowIdxSize; i++) {
        LOG_PRINT("expandedRowIdxData[%ld] is: %d\n", i, expandedRowIdxData[i]);
    }
    auto expertTokensBeforeCapacitySize = GetShapeSize(expertTokensCountOrCumsumOutOptionalShape);
    std::vector<int64_t> expertTokenIdxData(expertTokensBeforeCapacitySize, 0);
    ret = aclrtMemcpy(expertTokenIdxData.data(), expertTokenIdxData.size() * sizeof(expertTokenIdxData[0]),
                      expertTokensCountOrCumsumOutOptionalDeviceAddr, expertTokensBeforeCapacitySize * sizeof(int64_t),
                      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 < expertTokensBeforeCapacitySize; i++) {
        LOG_PRINT("expertTokenIdxData[%ld] is: %ld\n", i, expertTokenIdxData[i]);
    }

    auto dynamicQuantScaleSize = GetShapeSize(expandedScaleOutOptionalShape);
    std::vector<float> dynamicQuantScaleData(dynamicQuantScaleSize, 0);
    ret = aclrtMemcpy(dynamicQuantScaleData.data(), dynamicQuantScaleData.size() * sizeof(dynamicQuantScaleData[0]),
                      expandedScaleOutOptionalDeviceAddr, dynamicQuantScaleSize * 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 < dynamicQuantScaleSize; i++) {
        LOG_PRINT("dynamicQuantScaleData[%ld] is: %f\n", i, dynamicQuantScaleData[i]);
    }
    // 6. Release aclTensor and aclScalar as defined in the API.
    aclDestroyTensor(x);
    aclDestroyTensor(expertIdx);
    aclDestroyTensor(scale);
    aclDestroyTensor(offset);
    aclDestroyTensor(expandedXOut);
    aclDestroyTensor(expandedRowIdxOut);
    aclDestroyTensor(expertTokensCountOrCumsumOutOptional);
    aclDestroyTensor(expandedScaleOutOptional);

    // 7. Release device resources. Modify it based on the definition of the specific API.
    aclrtFree(xDeviceAddr);
    aclrtFree(expertIdxDeviceAddr);
    aclrtFree(scaleDeviceAddr);
    aclrtFree(offsetDeviceAddr);
    aclrtFree(expandedXOutDeviceAddr);
    aclrtFree(expandedRowIdxOutDeviceAddr);
    aclrtFree(expertTokensCountOrCumsumOutOptionalDeviceAddr);
    aclrtFree(expandedScaleOutOptionalDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}