aclnnAlltoAllvGroupedMatMulV2

📄 View Source Code

Applicable Products

  • Ascend 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: Completes fusion of routing expert AlltoAllv, Permute, and GroupedMatMul, and implements parallel fusion with shared expert MatMul. Communication before computation.

  • Formula:

    • Routed experts:
    $$ ataOut = AlltoAllv(gmmX) \\ permuteOut = Permute(ataOut) \\ gmmY = permuteOut \times gmmWeight $$
    • Shared expert:
    $$ mmY = mmX \times mmWeight $$

Compared with the aclnnAlltoAllvGroupedMatMul 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.

    • Atlas A2 products: Support aiv.
    • Atlas A3 products: Support aiv and ai_cpu.
    • Ascend 950DT products: Support ai_cpu and ccu.

Function Prototype

Each operator uses a two-phase API. Call aclnnAlltoAllvGroupedMatMulV2GetWorkspaceSize first to obtain the input parameters and calculate the required workspace size based on the computing process, and then call aclnnAlltoAllvGroupedMatMulV2 to perform the calculation.

aclnnStatus aclnnAlltoAllvGroupedMatMulV2GetWorkspaceSize(
    const aclTensor*   gmmX,
    const aclTensor*   gmmWeight,
    const aclTensor*   sendCountsTensorOptional,
    const aclTensor*   recvCountsTensorOptional,
    const aclTensor*   mmXOptional,
    const aclTensor*   mmWeightOptional,
    const char*        group,
    const char*        commMode,
    int64_t            epWorldSize,
    const aclIntArray* sendCounts,
    const aclIntArray* recvCounts,
    bool               transGmmWeight,
    bool               transMmWeight,
    bool               permuteOutFlag,
    aclTensor*         gmmY,
    aclTensor*         mmYOptional,
    aclTensor*         permuteOutOptional,
    uint64_t*          workspaceSize,
    aclOpExecutor**    executor)
aclnnStatus aclnnAlltoAllvGroupedMatMulV2(
    void*          workspace,
    uint64_t       workspaceSize,
    aclOpExecutor* executor,
    aclrtStream    stream)

aclnnAlltoAllvGroupedMatMulV2GetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor
    gmmX(aclTensor*) Input The result after performing AlltoAllv communication and Permute operations on this input serves as the left matrix of the GroupedMatMul computation. Supports 2 dimensions, with shape (BSK, H1). FLOAT16, BFLOAT16 ND 2 x
    gmmWeight(aclTensor*) Input The right matrix of the GroupedMatMul computation. Supports 3 dimensions, with shape (e, H1, N1). Keep consistent with gmmX ND 3 √ (only applicable to transpose scenarios)
    sendCountsTensorOptional(aclTensor*) Input Reserved parameter. Only nullptr is supported in the current version. - - - - -
    recvCountsTensorOptional(aclTensor*) Input Reserved parameter. Only nullptr is supported in the current version. - - - - -
    mmXOptional(aclTensor*) 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 set to nullptr. Keep consistent with gmmX ND 2 x
    mmWeightOptional(aclTensor*) Input Optional input, the right matrix in the shared expert MatMul computation. Two dimensions supported, shape (H2, N2). Must be passed together with mmXOptional or both be nullptr. Keep consistent with gmmX ND 2 √ (only applicable to transpose use cases)
    group(char*) Input Communicator for expert parallelism. String length range: (0, 128). Obtained through the Hccl API "extern HcclResult HcclGetCommName(HcclComm comm, char* commName);", where commName is the group. STRING - - -
    commMode(char*) Input Specifies the current communication type. Atlas A2 products support input "aiv";
    Atlas A3 products support input "aiv" and "ai_cpu";
    Ascend 950DT products support input "ai_cpu" and "ccu".
    STRING - - -
    epWorldSize(int64_t) Input Size of the EP communicator. Atlas A2 products support 2, 4, 8 when commMode is "aiv";
    Atlas A3 products support 2, 4, 8, 16, 32, 64, 128;
    Ascend 950DT products support 2, 4, 8, 16, 32, 64.
    INT64 - - -
    sendCounts(aclIntArray*) Input Indicates the number of tokens sent to other devices. The data type is INT64, and the length is e * epWorldSize. The maximum length is 1024 when commMode is "aiv", and 256 in other modes. The input type must be list. aclIntArray* (element type INT64) - - -
    recvCounts(aclIntArray*) Input Indicates the number of tokens received from other devices. Supports the INT64 data type, with a length of e * epWorldSize. The maximum value is 1024 when commMode is "aiv" and 256 in other modes. The input type must be list. aclIntArray* (element type INT64) - - -
    transGmmWeight(bool) Input Whether the right matrix of GroupedMatMul is required to be transposed. true indicates transpose is required, false indicates no transpose. BOOL - - -
    transMmWeight(bool) Input Whether the right matrix of the shared expert MatMul requires transpose. true indicates transpose is required, false indicates no transpose. BOOL - - -
    permuteOutFlag(bool) Input Whether permuteOutOptional is required for output. true indicates that output is required, false indicates that output is not required. BOOL - - -
    gmmY(aclTensor*) Output Output computed by routed experts. Supports 2 dimensions, with shape (A, N1). Keep consistent with gmmX ND 2 x
    mmYOptional(aclTensor*) Output Output of the shared expert computation. Supports 2 dimensions, shape (BS, N2). Output only when both mmXOptional and mmWeightOptional are provided. Keep consistent with mmXOptional ND 2 x
    permuteOutOptional(aclTensor*) Output Output after permute. Supports 2 dimensions with shape (A, H1). Output only when permuteOutFlag is true. Keep consistent with gmmX. ND 2 x
    workspaceSize (uint64_t*) Output Returns the size of the Device side-applied workspace. - UINT64 - - -
    executor(aclOpExecutor**) Output Returns the op executor, which contains the computation flow of the operator. - aclOpExecutor* - - -
  • 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 A null pointer is passed in for a mandatory 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.

