1# Copyright 2019 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, NCCL_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='GPU') 26 27init() 28rank = get_rank() 29size = get_group_size() 30x = np.ones([size, 1, 3, 3]).astype(np.float32) * 0.01 * (rank + 1) 31 32 33class Net(nn.Cell): 34 def __init__(self): 35 super(Net, self).__init__() 36 self.x = Parameter(initializer(Tensor(x), x.shape), name='x') 37 38 self.op0 = "sum" 39 self.op1 = "max" 40 self.op2 = "min" 41 self.op3 = "prod" 42 43 self.reduce_scatter1 = P.ReduceScatter(self.op0, group=NCCL_WORLD_COMM_GROUP) 44 self.reduce_scatter2 = P.ReduceScatter(self.op1, group=NCCL_WORLD_COMM_GROUP) 45 self.reduce_scatter3 = P.ReduceScatter(self.op2, group=NCCL_WORLD_COMM_GROUP) 46 47 def construct(self): 48 return (self.reduce_scatter1(self.x), 49 self.reduce_scatter2(self.x), 50 self.reduce_scatter3(self.x)) 51 52 53def test_ReduceScatter(): 54 reduce_scatter = Net() 55 output = reduce_scatter() 56 57 sum_ones = np.ones([size, 1, 3, 3]).astype(np.float32) * 0 58 for i in range(size): 59 sum_ones += np.ones([size, 1, 3, 3]).astype(np.float32) * 0.01 * (i + 1) 60 expect0 = sum_ones[rank: rank + 1] 61 diff0 = output[0].asnumpy() - expect0 62 error0 = np.ones(shape=expect0.shape) * 1.0e-5 63 assert np.all(diff0 < error0) 64 assert output[0].shape == expect0.shape 65 66 expect1 = np.ones([1, 1, 3, 3]).astype(np.float32) * 0.01 * size 67 diff1 = output[1].asnumpy() - expect1 68 error1 = np.ones(shape=expect1.shape) * 1.0e-5 69 assert np.all(diff1 < error1) 70 assert output[1].shape == expect1.shape 71 72 expect2 = np.ones([1, 1, 3, 3]).astype(np.float32) * 0.01 * 1 73 diff2 = output[2].asnumpy() - expect2 74 error2 = np.ones(shape=expect2.shape) * 1.0e-5 75 assert np.all(diff2 < error2) 76 assert output[2].shape == expect2.shape 77