aclnnAlltoAllQuantMatmul

Applicable Products

  • Ascend 950PR&950DT products: Supported
  • Atlas A3 products: Not 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 AlltoAll communication, Permute (ensuring contiguous addresses after communication), Quant, Matmul, and Dequant computations, communication before computation. Supports K-C quantization, K-C dynamic quantization, and mx quantization mode.

  • Formula: Assume that the input shape of x1 is (BS, H). In the mx quantization scenario, the input shape of x1ScaleOptional is (BS, ceil(H/64), 2), and rankSize is the number of NPU devices.

    • Atlas A2 products:

      • K-C Quantization Scenario:

        $$ commOut = AlltoAll(x1.view(rankSize, BS/rankSize, H)) \\ permutedOut = commOut.permute(1, 0, 2).view(BS/rankSize, rankSize*H) \\ output_{quant} = x1 @ x2 \\ output = output_{quant} \times x1_{scale} \times x2_{scale} \\ output = output + bias $$
      • K-C Dynamic Quantization scenario:

        $$ commOut = AlltoAll(x1.view(rankSize, BS/rankSize, H)) \\ permutedOut = commOut.permute(1, 0, 2).view(BS/rankSize, rankSize*H) \\ x1_{quant}, x1_{scale} = Quant(permutedOut) \\ output_{quant} = x1_{quant} @ x2 \\ output = output_{quant} \times x1_{scale} \times x2_{scale} \\ output = output + bias $$
    • Ascend 950PR&950DT products:

      • K-C Dynamic Quantization scenario:

        $$ commOut = AlltoAll(x1.view(rankSize, BS/rankSize, H)) \\ permutedOut = commOut.permute(1, 0, 2).view(BS/rankSize, rankSize*H) \\ dynQuantX1, dynQuantX1Scale = dynamicQuant(permutedOut) \\ output = (dynQuantX1@x2 + bias) \times dynQuantX1Scale \times x2Scale $$
      • mx quantization scenario:

        $$ commOut = AlltoAll(x1.view(rankSize, BS/rankSize, H)) \\ permutedOut = commOut.permute(1, 0, 2).view(BS/rankSize, rankSize*H) \\ commScale = AlltoAll(x1Scale.view(rankSize, BS/rankSize, ceil(H/64), 2)) \\ permutedScale = commScale.permute(1, 0, 2, 3).view(BS/rankSize, ceil(H/64)*rankSize, 2) \\ output = \sum_{0}^{\left \lfloor \frac{k}{blockSize=32} \right \rfloor} (permutedOut @ x2 * (permutedScale * x2Scale)) + bias $$

Function Prototype

Each operator uses a two-phase API. You must call the "aclnnAlltoAllQuantMatmulGetWorkspaceSize" API first to obtain the workspace size required for computation and the executor that contains the operator computation flow. Then call the "aclnnAlltoAllQuantMatmul" API to perform the computation.

aclnnStatus aclnnAlltoAllQuantMatmulGetWorkspaceSize(
  const aclTensor*   x1,
  const aclTensor*   x2,
  const aclTensor*   biasOptional,
  const aclTensor*   x1ScaleOptional,
  const aclTensor*   x2Scale,
  const aclTensor*   commScaleOptional,
  const aclTensor*   x1OffsetOptional,
  const aclTensor*   x2OffsetOptional,
  const char*        group,
  const aclIntArray* alltoAllAxesOptional,
  int64_t            x1QuantMode,
  int64_t            x2QuantMode,
  int64_t            commQuantMode,
  int64_t            commQuantDtype,
  int64_t            x1QuantDtype,
  int64_t            groupSize,
  bool               transposeX1,
  bool               transposeX2,
  const aclTensor*   output,
  const aclTensor*   alltoAllOutOptional,
  uint64_t*          workspaceSize,
  aclOpExecutor**    executor)
aclnnStatus aclnnAlltoAllQuantMatmul(
  void*          workspace,
  uint64_t       workspaceSize,
  aclOpExecutor* executor,
  aclrtStream    stream)

