aclnnAlltoAllvQuantGroupedMatMul

Applicable Products

  • Ascend 950DT products: Supported
  • Atlas A3 products: Not supported
  • Atlas A2 products: Not supported
  • Atlas 200I/500 A2 inference products: Not supported
  • Atlas inference products: Not supported
  • Atlas training products: Not supported

Function

  • Description: Completes routed-expert AlltoAllv and quantized GroupedMatMul fusion, and implements parallel fusion with quantized MatMul of the shared expert, communication before computation.

  • Formula: Assume that the total number of devices in the communicator is epWorldSize and the number of routed experts on each device after communication is e. The grouped matrix multiplication on each device computes only the experts on that device. The formula for each device is as follows:

    • Grouped matrix multiplication computation for the shared expert on the local device

      $$ mm\_y=(mm\_x × mm\_x\_scale) @ (mm\_weight × mm\_weight\_scale) $$
    • Alltoallv communication and permute

      $$ permute\_out=Alltoallv(gmm\_x) $$
    • Grouped matrix multiplication computation for local routed experts by expert dimension

      $$ gmm\_y=(permute\_out × gmm\_x\_scale) @ (gmm\_weight × gmm\_weight\_scale) $$

Function Prototype

Each operator uses a two-phase API. First call aclnnAlltoAllvQuantGroupedMatMulGetWorkspaceSize to obtain the input parameters and calculate the workspace size required for the computation flow. Then call aclnnAlltoAllvQuantGroupedMatMul to perform the computation.

aclnnStatus aclnnAlltoAllvQuantGroupedMatMulGetWorkspaceSize(
    const aclTensor*   gmmX,
    const aclTensor*   gmmWeight,
    const aclTensor*   gmmXScale,
    const aclTensor*   gmmWeightScale,
    const aclTensor*   sendCountsTensorOptional,
    const aclTensor*   recvCountsTensorOptional,
    const aclTensor*   mmXOptional,
    const aclTensor*   mmWeightOptional,
    const aclTensor*   mmXScaleOptional,
    const aclTensor*   mmWeightScaleOptional,
    int64_t            gmmXQuantMode,
    int64_t            gmmWeightQuantMode,
    int64_t            mmXQuantMode,
    int64_t            mmWeightQuantMode,
    const char*        group,
    int64_t            epWorldSize,
    const aclIntArray* sendCounts,
    const aclIntArray* recvCounts,
    bool               transGmmWeight,
    bool               transMmWeight,
    int64_t            groupSize,
    bool               permuteOutFlag,
    aclTensor*         gmmY,
    aclTensor*         mmYOptional,
    aclTensor*         permuteOutOptional,
    uint64_t*          workspaceSize,
    aclOpExecutor**    executor)
aclnnStatus aclnnAlltoAllvQuantGroupedMatMul(
    void*          workspace,
    uint64_t       workspaceSize,
    aclOpExecutor* executor,
    aclrtStream    stream)

