1# Copyright 2020 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, 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([3, 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.x1 = Parameter(initializer(Tensor(x), x.shape), name='x1') 37 self.x2 = Parameter(initializer(Tensor(x), x.shape), name='x2') 38 self.x3 = Parameter(initializer(Tensor(x), x.shape), name='x3') 39 40 self.broadcast1 = P.Broadcast(0) 41 self.broadcast2 = P.Broadcast(1) 42 self.broadcast3 = P.Broadcast(2) 43 44 def construct(self): 45 return (self.broadcast1((self.x1,)), 46 self.broadcast2((self.x2,)), 47 self.broadcast3((self.x3,))) 48 49 50def test_Broadcast(): 51 broadcast = Net() 52 output = broadcast() 53 54 expect0 = np.ones([3, 1, 3, 3]).astype(np.float32) * 1 55 expect1 = np.ones([3, 1, 3, 3]).astype(np.float32) * 2 56 expect2 = np.ones([3, 1, 3, 3]).astype(np.float32) * 3 57 58 diff0 = output[0][0].asnumpy() - expect0 59 error0 = np.ones(shape=expect0.shape) * 1.0e-5 60 assert np.all(diff0 < error0) 61 assert output[0][0].shape == expect0.shape 62 63 diff1 = output[1][0].asnumpy() - expect1 64 error1 = np.ones(shape=expect1.shape) * 1.0e-5 65 assert np.all(diff1 < error1) 66 assert output[1][0].shape == expect1.shape 67 68 diff2 = output[2][0].asnumpy() - expect2 69 error2 = np.ones(shape=expect2.shape) * 1.0e-5 70 assert np.all(diff2 < error2) 71 assert output[2][0].shape == expect2.shape 72