You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_bool_grad.py 2.5 kB

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