1# Copyright 2024 Huawei Technologies Co., Ltd 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================ 15 16"""test lccl allreduce with 8p""" 17 18import os 19import numpy as np 20 21import mindspore.context as context 22import mindspore.nn as nn 23from mindspore import Tensor 24from mindspore.common.initializer import initializer 25from mindspore.common.parameter import Parameter 26from mindspore.communication.management import init, HCCL_WORLD_COMM_GROUP, get_rank, get_group_size 27from mindspore.ops import operations as P 28 29context.set_context(mode=context.GRAPH_MODE, device_target='Ascend') 30context.set_context(jit_level='O0') 31 32init() 33rank = get_rank() 34size = get_group_size() 35x = Tensor(np.random.rand(32, 4096).astype(np.float16)*0.01) 36weight1 = np.random.rand(4096, 2048).astype(np.float16)*0.01 37weight2 = np.random.rand(2048, 16).astype(np.float16)*0.01 38 39 40class Net(nn.Cell): 41 def __init__(self): 42 super(Net, self).__init__() 43 self.weight1 = Parameter(initializer( 44 Tensor(weight1), weight1.shape), name='weight1') 45 self.weight2 = Parameter(initializer( 46 Tensor(weight2), weight2.shape), name='weight2') 47 self.matmul1 = P.MatMul() 48 self.matmul2 = P.MatMul() 49 50 self.op0 = "sum" 51 self.op1 = "sum" 52 53 self.all_reduce1 = P.AllReduce(self.op0, group=HCCL_WORLD_COMM_GROUP) 54 self.all_reduce2 = P.AllReduce(self.op1, group=HCCL_WORLD_COMM_GROUP) 55 56 def construct(self, input_x): 57 output = self.matmul1(input_x, self.weight1) 58 output = self.all_reduce1(output) 59 output = output * 0.01 60 output = self.matmul2(output, self.weight2) 61 output = self.all_reduce2(output) 62 return output 63 64 65def test_MatMulAllReduce(): 66 """ 67 Feature: lccl MatMulAllReduce fustion operator test. 68 Description: lccl MatMulAllReduce 8P case. 69 Expectation: success 70 """ 71 os.environ["DISABLE_MATMUL_ALLREDUCE_FUSION"] = "True" 72 mmar_no_fusion_net = Net() 73 output_no_fusion = mmar_no_fusion_net(x) 74 75 os.environ["DISABLE_MATMUL_ALLREDUCE_FUSION"] = "False" 76 mmar_fusion_net = Net() 77 mmar_fusion_net.phase = "prefill" 78 output_fusion = mmar_fusion_net(x) 79 80 print(output_no_fusion.asnumpy(), output_fusion.asnumpy(), 81 output_no_fusion.asnumpy() - output_fusion.asnumpy()) 82