aclnnGroupedMatMulAlltoAllv

📄 View Source Code

Applicable Products

  • Ascend 950DT products: Supported
  • Atlas A3 products: 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: 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 $$

Function Prototype

Each operator uses a two-phase API. You must first call the aclnnGroupedMatMulAlltoAllvGetWorkspaceSize API to obtain the input parameters and calculate the required workspace size according to the computation process, and then call the aclnnGroupedMatMulAlltoAllv API to execute the computation.

aclnnStatus aclnnGroupedMatMulAlltoAllvGetWorkspaceSize(
    const aclTensor*   gmmX,
    const aclTensor*   gmmWeight,
    const aclTensor*   sendCountsTensorOptional,
    const aclTensor*   recvCountsTensorOptional,
    const aclTensor*   mmXOptional,
    const aclTensor*   mmWeightOptional,
    const char*        group,
    int64_t            epWorldSize,
    const aclIntArray* sendCounts,
    const aclIntArray* recvCounts,
    bool               transGmmWeight,
    bool               transMmWeight,
    aclTensor*         y,
    aclTensor*         mmYOptional,
    uint64_t*          workspaceSize,
    aclOpExecutor**    executor)
aclnnStatus aclnnGroupedMatMulAlltoAllv(
    void*           workspace,
    uint64_t        workspaceSize,
    aclOpExecutor*  executor,
    aclrtStream     stream)

aclnnGroupedMatMulAlltoAllvGetWorkspaceSize

  • Parameters

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (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.
    • Data type keeps 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. You must 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 The left matrix in the MatMul computation of the shared expert.
    • Must be passed in together with mmWeightOptional and mmYOptional, or all set to 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 both be nullptr.
    • Data type must be kept 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 - - -
    epWorldSize (int64_t) Input Size of the ep communicator.
    • 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 256.
    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 is INT64.
    • The list size is e * epWorldSize, with a maximum of 256.
    aclIntArray* (element type INT64) - - -
    transGmmWeight(bool) Input Whether gmmWeight needs to be transposed. true indicates that transpose is required, and false indicates no transpose. BOOL - - -
    transMmWeight(bool) Input Whether shared expert mmWeightOptional needs to be transposed. true indicates that transpose is required; false indicates that transpose is not required. BOOL - - -
    y(aclTensor*) Output Final computation result.
    • The data type is kept consistent with that of input gmmX.
    • Supports 2 dimensions, with the shape (BSK, N1).
    FLOAT16, BFLOAT16 ND 2 ×
    mmYOptional(aclTensor*) Output Output of the shared expert MatMul.
    • The data type must keep consistent with that of mmXOptional.
    • Supports 2 dimensions, with shape (BS, N2).
    • Output only when both mmXOptional and mmWeightOptional are passed; otherwise, nullptr must be passed.
    FLOAT16, BFLOAT16 ND 2 ×
    workspaceSize(uint64_t*) Output Returns the size of the workspace to be requested on the device. - UINT64 - - -
    executor(aclOpExecutor**) Output Returns the op executor that 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 The parameter must be a required input, output, or 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 out of the supported range.

aclnnGroupedMatMulAlltoAllv

  • Parameters

    Parameter Input/Output Description
    workspace Input Workspace memory address applied for on the Device.
    workspaceSize Input Size of the workspace applied for on the Device, obtained by calling the first-phase API aclnnGroupedMatMulAlltoAllvGetWorkspaceSize.
    executor Input op executor that contains the operator computation flow.
    stream Input Stream that executes tasks.
  • Return Value

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

Constraints

  • Deterministic computation:

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

    • Atlas A3 products: support AI_CPU communication.
    • Ascend 950DT products: support AI_CPU communication.
  • 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: Indicates the number of experts on a single card. 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: indicates the number of TopK experts selected. K ranges from [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 A3 products: Performance degradation may occur when the communication volume per device is less than 2MB.

Example

The following sample code is provided for reference only. For details about how to compile and run the code, 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 <vector>
    #include "acl/acl.h"
    #include "hccl/hccl.h"
    #include "aclnnop/aclnn_grouped_mat_mul_allto_allv.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 = aclnnGroupedMatMulAlltoAllvGetWorkspaceSize(gmmX,
            gmmW,
            sendCountsTensor,
            recvCountsTensor,
            mmX,
            mmW,
            hcomName,
            EP_WORLD_SIZE,
            sendCounts,
            recvCounts,
            false,
            false,
            gmmY,
            mmY,
            &workspaceSize,
            &executor);
        CHECK_RET(
            ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnGroupedMatMulAlltoAllvGetWorkspaceSize 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 = aclnnGroupedMatMulAlltoAllv(workspaceAddr, workspaceSize, executor, args.stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnGroupedMatMulAlltoAllv 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);
        // Release device resources, which needs to be modified 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;
    }