aclnnAlltoAllvGroupedMatMulV2

  • Parameters

    Parameter Input/Output Description
    workspace Input Device-side-applied workspace memory address.
    workspaceSize Input Device-side-applied workspace size, obtained by the first-phase API aclnnAlltoAllvGroupedMatMulV2GetWorkspaceSize.
    executor Input Op executor, which 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 constraints:

    • Atlas A2 products: support AIV communication; epWorldSize in AIV mode supports 2, 4, and 8.
    • Atlas A3 products: support AIV and AICPU communication.
    • Ascend 950DT products: support CCU communication and AICPU communication. CCU supports only intra-node UB domain interconnection, and AI_CPU supports cross-node UB domain interconnection.
  • Deterministic computation:

    • aclnnAlltoAllvGroupedMatMulV2 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 per card, e ≤ 48, and e * epWorldSize supports up to 384.
    • 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.
  • Additional constraints and memory layout when commMode is "aiv":

    • For Atlas A2, epWorldSize supports 2, 4, and 8; for Atlas A3, epWorldSize supports 2, 4, 8, 16, 32, 64, and 128. gmmX, gmmWeight, and gmmY must be of the same FLOAT16 or BFLOAT16 data type and ND format, and their shapes are 2D, 3D, and 2D respectively.
    • In AIV mode, the value range of BSK/A is [1, 5000000] and that of H1/N1 is [1, 65535]. The number of local experts e does not exceed 512, and epWorldSize * e does not exceed 1024.
    • The sendCounts and recvCounts API attributes are INT64 arrays of direct counts, with the layout of [rank][localExpert]. The host side verifies that each item is non-negative and does not exceed the corresponding local input/output M, that the sum of sendCounts equals BSK, and that the sum of recvCounts equals A.
  • Atlas A3 products : Performance degradation may occur when the communication volume of a single device is below 2MB.

Example

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