aclnnAlltoAllvQuantGroupedMatMulGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    gmmX Input After AlltoAllv communication and Permute operations, this input serves as the left matrix for the GroupedMatMul computation. Only 2D inputs with shape (BSK, H1) are supported in the Current Version, and only the Non-transpose use case is supported. HIFLOAT8, FLOAT8_E4M3FN, FLOAT8_E5M2, FLOAT4_E2M1 ND 2 x
    gmmWeight Input Right matrix for the GroupedMatMul computation. The current version supports only 3-dimensional input. The non-transpose shape is (e, H1, N1), and the transpose shape is (e, N1, H1). HIFLOAT8, FLOAT8_E4M3FN, FLOAT8_E5M2, FLOAT4_E2M1 ND 3 √ (applicable to the transpose use case only)
    gmmXScale Input Quantization coefficient of gmmX.
    • Supports 1 dimension in the pertensor quantization scenario, with shape (1).
    • Supports 3 dimensions in the mx quantization scenario, with shape (BSK, ceildiv(H1, 64), 2).
    FLOAT32, FLOAT8_E8M0 ND 1, 3 x
    gmmWeightScale Input Quantization coefficient of gmmWeight.
    • The pertensor quantization scenario supports 1 dimension, with shape (1).
    • The mx quantization scenario supports 4 dimensions. The non-transpose shape is (e, ceildiv(H1, 64), N1, 2), and the transpose shape is (e, N1, ceildiv(H1, 64), 2).
    FLOAT32, FLOAT8_E8M0 ND 1, 4 √ (Transpose use case only)
    sendCountsTensorOptional Input Reserved parameter. Only nullptr is supported in the Current Version. - - - - -
    recvCountsTensorOptional Input Reserved parameter. Only nullptr can be passed in the current version. - - - - -
    mmXOptional Input Optional Input. Left matrix in the Shared Expert MatMul computation.
    • Supports 2 dimensions with shape (BS, H2).
    • Must be passed in together with mmWeightOptional, or both must be nullptr.
    Consistent with gmmX ND 2 x
    mmWeightOptional Input Optional Input, the right matrix in the MatMul computation of the Shared Expert.
    • Supports 2 dimensions with shape (H2, N2) for Non-transpose and (N2, H2) for Transpose.
    • Must be passed in together with mmXOptional, or both must be nullptr.
    Consistent with gmmWeight ND 2 √ (applicable to the transpose use case only)
    mmXScaleOptional Input Optional input, the quantization coefficient of mmX.
    • The pertensor quantization scenario supports 1 dimension, with shape (1).
    • The mx quantization scenario supports 3 dimensions, with shape (BS, ceildiv(H2, 64), 2).
    • Must be passed together with mmXOptional, or both must be nullptr.
    FLOAT32, FLOAT8_E8M0 ND 1, 3 x
    mmWeightScaleOptional Input Optional input, quantization coefficient of mmWeight.
    • In the pertensor quantization scenario, 1 dimension is supported with the shape (1).
    • In the mx quantization scenario, 3 dimensions are supported. The non-transpose shape is (ceildiv(H2, 64), N2, 2), and the transpose shape is (N2, ceildiv(H2, 64), 2).
    • Must be passed together with mmXOptional or both set to nullptr.
    FLOAT32, FLOAT8_E8M0 ND 1, 3 √ (applicable only to the transpose use case)
    gmmXQuantMode Input Quantization mode of gmmX. Current Version supports 1 (pertensor Quantization Scenario) and 6 (mx Quantization Scenario). INT64 - - -
    gmmWeightQuantMode Input Quantization mode of gmmWeight. Current Version supports 1 (pertensor quantization scenario) and 6 (MX quantization scenario). INT64 - - -
    mmXQuantMode Input The quantization mode of mmX. Current Version supports 1 (pertensor quantization scenario) and 6 (MX quantization scenario). INT64 - - -
    mmWeightQuantMode Input Quantization mode of mmWeight. The Current Version supports 1 (pertensor quantization scenario) and 6 (mx quantization scenario). INT64 - - -
    group Input Communicator for expert parallelism. The string length must be within the range of (0, 128). Obtain the value through the Hccl API "extern HcclResult HcclGetCommName(HcclComm comm, char* commName);", where commName is group. STRING - - -
    epWorldSize Input Size of the ep communicator. Ascend 950DT products support 2, 4, 8, 16, 32, 64, 128, 256. INT64 - - -
    sendCounts Input Indicates the number of tokens sent to other devices. The data type is INT64, with a length of e * epWorldSize and a maximum of 256. The input must be a list. aclIntArray* (element type INT64) - - -
    recvCounts Input Indicates the number of tokens received from other devices. The data type is INT64, with a length of e * epWorldSize and a maximum of 256. The input must be a list. aclIntArray* (element type INT64) - - -
    transGmmWeight Input Whether the right matrix of GroupedMatMul requires transpose. true indicates transpose is required, false indicates non-transpose. BOOL - - -
    transMmWeight Input Whether the right matrix of the Shared Expert MatMul needs to be transposed. true indicates that transpose is required, and false indicates non-transpose. BOOL - - -
    groupSize Input Indicates how many elements of the gmmX/gmmWeight/mmX/mmWeight input along the corresponding dimension can be quantized by one element of the gmmXScale/gmmWeightScale/mmXScale/mmWeightScale input. The groupSize input is concatenated from three values: groupSizeM, groupSizeN, and groupSizeK, each occupying 16 bits. The formula is groupSize = groupSizeK | groupSizeN << 16 | groupSizeM << 32. INT64 - - -
    permuteOutFlag Input Whether permuteOutOptional needs to be output. true indicates that the output is required; false indicates that the output is not required. BOOL - - -
    gmmY Output Output computed by the routing Expert. Supports two dimensions, with shape (A, N1). FLOAT16, BFLOAT16 ND 2 x
    mmYOptional Output Output of the Shared Expert computation. Supports 2 dimensions with shape (BS, N2). Output only when mmXOptional and mmWeightOptional are passed in. Consistent with gmmY ND 2 x
    permuteOutOptional Output Output after permute. Supports two dimensions, with shape (A, H1). Output only when permuteOutFlag is true. Consistent with gmmX ND 2 x
    workspaceSize Output Returns the size of the workspace to be allocated on the Device. - UINT64 - - -
    executor Output Returns the op executor, which contains the computation flow of the operator. - aclOpExecutor* - - -
  • The relationship between the enumeration values of gmmXQuantMode, gmmWeightQuantMode, mmXQuantMode, and mmWeightQuantMode and the quantization mode is as follows:

    • 0: non-quantized
    • 1: pertensor
    • 2: perchannel
    • 3: pertoken
    • 4: pergroup
    • 5: perblock
    • 6: mx quantization
    • 7: pertoken dynamic quantization
  • Return Value

    aclnnStatus: return status code. For details, see aclnn Return Codes. The first-phase API validates input parameters and reports errors in the following cases:

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 The parameter is a required input, output, or required attribute, but a null pointer is passed.
    ACLNN_ERR_PARAM_INVALID 161002 The data type, data format, or dimension of gmmX, gmmWeight, sendCountsTensorOptional, recvCountsTensorOptional, mmXOptional, mmWeightOptional, group, epWorldSize, sendCounts, or recvCounts is not within the supported range.

