aclnnGroupedMatMulAlltoAllvV2

📄 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: Fuses routed expert GroupedMatMul, Unpermute, and AlltoAllv, and performs parallel fusion with the shared expert MatMul, computing before communication.

  • Formula:

    • Routed experts:
    $$ gmmY = gmmX \times gmmWeight \\ unpermuteOut = Unpermute(gmmY) \\ y = AlltoAllv(unpermuteOut) $$
    • Shared expert:
    $$ mmY = mmX \times mmWeight $$

Compared with the aclnnGroupedMatMulAlltoAllv API, the changes to this API are as follows:

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

    • Atlas A3 products: support ai_cpu and aiv.
    • Atlas A2 products: only support aiv; ai_cpu and ccu are not supported.
    • Ascend 950DT products: Supported: ai_cpu and ccu.

Function Prototype

Each operator uses a two-phase API. Call the aclnnGroupedMatMulAlltoAllvV2GetWorkspaceSize API first to obtain the input parameters and calculate the required workspace size based on the computation flow, and then call the aclnnGroupedMatMulAlltoAllvV2 API to perform the computation.

aclnnStatus aclnnGroupedMatMulAlltoAllvV2GetWorkspaceSize(
    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,
    aclTensor*         y,
    aclTensor*         mmYOptional,
    uint64_t*          workspaceSize,
    aclOpExecutor**    executor)
aclnnStatus aclnnGroupedMatMulAlltoAllvV2(
    void*           workspace,
    uint64_t        workspaceSize,
    aclOpExecutor*  executor,
    aclrtStream     stream)

aclnnGroupedMatMulAlltoAllvV2GetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Shape Non-contiguous Tensor
    gmmX(aclTensor*) Input Left matrix of the GroupedMatMul computation.
    • The data type must keep consistent with gmmWeight.
    • Supports 2 dimensions with shape (A, H1).
    FLOAT16, BFLOAT16 ND 2 ×
    gmmWeight(aclTensor*) Input Right matrix of the GroupedMatMul computation.
    • The data type must keep consistent with gmmX.
    • Supports 3 dimensions, with shape (e, H1, N1).
    FLOAT16, BFLOAT16 ND 3 ×
    sendCountsTensorOptional (aclTensor*) Optional input The shape is (e * epWorldSize,). Not supported in the current version. Pass nullptr. INT32, INT64 ND 1 ×
    recvCountsTensorOptional (aclTensor*) Optional input The shape is (e * epWorldSize,). Not supported in the current version. Pass nullptr. INT32, INT64 ND 1 ×
    mmXOptional(aclTensor*) Optional input Left matrix in the shared expert MatMul computation.
    • Must be passed together with mmWeightOptional and mmYOptional, or all be nullptr.
    • The data type must be kept consistent with that of gmmX.
    • Supports 2 dimensions with shape (BS, H2).
    FLOAT16, BFLOAT16 ND 2 ×
    mmWeightOptional(aclTensor*) Optional input Right matrix in the shared expert MatMul computation.
    • Must be passed in together with mmXOptional and mmYOptional, or all must be nullptr.
    • The data type must keep consistent with gmmX.
    • Supports 2 dimensions, with shape (H2, N2).
    FLOAT16, BFLOAT16 ND 2 ×
    group(char*) Input Communicator name for expert parallelism. The string length must be greater than 0 and less than 128. STRING - - -
    commMode(char*) Input Specifies the current communication type. Only "aiv" is supported on Atlas A2 products; "ai_cpu" and "aiv" are supported on Atlas A3 products; "ai_cpu" and "ccu" are supported on Ascend 950DT products. STRING - - -
    epWorldSize (int64_t) Input Size of the ep communicator.
    • Atlas A2 products support 2, 4, and 8.
    • Atlas A3 products support 8, 16, 32, 64, and 128.
    • Ascend 950DT products support 2, 4, 8, 16, 32, and 64.
    INT64 - - -
    sendCounts(aclIntArray*) Input Indicates the number of tokens sent to other devices.
    • The input type must be aclIntArray*, and the element type is INT64.
    • The list size is e * epWorldSize, with a maximum of 1024 for AIV communication and 256 for other communication engines.
    aclIntArray* (element type INT64) - - -
    recvCounts(aclIntArray*) Input Indicates the number of tokens received from other devices.
    • The input type must be aclIntArray*, and the element type must be INT64.
    • The list size is e * epWorldSize, with a maximum of 1024 for AIV communication and 256 for other communication engines.
    aclIntArray* (element type INT64) - - -
    transGmmWeight(bool) Input Whether gmmWeight needs to be transposed. true indicates transpose is required; false indicates no transpose. BOOL - - -
    transMmWeight(bool) Input Whether the shared expert mmWeightOptional needs to be transposed. true indicates transpose is required; false indicates no transpose. BOOL - - -
    y(aclTensor*) Output Final computation result.
    • Data type keeps consistent with input gmmX.
    • Supports 2 dimensions with shape (BSK, N1).
    FLOAT16, BFLOAT16 ND 2 ×
    mmYOptional(aclTensor*) Output Output of the shared expert MatMul.
    • The data type must keep consistent with mmXOptional.
    • Supports 2 dimensions, with shape (BS, N2).
    • Output only when both mmXOptional and mmWeightOptional are passed in; otherwise, nullptr must be passed.
    FLOAT16, BFLOAT16 ND 2 ×
    workspaceSize (uint64_t*) Output Returns the size of the Device side-applied workspace. - UINT64 - - -
    executor(aclOpExecutor**) Output Returns the op executor containing the computation process 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 The parameter should be a required input, output, or required attribute, but a null pointer is passed in.
    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 supported.