aclnnAlltoAllQuantMatmulGetWorkspaceSize

  • Parameters:

    Parameter Input/Output Description Instruction Data Type Data Format Dimension (Shape) Non-contiguous Tensor
    x1 Input Left matrix input of the fused operator, corresponding to x1 in the formula. After AlltoAll communication and Permute operations, this input serves as the left matrix input for the MatMul computation. Data type restrictions vary by device model. For details, see Constraints. FLOAT16, BFLOAT16, FLOAT8_E4M3FN, FLOAT8_E5M2, FLOAT4_E2M1, INT4 ND 2D, shape (BS, H) x
    x2 Input Right matrix input of the fused operator, also the right matrix for the MatMul computation, corresponding to x2 in the formula. Right matrix input for the MatMul computation. Data type and non-contiguous tensor restrictions vary by product model. For details, see Constraints. FLOAT8_E4M3FN, FLOAT8_E5M2, FLOAT4_E2M1, INT8, INT4 ND 2 dimensions, shape (H*rankSize, N) Support varies by product model. See Constraints.
    biasOptional Input Optional input. Bias added after the matmul computation, corresponding to bias in the formula. Data type restrictions vary by product model. For details, see Constraints. FLOAT16, BFLOAT16, FLOAT32 ND 1D, shape (N) x
    x1ScaleOptional Input Optional input, quantization scale of the left matrix. Required in the K-C quantization and mx quantization use cases. In the K-C dynamic quantization use case, x1ScaleOptional can be passed in as smoothScale, in which case its data type must be the same as that of x1. FLOAT32, FLOAT16, BFLOAT16, FLOAT8_E8M0 ND 1D/3D. In the K-C quantization use case, the shape is (BS). In the K-C dynamic quantization use case, the shape is (H*rankSize). In the mx quantization use case, the shape is (BS, ceil(H/64), 2) x
    x2Scale Input Quantization scale of the right matrix. Corresponds to x2Scale in the formula. FLOAT32, FLOAT8_E8M0 ND 1D/3D. The shape is (N) for K-C quantization and K-C dynamic quantization. The shape is (N, ceil(H*rankSize/64), 2) for the mx quantization use case. x
    commScaleOptional Input Optional input, quantization coefficient for low-bit communication. Reserved parameter. Low-bit communication is not supported yet. - - - -
    x1OffsetOptional Input Optional input, quantization offset of the left matrix. Reserved parameter, which is not supported currently. - - - -
    x2OffsetOptional Input Optional input, quantization bias of the right matrix. Reserved parameter, which is not supported currently. - - - -
    alltoAllAxesOptional Input Optional input. Direction of data exchange for AlltoAll and Permute. Only empty or [-2, -1] is supported. If empty, [-2, -1] is used by default. The input is converted from (BS, H) to (BS/rankSize, rankSize*H). aclIntArray* (element type INT64) - 1 dimension, shape (2). -
    group Input String on the host that identifies the column group, that is, the communicator name. Obtain commName through the Hccl API HcclGetCommName and use it as this parameter. Required string length: (0, 128). - - - -
    x1QuantMode Input Quantization mode of the left matrix. The value varies by device model. For details, see Constraints. - - - -
    x2QuantMode Input Quantization mode of the right matrix. Values are subject to different restrictions depending on the device model. For details, see Constraints. - - - -
    commQuantMode Input Quantization mode for low-bit communication. Reserved parameter. Currently, only 0 is supported, indicating no quantization. - - - -
    commQuantDtype Input Quantization type for low-bit communication. Reserved parameter. Currently, only -1 is supported, indicating ACL_DT_UNDEFINED. - - - -
    x1QuantDtype Input Quantization type of the left matrix in quantized Matmul. The result after AlltoAll communication and the Permute operation is quantized based on this parameter configuration and used as the left matrix input for MatMul computation. Value restrictions vary by product model. For details, see Constraints. - - - -
    groupSize Input Quantization group sizes in three directions of the Matmul computation. The value is a concatenation of groupSizeM, groupSizeN, and groupSizeK, with each value occupying 16 bits. The three values occupy the lower 48 bits of the int64_t type groupSize (the upper 16 bits of groupSize are invalid).
    • In the mx quantization use case, only [groupSizeM, groupSizeN, groupSizeK] = [1, 1, 32] is supported. For the corresponding specific value of groupSize, see Constraints. In other quantization use cases, the parameter is set to 0 by default and does not take effect.
    • Parameter auto-deduction is supported. If any one or more of groupSizeM, groupSizeN, and groupSizeK decomposed based on the formula is 0, the operator automatically derives these parameter values. For details, see Constraints.
    - - - -
    transposeX1 Input Indicates whether the left matrix is transposed. Configuring it to True is not supported yet. - - - -
    transposeX2 Input Specifies whether the right matrix is transposed. If set to True, the shape of the right matrix is (N, rankSize*H). In mx quantization mode, this parameter must be set to True. - - - -
    Output Output Final computation result. Data types have different restrictions depending on the device model. For details, see Constraints. FLOAT16, BFLOAT16, FLOAT32 ND 2D, shape (BS/rankSize, N) x
    alltoAllOutOptional Output Receives the content after AlltoAll and Permute. The data type must be the same as that of input x1. If nullptr is passed in, no communication output is generated. FLOAT16, BFLOAT16, FLOAT8_E4M3FN, FLOAT8_E5M2, FLOAT4_E2M1, INT4 ND 2 dimensions, shape (BS/rankSize, rankSize*H) x
    workspaceSize Output Returns the size of the workspace to be allocated on the device. - - - - -
    executor Output Returns the op executor, which contains the computation flow of the operator. - - - - -

    The mapping between the enumeration values of x1QuantMode, x2QuantMode, and commQuantMode and the quantization modes is as follows:

    • 0: no quantization
    • 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 performs input parameter validation and returns an error in the following scenarios:

    Return Value Error Code Description
    ACLNN_ERR_PARAM_NULLPTR 161001 A required input or output tensor is a null pointer.
    ACLNN_ERR_PARAM_INVALID 161002 The data type of an input or output Tensor is not in the supported range.
    The input Tensor is an empty Tensor.
    alltoAllAxesOptional is invalid.
    transposeX1 is true.
    The communicator length is invalid.
    The dimensions of input or output Tensors are invalid.
    The format of input or output Tensors is a private format.

