• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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):
37        predict = self.network(x, y, b)
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):
47        return grad_all(self.network)(x, y, b)
48
49
50# model_parallel test
51def test_batch_parallel_dropout():
52    class Net(nn.Cell):
53        def __init__(self):
54            super().__init__()
55            self.matmul1 = P.MatMul()
56            self.dropout = nn.Dropout()
57            self.matmul2 = P.MatMul()
58
59        def construct(self, x, y, b):
60            out = self.matmul1(x, y)
61            out = self.dropout(out)
62            out = self.matmul2(out, b)
63            return out
64
65    context.set_auto_parallel_context(device_num=8, global_rank=0)
66    net = GradWrap(NetWithLoss(Net()))
67    context.set_auto_parallel_context(parallel_mode="semi_auto_parallel")
68    net.set_auto_parallel()
69
70    x = Tensor(np.ones([128, 32]), dtype=ms.float32)
71    y = Tensor(np.ones([32, 64]), dtype=ms.float32)
72    b = Tensor(np.ones([64, 64]), dtype=ms.float32)
73    net.set_train()
74    _cell_graph_executor.compile(net, x, y, b)
75