• 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.context as context
18import mindspore.nn as nn
19from mindspore import Tensor, Parameter
20from mindspore.common.api import _cell_graph_executor
21from mindspore.communication.management import init
22from mindspore.nn import Dense
23from mindspore.nn import Momentum
24from mindspore.nn import TrainOneStepCell, WithLossCell
25from mindspore.ops import operations as P
26from mindspore.context import ParallelMode
27from mindspore.communication._comm_helper import GlobalComm
28
29class Net(nn.Cell):
30    def __init__(self, input_channel, out_channel):
31        super(Net, self).__init__()
32        weight_init1 = np.ones([64, 128]).astype(np.float32)
33        weight_init2 = np.ones([32, 64]).astype(np.float32)
34        self.weight1 = Parameter(Tensor(weight_init1), "loss_weight1", layerwise_parallel=True)
35        self.weight2 = Parameter(Tensor(weight_init2), "loss_weight2", layerwise_parallel=True)
36        self.fc = P.MatMul(transpose_b=True)
37        self.dense = Dense(input_channel, out_channel)
38
39    def construct(self, x):
40        x = self.dense(x)
41        x = self.fc(x, self.weight1)
42        x = self.fc(x, self.weight2)
43        return x
44
45
46def test_dense_gen_graph():
47    context.set_context(mode=context.GRAPH_MODE)
48    context.reset_auto_parallel_context()
49    context.set_auto_parallel_context(parallel_mode=ParallelMode.HYBRID_PARALLEL, gradients_mean=True, device_num=8)
50    GlobalComm.CHECK_ENVS = False
51    init()
52    GlobalComm.CHECK_ENVS = True
53    network = Net(512, 128)
54
55    loss_fn = nn.SoftmaxCrossEntropyWithLogits()
56    optimizer = Momentum(filter(lambda x: x.requires_grad, network.get_parameters()),
57                         learning_rate=0.1,
58                         momentum=0.9)
59    network = WithLossCell(network, loss_fn)
60    network = TrainOneStepCell(network, optimizer)
61
62    predict = Tensor(np.ones([64, 512]).astype(np.float32) * 0.01)
63    label = Tensor(np.zeros([64, 32]).astype(np.float32))
64    network.set_auto_parallel()
65    _cell_graph_executor.compile(network, predict, label)
66