aclnnAlltoAllQuantMatmul

  • Parameters:

    Parameter Input/Output Description
    workspace Input Workspace memory address allocated on the Device.
    workspaceSize Input Workspace size allocated on the Device, obtained by calling the first-phase API aclnnAlltoAllQuantMatmulGetWorkspaceSize.
    executor Input op executor, containing the operator computation flow.
    stream Input Stream where tasks are executed.
  • Return value

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

Constraints

  • aclnnAlltoAllQuantMatmul supports deterministic computation by default.

  • Number of NPU cards (rankSize), with different restrictions based on the device model:

    • Atlas A2 products: 2, 4, and 8 devices are supported.
    • Ascend 950PR&950DT products: 2, 4, 8, and 16 devices are supported.
  • The variable BS used in the shape in Parameters must be divisible by rankSize.

  • The values of BS and N must not exceed 2147483647 (INT32_MAX). The value of BS must not be less than 2, and the value of N must not be less than 1.

  • Empty tensors are not supported.

  • Support for non-contiguous tensors varies by device model:

    • Atlas A2 products: Any non-contiguous tensor is not supported.
    • Ascend 950PR&950DT products: Only x2 can be a non-contiguous tensor. Other non-contiguous tensors are not supported.
  • The input x1, x2, x2Scale, and output must not be null pointers, and

    • Ascend 950PR&950DT products: When x1QuantMode is pertoken dynamic quantization, x1ScaleOptional cannot be passed in.
  • Constraints on groupSize:

    • groupSize is valid only when both the x1ScaleOptional and x2Scale inputs are two-dimensional or higher; otherwise, 0 must be passed in.
    • The passed groupSize is internally decomposed into groupSizeM, groupSizeN, and groupSizeK according to the following formula. If one or more of them is 0, groupSizeM, groupSizeN, and groupSizeK are reset for computation based on the shapes of the x1/x2/x1ScaleOptional/x2Scale inputs. Principle: If groupSizeM=0, the quantization grouping value in the m direction is inferred by the API. The inference formula is groupSizeM = m / scaleM (m must be divisible by scaleM), where m is the same as m in the x1 shape, and scaleM is the same as m in the x1ScaleOptional shape. The k and n directions follow the same rule.
      $$ groupSize = groupSizeK | groupSizeN << 16 | groupSizeM << 32 $$
    • Assume that the input x and scale are divisible along all dimensions, and the automatically derived groupSizeM, groupSizeN, and groupSizeK satisfy [1,1,32]. The supported groupSize values in the mx quantization scenario are as follows:

| groupSize | Based On The Formula [gsM,gsN,gsK] | Based On Automatic Derivation [gsM,gsN,gsK] | | :------: | :------: | :------: | | 4295032864 | [1,1,32] | - | | 0 | [0,0,0] | [1,1,32] | | 32 | [0,0,32] | [1,1,32] | | 65536 | [0,1,0] | [1,1,32] | | 65568 | [0,1,32] | [1,1,32] | | 4294967296 | [1,0,0] | [1,1,32] | | 4294967328 | [1,0,32] | [1,1,32] | | 4295032832 | [1,1,0] | [1,1,32] |

  • The data types, data dimensions, and quantization modes of the input and output of this operator have different restrictions depending on the device model:

    • Atlas A2 products:
      • Quantization modes:
        • Currently supports per-token quantization and per-token dynamic quantization for the left matrix, with x1QuantMode=3 or 7; and per-channel quantization for the right matrix, with x2QuantMode=2.
      • Type constraints:
        • The data types of x1 and alltoAllOutOptional must be consistent.
        • If x1, x2, or alltoallout is of the int32 type, it is treated as eight packed int4 values and will be reinterpreted as int4.
        • In A16W8 and A16W4 modes, for the smoothQuant scenario, the data types of x1ScaleOptional and x1 must be consistent.
        • For A16W8, the supported data type combinations of x1, x2, biasOptional, and output are:

| x1 | x2 | biasOptional | Output | | :------: | :------: | :------: | :------: | | FLOAT16 | INT8 | FLOAT16 | FLOAT16 | | FLOAT16 | INT8 | FLOAT32 | FLOAT16 | | BFLOAT16 | INT8 | BFLOAT16 | BFLOAT16 | | BFLOAT16 | INT8 | FLOAT32 | BFLOAT16 |

  * For A16W4, the supported data type combinations of x1, x2, biasOptional, and output are:

