aclnnMatmulReduceScatterV2
Applicable Products
Ascend 950PR&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: The aclnnMatmulReduceScatterV2 API is a functional extension of the aclnnMatmulReduceScatter API. In addition to supporting x1 and x2 inputs of type FLOAT16/BFLOAT16,
Ascend 950PR&950DT products :- Adds support for the low-precision data types FLOAT8_E4M3FN/FLOAT8_E5M2/HIFLOAT8/FLOAT4_E2M1. Supports pertensor, perblock, and mx quantization modes. For mx quantization, MXFP8 and MXFP4 quantization use cases are supported.
Atlas A3 products ,Atlas A2 products :- Adds support for the low-precision data type INT8. Supports the pertoken/perchannel quantization mode.
Formula:
Case 1: If the data types of x1 and x2 are FLOAT16/BFLOAT16, perform ReduceScatter communication after matmul computation on the input parameters x1, x2, and bias.
$$ output=ReduceScatter(x1@x2 + bias_{optional}) $$Case 2: If the data types of x1 and x2 are FLOAT8_E4M3FN/FLOAT8_E5M2/HIFLOAT8 in the pertensor scenario, or the data types of x1 and x2 are INT8 in the perchannel or pertoken scenario, and amaxOut is not output, perform ReduceScatter communication after matmul computation and dequant computation on the input parameters x1 and x2.
$$ output=ReduceScatter((x1Scale*x2Scale)*(x1@x2) + bias_{optional}) $$Case 3: If the data types of x1 and x2 are FLOAT8_E4M3FN/FLOAT8_E5M2/HIFLOAT8 in the perblock scenario, and amaxOut is not output, when the shape of x1 is (m, k), the shape of x2 is (k, n), the shape of x1Scale is (ceildiv(m, 128), ceildiv(k, 128)), and the shape of x2Scale is (ceildiv(k, 128), ceildiv(n, 128)), the inputs x1 and x2 undergo matmul calculation and dequant calculation, and then ReduceScatter communication is performed.
$$ output=ReduceScatter(\sum_{0}^{\left \lfloor \frac{k}{blockSize=128} \right \rfloor} (x1_{pr}@x2_{rq}*(x1Scale_{pr}*x2Scale_{rq}))) $$Case 4: If the data types of x1 and x2 are FLOAT8_E4M3FN/FLOAT8_E5M2/FLOAT4_E2M1 in the mx quantization scenario, and amaxOut is not output, when the shape of x1 is (m, k) and the shape of x1Scale is (m, ceildiv(k, 64), 2), the inputs x1 and x2 undergo matmul calculation and dequant calculation, and then ReduceScatter communication is performed. x2 supports the transposed/non-transposed scenarios: when x2 is transposed, the shape of x2 is (n, k) and the shape of x2Scale is (n, ceildiv(k, 64), 2); when x2 is not transposed, the shape of x2 is (k, n) and the shape of x2Scale is (ceildiv(k, 64), n, 2).
$$ output=ReduceScatter(\sum_{0}^{\left \lfloor \frac{k}{blockSize=32} \right \rfloor} (x1_{pr}@x2_{rq}*(x1Scale_{pr}*x2Scale_{rq}))) $$
Function Prototype
Each operator uses a two-phase API. Call the aclnnMatmulReduceScatterV2GetWorkspaceSize API first to obtain the workspace size required for computation and the executor containing the operator computation process, and then call the aclnnMatmulReduceScatterV2 API to perform the computation.
aclnnStatus aclnnMatmulReduceScatterV2GetWorkspaceSize(
const aclTensor* x1,
const aclTensor* x2,
const aclTensor* bias,
const aclTensor* x1Scale,
const aclTensor* x2Scale,
const aclTensor* quantScale,
int64_t blockSize,
const char* group,
const char* reduceOp,
int64_t commTurn,
int64_t streamMode,
int64_t groupSize,
const char* commMode,
aclTensor* output,
aclTensor* amaxOutOptional,
uint64_t* workspaceSize,
aclOpExecutor** executor)aclnnStatus aclnnMatmulReduceScatterV2(
void *workspace,
uint64_t workspaceSize,
aclOpExecutor *executor,
aclrtStream stream)aclnnMatmulReduceScatterV2GetWorkspaceSize
Parameters:
Parameter Input/Output Description Instruction Data Type Data Format Dimension (shape) Non-contiguous Tensor x1(aclTensor*) Input MM left matrix, which is x1 in the formula. The current version supports only two-dimensional input with shape [m, k], and only the non-transposed case. FLOAT16, BFLOAT16, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8, FLOAT4_E2M1, INT8 ND 2 × x2(aclTensor*) Input MM right matrix, which is x2 in the formula. FLOAT16, BFLOAT16, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8, FLOAT4_E2M1, INT8 ND, FRACTAL_NZ 2 √ (transposed scenarios only) bias(aclTensor*) Input Corresponds to bias in the formula. - Passing nullptr is supported.
- The current version supports only 1D inputs.
FLOAT16, BFLOAT16, FLOAT ND 1 × x1Scale(aclTensor*) Input Dequantization parameter of the matmul left matrix. Supports passing a null pointer. FLOAT16, BFLOAT16, FLOAT, FLOAT8_E8M0 ND 1-3 × x2Scale(aclTensor*) Input Dequantization parameter of the matmul right matrix. Supports nullptr input. In MX quantization use cases, x2Scale supports transposed/non-transposed input. FLOAT16, BFLOAT16, FLOAT, INT64, FLOAT8_E8M0 ND 1-3 √ (transposed use cases only) quantScale(aclTensor*) Input Quantization scale of the output matrix. Currently, only nullptr is supported. FLOAT ND 1 × blockSize (int64_t) Input Indicates the number of elements along the M and N axes of the mm output matrix that are quantized together in the corresponding direction. blockSize is concatenated from three values: blockSizeM, blockSizeN, and blockSizeK, each occupying 16 bits, calculated as blockSize = blockSizeK | blockSizeN << 16 | blockSizeM << 32. The mm output matrix does not involve the K axis, so blockSizeK is fixed to 0. The current version supports only blockSizeM=blockSizeN=0. - - - - group(char*) Input Communicator name. Obtained through the Hccl API "extern HcclResult HcclGetCommName(HcclComm comm, char* commName);", where commName is the group. - - - - reduceOp(char*) Input Type of the reduce operation. Currently, only "sum" is supported. - - - - commTurn (int64_t) Input Number of communication data splits, that is, total data volume/single communication volume. Only 0 is supported in the current version. - - - - streamMode (int64_t) Input Enumeration of the stream mode. Currently, only enum value 1 is supported. - - - - groupSize (int64_t) Input Indicates, in dequantization, how many numbers of the x1/x2 input along a dimension can be dequantized by one number of the x1Scale/x2Scale input along the corresponding dimension. The groupSize input is a concatenation of three values: groupSizeM, groupSizeN, and groupSizeK, each 16 bits. The formula is groupSize = groupSizeK | groupSizeN << 16 | groupSizeM << 32. - - - - commMode(char*) Input Communication mode. Supports "ai_cpu", "ccu", or "aiv". - - - - output(aclTensor*) Output Result of the ReduceScatter communication and MatMul computation, that is, output in the formula. Empty tensors are supported only when the output type is FLOAT16 or BFLOAT16. FLOAT16, BFLOAT16, FLOAT ND 2 × amaxOutOptional(aclTensor*) Output Maximum value result of the matmul computation, that is, amaxOut in the formula. In the current version, only nullptr or an empty tensor is supported. FLOAT ND 1 × workspaceSize (uint64_t*) Output Returns the workspace size to be requested on the device. - - - - - executor(aclOpExecutor**) Output Returns the op executor containing the operator computation flow. - - - - - Atlas A2 products ,Atlas A3 products :- x1, x2: When commMode is aiv, the data types FLOAT16, BFLOAT16, and INT8 are supported. x1 only supports the ND data format, and x2 supports the ND and FRACTAL_NZ data formats.
- bias: When commMode is aiv, if the data type of x1 and x2 is INT8, the data type of bias can be FLOAT16, BFLOAT16, or FLOAT; if the data type of x1 and x2 is FLOAT16, the data type of bias must be FLOAT16 or FLOAT; if the data type of x1 and x2 is BFLOAT16, the data type of bias must be BFLOAT16 or FLOAT.
- x1Scale: When commMode is aiv, the FLOAT data type is supported. When the data types of x1 and x2 are FLOAT16 or BFLOAT16, only nullptr is supported as input. In the pertoken scenario, the shape is (m, 1).
- x2Scale: When commMode is aiv, the data types FLOAT and INT64 are supported, and the ND data format is supported. The INT64 data type is only supported when the output data type is FLOAT16. When the data types of x1 and x2 are FLOAT16 or BFLOAT16, only nullptr is supported as input. In the perchannel scenario, the shape is (1, n).
- groupSize: The current version only supports an input of 0.
- commMode: Currently only supports aiv mode. In aiv mode, AI VECTOR cores are used to complete communication tasks. The current version only supports passing in "aiv".
- output: The supported data types are FLOAT16 and BFLOAT16. If the type of x1 is FLOAT16 or BFLOAT16, the type of output is the same as that of x1.
Ascend 950PR&950DT products :- x1 and x2: The supported data types are FLOAT16, BFLOAT16, FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8, and FLOAT4_E2M1; only ND is supported for the data format.
- bias: If the data type of x1 is FLOAT16 or BFLOAT16, the data type of bias must be FLOAT16 or BFLOAT16. If the data type of x1 is FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8, or FLOAT4_E2M1, the data type of bias must be FLOAT in the pertensor and mx quantization scenarios. In the perblock scenario, only nullptr is supported as the input.
- x1Scale: When the data types of x1 and x2 are FLOAT16 or BFLOAT16, only nullptr is supported as the input. In the pertensor scenario, the shape is [1]. In the perblock scenario, the shape is [ceildiv(m, 128), ceildiv(k, 128)]. In the pertensor and perblock scenarios, the supported data type is FLOAT. In the mx quantization scenario (MXFP8 and MXFP4), the data type is FLOAT8_E8M0 and the shape is (m, ceilDiv(k, 64), 2).
- x2Scale: When the data types of x1 and x2 are FLOAT16 or BFLOAT16, only nullptr is supported as the input. In the pertensor scenario, the shape is [1]. In the perblock scenario, the shape is [ceildiv(k, 128), ceildiv(n, 128)]. In the pertensor and perblock scenarios, the supported data type is FLOAT. In the mx scenario (MXFP8 and MXFP4), the data type is FLOAT8_E8M0, the shape is (n, ceilDiv(k, 64), 2) when x2 is transposed, and (ceilDiv(k, 64), n, 2) when x2 is not transposed.
- groupSize:
- The groupSize value is valid only when both x1Scale and x2Scale inputs are 2-dimensional or higher. In other scenarios, pass 0.
- The groupSize value supports formula deduction: the passed-in groupSize is internally decomposed into groupSizeM, groupSizeN, and groupSizeK by the following formula. If 1 or more of them is 0, groupSizeM, groupSizeN, and groupSizeK are reset based on the input shapes of x1/x2/x1Scale/x2Scale for calculation. Setting principle: if groupSizeM=0, the quantization group value in the m direction is determined by interface deduction, and the deduction formula is groupSizeM = m / scaleM (must ensure that m is divisible by scaleM), where m is the same as m in the shape of x1, and scaleM is the same as m in the shape of x1Scale; if groupSizeK=0, the quantization group value in the k direction is determined by interface deduction, and the deduction formula is groupSizeK = k / scaleK (must ensure that k is divisible by scaleK), where k is the same as k in the shape of x1, and scaleK is the same as k in the shape of x1Scale; if groupSizeN=0, the quantization group value in the n direction is determined by interface deduction, and the deduction formula is groupSizeN = n / scaleN (must ensure that n is divisible by scaleN), where n is the same as n in the shape of x2, and scaleN is the same as n in the shape of x2Scale.$$ groupSize = groupSizeK | groupSizeN << 16 | groupSizeM << 32 $$
- If the reset condition is met, in general, when both the x1Scale and x2Scale inputs are 2-dimensional and the data type is FLOAT, the value combination of [groupSizeM, groupSizeN, groupSizeK] is derived as [128, 128, 128], and the corresponding groupSize value is 549764202624; when both the x1Scale and x2Scale inputs are 3-dimensional and the data type is FLOAT8_E8M0, the value combination of [groupSizeM, groupSizeN, groupSizeK] is derived as [1, 1, 32], and the corresponding groupSize value is 4295032864.
- commMode: The current version supports "ai_cpu" or "ccu" as the input.
- output: If the type of x1 is FLOAT16 or BFLOAT16, the type of output is the same as that of x1. If the type of x1 is FLOAT8_E4M3FN, FLOAT8_E5M2, HIFLOAT8, or FLOAT4_E2M1, the supported data types are FLOAT16, BFLOAT16, and FLOAT.$$ groupSize = groupSizeK | groupSizeN << 16 | groupSizeM << 32 $$
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 x1, x2, or output is a null pointer. ACLNN_ERR_PARAM_INVALID 161002 The data format or data type of x1, x2, output, bias (if not null), x1Scale (if not null), x2Scale (if not null), or quantScale (if not null) is out of the supported range.
aclnnMatmulReduceScatterV2
Parameters:
Parameter Input/Output Description workspace Input Workspace memory address allocated on the Device. workspaceSize Input Size of the workspace allocated on the Device, obtained by the first-phase API aclnnMatmulReduceScatterV2GetWorkspaceSize.executor Input Op executor that contains the operator computation process. stream Input The stream for executing tasks. Return Value
aclnnStatus: return status code. For details, see aclnn Return Codes.
Constraints
Communication constraints:
Atlas A2 products : Only commMode "aiv" is supported, and the communication buffer must be greater than or equal to 200 MB.
Atlas A3 products : Only commMode "aiv" is supported, and the communication buffer must be greater than or equal to 200 MB.
Ascend 950PR&950DT products : In the current version, only commMode "ai_cpu" or "ccu" is supported as input.
Deterministic computation:
aclnnMatmulReduceScatterV2defaults to a deterministic implementation.
Ascend 950PR&950DT products :- Only supports transposed or non-transposed x2 matrix. The x1 matrix only supports the non-transposed scenario.
- Input x1 is 2-dimensional with shape ((m, k)), where m must be an integer multiple of the number of cards rank_size.
- The input x2 is 2-dimensional, and its viewshape must be (k, n). The axes must meet the input requirements of the mm operator, the k axes must be equal, and the value range of the k axis is [256, 65535).
- bias is 1-dimensional, with shape (n,).
- The output is 2-dimensional, with shape (m/rank_size, n), where rank_size is the number of cards.
- When the data types of x1 and x2 are FLOAT16/BFLOAT16, x1/x2 support the null tensor scenario, where m and n can be null, k cannot be null, and the following conditions must be met:
- m is null, k is not null, and n is not null.
- m is not null, k is not null, and n is null.
- m is null, k is not null, and n is null.
- When the data types of x1 and x2 are FLOAT8_E4M3FN/FLOAT8_E5M2/HIFLOAT8/FLOAT4_E2M1, empty tensors are not supported.
- When the data types of x1 and x2 are FLOAT16/BFLOAT16/HIFLOAT8/FLOAT4_E2M1, the data types of x1 and x2 must be consistent.
- When the data types of x1 and x2 are FLOAT8_E4M3FN/FLOAT8_E5M2, the data types of x1 and x2 can be either of them.
- In the mx quantization scenario, x2/x2Scale supports transposed/non-transposed input.
- In the mx quantization scenario, when x1 and x2 are FLOAT4_E2M1 (MXFP4 quantization) inputs, k must be an even number. When x2 is a non-transpose input, n must also be an even number.
- Supports 2, 4, 8, 16, 32, and 64 devices; supports CCU communication and AICPU communication. CCU only supports interconnection within the UB domain of a single machine, and AICPU supports interconnection across machines within the UB domain.
- The total amount of ReduceScatter collective communication data cannot exceed 16 * 256MB. The total amount is calculated as follows: m * n * sizeof(output_dtype). Because the internal implementation may vary with the shape, the actual supported total communication amount may be slightly smaller than this value.
Atlas A3 products andAtlas A2 products :- Only supports transposed or non-transposed x2 matrix. The x1 matrix only supports the non-transposed scenario.
- Input x1 is 2-dimensional with shape ((m, k)), where m must be an integer multiple of the number of cards rank_size.
- Input x2 must be 2-dimensional, with shape (k, n). The axes meet the mm operator input parameter requirements, the k axes are equal, and the k-axis value range is ([256, 65535)).
- bias is 1-dimensional, with shape (n,).
- The output is 2-dimensional, with shape (m/rank_size, n), where rank_size is the number of cards.
- Empty tensors are not supported.
- The data types of x1 and x2 must remain consistent.
- Supports 2, 4, and 8 cards.
Example
The following sample code is for reference only. For details about how to compile and run the sample, see Compile and Run Samples.
NOTE: This sample code calls some HCCL collective communication library APIs: HcclGetCommName, HcclCommInitAll, and HcclCommDestroy. For details, see <<HCCL API (C)>>.
Atlas A2 products andAtlas A3 products :#include <iostream> #include <vector> #include <thread> #include "hccl/hccl.h" #include "aclnn/opdev/fp16_t.h" #include "aclnnop/aclnn_matmul_reduce_scatter_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) constexpr int DEV_NUM = 2; 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; }; int LaunchOneThreadMmReduceScatterV2(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); LOG_PRINT("[INFO] rank = %d, hcomName = %s, stream = %p\n", args.rankId, hcomName, args.stream); std::vector<int64_t> x1Shape = {1024, 256}; std::vector<int64_t> x2Shape = {256, 512}; std::vector<int64_t> biasShape = {512}; std::vector<int64_t> x1ScaleShape = {1024}; std::vector<int64_t> x2ScaleShape = {512}; std::vector<int64_t> outShape = {1024 / DEV_NUM, 512}; void *x1DeviceAddr = nullptr; void *x2DeviceAddr = nullptr; void *biasDeviceAddr = nullptr; void *x1ScaleDeviceAddr = nullptr; void *x2ScaleDeviceAddr = nullptr; void *outDeviceAddr = nullptr; aclTensor *x1 = nullptr; aclTensor *x2 = nullptr; aclTensor *bias = nullptr; aclTensor *x1Scale = nullptr; aclTensor *x2Scale = nullptr; aclTensor *quantScale = nullptr; aclTensor *out = nullptr; aclTensor *amaxOut = nullptr; int32_t commTurn = 0; int32_t streamMode = 1; int32_t blockSize = 0; int32_t groupSize = 0; uint64_t workspaceSize = 0; aclOpExecutor *executor = nullptr; void *workspaceAddr = nullptr; long long x1ShapeSize = GetShapeSize(x1Shape); long long x2ShapeSize = GetShapeSize(x2Shape); long long biasShapeSize = GetShapeSize(biasShape); long long x1ScaleShapeSize = GetShapeSize(x1ScaleShape); long long x2ScaleShapeSize = GetShapeSize(x2ScaleShape); long long outShapeSize = GetShapeSize(outShape); std::vector<int8_t> x1HostData(x1ShapeSize, 0); std::vector<int8_t> x2HostData(x2ShapeSize, 0); std::vector<int32_t> biasHostData(biasShapeSize, 0); std::vector<float> x1ScaleHostData(x1ScaleShapeSize, 0); std::vector<float> x2ScaleHostData(x2ScaleShapeSize, 0); std::vector<op::fp16_t> outHostData(outShapeSize, 0); // Create a tensor. ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_INT8, &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_FLOAT, &bias); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(x1ScaleHostData, x1ScaleShape, &x1ScaleDeviceAddr, aclDataType::ACL_FLOAT, &x1Scale); 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); // Call the first-phase API. ret = aclnnMatmulReduceScatterV2GetWorkspaceSize( x1, x2, bias, x1Scale, x2Scale, quantScale, blockSize, hcomName, "sum", commTurn, streamMode, groupSize, "aiv", out, amaxOut, &workspaceSize, &executor); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnMatmulReduceScatterV2GetWorkspaceSize failed. ret = %d \n", ret); return ret); // Allocate device memory based on 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("[ERROR] aclrtMalloc workspace failed. ret = %d \n", ret); return ret); } // Call the second-phase API. ret = aclnnMatmulReduceScatterV2(workspaceAddr, workspaceSize, executor, args.stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnMatmulReduceScatterV2 failed. ret = %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("[ERROR] aclrtSynchronizeStreamWithTimeout failed. ret = %d \n", ret); return ret); LOG_PRINT("[INFO] device_%d aclnnMatmulReduceScatterV2 execute successfully.\n", args.rankId); // Release device resources. Modify as required by the specific API definition. if (x1 != nullptr) { aclDestroyTensor(x1); } if (x2 != nullptr) { aclDestroyTensor(x2); } if (bias != nullptr) { aclDestroyTensor(bias); } if (x1Scale != nullptr) { aclDestroyTensor(x1Scale); } if (x2Scale != nullptr) { aclDestroyTensor(x2Scale); } if (quantScale != nullptr) { aclDestroyTensor(quantScale); } if (out != nullptr) { aclDestroyTensor(out); } if (amaxOut != nullptr) { aclDestroyTensor(amaxOut); } if (x1DeviceAddr != nullptr) { aclrtFree(x1DeviceAddr); } if (x2DeviceAddr != nullptr) { aclrtFree(x2DeviceAddr); } if (biasDeviceAddr != nullptr) { aclrtFree(biasDeviceAddr); } if (x1ScaleDeviceAddr != nullptr) { aclrtFree(x1ScaleDeviceAddr); } if (x2ScaleDeviceAddr != nullptr) { aclrtFree(x2ScaleDeviceAddr); } if (outDeviceAddr != nullptr) { aclrtFree(outDeviceAddr); } if (workspaceSize > 0) { aclrtFree(workspaceAddr); } ret = HcclCommDestroy(args.hcclComm); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclCommDestroy failed. ret = %d \n", ret); return ret); ret = aclrtDestroyStream(args.stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtDestroyStream failed. ret = %d \n", ret); return ret); ret = aclrtResetDevice(args.rankId); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtResetDevice failed. ret = %d \n", ret); return ret); ret = aclrtDestroyContext(args.context); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtDestroyContext failed. ret = %d \n", ret); return ret); 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[DEV_NUM]; aclrtContext context[DEV_NUM]; for (uint32_t rankId = 0; rankId < DEV_NUM; 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("aclrtCreateContext failed. ERROR: %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[DEV_NUM]; for (int i = 0; i < DEV_NUM; i++) { devices[i] = i; } // Initialize the communicator. HcclComm comms[DEV_NUM]; ret = HcclCommInitAll(DEV_NUM, devices, comms); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclCommInitAll failed. ret = %d \n", ret); return ret); Args args[DEV_NUM]; // Start multiple threads. std::vector<std::unique_ptr<std::thread>> threads(DEV_NUM); for (uint32_t rankId = 0; rankId < DEV_NUM; rankId++) { args[rankId].rankId = rankId; args[rankId].hcclComm = comms[rankId]; args[rankId].context = context[rankId]; args[rankId].stream = stream[rankId]; threads[rankId].reset(new(std::nothrow) std::thread(&LaunchOneThreadMmReduceScatterV2, std::ref(args[rankId]))); } for (uint32_t rankId = 0; rankId < DEV_NUM; rankId++) { threads[rankId]->join(); } aclFinalize(); return 0; }
Ascend 950PR&950DT products :#include <iostream> #include <vector> #include <thread> #include <cstdlib> #include <cstring> #include "hccl/hccl.h" #include "aclnnop/aclnn_matmul_reduce_scatter_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) constexpr int DEV_NUM = 2; constexpr const char *COMM_MODE = "ccu"; 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; }; int LaunchOneThreadMmReduceScatterV2(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); LOG_PRINT("[INFO] rank = %d, hcomName = %s, stream = %p\n", args.rankId, hcomName, args.stream); std::vector<int64_t> x1Shape = {1024, 256}; std::vector<int64_t> x2Shape = {256, 512}; std::vector<int64_t> biasShape = {512}; std::vector<int64_t> x1ScaleShape = {1}; std::vector<int64_t> x2ScaleShape = {1}; std::vector<int64_t> outShape = {1024 / DEV_NUM, 512}; void *x1DeviceAddr = nullptr; void *x2DeviceAddr = nullptr; void *biasDeviceAddr = nullptr; void *x1ScaleDeviceAddr = nullptr; void *x2ScaleDeviceAddr = nullptr; void *outDeviceAddr = nullptr; aclTensor *x1 = nullptr; aclTensor *x2 = nullptr; aclTensor *bias = nullptr; aclTensor *x1Scale = nullptr; aclTensor *x2Scale = nullptr; aclTensor *quantScale = nullptr; aclTensor *out = nullptr; aclTensor *amaxOut = nullptr; int32_t commTurn = 0; int32_t streamMode = 1; int32_t blockSize = 0; int32_t groupSize = 0; uint64_t workspaceSize = 0; aclOpExecutor *executor = nullptr; void *workspaceAddr = nullptr; long long x1ShapeSize = GetShapeSize(x1Shape); long long x2ShapeSize = GetShapeSize(x2Shape); long long biasShapeSize = GetShapeSize(biasShape); long long x1ScaleShapeSize = GetShapeSize(x1ScaleShape); long long x2ScaleShapeSize = GetShapeSize(x2ScaleShape); long long outShapeSize = GetShapeSize(outShape); std::vector<int8_t> x1HostData(x1ShapeSize, 0); std::vector<int8_t> x2HostData(x2ShapeSize, 0); std::vector<int32_t> biasHostData(biasShapeSize, 0); std::vector<int32_t> x1ScaleHostData(x1ScaleShapeSize, 0); std::vector<int32_t> x2ScaleHostData(x2ScaleShapeSize, 0); std::vector<int16_t> outHostData(outShapeSize, 0); // Create a tensor. ret = CreateAclTensor(x1HostData, x1Shape, &x1DeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &x1); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(x2HostData, x2Shape, &x2DeviceAddr, aclDataType::ACL_FLOAT8_E4M3FN, &x2); CHECK_RET(ret == ACL_SUCCESS, return ret); ret = CreateAclTensor(x1ScaleHostData, x1ScaleShape, &x1ScaleDeviceAddr, aclDataType::ACL_FLOAT, &x1Scale); 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); // Call the first-phase API. ret = aclnnMatmulReduceScatterV2GetWorkspaceSize( x1, x2, bias, x1Scale, x2Scale, quantScale, blockSize, hcomName, "sum", commTurn, streamMode, groupSize, COMM_MODE, out, amaxOut, &workspaceSize, &executor); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnMatmulReduceScatterV2GetWorkspaceSize failed. ret = %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("[ERROR] aclrtMalloc workspace failed. ret = %d \n", ret); return ret); } // Call the second-phase API. ret = aclnnMatmulReduceScatterV2(workspaceAddr, workspaceSize, executor, args.stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclnnMatmulReduceScatterV2 failed. ret = %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("[ERROR] aclrtSynchronizeStreamWithTimeout failed. ret = %d \n", ret); return ret); LOG_PRINT("[INFO] device_%d aclnnMatmulReduceScatterV2 execute successfully.\n", args.rankId); // Release device resources. Modify it based on the specific API definition. if (x1 != nullptr) { aclDestroyTensor(x1); } if (x2 != nullptr) { aclDestroyTensor(x2); } if (bias != nullptr) { aclDestroyTensor(bias); } if (x1Scale != nullptr) { aclDestroyTensor(x1Scale); } if (x2Scale != nullptr) { aclDestroyTensor(x2Scale); } if (quantScale != nullptr) { aclDestroyTensor(quantScale); } if (out != nullptr) { aclDestroyTensor(out); } if (amaxOut != nullptr) { aclDestroyTensor(amaxOut); } if (x1DeviceAddr != nullptr) { aclrtFree(x1DeviceAddr); } if (x2DeviceAddr != nullptr) { aclrtFree(x2DeviceAddr); } if (biasDeviceAddr != nullptr) { aclrtFree(biasDeviceAddr); } if (x1ScaleDeviceAddr != nullptr) { aclrtFree(x1ScaleDeviceAddr); } if (x2ScaleDeviceAddr != nullptr) { aclrtFree(x2ScaleDeviceAddr); } if (outDeviceAddr != nullptr) { aclrtFree(outDeviceAddr); } if (workspaceSize > 0) { aclrtFree(workspaceAddr); } ret = HcclCommDestroy(args.hcclComm); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclCommDestroy failed. ret = %d \n", ret); return ret); ret = aclrtDestroyStream(args.stream); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtDestroyStream failed. ret = %d \n", ret); return ret); ret = aclrtResetDevice(args.rankId); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtResetDevice failed. ret = %d \n", ret); return ret); ret = aclrtDestroyContext(args.context); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclrtDestroyContext failed. ret = %d \n", ret); return ret); return 0; } int main(int argc, char *argv[]) { class EnvGuard { public: EnvGuard(const char *key, const char *val, bool enable = true) : key_(enable ? key : nullptr) { if (!enable) return; const char *old = getenv(key); if (old != nullptr) { strncpy(saved_, old, sizeof(saved_) - 1); } setenv(key, val, 1); } ~EnvGuard() { if (key_ == nullptr) return; if (saved_[0] != '\0') { setenv(key_, saved_, 1); } else { unsetenv(key_); } } private: const char *key_; char saved_[256] = {0}; }; EnvGuard envGuard("HCCL_OP_EXPANSION_MODE", "CCU_SCHED", strcmp(COMM_MODE, "ccu") == 0); int ret = aclInit(nullptr); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] aclInit failed. ret = %d \n", ret); return ret); aclrtStream stream[DEV_NUM]; aclrtContext context[DEV_NUM]; for (uint32_t rankId = 0; rankId < DEV_NUM; 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("aclrtCreateContext failed. ERROR: %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[DEV_NUM]; for (int i = 0; i < DEV_NUM; i++) { devices[i] = i; } // Initialize the collective communication communicator. HcclComm comms[DEV_NUM]; ret = HcclCommInitAll(DEV_NUM, devices, comms); CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("[ERROR] HcclCommInitAll failed. ret = %d \n", ret); return ret); Args args[DEV_NUM]; // Start multiple threads. std::vector<std::unique_ptr<std::thread>> threads(DEV_NUM); for (uint32_t rankId = 0; rankId < DEV_NUM; rankId++) { args[rankId].rankId = rankId; args[rankId].hcclComm = comms[rankId]; args[rankId].context = context[rankId]; args[rankId].stream = stream[rankId]; threads[rankId].reset(new(std::nothrow) std::thread(&LaunchOneThreadMmReduceScatterV2, std::ref(args[rankId]))); } for (uint32_t rankId = 0; rankId < DEV_NUM; rankId++) { threads[rankId]->join(); } aclFinalize(); return 0; }