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_prelu_cell.py 3.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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. from mindspore.train import Model, ParallelMode
  15. from mindspore.nn.loss import SoftmaxCrossEntropyWithLogits
  16. from mindspore.nn.optim.momentum import Momentum
  17. from mindspore import Tensor
  18. import mindspore as ms
  19. import numpy as np
  20. from mindspore.ops import operations as P
  21. import mindspore.nn as nn
  22. from mindspore.common.parameter import Parameter
  23. from tests.dataset_mock import MindData
  24. from mindspore import context
  25. from mindspore.ops import functional as F
  26. from mindspore.common.initializer import initializer
  27. context.set_context(mode=context.GRAPH_MODE)
  28. class Dataset(MindData):
  29. def __init__(self, predict, label, length=3, input_num=2):
  30. super(Dataset, self).__init__(size=length)
  31. self.predict = predict
  32. self.label = label
  33. self.index = 0
  34. self.length = length
  35. self.input_num = input_num
  36. def __iter__(self):
  37. return self
  38. def __next__(self):
  39. if self.index >= self.length:
  40. raise StopIteration
  41. self.index += 1
  42. if self.input_num == 2:
  43. return self.predict, self.label
  44. else:
  45. return self.predict,
  46. def reset(self):
  47. self.index = 0
  48. class PReLU(nn.Cell):
  49. def __init__(self, channel=1, w=0.25):
  50. super(PReLU, self).__init__()
  51. if isinstance(w, (np.float32, float)):
  52. tmp = np.empty((channel,), dtype=np.float32)
  53. tmp.fill(w)
  54. w = Tensor(tmp)
  55. elif isinstance(w, list):
  56. w = Tensor(w)
  57. if not isinstance(w, Tensor):
  58. raise TypeError("w only support np.float32, float or Tensor type.")
  59. self.w = Parameter(initializer(w, [channel,]), name='a')
  60. self.prelu = P.PReLU()
  61. self.relu = P.ReLU().set_strategy(((1, ), ))
  62. self.sub = P.Sub().set_strategy(((1, ), (1, )))
  63. self.assign_sub = P.AssignSub().set_strategy(((1, ), (1, )))
  64. def construct(self, x):
  65. u = self.relu(self.w)
  66. tmp = self.sub(self.w, u)
  67. x = F.depend(x, self.assign_sub(self.w, tmp))
  68. v = self.prelu(x, u)
  69. return v
  70. class PReLUNet(nn.Cell):
  71. def __init__(self):
  72. super(PReLUNet, self).__init__()
  73. self.prelu = PReLU(channel=256)
  74. def construct(self, x):
  75. x = self.prelu(x)
  76. return x
  77. def prelu_net():
  78. return PReLUNet()
  79. def reshape_common(parallel_mode):
  80. batch_size = 32
  81. learning_rate = 0.1
  82. momentum = 0.9
  83. epoch_size = 2
  84. context.reset_auto_parallel_context()
  85. context.set_auto_parallel_context(parallel_mode=parallel_mode, device_num=8)
  86. predict = Tensor(np.ones([32, 256]), dtype=ms.float32)
  87. label = Tensor(np.ones([32]), dtype=ms.int32)
  88. dataset = Dataset(predict, label, 2)
  89. net = prelu_net()
  90. loss = SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
  91. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  92. model = Model(net, loss, opt)
  93. model.train(epoch_size, dataset, dataset_sink_mode=False)
  94. def test_prelu_cell():
  95. reshape_common(ParallelMode.SEMI_AUTO_PARALLEL)