| x1 | x2 | biasOptional | Output | | :------: | :------: | :------: | :------: | | FLOAT16 | INT4 | FLOAT16 | FLOAT16 | | FLOAT16 | INT4 | FLOAT32 | FLOAT16 | | BFLOAT16 | INT4 | BFLOAT16 | BFLOAT16 | | BFLOAT16 | INT4 | FLOAT32 | BFLOAT16 |

  * For A4W4, x1ScaleOptional supports only FLOAT32. The supported data type combinations of x1, x2, biasOptional, and output are:

| x1 | x2 | biasOptional | Output | | :------: | :------: | :------: | :------: | | INT4 | INT4 | FLOAT16 | FLOAT16 | | INT4 | INT4 | FLOAT32 | FLOAT16 | | INT4 | INT4 | BFLOAT16 | BFLOAT16 | | INT4 | INT4 | FLOAT32 | BFLOAT16 |

* Dimension Constraints:
  * For A16W8, rankSize *H must be divisible by 16. Value range of rankSize* H: [1, 35000].
  * For A16W4, rankSize *H must be divisible by 16. N must be an even number. Value range of rankSize* H: [1, 35000].
  * For A4W4, H and N must be even numbers. Value range of rankSize * H: [1, 35000].
  • Ascend 950PR&950DT products:
    • Quantization modes:
      • Currently supported: K-C dynamic quantization, left matrix perToken dynamic quantization, x1QuantMode=7, right matrix perChannel quantization, x2QuantMode=2; mx quantization, left matrix mx quantization, x1QuantMode=6, right matrix mx quantization, x2QuantMode=6.
    • Type constraints:
      • The data types of x1 and alltoAllOutOptional must be consistent.
      • x1QuantDtype takes effect in the K-C Dynamic Quantization scenario, supporting 35 (indicating aclDataType.ACL_FLOAT8_E5M2) and 36 (indicating aclDataType.ACL_FLOAT8_E4M3FN). It does not take effect in other quantization scenarios.
      • biasOptional can be empty.
      • The supported input/output data type combinations are:
        • K-C Dynamic Quantization:

| x1 | x2 | biasOptional | Output | x1QuantMode | x2QuantMode | x1ScaleOptional | x2Scale | | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | | FLOAT16 | FLOAT8_E4M3FN | FLOAT32 | FLOAT16 | 7 | 2 | - | FLOAT32 | | FLOAT16 | FLOAT8_E4M3FN | FLOAT32 | BFLOAT16 | 7 | 2 | - | FLOAT32 | | FLOAT16 | FLOAT8_E4M3FN | FLOAT32 | FLOAT32 | 7 | 2 | - | FLOAT32 | | FLOAT16 | FLOAT8_E5M2 | FLOAT32 | FLOAT16 | 7 | 2 | - | FLOAT32 | | FLOAT16 | FLOAT8_E5M2 | FLOAT32 | BFLOAT16 | 7 | 2 | - | FLOAT32 | | FLOAT16 | FLOAT8_E5M2 | FLOAT32 | FLOAT32 | 7 | 2 | - | FLOAT32 | | BFLOAT16 | FLOAT8_E4M3FN | FLOAT32 | FLOAT16 | 7 | 2 | - | FLOAT32 | | BFLOAT16 | FLOAT8_E4M3FN | FLOAT32 | BFLOAT16 | 7 | 2 | - | FLOAT32 | | BFLOAT16 | FLOAT8_E4M3FN | FLOAT32 | FLOAT32 | 7 | 2 | - | FLOAT32 | | BFLOAT16 | FLOAT8_E5M2 | FLOAT32 | FLOAT16 | 7 | 2 | - | FLOAT32 | | BFLOAT16 | FLOAT8_E5M2 | FLOAT32 | BFLOAT16 | 7 | 2 | - | FLOAT32 | | BFLOAT16 | FLOAT8_E5M2 | FLOAT32 | FLOAT32 | 7 | 2 | - | FLOAT32 |

    * mx quantization:

