aclnnAlltoAllvQuantGroupedMatMulV2

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) $$

Compared with the aclnnAlltoAllvQuantGroupedMatMul API, this API has the following changes:

  • Adds the commMode parameter. Users can use this parameter to specify the communication engine used by the chip.

    • Ascend 950DT products: support ai_cpu and ccu.

Function Prototype

Each operator is a two-phase API. Call the aclnnAlltoAllvQuantGroupedMatMulV2GetWorkspaceSize API first to obtain the input parameters and calculate the required workspace size based on the computation flow, and then call the aclnnAlltoAllvQuantGroupedMatMulV2 API to execute the computation.

aclnnStatus aclnnAlltoAllvQuantGroupedMatMulV2GetWorkspaceSize(
    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,
    const char*        commMode,
    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 aclnnAlltoAllvQuantGroupedMatMulV2(
    void*          workspace,
    uint64_t       workspaceSize,
    aclOpExecutor* executor,
    aclrtStream    stream)

aclnnAlltoAllvQuantGroupedMatMulV2GetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    gmmX Input After AlltoAllv communication and the Permute operation, the result of this input is used as the left matrix of the GroupedMatMul computation. The current version supports only 2D input with shape (BSK, H1), and only the non-transpose use case is supported. HIFLOAT8, FLOAT8_E4M3FN, FLOAT8_E5M2, FLOAT4_E2M1 ND 2 x
    gmmWeight Input Right matrix of the GroupedMatMul computation. The current version supports only 3D inputs. 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 √ (transpose use case only)
    gmmXScale Input Quantization scale of gmmX.
    • 1D is supported in the pertensor quantization scenario, with shape (1).
    • 3D is supported in the mx quantization scenario, with shape (BSK, ceildiv(H1, 64), 2).
    FLOAT32, FLOAT8_E8M0 ND 1, 3 x
    gmmWeightScale Input Quantization scale of gmmWeight.
    • In the pertensor quantization scenario, 1 dimension is supported and the shape is (1).
    • In the mx quantization scenario, 4 dimensions are supported. The shape is (e, ceildiv(H1, 64), N1, 2) for non-transpose and (e, N1, ceildiv(H1, 64), 2) for transpose.
    FLOAT32, FLOAT8_E8M0 ND 1, 4 √ (applicable only to the transpose use case)
    sendCountsTensorOptional Input Reserved parameter. In the current version, only nullptr can be passed. - - - - -
    recvCountsTensorOptional Input Reserved parameter. Only nullptr is supported in the current version. - - - - -
    mmXOptional Input Optional input, the left matrix in the shared expert MatMul computation.
    • Supports 2 dimensions. The shape is (BS, H2).
    • Must be passed in together with mmWeightOptional, or both must be nullptr.
    Same as gmmX ND 2 x
    mmWeightOptional Input Optional input. Right matrix in the shared expert MatMul computation.
    • Supports 2 dimensions. The shape is (H2, N2) for non-transpose and (N2, H2) for transpose.
    • Must be passed in together with mmXOptional, or both must be nullptr.
    Same as gmmWeight ND 2 √ (only for the transpose use case)
    mmXScaleOptional Input Optional input. Quantization coefficients of mmX.
    • For the pertensor quantization scenario, 1-D is supported, with shape (1).
    • For the mx quantization scenario, 3-D is supported, 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.
    • pertensor quantization scenario supports 1 dimension, with shape (1).
    • mx quantization scenario supports 3 dimensions. 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 be nullptr.
    FLOAT32, FLOAT8_E8M0 ND 1, 3 √ (applicable only to transpose)
    gmmXQuantMode Input Quantization mode of gmmX. The current version supports 1 (pertensor quantization scenario) and 6 (mx quantization scenario). INT64 - - -
    gmmWeightQuantMode Input Quantization mode of gmmWeight. The current version supports 1 (pertensor quantization scenario) and 6 (mx quantization scenario). INT64 - - -
    mmXQuantMode Input Quantization mode of mmX. The 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 name for expert parallelism. The string length must be in the range (0, 128). Obtained through the Hccl API "extern HcclResult HcclGetCommName(HcclComm comm, char* commName);", where commName is group. STRING - - -
    commMode Input Specifies the current communication type. Supported values are "ai_cpu" and "ccu". STRING - - -
    epWorldSize Input EP communicator size. 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. The length is e * epWorldSize, with a maximum of 256. The input type must be a list. aclIntArray* (element type INT64) - - -
    recvCounts Input Indicates the number of tokens received from other devices. Data type: INT64; length: e * epWorldSize, up to 256. Input type must be list. aclIntArray* (element type INT64) - - -
    transGmmWeight Input Whether the right matrix of GroupedMatMul needs to be transposed. true indicates transpose, false indicates non-transpose. BOOL - - -
    transMmWeight Input Whether the right matrix of the shared expert MatMul needs to be transposed. true indicates transpose, false indicates non-transpose. BOOL - - -
    groupSize Input Indicates the number of elements of the gmmX/gmmWeight/mmX/mmWeight input along a dimension that can be quantized by one element of the gmmXScale/gmmWeightScale/mmXScale/mmWeightScale input along the corresponding dimension. The groupSize input is formed by concatenating three values: groupSizeM, groupSizeN, and groupSizeK, each occupying 16 bits. The formula is groupSize = groupSizeK | groupSizeN << 16 | groupSizeM << 32. INT64 - - -
    permuteOutFlag Input Indicates whether permuteOutOptional needs to be output. true indicates output is required, and false indicates output is not required. BOOL - - -
    gmmY Output Output of the routing expert computation. 2-D tensor 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 is generated only when both mmXOptional and mmWeightOptional are passed in. Same as gmmY ND 2 x
    permuteOutOptional Output Output after permute. Supports 2 dimensions with shape (A, H1). Output only when permuteOutFlag is true. Same as gmmX ND 2 x
    workspaceSize Output Returns the workspace size to be allocated on the Device. - UINT64 - - -
    executor Output Returns the op executor that contains the computation process 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. An error is reported in the following cases:

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 A null pointer is passed in for a parameter that must be a required input, output, or attribute.
    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.

aclnnAlltoAllvQuantGroupedMatMulV2

  • Parameters

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

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

Constraints

  • Communication engine constraints: Supports CCU communication and AI_CPU communication. CCU supports intra-machine UB domain interconnection only, while AI_CPU supports inter-machine UB domain interconnection.

  • Deterministic computation:

    • aclnnAlltoAllvQuantGroupedMatMulV2 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: The quantization API is supported only on Ascend 950DT products. The following example is based on this products. The 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_v2.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 using 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 = aclnnAlltoAllvQuantGroupedMatMulV2GetWorkspaceSize(gmmX,
        gmmW,
        gmmXScale,
        gmmWScale,
        nullptr, // sendCountsTensorOptional
        nullptr, // recvCountsTensorOptional
        mmX,
        mmW,
        mmXScale,
        mmWScale,
        1, // gmmXQuantMode
        1, // gmmWeightQuantMode
        1, // mmXQuantMode
        1, // mmWeightQuantMode
        hcomName,
        "ai_cpu",
        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] aclnnAlltoAllvQuantGroupedMatMulV2GetWorkspaceSize 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 = aclnnAlltoAllvQuantGroupedMatMulV2(workspaceAddr, workspaceSize, executor, args.stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnAlltoAllvQuantGroupedMatMulV2 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;
}