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

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