aclnnAlltoAllvQuantGroupedMatMul

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address requested on the device.
    workspaceSize Input Workspace memory size requested on the device, obtained by calling the first-phase API aclnnAlltoAllvQuantGroupedMatMulGetWorkspaceSize.
    executor Input Op executor that contains the operator computation flow.
    stream Input Stream for task execution.
  • Return Value

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

Constraints

  • Communication engine constraint: only AI_CPU communication is supported.

  • Deterministic computation:

    • aclnnAlltoAllvQuantGroupedMatMul defaults to a deterministic implementation.
  • Variables used in shape in the parameter description:

    • BSK: the number of tokens sent by the current card, which is the cumulative sum of the sendCounts parameter. Value range: (0, 52428800).
    • H1: Indicates the hidden size of the routed expert. Value range: (0, 65536).
    • H2: Indicates the hidden size of the shared expert. Value range: (0, 12288].
    • e: number of experts on a single card, value range (0, 32], and the maximum supported value of e * epWorldSize is 256.
    • N1: Indicates the head_num of the routed expert. Value range: (0, 65536).
    • N2: Indicates the head_num of the shared expert. Value range: (0, 65536).
    • BS: batch sequence size.
    • K: indicates the number of TopK experts selected. K ranges from [2, 8].
    • A: the number of tokens received by the current card, which is the cumulative sum of the recvCounts parameter.
    • The sum of the A parameters of all devices in the ep communicator equals the sum of the BSK parameters on all devices.
    • For mx quantization, when gmmX and gmmWeight are FLOAT4_E2M1, H1 and H2 must be even numbers and cannot be 2. In addition, when transGmmWeight and transMmWeight are false, N1 and N2 must be even numbers.
    • The transpose states of gmmWeight and gmmWeightScale must be consistent: both transposed or both not transposed. The transpose states of mmWeight and mmWeightScale must also be consistent.
    • groupSize:
      • The value of groupSize is valid only when the gmmXScale/gmmWeightScale/mmXScale/mmWeightScale inputs are all 2 dimensions and above. In other use cases, 0 must be passed in.
      • The groupSize value supports formula deduction: the input groupSize is internally decomposed into groupSizeM, groupSizeN, and groupSizeK according to the following formula. If one or more of them is 0, the groupSizeM, groupSizeN, and groupSizeK used for computation are reset based on the shapes of the gmmX/gmmWeight/mmX/mmWeight/gmmXScale/gmmWeightScale/mmXScale/mmWeightScale inputs. Setting principle: If groupSizeM=0, the quantization group value in the m direction is determined by interface deduction, and the deduction formula is groupSizeM = m / scaleM (m must be divisible by scaleM), where m is consistent with m in the gmmX/mmX shape and scaleM is consistent with m in the gmmXScale/mmXScale shape; if groupSizeK=0, the quantization group value in the k direction is determined by interface deduction, and the deduction formula is groupSizeK = k / scaleK (k must be divisible by scaleK), where k is consistent with k in the gmmX/mmX shape and scaleK is consistent with k in the gmmXScale/mmXScale shape; if groupSizeN=0, the quantization group value in the n direction is determined by interface deduction, and the deduction formula is groupSizeN = n / scaleN (n must be divisible by scaleN), where n is consistent with n in the gmmWeight/mmWeight shape and scaleN is consistent with n in the gmmWeightScale/mmWeightScale shape.
        $$ groupSize = groupSizeK | groupSizeN << 16 | groupSizeM << 32 $$
      • If the reset condition is met and the gmmXScale/gmmWeightScale/mmXScale/mmWeightScale inputs are 2D or higher with the data type FLOAT8_E8M0 for all, the [groupSizeM, groupSizeN, groupSizeK] combination is derived as [1, 1, 32], corresponding to a groupSize value of 4295032864.
  • Quantization parameter constraints:

    • The current version supports pertensor quantization and mx quantization.
  • Type constraints

    • Pertensor quantization

      gmmXgmmWeightgmmXScalegmmWeightScalemmXScalemmWeightScalegmmY
      HIFLOAT8HIFLOAT8FLOAT32FLOAT32FLOAT32FLOAT32FLOAT16/BFLOAT16
    • mx quantization

      gmmXgmmWeightgmmXScalegmmWeightScalemmXScalemmWeightScalegmmY
      FLOAT8_E4M3FNFLOAT8_E4M3FNFLOAT8_E8M0FLOAT8_E8M0FLOAT8_E8M0FLOAT8_E8M0FLOAT16/BFLOAT16
      FLOAT8_E4M3FNFLOAT8_E5M2FLOAT8_E8M0FLOAT8_E8M0FLOAT8_E8M0FLOAT8_E8M0FLOAT16/BFLOAT16
      FLOAT8_E5M2FLOAT8_E4M3FNFLOAT8_E8M0FLOAT8_E8M0FLOAT8_E8M0FLOAT8_E8M0FLOAT16/BFLOAT16
      FLOAT8_E5M2FLOAT8_E5M2FLOAT8_E8M0FLOAT8_E8M0FLOAT8_E8M0FLOAT8_E8M0FLOAT16/BFLOAT16
      FLOAT4_E2M1FLOAT4_E2M1FLOAT8_E8M0FLOAT8_E8M0FLOAT8_E8M0FLOAT8_E8M0FLOAT16/BFLOAT16
    • mmX has the same data type as gmmX, mmWeight has the same data type as gmmWeight, mmY has the same data type as gmmY, and permuteOut has the same data type as gmmX.

