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([1, 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.all_gather = P.AllGather(group=NCCL_WORLD_COMM_GROUP) 37 self.x = Parameter(initializer(Tensor(x), x.shape), name='x') 38 39 def construct(self): 40 return self.all_gather(self.x) 41 42 43def test_AllGather(): 44 all_gather = Net() 45 output = all_gather() 46 47 expect = np.ones([1, 1, 3, 3]).astype(np.float32) * 0.01 * (0 + 1) 48 for i in range(size - 1): 49 tmp = np.ones([1, 1, 3, 3]).astype(np.float32) * 0.01 * (i + 2) 50 expect = np.concatenate((expect, tmp)) 51 diff = np.absolute(output.asnumpy() - expect) 52 error = np.ones(shape=expect.shape) * 1.0e-5 53 assert np.all(diff < error) 54 assert output.shape == expect.shape 55