• 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_l2normalize_matmul():
52    class Net(nn.Cell):
53        def __init__(self, strategy1, strategy2, strategy3):
54            super().__init__()
55            self.norm1 = P.L2Normalize(axis=0).shard(strategy1)
56            self.norm2 = P.L2Normalize(axis=0).shard(strategy1)
57            self.mul1 = P.Mul().shard(strategy2)
58            self.mul2 = P.Mul().shard(strategy3)
59
60        def construct(self, x, y, b):
61            y = self.norm1(y)
62            x = self.norm2(x)
63            out = self.mul1(x, y)
64            out = self.mul2(out, b)
65            return out
66
67    context.set_auto_parallel_context(device_num=8, global_rank=0)
68    strategy1 = ((1, 1, 4),)
69    strategy2 = ((1, 1, 4), (1, 1, 4))
70    strategy3 = ((1, 1, 8), (1, 1, 8))
71    net = GradWrap(NetWithLoss(Net(strategy1, strategy2, strategy3)))
72    context.set_auto_parallel_context(parallel_mode="semi_auto_parallel")
73    net.set_auto_parallel()
74
75    x = Tensor(np.ones([128, 32, 64]), dtype=ms.float32)
76    y = Tensor(np.ones([128, 32, 64]), dtype=ms.float32)
77    b = Tensor(np.ones([128, 32, 64]), dtype=ms.float32)
78    net.set_train()
79    _cell_graph_executor.compile(net, x, y, b)
80