Example

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

NOTE: Since the Quantization API supports only Ascend 950DT products, the following example is implemented based on this products. This sample code uses 2 devices as an example. Modify EP_WORLD_SIZE based on the actual number of devices in your environment.

#include <thread>
#include <iostream>
#include <string>
#include <vector>
#include "acl/acl.h"
#include "hccl/hccl.h"
#include "aclnnop/aclnn_allto_allv_quant_grouped_mat_mul.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;
}

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);
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtMalloc failed. ret: %d\n", ret); return ret);
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtMemcpy failed. ret: %d\n", ret); return ret);
    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];
    }
    *tensor = aclCreateTensor(shape.data(),
        shape.size(),
        dataType,
        strides.data(),
        0,
        aclFormat::ACL_FORMAT_ND,
        shape.data(),
        shape.size(),
        *deviceAddr);
    return 0;
}

struct Args {
    int rankId;
    HcclComm hcclComm;
    aclrtStream stream;
    aclrtContext context;
};

// Basic shape information
constexpr int64_t EP_WORLD_SIZE = 2;
constexpr int64_t BS = 4096;
constexpr int64_t K = 2;
constexpr int64_t H = 7168;
constexpr int64_t e = 4;
constexpr int64_t N1 = 4096;
constexpr int64_t N2 = 4096;
constexpr int64_t A = BS * K;

