• 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 functional as F
24from mindspore.ops import operations as P
25
26
27grad_all = C.GradOperation(get_all=True)
28
29
30class GradWrap(nn.Cell):
31    def __init__(self, network):
32        super(GradWrap, self).__init__()
33        self.network = network
34
35    def construct(self, x, y):
36        return grad_all(self.network)(x, y)
37
38
39def test_sum_as_loss():
40    class Net(nn.Cell):
41        def __init__(self, strategy0, strategy1):
42            super().__init__()
43            self.fc_nobias = P.MatMul(transpose_b=True).shard(strategy0)
44            self.reduce_sum = P.ReduceSum(keep_dims=False).shard(strategy1)
45            self.mul = P.Mul().shard(strategy=((), ()))
46
47        def construct(self, x, y):
48            out = self.fc_nobias(x, y)
49            out = self.reduce_sum(out, (0, 1))
50            out = self.mul(out, F.scalar_to_array(2.0))
51            return out
52
53    context.set_auto_parallel_context(device_num=16, global_rank=0)
54
55    strategy0 = ((4, 1), (4, 1))
56    strategy1 = ((4, 1),)
57    net = GradWrap(Net(strategy0, strategy1))
58    context.set_auto_parallel_context(parallel_mode="semi_auto_parallel")
59    net.set_auto_parallel()
60
61    x = Tensor(np.ones([64, 32]), dtype=ms.float32)
62    y = Tensor(np.ones([64, 32]), dtype=ms.float32)
63    net.set_train()
64    _cell_graph_executor.compile(net, x, y)
65