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, Parameter 20from mindspore.communication.management import init 21from mindspore.ops import operations as P 22from mindspore.communication._comm_helper import GlobalComm 23 24class DataParallelNet(nn.Cell): 25 def __init__(self): 26 super(DataParallelNet, self).__init__() 27 weight_init = np.random.rand(512, 64).astype(np.float32) 28 self.weight = Parameter(Tensor(weight_init), name="weight", layerwise_parallel=False) 29 self.fc = P.MatMul() 30 31 def construct(self, x): 32 x = self.fc(x, self.weight) 33 return x 34 35 36class ModelParallelNet(nn.Cell): 37 def __init__(self): 38 super(ModelParallelNet, self).__init__() 39 weight_init = np.random.rand(512, 64).astype(np.float32) 40 self.weight = Parameter(Tensor(weight_init), name="weight", layerwise_parallel=True) 41 self.fc = P.MatMul() 42 43 def construct(self, x): 44 x = self.fc(x, self.weight) 45 return x 46 47 48def test_param_broadcast(): 49 context.set_context(mode=context.GRAPH_MODE) 50 context.reset_auto_parallel_context() 51 context.set_auto_parallel_context(parallel_mode="data_parallel", parameter_broadcast=True) 52 GlobalComm.CHECK_ENVS = False 53 init() 54 GlobalComm.CHECK_ENVS = True 55 network = DataParallelNet() 56 network.set_train() 57 58 predict = Tensor(np.ones([64, 512]).astype(np.float32) * 0.01) 59 _ = network(predict) 60 context.reset_auto_parallel_context() 61 62 63def test_param_not_broadcast(): 64 context.set_context(mode=context.GRAPH_MODE) 65 context.reset_auto_parallel_context() 66 context.set_auto_parallel_context(parallel_mode="data_parallel", parameter_broadcast=False) 67 GlobalComm.CHECK_ENVS = False 68 init() 69 GlobalComm.CHECK_ENVS = True 70 network = ModelParallelNet() 71 network.set_train() 72 73 predict = Tensor(np.ones([64, 512]).astype(np.float32) * 0.01) 74 _ = network(predict) 75 context.reset_auto_parallel_context() 76