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 as ms 18from mindspore import context, Tensor, Parameter 19from mindspore.common.api import _cell_graph_executor 20from mindspore.nn import Cell 21from mindspore.ops import operations as P 22 23 24class Net(Cell): 25 def __init__(self, mul_weight, strategy1=None, strategy2=None): 26 super().__init__() 27 self.mul = P.Mul().shard(strategy1) 28 self.neg = P.Neg().shard(strategy2) 29 self.mul_weight = Parameter(mul_weight, "w1") 30 31 def construct(self, x, b): 32 out = self.mul(x, self.mul_weight) 33 out = self.neg(out) 34 return out 35 36 37class EvalNet(Cell): 38 def __init__(self, network, strategy2=None): 39 super().__init__() 40 self.network = network 41 self.relu = P.ReLU().shard(strategy2) 42 43 def construct(self, x, b): 44 out = self.network(x, b) 45 out1 = self.relu(out) 46 return out, out1 47 48 49_x = Tensor(np.ones([64, 64]), dtype=ms.float32) 50_w1 = Tensor(np.ones([64, 64]), dtype=ms.float32) 51_b = Tensor(np.ones([64, 64]), dtype=ms.float32) 52 53 54def test_train_and_eval(): 55 context.set_context(mode=0) 56 context.set_auto_parallel_context(parallel_mode="semi_auto_parallel", device_num=16) 57 strategy1 = ((4, 4), (4, 4)) 58 strategy2 = ((4, 4),) 59 net = Net(_w1, strategy1, strategy2) 60 eval_net = EvalNet(net, strategy2=strategy2) 61 net.set_auto_parallel() 62 net.set_train() 63 _cell_graph_executor.compile(net, _x, _b, phase='train', auto_parallel_mode=True) 64 65 eval_net.set_train(mode=False) 66 eval_net.set_auto_parallel() 67 _cell_graph_executor.compile(eval_net, _x, _b, phase='eval', auto_parallel_mode=True) 68 69 context.reset_auto_parallel_context() 70 71def test_train_and_eval_auto(): 72 context.set_context(mode=0) 73 context.set_auto_parallel_context(parallel_mode="auto_parallel", device_num=16) 74 strategy1 = ((4, 4), (4, 4)) 75 strategy2 = ((4, 4),) 76 net = Net(_w1, strategy1, strategy2) 77 eval_net = EvalNet(net, strategy2=strategy2) 78 net.set_auto_parallel() 79 net.set_train() 80 _cell_graph_executor.compile(net, _x, _b, phase='train', auto_parallel_mode=True) 81 82 eval_net.set_train(mode=False) 83 eval_net.set_auto_parallel() 84 _cell_graph_executor.compile(eval_net, _x, _b, phase='eval', auto_parallel_mode=True) 85 86 context.reset_auto_parallel_context() 87