1# Copyright 2020 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.parameter import Parameter 22from mindspore.nn.optim import Momentum 23from mindspore.ops import operations as P 24from mindspore.train import Model 25from tests.dataset_mock import MindData 26 27context.set_context(mode=context.GRAPH_MODE) 28 29 30class Dataset(MindData): 31 def __init__(self, predict, label, length=3): 32 super(Dataset, self).__init__(size=length) 33 self.predict = predict 34 self.label = label 35 self.index = 0 36 self.length = length 37 38 def __iter__(self): 39 return self 40 41 def __next__(self): 42 if self.index >= self.length: 43 raise StopIteration 44 self.index += 1 45 return self.predict, self.label 46 47 def reset(self): 48 self.index = 0 49 50 51class CommonNet(nn.Cell): 52 def __init__(self): 53 super(CommonNet, self).__init__() 54 self.weight = Parameter(Tensor(np.ones([256, 64]), dtype=ms.float32), name="mul_weight") 55 self.logicalnot = P.LogicalNot().shard(((4, 2),)) 56 self.equal = P.Equal().shard(((4, 2), (4, 2))) 57 58 def construct(self, x, label): 59 x = self.equal(x, self.weight) 60 x = self.logicalnot(x) 61 return x 62 63 64def common_net(): 65 epoch_size = 1 66 67 context.reset_auto_parallel_context() 68 69 context.set_auto_parallel_context(parallel_mode="semi_auto_parallel", device_num=8) 70 predict = Tensor(np.ones([32, 64]), dtype=ms.float32) 71 label = Tensor(np.ones([32]), dtype=ms.int32) 72 dataset = Dataset(predict, label, 2) 73 net = CommonNet() 74 75 optimizer = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9) 76 model = Model(net, optimizer=optimizer) 77 model.train(epoch_size, dataset, dataset_sink_mode=False) 78 79 80def test_bool_grad(): 81 common_net() 82