| x1 | x2 | biasOptional | Output | x1QuantMode | x2QuantMode | x1ScaleOptional | x2Scale | | :------: | :------: | :------: | :------: | :------: | :------: | :------: | :------: | | FLOAT8_E4M3FN | FLOAT8_E4M3FN | FLOAT32 | FLOAT16 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT8_E4M3FN | FLOAT8_E4M3FN | FLOAT32 | BFLOAT16 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT8_E4M3FN | FLOAT8_E4M3FN | FLOAT32 | FLOAT32 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT8_E4M3FN | FLOAT8_E5M2 | FLOAT32 | FLOAT16 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT8_E4M3FN | FLOAT8_E5M2 | FLOAT32 | BFLOAT16 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT8_E4M3FN | FLOAT8_E5M2 | FLOAT32 | FLOAT32 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT8_E5M2 | FLOAT8_E4M3FN | FLOAT32 | FLOAT16 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT8_E5M2 | FLOAT8_E4M3FN | FLOAT32 | BFLOAT16 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT8_E5M2 | FLOAT8_E4M3FN | FLOAT32 | FLOAT32 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT8_E5M2 | FLOAT8_E5M2 | FLOAT32 | FLOAT16 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT8_E5M2 | FLOAT8_E5M2 | FLOAT32 | BFLOAT16 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT8_E5M2 | FLOAT8_E5M2 | FLOAT32 | FLOAT32 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT4_E2M1 | FLOAT4_E2M1 | FLOAT32 | FLOAT16 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT4_E2M1 | FLOAT4_E2M1 | FLOAT32 | BFLOAT16 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 | | FLOAT4_E2M1 | FLOAT4_E2M1 | FLOAT32 | FLOAT32 | 6 | 6 | FLOAT8_E8M0 | FLOAT8_E8M0 |

* Dimension Constraints:
  * The range of rankSize * H only supports [1, 65535].
  * In the mx quantization scenario, H must be divisible by 64.
  * In the mx quantization scenario, x2 must be transposed, with shape (H*rankSize, N) and transposeX2 set to True.
  • The communication-computation fusion operator does not support concurrent calls, and different communication-computation fusion operators also do not support concurrent calls.

  • Cross-supernode communication is not supported. Only intra-supernode communication is supported.

  • Communication constraints:

    • Atlas A2 products: MTE communication is supported, and the communication buffer must be greater than or equal to 200 MB.
    • Ascend 950PR&950DT products: AI_CPU communication is supported.

Example

