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_one_hot_net.py 12 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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, Parameter
  18. from mindspore import context
  19. from mindspore.common import dtype as mstype
  20. from mindspore.common.api import _executor
  21. from mindspore.nn.cell import Cell
  22. from mindspore.nn.optim.momentum import Momentum
  23. from mindspore.ops import composite as C
  24. from mindspore.ops import functional as F
  25. from mindspore.ops import operations as P
  26. from mindspore.train import Model, ParallelMode
  27. from tests.dataset_mock import MindData
  28. from tests.ut.python.ops.test_math_ops import VirtualLoss
  29. grad_all = C.GradOperation('get_all', get_all=True)
  30. device_num = 16
  31. device_id = 2
  32. class StrategyModel():
  33. onehot_strategy = ((1, device_num), (), ())
  34. twod_strategy = ((1, device_num),)
  35. twod_strategy_m = ((device_num, 1),)
  36. scalar_twod_strategy = ((), (1, device_num))
  37. twod_scalar_strategy = ((1, device_num), ())
  38. scalar_strategy = ((),)
  39. oned_strategy = ((1,),)
  40. scalar_scalar_strategy = ((), ())
  41. twod_twod_strategy = ((1, device_num), (1, device_num))
  42. twod_twodbc_strategy = ((1, device_num), (1, 1))
  43. twodbc_twod_strategy = ((1, 1), (device_num, 1))
  44. class StrategyBatch():
  45. onehot_strategy = ((device_num, 1), (), ())
  46. twod_strategy = ((1, device_num),)
  47. twod_strategy_m = ((device_num, 1),)
  48. scalar_twod_strategy = ((), (1, device_num))
  49. twod_scalar_strategy = ((1, device_num), ())
  50. scalar_strategy = ((),)
  51. oned_strategy = ((1,),)
  52. scalar_scalar_strategy = ((), ())
  53. twod_twod_strategy = ((1, device_num), (1, device_num))
  54. twod_twodbc_strategy = ((1, device_num), (1, 1))
  55. twodbc_twod_strategy = ((1, 1), (device_num, 1))
  56. class Args():
  57. a = 1
  58. b = 2
  59. c = 3
  60. d = 4
  61. e = 5
  62. num_classes = 512
  63. emb_size = 512
  64. class SemiAutoOneHotNet(Cell):
  65. def __init__(self, args, strategy):
  66. super(SemiAutoOneHotNet, self).__init__()
  67. self.a = args.a
  68. self.b = args.b
  69. self.c = args.c
  70. self.d = args.d
  71. self.e = args.e
  72. self.cast = P.Cast()
  73. self.cast.set_strategy(strategy=strategy.twod_strategy)
  74. self.cast1 = P.Cast()
  75. self.cast1.set_strategy(strategy=strategy.twod_strategy)
  76. self.cast2 = P.Cast()
  77. self.cast2.set_strategy(strategy=strategy.twod_strategy)
  78. self.cast3 = P.Cast()
  79. self.cast3.set_strategy(strategy=strategy.scalar_strategy)
  80. self.cast4 = P.Cast()
  81. self.cast4.set_strategy(strategy=strategy.scalar_strategy)
  82. self.a_const = Tensor(self.a, dtype=mstype.float32)
  83. self.b_const = Tensor(self.b, dtype=mstype.float32)
  84. self.c_const = Tensor(self.c, dtype=mstype.float32)
  85. self.d_const = Tensor(self.d, dtype=mstype.float32)
  86. self.e_const = Tensor(self.e, dtype=mstype.float32)
  87. self.m_const_zero = Tensor(0, dtype=mstype.float32)
  88. self.a_const_one = Tensor(1, dtype=mstype.float32)
  89. self.onehot = P.OneHot()
  90. self.onehot.set_strategy(strategy=strategy.onehot_strategy)
  91. self.exp = P.Exp()
  92. self.exp.set_strategy(strategy=strategy.twod_strategy)
  93. self.exp2 = P.Exp()
  94. self.exp2.set_strategy(strategy=strategy.twod_strategy)
  95. self.exp3 = P.Exp()
  96. self.exp3.set_strategy(strategy=strategy.twod_strategy)
  97. self.mul_const = P.Mul()
  98. self.mul_const.set_strategy(strategy=strategy.scalar_twod_strategy)
  99. self.mul_const2 = P.TensorAdd()
  100. self.mul_const2.set_strategy(strategy=strategy.scalar_twod_strategy)
  101. self.mul_const3 = P.Sub()
  102. self.mul_const3.set_strategy(strategy=strategy.twod_scalar_strategy)
  103. self.mul_const4 = P.Sub()
  104. self.mul_const4.set_strategy(strategy=strategy.scalar_twod_strategy)
  105. self.mul_const5 = P.Mul()
  106. self.mul_const5.set_strategy(strategy=strategy.twod_scalar_strategy)
  107. self.mul = P.Mul()
  108. self.mul.set_strategy(strategy=strategy.twod_twod_strategy)
  109. self.mul2 = P.Mul()
  110. self.mul2.set_strategy(strategy=strategy.twod_twod_strategy)
  111. self.mul3 = P.TensorAdd()
  112. self.mul3.set_strategy(strategy=strategy.twod_twod_strategy)
  113. self.mul4 = P.Sub()
  114. self.mul4.set_strategy(strategy=strategy.twod_twodbc_strategy)
  115. self.mul5 = P.RealDiv()
  116. self.mul5.set_strategy(strategy=strategy.twod_twodbc_strategy)
  117. self.mul6 = P.Mul()
  118. self.mul6.set_strategy(strategy=strategy.twod_twod_strategy)
  119. self.mul7 = P.Mul()
  120. self.mul7.set_strategy(strategy=strategy.twod_scalar_strategy)
  121. self.mul8 = P.RealDiv()
  122. self.mul8.set_strategy(strategy=strategy.scalar_scalar_strategy)
  123. self.mul9 = P.TensorAdd()
  124. self.mul9.set_strategy(strategy=strategy.twod_scalar_strategy)
  125. self.reduce_max = P.ReduceMax(keep_dims=True)
  126. self.reduce_max.set_strategy(strategy=strategy.twod_strategy)
  127. self.reduce_sum = P.ReduceSum(keep_dims=False)
  128. self.reduce_sum.set_strategy(strategy=strategy.twod_strategy)
  129. self.reduce_sum_2 = P.ReduceSum(keep_dims=False)
  130. self.reduce_sum_2.set_strategy(strategy=strategy.twod_strategy)
  131. self.reduce_sum_3 = P.ReduceSum(keep_dims=False)
  132. self.reduce_sum_3.set_strategy(strategy=strategy.oned_strategy)
  133. self.reshape = P.Reshape()
  134. self.log = P.Log()
  135. self.log.set_strategy(strategy=strategy.twod_strategy)
  136. self.on_value = Tensor(1.0, mstype.float32)
  137. self.off_value = Tensor(0.0, mstype.float32)
  138. self.normalize = P.L2Normalize(axis=1)
  139. self.normalize.set_strategy(strategy=strategy.twod_strategy_m)
  140. self.normalize2 = P.L2Normalize(axis=1)
  141. self.normalize2.set_strategy(strategy=strategy.twod_strategy_m)
  142. self.fc = P.MatMul(transpose_b=True)
  143. self.fc.set_strategy(strategy=strategy.twodbc_twod_strategy)
  144. weight_shape = [args.num_classes, args.emb_size]
  145. weight_np = np.zeros(weight_shape, np.float32)
  146. self.weight = Parameter(Tensor(weight_np), name='model_parallel_weight')
  147. def construct(self, input_, label):
  148. input_n = self.normalize(input_)
  149. w = self.normalize2(self.weight)
  150. fc_o = self.fc(input_n, w)
  151. fc_o_shape = F.shape(fc_o)
  152. one_hot_float = self.onehot(label, fc_o_shape[1], self.on_value, self.off_value)
  153. local_label = self.cast(one_hot_float, mstype.int32)
  154. exp_o = self.exp(fc_o)
  155. mul_const_o = self.mul_const(self.a_const, exp_o)
  156. mul_const2_o = self.mul_const2(self.b_const, mul_const_o)
  157. exp2_o = self.exp2(mul_const2_o)
  158. mul_const3_o = self.mul_const3(exp2_o, self.c_const)
  159. mul_const4_o = self.mul_const4(F.scalar_to_array(1), local_label)
  160. mul6_o = self.mul6(self.mul(mul_const3_o, one_hot_float),
  161. self.mul2(fc_o, self.cast2(mul_const4_o, mstype.float32)))
  162. mul_const5_o = self.mul_const5(mul6_o, self.d_const)
  163. max_o = self.reduce_max(mul_const5_o, -1)
  164. mul4_o = self.mul4(mul_const5_o, max_o)
  165. exp3_o = self.exp3(mul4_o)
  166. sum_o = self.reduce_sum(exp3_o, -1)
  167. reshape_o = self.reshape(sum_o, (F.shape(sum_o)[0], 1))
  168. mul5_o = self.mul5(exp3_o, reshape_o)
  169. log_o = self.log(self.mul9(mul5_o, self.e_const))
  170. mul3_o = self.mul3(log_o, one_hot_float)
  171. mul7_o = self.mul7(mul3_o, self.cast3(F.scalar_to_array(-1), mstype.float32))
  172. sum2_o = self.reduce_sum_2(mul7_o, -1)
  173. loss = self.mul8(self.reduce_sum_3(sum2_o, -1),
  174. self.cast4(F.scalar_to_array(F.shape(mul_const5_o)[0]), mstype.float32))
  175. return loss
  176. class Dataset(MindData):
  177. def __init__(self, predict, label, length=3, input_num=2):
  178. super(Dataset, self).__init__(size=length)
  179. self.predict = predict
  180. self.label = label
  181. self.index = 0
  182. self.length = length
  183. self.input_num = input_num
  184. def __iter__(self):
  185. return self
  186. def __next__(self):
  187. if self.index >= self.length:
  188. raise StopIteration
  189. self.index += 1
  190. if self.input_num == 2:
  191. return (self.predict, self.label)
  192. return (self.predict,)
  193. def reset(self):
  194. self.index = 0
  195. class NetWithLoss(nn.Cell):
  196. def __init__(self, network):
  197. super(NetWithLoss, self).__init__()
  198. self.loss = VirtualLoss()
  199. self.network = network
  200. def construct(self, x, b):
  201. predict = self.network(x, b)
  202. return self.loss(predict)
  203. class GradWrap(nn.Cell):
  204. def __init__(self, network):
  205. super(GradWrap, self).__init__()
  206. self.network = network
  207. def construct(self, x, b):
  208. return grad_all(self.network)(x, b)
  209. def bn_with_initialize(out_channels):
  210. bn = nn.BatchNorm2d(out_channels, momentum=0.3, eps=1e-5).add_flags_recursive(fp32=True)
  211. return bn
  212. def fc_with_initialize(input_channels, out_channels):
  213. return nn.Dense(input_channels, out_channels)
  214. class BNReshapeDenseBNNet(nn.Cell):
  215. def __init__(self):
  216. super(BNReshapeDenseBNNet, self).__init__()
  217. self.batch_norm = bn_with_initialize(2)
  218. self.reshape = P.Reshape()
  219. self.batch_norm2 = nn.BatchNorm1d(512, affine=False)
  220. self.fc = fc_with_initialize(2 * 32 * 32, 512)
  221. self.loss = SemiAutoOneHotNet(args=Args(), strategy=StrategyBatch())
  222. def construct(self, x, label):
  223. x = self.batch_norm(x)
  224. x = self.reshape(x, (16, 2 * 32 * 32))
  225. x = self.fc(x)
  226. x = self.batch_norm2(x)
  227. loss = self.loss(x, label)
  228. return loss
  229. def test_bn_reshape_dense_bn_train_loss():
  230. batch_size = 16
  231. context.set_auto_parallel_context(device_num=device_num, global_rank=0)
  232. context.set_auto_parallel_context(parallel_mode="semi_auto_parallel")
  233. input_ = Tensor(np.ones([batch_size, 2, 32, 32]).astype(np.float32) * 0.01)
  234. label = Tensor(np.ones([batch_size]), dtype=ms.int32)
  235. net = GradWrap(NetWithLoss(BNReshapeDenseBNNet()))
  236. net.set_auto_parallel()
  237. _executor.compile(net, input_, label)
  238. def test_semi_one_hot_net_batch():
  239. batch_size = 16
  240. context.set_auto_parallel_context(device_num=device_num, global_rank=0)
  241. context.set_auto_parallel_context(parallel_mode="semi_auto_parallel")
  242. input_ = Tensor(np.ones([batch_size * 1, 512]).astype(np.float32) * 0.01)
  243. label = Tensor(np.ones([batch_size]), dtype=ms.int32)
  244. net = SemiAutoOneHotNet(args=Args(), strategy=StrategyBatch())
  245. net = GradWrap(NetWithLoss(net))
  246. net.set_auto_parallel()
  247. _executor.compile(net, input_, label)
  248. def test_semi_one_hot_net_model():
  249. batch_size = 16
  250. learning_rate = 0.1
  251. momentum = 0.9
  252. epoch_size = 2
  253. predict = Tensor(np.ones([batch_size, 512]), dtype=ms.float32)
  254. label = Tensor(np.ones([batch_size]), dtype=ms.int32)
  255. dataset = Dataset(predict, label, 2, input_num=2)
  256. context.reset_auto_parallel_context()
  257. context.set_auto_parallel_context(parallel_mode=ParallelMode.SEMI_AUTO_PARALLEL, device_num=16)
  258. context.set_context(mode=context.GRAPH_MODE)
  259. net = SemiAutoOneHotNet(args=Args(), strategy=StrategyModel())
  260. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  261. model = Model(net, optimizer=opt)
  262. model.train(epoch_size, dataset, dataset_sink_mode=False)