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# ============================================================================ 15import numpy as np 16 17import mindspore.context as context 18import mindspore.nn as nn 19from mindspore import Tensor 20from mindspore.common.initializer import initializer 21from mindspore.common.parameter import Parameter 22from mindspore.communication.management import init, HCCL_WORLD_COMM_GROUP, get_rank, get_group_size 23from mindspore.ops import operations as P 24 25context.set_context(mode=context.GRAPH_MODE, device_target='Ascend') 26context.set_context(jit_level='O0') 27 28init() 29rank = get_rank() 30size = get_group_size() 31x = np.ones([size, 1, 3, 3]).astype(np.float32) * 0.01 * (rank + 1) 32 33 34class Net(nn.Cell): 35 def __init__(self): 36 super(Net, self).__init__() 37 self.x = Parameter(initializer(Tensor(x), x.shape), name='x') 38 39 self.op0 = "sum" 40 self.op1 = "max" 41 self.op2 = "min" 42 self.op3 = "prod" 43 44 self.reduce_scatter1 = P.ReduceScatter(self.op0, group=HCCL_WORLD_COMM_GROUP) 45 self.reduce_scatter2 = P.ReduceScatter(self.op1, group=HCCL_WORLD_COMM_GROUP) 46 self.reduce_scatter3 = P.ReduceScatter(self.op2, group=HCCL_WORLD_COMM_GROUP) 47 48 def construct(self): 49 return (self.reduce_scatter1(self.x), 50 self.reduce_scatter2(self.x), 51 self.reduce_scatter3(self.x)) 52 53 54def test_ReduceScatter(): 55 """ 56 Feature: lccl operator test. 57 Description: msrun lccl reduce_scatter 8P case. 58 Expectation: success 59 """ 60 reduce_scatter = Net() 61 output = reduce_scatter() 62 63 sum_ones = np.ones([size, 1, 3, 3]).astype(np.float32) * 0 64 for i in range(size): 65 sum_ones += np.ones([size, 1, 3, 3]).astype(np.float32) * 0.01 * (i + 1) 66 expect0 = sum_ones[rank: rank + 1] 67 diff0 = output[0].asnumpy() - expect0 68 error0 = np.ones(shape=expect0.shape) * 1.0e-5 69 assert np.all(diff0 < error0) 70 assert output[0].shape == expect0.shape 71 72 expect1 = np.ones([1, 1, 3, 3]).astype(np.float32) * 0.01 * size 73 diff1 = output[1].asnumpy() - expect1 74 error1 = np.ones(shape=expect1.shape) * 1.0e-5 75 assert np.all(diff1 < error1) 76 assert output[1].shape == expect1.shape 77 78 expect2 = np.ones([1, 1, 3, 3]).astype(np.float32) * 0.01 * 1 79 diff2 = output[2].asnumpy() - expect2 80 error2 = np.ones(shape=expect2.shape) * 1.0e-5 81 assert np.all(diff2 < error2) 82 assert output[2].shape == expect2.shape 83