Note:

  • The sample code calls some HCCL collective communication library APIs, such as HcclGetCommName, HcclCommInitAll, and HcclCommDestroy. For details, see <<HCCL API (C)>>.
  • The sample code uses 8 devices as an example. Modify EP_WORLD_SIZE based on the actual number of devices.
  • Ascend 950DT products:

    #include <thread>
    #include <iostream>
    #include <string>
    #include <cstring>
    #include <vector>
    #include "acl/acl.h"
    #include "hccl/hccl.h"
    #include "aclnnop/aclnn_allto_allv_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;
    };
    
    // shape basic 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;
    
    std::vector<int16_t> pPermuteData(A *H, 0);
    std::vector<int16_t> pGmmYData(A *N1, 0);
    std::vector<int16_t> pmmXData(BS *H, 0);
    std::vector<int16_t> pmmWData(H *N2, 0);
    std::vector<int16_t> pmmYData(BS *N2, 0);
    
    int LaunchOneThreadAlltoAllvGmm(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> sendCountsShape = {EP_WORLD_SIZE * e};
        std::vector<int64_t> recvCountsShape = {EP_WORLD_SIZE * e};
    
        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;
    
        aclTensor *gmmX = nullptr;
        aclTensor *gmmW = nullptr;
        aclTensor *gmmY = nullptr;
        aclTensor *mmX = nullptr;
        aclTensor *mmW = nullptr;
        aclTensor *mmY = nullptr;
        aclTensor *permute = nullptr;
        aclTensor *sendCountsTensor = nullptr;
        aclTensor *recvCountsTensor = nullptr;
    
        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);
    
        std::vector<uint16_t> gmmXHostData(gmmXShapeSize, (args.rankId + 1) * 1024); // BF16, FP16
        std::vector<uint16_t> gmmWHostData(gmmWShapeSize, (args.rankId + 1) * 512);
        std::vector<uint16_t> gmmYHostData(gmmYShapeSize, 65535);
        std::vector<uint16_t> permuteHostData(permuteShapeSize, 65535);
        std::vector<uint16_t> mmXHostData(mmXShapeSize, (args.rankId + 1) * 1024); // BF16, FP16
        std::vector<uint16_t> mmWHostData(mmWShapeSize, (args.rankId + 1) * 512);
        std::vector<uint16_t> mmYHostData(mmYShapeSize, 0);
    
        ret = CreateAclTensor(gmmXHostData, gmmXShape, &gmmXDeviceAddr, aclDataType::ACL_FLOAT16, &gmmX);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(gmmWHostData, gmmWShape, &gmmWDeviceAddr, aclDataType::ACL_FLOAT16, &gmmW);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(gmmYHostData, gmmYShape, &gmmYDeviceAddr, aclDataType::ACL_FLOAT16, &gmmY);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(mmXHostData, mmXShape, &mmXDeviceAddr, aclDataType::ACL_FLOAT16, &mmX);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(mmWHostData, mmWShape, &mmWDeviceAddr, aclDataType::ACL_FLOAT16, &mmW);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(mmYHostData, mmYShape, &mmYDeviceAddr, aclDataType::ACL_FLOAT16, &mmY);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
    
        ret = CreateAclTensor(permuteHostData, permuteShape, &permuteDeviceAddr, aclDataType::ACL_FLOAT16, &permute);
        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 = aclnnAlltoAllvGroupedMatMulV2GetWorkspaceSize(gmmX, gmmW, sendCountsTensor, recvCountsTensor, mmX, mmW,
                                                            hcomName, "ai_cpu", EP_WORLD_SIZE, sendCounts, recvCounts, false, false,
                                                            true, gmmY, mmY, permute, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS,
                LOG_PRINT("[ERROR] aclnnAlltoAllvGroupedMatMulV2GetWorkspaceSize 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 = aclnnAlltoAllvGroupedMatMulV2(workspaceAddr, workspaceSize, executor, args.stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnAlltoAllvGroupedMatMulV2 failed. ret = %d \n", ret);
                return ret);
        // (Boilerplate) Synchronize and wait for task execution to complete.
        ret = aclrtSynchronizeStreamWithTimeout(args.stream, 10000000);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtSynchronizeStreamWithTimeout failed. ret = %d \n", ret);
                return ret);
        LOG_PRINT("[INFO] device_%d aclnnAlltoAllvGroupedMatMulV2 execute successfully.\n", args.rankId);
        // Release device resources. Modify based on the specific API definition.
        if (args.rankId == 0) {
            size_t size = A * H * sizeof(int16_t);
            aclrtMemcpy(pPermuteData.data(), size, permuteDeviceAddr, size, ACL_MEMCPY_DEVICE_TO_HOST);
        }
        if (args.rankId == 0) {
            size_t size = A * N1 * sizeof(int16_t);
            aclrtMemcpy(pGmmYData.data(), size, gmmYDeviceAddr, size, ACL_MEMCPY_DEVICE_TO_HOST);
        }
        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 (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 (workspaceSize > 0) {
            aclrtFree(workspaceAddr);
        }
        HcclCommDestroy(args.hcclComm);
        aclrtDestroyStream(args.stream);
        aclrtDestroyContext(args.context);
        aclrtResetDevice(args.rankId);
        return 0;
    }
    
    int main(int argc, char *argv[])
    {
        int ret = aclInit(nullptr);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclInit failed. ret = %d \n", ret); return ret);
        aclrtStream stream[EP_WORLD_SIZE];
        aclrtContext context[EP_WORLD_SIZE];
        for (uint32_t rankId = 0; rankId < EP_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[EP_WORLD_SIZE];
        for (int i = 0; i < EP_WORLD_SIZE; i++) {
            devices[i] = i;
        }
        // Initialize the communicator.
        HcclComm comms[EP_WORLD_SIZE];
        ret = HcclCommInitAll(EP_WORLD_SIZE, devices, comms);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclCommInitAll failed. ret = %d \n", ret); return ret);
    
        Args args[EP_WORLD_SIZE];
        // Start multiple threads.
        std::vector<std::unique_ptr<std::thread>> threads(EP_WORLD_SIZE);
        for (uint32_t rankId = 0; rankId < EP_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(&LaunchOneThreadAlltoAllvGmm, std::ref(args[rankId])));
        }
        for (uint32_t rankId = 0; rankId < EP_WORLD_SIZE; rankId++) {
            threads[rankId]->join();
        }
        aclFinalize();
        return 0;
    }