int LaunchOneThreadAlltoAllvQuantGroupedMatMul(Args &args)
{
    int ret = aclrtSetCurrentContext(args.context);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtSetCurrentContext failed. ret: %d\n", ret); return ret);
    char hcomName[128] = {0};
    ret = HcclGetCommName(args.hcclComm, hcomName);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclGetCommName failed. ret: %d\n", ret); return -1);

    std::vector<int64_t> gmmXShape = {BS * K, H};
    std::vector<int64_t> gmmWShape = {e, H, N1};
    std::vector<int64_t> gmmYShape = {A, N1};
    std::vector<int64_t> permuteShape = {A, H};
    std::vector<int64_t> mmXShape = {BS, H};
    std::vector<int64_t> mmWShape = {H, N2};
    std::vector<int64_t> mmYShape = {BS, N2};
    std::vector<int64_t> scaleShape = {1}; // Scale factor shape

    std::vector<int64_t> sendCountsList(EP_WORLD_SIZE * e, BS * K / (EP_WORLD_SIZE * e));
    std::vector<int64_t> recvCountsList(EP_WORLD_SIZE * e, BS * K / (EP_WORLD_SIZE * e));

    void *gmmXDeviceAddr = nullptr;
    void *gmmWDeviceAddr = nullptr;
    void *gmmYDeviceAddr = nullptr;
    void *permuteDeviceAddr = nullptr;
    void *mmXDeviceAddr = nullptr;
    void *mmWDeviceAddr = nullptr;
    void *mmYDeviceAddr = nullptr;
    void *gmmXScaleDeviceAddr = nullptr;
    void *gmmWScaleDeviceAddr = nullptr;
    void *mmXScaleDeviceAddr = nullptr;
    void *mmWScaleDeviceAddr = nullptr;

    aclTensor *gmmX = nullptr;
    aclTensor *gmmW = nullptr;
    aclTensor *gmmY = nullptr;
    aclTensor *mmX = nullptr;
    aclTensor *mmW = nullptr;
    aclTensor *mmY = nullptr;
    aclTensor *permute = nullptr;
    aclTensor *gmmXScale = nullptr;
    aclTensor *gmmWScale = nullptr;
    aclTensor *mmXScale = nullptr;
    aclTensor *mmWScale = nullptr;
    int64_t groupSize = 0;

    uint64_t workspaceSize = 0;
    aclOpExecutor *executor = nullptr;
    void *workspaceAddr = nullptr;

    long long gmmXShapeSize = GetShapeSize(gmmXShape);
    long long gmmWShapeSize = GetShapeSize(gmmWShape);
    long long gmmYShapeSize = GetShapeSize(gmmYShape);
    long long permuteShapeSize = GetShapeSize(permuteShape);
    long long mmXShapeSize = GetShapeSize(mmXShape);
    long long mmWShapeSize = GetShapeSize(mmWShape);
    long long mmYShapeSize = GetShapeSize(mmYShape);

    // HIFLOAT8 data (simulated with uint8_t)
    std::vector<uint8_t> gmmXHostData(gmmXShapeSize, (args.rankId + 1) * 10);
    std::vector<uint8_t> gmmWHostData(gmmWShapeSize, (args.rankId + 1) * 5);
    std::vector<uint8_t> mmXHostData(mmXShapeSize, (args.rankId + 1) * 10);
    std::vector<uint8_t> mmWHostData(mmWShapeSize, (args.rankId + 1) * 5);

    // Output data (FLOAT16/BFLOAT16)
    std::vector<uint16_t> gmmYHostData(gmmYShapeSize, 65535);
    std::vector<uint16_t> mmYHostData(mmYShapeSize, 0);
    std::vector<uint8_t> permuteHostData(permuteShapeSize, 255);

    // Scale factor data (FLOAT32)
    std::vector<float> gmmXScaleHostData(1, 1.0f);
    std::vector<float> gmmWScaleHostData(1, 1.0f);
    std::vector<float> mmXScaleHostData(1, 1.0f);
    std::vector<float> mmWScaleHostData(1, 1.0f);

    // Create tensors.
    ret = CreateAclTensor(gmmXHostData, gmmXShape, &gmmXDeviceAddr, ACL_HIFLOAT8, &gmmX);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gmmWHostData, gmmWShape, &gmmWDeviceAddr, ACL_HIFLOAT8, &gmmW);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gmmYHostData, gmmYShape, &gmmYDeviceAddr, ACL_FLOAT16, &gmmY);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(mmXHostData, mmXShape, &mmXDeviceAddr, ACL_HIFLOAT8, &mmX);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(mmWHostData, mmWShape, &mmWDeviceAddr, ACL_HIFLOAT8, &mmW);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(mmYHostData, mmYShape, &mmYDeviceAddr, ACL_FLOAT16, &mmY);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(permuteHostData, permuteShape, &permuteDeviceAddr, ACL_HIFLOAT8, &permute);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gmmXScaleHostData, scaleShape, &gmmXScaleDeviceAddr, ACL_FLOAT, &gmmXScale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(gmmWScaleHostData, scaleShape, &gmmWScaleDeviceAddr, ACL_FLOAT, &gmmWScale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(mmXScaleHostData, scaleShape, &mmXScaleDeviceAddr, ACL_FLOAT, &mmXScale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);
    ret = CreateAclTensor(mmWScaleHostData, scaleShape, &mmWScaleDeviceAddr, ACL_FLOAT, &mmWScale);
    CHECK_RET(ret == ACL_SUCCESS, return ret);

    aclIntArray *sendCounts = aclCreateIntArray(sendCountsList.data(), sendCountsList.size());
    aclIntArray *recvCounts = aclCreateIntArray(recvCountsList.data(), recvCountsList.size());

    // Call the first-phase API.
    ret = aclnnAlltoAllvQuantGroupedMatMulGetWorkspaceSize(gmmX,
        gmmW,
        gmmXScale,
        gmmWScale,
        nullptr, // sendCountsTensorOptional
        nullptr, // recvCountsTensorOptional
        mmX,
        mmW,
        mmXScale,
        mmWScale,
        1, // gmmXQuantMode
        1, // gmmWeightQuantMode
        1, // mmXQuantMode
        1, // mmWeightQuantMode
        hcomName,
        EP_WORLD_SIZE,
        sendCounts,
        recvCounts,
        false, // transGmmWeight
        false, // transMmWeight
        groupSize,
        true,  // permuteOutFlag
        gmmY,
        mmY,
        permute,
        &workspaceSize,
        &executor);
    CHECK_RET(
        ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnAlltoAllvQuantGroupedMatMulGetWorkspaceSize failed. ret = %d \n", ret);
        return ret);

    if (workspaceSize > 0) {
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtMalloc workspace failed. ret = %d \n", ret); return ret);
    }

    // Call the second-phase API.
    ret = aclnnAlltoAllvQuantGroupedMatMul(workspaceAddr, workspaceSize, executor, args.stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnAlltoAllvQuantGroupedMatMul failed. ret = %d \n", ret);
            return ret);

    // Synchronously wait for the task to complete.
    ret = aclrtSynchronizeStreamWithTimeout(args.stream, 10000000);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtSynchronizeStreamWithTimeout failed. ret = %d \n", ret);
            return ret);

    // Release device resources.
    if (gmmX != nullptr) aclDestroyTensor(gmmX);
    if (gmmW != nullptr) aclDestroyTensor(gmmW);
    if (gmmY != nullptr) aclDestroyTensor(gmmY);
    if (mmX != nullptr) aclDestroyTensor(mmX);
    if (mmW != nullptr) aclDestroyTensor(mmW);
    if (mmY != nullptr) aclDestroyTensor(mmY);
    if (permute != nullptr) aclDestroyTensor(permute);
    if (gmmXScale != nullptr) aclDestroyTensor(gmmXScale);
    if (gmmWScale != nullptr) aclDestroyTensor(gmmWScale);
    if (mmXScale != nullptr) aclDestroyTensor(mmXScale);
    if (mmWScale != nullptr) aclDestroyTensor(mmWScale);

    if (gmmXDeviceAddr != nullptr) aclrtFree(gmmXDeviceAddr);
    if (gmmWDeviceAddr != nullptr) aclrtFree(gmmWDeviceAddr);
    if (gmmYDeviceAddr != nullptr) aclrtFree(gmmYDeviceAddr);
    if (mmXDeviceAddr != nullptr) aclrtFree(mmXDeviceAddr);
    if (mmWDeviceAddr != nullptr) aclrtFree(mmWDeviceAddr);
    if (mmYDeviceAddr != nullptr) aclrtFree(mmYDeviceAddr);
    if (permuteDeviceAddr != nullptr) aclrtFree(permuteDeviceAddr);
    if (gmmXScaleDeviceAddr != nullptr) aclrtFree(gmmXScaleDeviceAddr);
    if (gmmWScaleDeviceAddr != nullptr) aclrtFree(gmmWScaleDeviceAddr);
    if (mmXScaleDeviceAddr != nullptr) aclrtFree(mmXScaleDeviceAddr);
    if (mmWScaleDeviceAddr != nullptr) aclrtFree(mmWScaleDeviceAddr);
    if (workspaceSize > 0) aclrtFree(workspaceAddr);

    HcclCommDestroy(args.hcclComm);
    aclrtDestroyStream(args.stream);
    aclrtDestroyContext(args.context);
    aclrtResetDevice(args.rankId);
    return 0;
}