aclnnGroupedMatMulAlltoAllvV2

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied on the Device side.
    workspaceSize Input Size of the workspace applied on the Device side, obtained by the first-phase API aclnnGroupedMatMulAlltoAllvV2GetWorkspaceSize.
    executor Input Op executor, which contains the computation flow of the operator.
    stream Input Stream for task execution.
  • Return Value

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

Constraints

  • Deterministic computation:

    • aclnnGroupedMatMulAlltoAllvV2 defaults to a deterministic implementation.
  • Communication engine constraints:

    • Atlas A3 products: AI_CPU communication and AIV communication are supported.
    • Atlas A2 products: Only AIV communication is supported.
    • Ascend 950DT products: Support CCU communication and AI_CPU communication. CCU supports only intra-machine interconnection within the UB domain, and AI_CPU supports cross-machine interconnection within the UB domain.
  • Variables used in shape in the parameter description:

    • BSK: The number of tokens received by the current card, which is the cumulative sum of the recvCounts 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 device. AIV communication requires e > 0, and e epWorldSize supports a maximum of 1024. Other communication engines require e<=32, and e epWorldSize supports a maximum of 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: Number of selected TopK experts. AIV communication of Atlas A3 products supports [2, 16], and other use cases support [2, 8].
    • A: the number of tokens sent by the current card, which is the cumulative sum of the sendCounts parameter.
    • The sum of the A parameters of all devices in the ep communicator equals the sum of the BSK parameters on all devices.
  • Atlas A2 products:
    • Both A and BSK must be in the range [1, 5000000]; N1 must not exceed 32768.
    • sendCounts and recvCounts are both INT64 direct count arrays, flattened in the order of [rank][localExpert]. The length of each must be equal to e * epWorldSize. Elements are non-negative, do not exceed A and BSK respectively, and their sums equal A and BSK respectively.
    • HCCL_BUFFSIZE on each device in the communicator must be set based on the maximum send volume, satisfying HCCL_BUFFSIZE >= max(200, ceil(A * N1 * 2 / 1048576) + 21), in MiB. Each FLOAT16 and BFLOAT16 element occupies 2 bytes, and 21 MiB is reserved for the control region.
  • Atlas A3 products: Performance degradation may occur if the per-device communication volume is less than 2MB.

Example

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

NOTE: This sample code calls some APIs of the HCCL collective communication library: HcclGetCommName, HcclCommInitAll, and HcclCommDestroy. For details, see HCCL API (C).

  • Atlas A3 products and Ascend 950DT products:

    #include <thread>
    #include <iostream>
    #include <string>
    #include <cstring>
    #include <vector>
    #include "acl/acl.h"
    #include "hccl/hccl.h"
    #include "aclnnop/aclnn_grouped_mat_mul_allto_allv_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 = 8;
    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> pGmmYData(BS *K *N1, 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 = {A, H};
        std::vector<int64_t> gmmWShape = {e, H, N1};
        std::vector<int64_t> gmmYShape = {BS * K, 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, A / (EP_WORLD_SIZE * e));
        std::vector<int64_t> recvCountsList(EP_WORLD_SIZE * e, A / (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 *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 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> 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);
    
        aclIntArray *sendCounts = aclCreateIntArray(sendCountsList.data(), sendCountsList.size());
        aclIntArray *recvCounts = aclCreateIntArray(recvCountsList.data(), recvCountsList.size());
    
        // Call the first-phase API.
        ret = aclnnGroupedMatMulAlltoAllvV2GetWorkspaceSize(gmmX, gmmW, sendCountsTensor, recvCountsTensor, mmX, mmW,
                                                            hcomName, "ai_cpu", EP_WORLD_SIZE, sendCounts, recvCounts, false, false,
                                                            gmmY, mmY, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS,
                LOG_PRINT("[ERROR] aclnnGroupedMatMulAlltoAllvV2GetWorkspaceSize 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 = aclnnGroupedMatMulAlltoAllvV2(workspaceAddr, workspaceSize, executor, args.stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnGroupedMatMulAlltoAllvV2 failed. ret = %d \n", ret);
                return ret);
        // (Boilerplate) Synchronize and wait for the 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 aclnnGroupedMatMulAlltoAllvV2 execute successfully.\n", args.rankId);
        // Release device resources. Modify according to the specific API definition.
        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 (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 (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;
    }