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 as ms 18import mindspore.nn as nn 19from mindspore import Tensor 20from mindspore import context 21from mindspore.common.api import _cell_graph_executor 22from mindspore.ops import composite as C 23from mindspore.ops import operations as P 24from tests.ut.python.ops.test_math_ops import VirtualLoss 25 26 27grad_all = C.GradOperation(get_all=True) 28 29 30class NetWithLoss(nn.Cell): 31 def __init__(self, network): 32 super(NetWithLoss, self).__init__() 33 self.loss = VirtualLoss() 34 self.network = network 35 36 def construct(self, x, y, b, a): 37 predict = self.network(x, y, b, a) 38 return self.loss(predict) 39 40 41class GradWrap(nn.Cell): 42 def __init__(self, network): 43 super(GradWrap, self).__init__() 44 self.network = network 45 46 def construct(self, x, y, b, a): 47 return grad_all(self.network)(x, y, b, a) 48 49 50def test_two_matmul(): 51 class Net(nn.Cell): 52 def __init__(self, strategy1, strategy2, strategy3, strategy4): 53 super().__init__() 54 self.matmul1 = P.MatMul().shard(strategy1) 55 self.matmul2 = P.MatMul().shard(strategy2) 56 self.matmul3 = P.MatMul().shard(strategy3) 57 self.matmul4 = P.MatMul().shard(strategy4) 58 59 def construct(self, x, y, b, a): 60 out = self.matmul1(x, y) 61 out1 = self.matmul2(out, b) 62 out2 = self.matmul3(out, a) 63 out3 = self.matmul4(out1, out2) 64 return out3 65 66 context.set_auto_parallel_context(device_num=8, global_rank=0) 67 strategy1 = ((2, 2), (2, 2)) 68 strategy2 = ((1, 8), (8, 1)) 69 strategy3 = ((4, 1), (1, 2)) 70 strategy4 = ((4, 2), (2, 1)) 71 net = GradWrap(NetWithLoss(Net(strategy1, strategy2, strategy3, strategy4))) 72 context.set_auto_parallel_context(parallel_mode="semi_auto_parallel") 73 74 x = Tensor(np.ones([128, 32]), dtype=ms.float32) 75 y = Tensor(np.ones([32, 128]), dtype=ms.float32) 76 b = Tensor(np.ones([128, 128]), dtype=ms.float32) 77 a = Tensor(np.ones([128, 128]), dtype=ms.float32) 78 net.set_auto_parallel() 79 net.set_train() 80 _cell_graph_executor.compile(net, x, y, b, a) 81