int main(int argc, char *argv[])
{
    // This sample is implemented based on Ascend 950DT products.
    int ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclInit failed. ret = %d \n", ret); return ret);

    constexpr uint32_t WORLD_SIZE = EP_WORLD_SIZE;
    aclrtStream stream[WORLD_SIZE];
    aclrtContext context[WORLD_SIZE];

    for (uint32_t rankId = 0; rankId < WORLD_SIZE; rankId++) {
        ret = aclrtSetDevice(rankId);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtSetDevice failed. ret = %d \n", ret); return ret);
        ret = aclrtCreateContext(&context[rankId], rankId);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtCreateContext failed. ret = %d \n", ret); return ret);
        ret = aclrtCreateStream(&stream[rankId]);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtCreateStream failed. ret = %d \n", ret); return ret);
    }

    int32_t devices[WORLD_SIZE];
    for (int i = 0; i < WORLD_SIZE; i++) {
        devices[i] = i;
    }

    // Initialize the communicator.
    HcclComm comms[WORLD_SIZE];
    ret = HcclCommInitAll(WORLD_SIZE, devices, comms);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclCommInitAll failed. ret = %d \n", ret); return ret);

    Args args[WORLD_SIZE];
    // Start multiple threads.
    std::vector<std::unique_ptr<std::thread>> threads(WORLD_SIZE);
    for (uint32_t rankId = 0; rankId < WORLD_SIZE; rankId++) {
        args[rankId].rankId = rankId;
        args[rankId].hcclComm = comms[rankId];
        args[rankId].stream = stream[rankId];
        args[rankId].context = context[rankId];
        threads[rankId].reset(new std::thread(&LaunchOneThreadAlltoAllvQuantGroupedMatMul, std::ref(args[rankId])));
    }

    for (uint32_t rankId = 0; rankId < WORLD_SIZE; rankId++) {
        threads[rankId]->join();
    }

    aclFinalize();
    return 0;
}