The following is sample code 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 A2 products:

    #include <thread>
    #include <iostream>
    #include <string>
    #include <cstring>
    #include <vector>
    #include <acl/acl.h>
    #include <hccl/hccl.h>
    #include "aclnn/opdev/fp16_t.h"
    #include "aclnnop/aclnn_allto_all_quant_matmul.h"
    
    int ndev = 2;
    
    #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 shapeSize = 1;
        for (auto i: shape) {
            shapeSize *= i;
        }
        return shapeSize;
    }
    
    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);
        // Call aclrtMalloc to allocate memory on the device
        auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
        // Call aclrtMemcpy to copy host data to device memory
        ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
        // Calculate the strides of the contiguous tensor
        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];
        }
        // Call the aclCreateTensor API to create an aclTensor
        *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
                                shape.data(), shape.size(), *deviceAddr);
        return 0;
    }
    
    struct Args {
        uint32_t rankId;
        HcclComm hcclComm;
        aclrtStream stream;
        aclrtContext context;
    };
    
    int launchOneThreadAlltoAllQuantMatmul(Args &args)
    {
        int ret;
        ret = aclrtSetCurrentContext(args.context);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext failed. ERROR: %d\n", ret); return ret);
        char hcom_name[128] = {0};
        ret = HcclGetCommName(args.hcclComm, hcom_name);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclGetCommName failed. ret = %d \n", ret); return -1);
        LOG_PRINT("[INFO] rank %d hcom: %s stream: %p, context : %p\n", args.rankId, hcom_name, args.stream,
                args.context);
    
        std::vector<int64_t> x1Shape = {32, 64};
        std::vector<int64_t> x2Shape = {64 * ndev, 128}; // ndev = 2. The shape of x2Shape remains unchanged before and after transposition.
        std::vector<int64_t> biasShape = {128};
        std::vector<int64_t> x2ScaleShape = {128};
        std::vector<int64_t> outShape = {32 / ndev, 128};
        std::vector<int64_t> allToAllOutShape = {32 / ndev, 64 * ndev};
        void *x1DeviceAddr = nullptr;
        void *x2DeviceAddr = nullptr;
        void *biasDeviceAddr = nullptr;
        void *x2ScaleDeviceAddr = nullptr;
        void *outDeviceAddr = nullptr;
        void *allToAllOutDeviceAddr = nullptr;
        aclTensor *x1 = nullptr;
        aclTensor *x2 = nullptr;
        aclTensor *bias = nullptr;
        aclTensor *x1ScaleOptional = nullptr;
        aclTensor *x2Scale = nullptr;
        aclTensor* commScaleOptional = nullptr;
        aclTensor* x1OffsetOptional = nullptr;
        aclTensor* x2OffsetOptional = nullptr;
        aclTensor *out = nullptr;
        aclTensor *allToAllOut = nullptr;
    
        int64_t a2aAxes[2] = {-2, -1};
        aclIntArray* alltoAllAxesOptional = aclCreateIntArray(a2aAxes, static_cast<uint64_t>(2));
        uint64_t workspaceSize = 0;
        int64_t x1QuantMode = 3;
        int64_t x2QuantMode = 2;
        int64_t commQuantMode = 0;
        int64_t commQuantDtype = -1;
        int64_t x1QuantDtype = 2;
        int64_t groupSize = 0;
        aclOpExecutor *executor;
        void *workspaceAddr = nullptr;
    
        long long x1ShapeSize = GetShapeSize(x1Shape);
        long long x2ShapeSize = GetShapeSize(x2Shape);
        long long biasShapeSize = GetShapeSize(biasShape);
        long long x2ScaleShapeSize = GetShapeSize(x2ScaleShape);
        long long outShapeSize = GetShapeSize(outShape);
        long long allToAllOutShapeSize = GetShapeSize(allToAllOutShape);
        std::vector<op::fp16_t> x1HostData(x1ShapeSize, 1);
        std::vector<int8_t> x2HostData(x2ShapeSize, 1);
        std::vector<op::fp16_t> biasHostData(biasShapeSize, 1);
        std::vector<float> x2ScaleHostData(x2ScaleShapeSize, 1);
        std::vector<op::fp16_t> outHostData(outShapeSize, 0);
        std::vector<op::fp16_t> allToAllOutHostData(allToAllOutShapeSize, 0);
    
        // Create tensors.
        ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_FLOAT16, &x1);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_INT8, &x2);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(biasHostData, biasShape, &biasDeviceAddr, aclDataType::ACL_FLOAT16, &bias);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(x2ScaleHostData, x2ScaleShape, &x2ScaleDeviceAddr, aclDataType::ACL_FLOAT, &x2Scale);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT16, &out);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(allToAllOutHostData, allToAllOutShape, &allToAllOutDeviceAddr, aclDataType::ACL_FLOAT16, &allToAllOut);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        // Call the first-phase API.
        ret = aclnnAlltoAllQuantMatmulGetWorkspaceSize(x1, x2, bias, x1ScaleOptional, x2Scale, commScaleOptional, x1OffsetOptional, x2OffsetOptional,
                                                hcom_name, alltoAllAxesOptional, x1QuantMode, x2QuantMode, commQuantMode, commQuantDtype, x1QuantDtype,
                                                groupSize, false, true,
                                                out, allToAllOut, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS,
                LOG_PRINT("aclnnAlltoAllQuantMatmulGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
        // Allocate device memory using the workspaceSize calculated by the first-phase API.
        if (workspaceSize > 0) {
            ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
            CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
        }
        // Call the second-phase API.
        ret = aclnnAlltoAllQuantMatmul(workspaceAddr, workspaceSize, executor, args.stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAlltoAllQuantMatmul failed. ERROR: %d\n", ret); return ret);
        // (Boilerplate) Synchronize and wait for the task execution to complete.
        ret = aclrtSynchronizeStreamWithTimeout(args.stream, 10000);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
        LOG_PRINT("device%d aclnnAlltoAllQuantMatmul execute success \n", args.rankId);
        // Release device resources. Modify them as required by the API definition.
        if (x1 != nullptr) {
            aclDestroyTensor(x1);
        }
        if (x2 != nullptr) {
            aclDestroyTensor(x2);
        }
        if (bias != nullptr) {
            aclDestroyTensor(bias);
        }
        if (x2Scale != nullptr) {
            aclDestroyTensor(x2Scale);
        }
        if (out != nullptr) {
            aclDestroyTensor(out);
        }
        if (allToAllOut != nullptr) {
            aclDestroyTensor(allToAllOut);
        }
        if (x1DeviceAddr != nullptr) {
            aclrtFree(x1DeviceAddr);
        }
        if (x2DeviceAddr != nullptr) {
            aclrtFree(x2DeviceAddr);
        }
        if (biasDeviceAddr != nullptr) {
            aclrtFree(biasDeviceAddr);
        }
        if (outDeviceAddr != nullptr) {
            aclrtFree(outDeviceAddr);
        }
        if (workspaceSize > 0) {
            aclrtFree(workspaceAddr);
        }
        aclrtDestroyStream(args.stream);
        HcclCommDestroy(args.hcclComm);
        aclrtDestroyContext(args.context);
        aclrtResetDevice(args.rankId);
        return 0;
    }
    
    int main(int argc, char *argv[])
    {
        // This sample is implemented based on Atlas A2 and must run on Atlas A2.
        int ret = aclInit(nullptr);
        int32_t devices[ndev];
        for (int i = 0; i < ndev; i++) {
            devices[i] = i;
        }
        HcclComm comms[128];
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
        // Initialize the communicator.
        for (int i = 0; i < ndev; i++) {
            ret = aclrtSetDevice(devices[i]);
            CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
        }
        ret = HcclCommInitAll(ndev, devices, comms);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("HcclCommInitAll failed. ERROR: %d\n", ret); return ret);
        Args args[ndev];
        aclrtStream stream[ndev];
        aclrtContext context[ndev];
        for (uint32_t rankId = 0; rankId < ndev; rankId++) {
            ret = aclrtSetDevice(rankId);
            CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
            ret = aclrtCreateContext(&context[rankId], rankId);
            CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
            ret = aclrtCreateStream(&stream[rankId]);
            CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
        }
        // Start multiple threads.
        std::vector<std::unique_ptr<std::thread>> threads(ndev);
        for (uint32_t rankId = 0; rankId < ndev; 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::nothrow) std::thread(&launchOneThreadAlltoAllQuantMatmul, std::ref(args[rankId])));
        }
        for (uint32_t rankId = 0; rankId < ndev; rankId++) {
            threads[rankId]->join();
        }
        aclFinalize();
        return 0;
    }
  • Ascend 950PR&950DT products:

    #include <thread>
    #include <iostream>
    #include <string>
    #include <cstring>
    #include <vector>
    #include <acl/acl.h>
    #include <hccl/hccl.h>
    #include "aclnn/opdev/fp16_t.h"
    #include "aclnnop/aclnn_allto_all_quant_matmul.h"
    
    int ndev = 2;
    
    #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 shapeSize = 1;
    for (auto i: shape) {
    shapeSize *= i;
    }
    return shapeSize;
    }
    
    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);
    // Call aclrtMalloc to allocate device memory.
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return ret);
    // Call aclrtMemcpy to copy host-side data to the device memory.
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return ret);
    // Compute the strides of the contiguous tensor.
    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];
    }
    // Call the aclCreateTensor API to create an aclTensor.
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, strides.data(), 0, aclFormat::ACL_FORMAT_ND,
    shape.data(), shape.size(), *deviceAddr);
    return 0;
    }
    
    struct Args {
    uint32_t rankId;
    HcclComm hcclComm;
    aclrtStream stream;
    aclrtContext context;
    };
    
    int launchOneThreadAlltoAllQuantMatmul(Args &args)
    {
    int ret;
    ret = aclrtSetCurrentContext(args.context);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetCurrentContext failed. ERROR: %d\n", ret); return ret);
    char hcom_name[128] = {0};
    ret = HcclGetCommName(args.hcclComm, hcom_name);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclGetCommName failed. ret = %d \n", ret); return -1);
    LOG_PRINT("[INFO] rank %d hcom: %s stream: %p, context : %p\n", args.rankId, hcom_name, args.stream,
    args.context);
    
        std::vector<int64_t> x1Shape = {32, 64};
        std::vector<int64_t> x2Shape = {64 * ndev, 128};
        std::vector<int64_t> biasShape = {128};
        std::vector<int64_t> x2ScaleShape = {128};
        std::vector<int64_t> outShape = {32 / ndev, 128};
        std::vector<int64_t> allToAllOutShape = {32 / ndev, 64 * ndev};
        void *x1DeviceAddr = nullptr;
        void *x2DeviceAddr = nullptr;
        void *biasDeviceAddr = nullptr;
        void *x2ScaleDeviceAddr = nullptr;
        void *outDeviceAddr = nullptr;
        void *allToAllOutDeviceAddr = nullptr;
        aclTensor *x1 = nullptr;
        aclTensor *x2 = nullptr;
        aclTensor *bias = nullptr;
        aclTensor *x1ScaleOptional = nullptr;
        aclTensor *x2Scale = nullptr;
        aclTensor* commScaleOptional = nullptr;
        aclTensor* x1OffsetOptional = nullptr;
        aclTensor* x2OffsetOptional = nullptr;
        aclTensor *out = nullptr;
        aclTensor *allToAllOut = nullptr;
    
        int64_t a2aAxes[2] = {-2, -1};
        aclIntArray* alltoAllAxesOptional = aclCreateIntArray(a2aAxes, static_cast<uint64_t>(2));
        uint64_t workspaceSize = 0;
        int64_t x1QuantMode = 7;
        int64_t x2QuantMode = 2;
        int64_t commQuantMode = 0;
        int64_t commQuantDtype = -1;
        int64_t x1QuantDtype = 35;
        int64_t groupSize = 0;
        aclOpExecutor *executor;
        void *workspaceAddr = nullptr;
    
        long long x1ShapeSize = GetShapeSize(x1Shape);
        long long x2ShapeSize = GetShapeSize(x2Shape);
        long long biasShapeSize = GetShapeSize(biasShape);
        long long x2ScaleShapeSize = GetShapeSize(x2ScaleShape);
        long long outShapeSize = GetShapeSize(outShape);
        long long allToAllOutShapeSize = GetShapeSize(allToAllOutShape);
        std::vector<op::fp16_t> x1HostData(x1ShapeSize, 1);
        std::vector<int8_t> x2HostData(x2ShapeSize, 1);
        std::vector<float> biasHostData(biasShapeSize, 1);
        std::vector<float> x2ScaleHostData(x2ScaleShapeSize, 1);
        std::vector<float> outHostData(outShapeSize, 0);
        std::vector<op::fp16_t> allToAllOutHostData(allToAllOutShapeSize, 0);
        // Create a tensor.
        ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_FLOAT16, &x1);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_FLOAT8_E5M2, &x2);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(biasHostData, biasShape, &biasDeviceAddr, aclDataType::ACL_FLOAT, &bias);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(x2ScaleHostData, x2ScaleShape, &x2ScaleDeviceAddr, aclDataType::ACL_FLOAT, &x2Scale);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(outHostData, outShape, &outDeviceAddr, aclDataType::ACL_FLOAT, &out);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        ret = CreateAclTensor(allToAllOutHostData, allToAllOutShape, &allToAllOutDeviceAddr, aclDataType::ACL_FLOAT16, &allToAllOut);
        CHECK_RET(ret == ACL_SUCCESS, return ret);
        // Call the first-phase API.
        ret = aclnnAlltoAllQuantMatmulGetWorkspaceSize(x1, x2, bias, x1ScaleOptional, x2Scale, commScaleOptional, x1OffsetOptional, x2OffsetOptional,
                                                hcom_name, alltoAllAxesOptional, x1QuantMode, x2QuantMode, commQuantMode, commQuantDtype, x1QuantDtype,
                                                groupSize, false, false,
                                                out, allToAllOut, &workspaceSize, &executor);
        CHECK_RET(ret == ACL_SUCCESS,
                LOG_PRINT("aclnnAlltoAllQuantMatmulGetWorkspaceSize failed. ERROR: %d\n", ret); return ret);
        // Allocate device memory based on the workspaceSize computed by the first-phase API.
        if (workspaceSize > 0) {
            ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
            CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return ret);
        }
        // Call the second-phase API.
        ret = aclnnAlltoAllQuantMatmul(workspaceAddr, workspaceSize, executor, args.stream);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnAlltoAllQuantMatmul failed. ERROR: %d\n", ret); return ret);
        // (boilerplate) Wait synchronously for the task to complete.
        ret = aclrtSynchronizeStreamWithTimeout(args.stream, 10000);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return ret);
        LOG_PRINT("device%d aclnnAlltoAllQuantMatmul execute success \n", args.rankId);
        // Release device resources. Modify the code based on the specific API definitions.
        if (x1 != nullptr) {
            aclDestroyTensor(x1);
        }
        if (x2 != nullptr) {
            aclDestroyTensor(x2);
        }
        if (bias != nullptr) {
            aclDestroyTensor(bias);
        }
        if (x2Scale != nullptr) {
            aclDestroyTensor(x2Scale);
        }
        if (out != nullptr) {
            aclDestroyTensor(out);
        }
        if (allToAllOut != nullptr) {
            aclDestroyTensor(allToAllOut);
        }
        if (x1DeviceAddr != nullptr) {
            aclrtFree(x1DeviceAddr);
        }
        if (x2DeviceAddr != nullptr) {
            aclrtFree(x2DeviceAddr);
        }
        if (biasDeviceAddr != nullptr) {
            aclrtFree(biasDeviceAddr);
        }
        if (outDeviceAddr != nullptr) {
            aclrtFree(outDeviceAddr);
        }
        if (workspaceSize > 0) {
            aclrtFree(workspaceAddr);
        }
        aclrtDestroyStream(args.stream);
        HcclCommDestroy(args.hcclComm);
        aclrtDestroyContext(args.context);
        aclrtResetDevice(args.rankId);
        return 0;
    }
    
    int main(int argc, char *argv[])
    {
    // This sample is implemented based on Ascend 950PR&950DT products and must run on Ascend 950PR&950DT products.
    int ret = aclInit(nullptr);
    int32_t devices[ndev];
    for (int i = 0; i < ndev; i++) {
    devices[i] = i;
    }
    HcclComm comms[128];
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return ret);
    // Initialize the communicator.
    for (int i = 0; i < ndev; i++) {
    ret = aclrtSetDevice(devices[i]);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
    }
    ret = HcclCommInitAll(ndev, devices, comms);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("HcclCommInitAll failed. ERROR: %d\n", ret); return ret);
    Args args[ndev];
    aclrtStream stream[ndev];
    aclrtContext context[ndev];
    for (uint32_t rankId = 0; rankId < ndev; rankId++) {
    ret = aclrtSetDevice(rankId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return ret);
    ret = aclrtCreateContext(&context[rankId], rankId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateContext failed. ERROR: %d\n", ret); return ret);
    ret = aclrtCreateStream(&stream[rankId]);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return ret);
    }
    // Start multiple threads.
    std::vector<std::unique_ptr<std::thread>> threads(ndev);
    for (uint32_t rankId = 0; rankId < ndev; 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::nothrow) std::thread(&launchOneThreadAlltoAllQuantMatmul, std::ref(args[rankId])));
    }
    for (uint32_t rankId = 0; rankId < ndev; rankId++) {
    threads[rankId]->join();
    }
    aclFinalize();
    return 0;
    }