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_reshape.py 23 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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.api import _executor
  20. from mindspore.common.parameter import Parameter
  21. from mindspore.common.parameter import ParameterTuple
  22. from mindspore.nn.loss import SoftmaxCrossEntropyWithLogits
  23. from mindspore.nn.optim.momentum import Momentum
  24. from mindspore.ops import composite as C
  25. from mindspore.ops import functional as F
  26. from mindspore.ops import operations as P
  27. from mindspore.ops.operations.comm_ops import _VirtualDataset
  28. from mindspore.parallel import set_algo_parameters
  29. from mindspore.train import Model, ParallelMode
  30. from tests.dataset_mock import MindData
  31. from tests.ut.python.ops.test_math_ops import VirtualLoss
  32. context.set_context(mode=context.GRAPH_MODE)
  33. context.reset_auto_parallel_context()
  34. class Dataset(MindData):
  35. def __init__(self, predict, label, length=3, input_num=2):
  36. super(Dataset, self).__init__(size=length)
  37. self.predict = predict
  38. self.label = label
  39. self.index = 0
  40. self.length = length
  41. self.input_num = input_num
  42. def __iter__(self):
  43. return self
  44. def __next__(self):
  45. if self.index >= self.length:
  46. raise StopIteration
  47. self.index += 1
  48. if self.input_num == 2:
  49. return (self.predict, self.label)
  50. return (self.predict,)
  51. def reset(self):
  52. self.index = 0
  53. class ReshapeNet(nn.Cell):
  54. def __init__(self, strategy0, strategy1, strategy2):
  55. super(ReshapeNet, self).__init__()
  56. self.relu = P.ReLU().set_strategy(strategy0)
  57. self.reshape = P.Reshape().set_strategy(strategy1)
  58. self.matmul = P.MatMul().set_strategy(strategy2)
  59. self.matmul_weight = Parameter(Tensor(np.ones([25088, 256]), dtype=ms.float32), name="weight")
  60. def construct(self, x):
  61. x = self.relu(x)
  62. x = self.reshape(x, (256, 25088))
  63. x = self.matmul(x, self.matmul_weight)
  64. return x
  65. def reshape_net(strategy0, strategy1, strategy2):
  66. return ReshapeNet(strategy0=strategy0, strategy1=strategy1, strategy2=strategy2)
  67. def reshape_common(parallel_mode, strategy0, strategy1, strategy2, strategy_loss):
  68. learning_rate = 0.1
  69. momentum = 0.9
  70. epoch_size = 2
  71. context.reset_auto_parallel_context()
  72. context.set_auto_parallel_context(parallel_mode=parallel_mode, device_num=8)
  73. predict = Tensor(np.ones([32, 512, 7, 7]), dtype=ms.float32)
  74. label = Tensor(np.ones([32]), dtype=ms.int32)
  75. dataset = Dataset(predict, label, 2)
  76. net = reshape_net(strategy0, strategy1, strategy2)
  77. loss = SoftmaxCrossEntropyWithLogits(is_grad=False, sparse=True)
  78. loss.softmax_cross_entropy.set_strategy(strategy_loss)
  79. loss.one_hot.set_strategy(((8, 1), (), ()))
  80. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  81. model = Model(net, loss, opt)
  82. model.train(epoch_size, dataset, dataset_sink_mode=False)
  83. def test_reshape1():
  84. strategy0 = ((8, 1, 1, 1),)
  85. strategy1 = None
  86. strategy2 = ((8, 1), (1, 1))
  87. strategy_loss = ((8, 1), (8, 1))
  88. reshape_common(ParallelMode.SEMI_AUTO_PARALLEL, strategy0, strategy1, strategy2, strategy_loss)
  89. def test_reshape1_strategy_1():
  90. strategy0 = ((8, 1, 1, 1),)
  91. strategy1 = ((8, 1, 1, 1),)
  92. strategy2 = ((8, 1), (1, 1))
  93. strategy_loss = ((8, 1), (8, 1))
  94. try:
  95. reshape_common(ParallelMode.SEMI_AUTO_PARALLEL, strategy0, strategy1, strategy2, strategy_loss)
  96. except ValueError:
  97. pass
  98. except TypeError:
  99. pass
  100. except RuntimeError:
  101. pass
  102. def test_reshape1_strategy_2():
  103. strategy0 = ((8, 1, 1, 1),)
  104. strategy1 = ((8, 1, 1, 1),)
  105. strategy2 = ((8, 1), (1, 1))
  106. strategy_loss = ((8, 1), (8, 1))
  107. try:
  108. reshape_common(ParallelMode.AUTO_PARALLEL, strategy0, strategy1, strategy2, strategy_loss)
  109. except ValueError:
  110. pass
  111. except TypeError:
  112. pass
  113. except RuntimeError:
  114. pass
  115. def test_reshape2():
  116. strategy0 = ((8, 1, 1, 1),)
  117. strategy1 = None
  118. strategy2 = ((8, 1), (1, 1))
  119. strategy_loss = ((8, 1), (8, 1))
  120. reshape_common(ParallelMode.SEMI_AUTO_PARALLEL, strategy0, strategy1, strategy2, strategy_loss)
  121. def test_reshape3():
  122. strategy0 = ((2, 1, 1, 1),)
  123. strategy1 = None
  124. strategy2 = ((8, 1), (1, 1))
  125. strategy_loss = ((8, 1), (8, 1))
  126. reshape_common(ParallelMode.SEMI_AUTO_PARALLEL, strategy0, strategy1, strategy2, strategy_loss)
  127. def test_reshape4():
  128. strategy0 = ((1, 1, 1, 1),)
  129. strategy1 = None
  130. strategy2 = ((8, 1), (1, 1))
  131. strategy_loss = ((8, 1), (8, 1))
  132. reshape_common(ParallelMode.SEMI_AUTO_PARALLEL, strategy0, strategy1, strategy2, strategy_loss)
  133. def test_reshape5():
  134. strategy0 = ((2, 1, 1, 1),)
  135. strategy1 = None
  136. strategy2 = ((1, 8), (8, 1))
  137. strategy_loss = ((8, 1), (8, 1))
  138. reshape_common(ParallelMode.SEMI_AUTO_PARALLEL, strategy0, strategy1, strategy2, strategy_loss)
  139. def test_reshape_auto():
  140. strategy0 = None
  141. strategy1 = None
  142. strategy2 = None
  143. strategy_loss = None
  144. reshape_common(ParallelMode.AUTO_PARALLEL, strategy0, strategy1, strategy2, strategy_loss)
  145. class NetWithLoss(nn.Cell):
  146. def __init__(self, network):
  147. super(NetWithLoss, self).__init__()
  148. self.loss = VirtualLoss()
  149. self.network = network
  150. def construct(self, x):
  151. predict = self.network(x)
  152. return self.loss(predict)
  153. class GradWrap(nn.Cell):
  154. def __init__(self, network):
  155. super(GradWrap, self).__init__()
  156. self.network = network
  157. def construct(self, x):
  158. return C.grad_all(self.network)(x)
  159. class ReshapeNet1(nn.Cell):
  160. def __init__(self, strategy0):
  161. super(ReshapeNet1, self).__init__()
  162. self.virtual_dataset = _VirtualDataset()
  163. self.reshape = P.Reshape()
  164. self.matmul = P.MatMul().set_strategy(strategy0)
  165. self.matmul_weight = Parameter(Tensor(np.ones([25088, 256]), dtype=ms.float32), name="weight")
  166. self.reshape2 = P.Reshape()
  167. def construct(self, x):
  168. x = self.virtual_dataset(x)
  169. x = self.reshape(x, (256, 25088))
  170. x = self.matmul(x, self.matmul_weight)
  171. x = self.reshape2(x, (256 * 256,))
  172. return x
  173. class ReshapeNet2(nn.Cell):
  174. def __init__(self, strategy0):
  175. super(ReshapeNet2, self).__init__()
  176. self.virtual_dataset = _VirtualDataset()
  177. self.reshape = P.Reshape()
  178. self.matmul = P.MatMul().set_strategy(strategy0)
  179. self.matmul_weight = Parameter(Tensor(np.ones([25088, 256]), dtype=ms.float32), name="weight")
  180. self.reshape2 = P.Reshape()
  181. self.reduce_sum = P.ReduceSum(keep_dims=True)
  182. self.reshape3 = P.Reshape()
  183. def construct(self, x):
  184. x = self.virtual_dataset(x)
  185. x = self.reshape(x, (256, 25088))
  186. x = self.matmul(x, self.matmul_weight)
  187. x = self.reshape2(x, (256 * 256,))
  188. x = self.reduce_sum(x, -1)
  189. x = self.reshape3(x, ())
  190. return x
  191. class ReshapeNet3(nn.Cell):
  192. def __init__(self, strategy0):
  193. super(ReshapeNet3, self).__init__()
  194. self.virtual_dataset = _VirtualDataset()
  195. self.reshape = P.Reshape()
  196. self.matmul = P.MatMul().set_strategy(strategy0)
  197. self.matmul_weight = Parameter(Tensor(np.ones([25088, 256]), dtype=ms.float32), name="weight")
  198. self.reshape2 = P.Reshape()
  199. self.reduce_sum = P.ReduceSum(keep_dims=False)
  200. self.reshape3 = P.Reshape()
  201. def construct(self, x):
  202. x = self.virtual_dataset(x)
  203. x = self.reshape(x, (256, 25088))
  204. x = self.matmul(x, self.matmul_weight)
  205. x = self.reshape2(x, (256 * 256,))
  206. x = self.reduce_sum(x, -1)
  207. x = self.reshape3(x, (1, 1))
  208. return x
  209. class ReshapeNet4(nn.Cell):
  210. def __init__(self, strategy0):
  211. super(ReshapeNet4, self).__init__()
  212. self.virtual_dataset = _VirtualDataset()
  213. self.reshape = P.Reshape()
  214. self.reshape2 = P.Reshape()
  215. self.matmul = P.MatMul().set_strategy(strategy0)
  216. self.matmul_weight = Parameter(Tensor(np.ones([25088, 256]), dtype=ms.float32), name="weight")
  217. def construct(self, x):
  218. x = self.virtual_dataset(x)
  219. x = self.reshape(x, (256, 25088))
  220. w = self.reshape2(self.matmul_weight, (25088, 256))
  221. x = self.matmul(x, w)
  222. return x
  223. class ReshapeNet5(nn.Cell):
  224. def __init__(self, strategy0):
  225. super(ReshapeNet5, self).__init__()
  226. self.virtual_dataset = _VirtualDataset()
  227. self.reshape = P.Reshape()
  228. self.matmul1 = P.MatMul().set_strategy(strategy0)
  229. self.matmul1_weight = Parameter(Tensor(np.ones([25088, 256]), dtype=ms.float32), name="weight")
  230. self.matmul2 = P.MatMul().set_strategy(strategy0)
  231. def construct(self, x):
  232. x = self.virtual_dataset(x)
  233. x = self.reshape(x, (256, 25088))
  234. matmul1_o = self.matmul1(x, self.matmul1_weight)
  235. matmul2_o = self.matmul2(matmul1_o, x)
  236. return matmul2_o
  237. class ReshapeNet6(nn.Cell):
  238. def __init__(self, strategy0):
  239. super(ReshapeNet6, self).__init__()
  240. self.virtual_dataset = _VirtualDataset()
  241. self.reshape = P.Reshape()
  242. self.matmul1_1 = P.MatMul().set_strategy(strategy0)
  243. self.matmul1_2 = P.MatMul().set_strategy(strategy0)
  244. self.matmul1_weight = Parameter(Tensor(np.ones([25088, 256]), dtype=ms.float32), name="weight")
  245. self.matmul2 = P.MatMul().set_strategy(strategy0)
  246. self.add = P.TensorAdd()
  247. def construct(self, x):
  248. x = self.virtual_dataset(x)
  249. x = self.reshape(x, (256, 25088))
  250. matmul1_1_o = self.matmul1_1(x, self.matmul1_weight)
  251. matmul1_2_o = self.matmul1_2(x, self.matmul1_weight)
  252. matmul1_o = self.add(matmul1_1_o, matmul1_2_o)
  253. matmul2_o = self.matmul2(matmul1_o, x)
  254. return matmul2_o
  255. def compile_net(net, input_):
  256. net.set_auto_parallel()
  257. _executor.compile(net, input_)
  258. def reshape_net2(backbone):
  259. batch_size = 16
  260. device_num = 16
  261. context.set_auto_parallel_context(device_num=device_num, global_rank=0)
  262. input_ = Tensor(np.ones([batch_size * device_num, 512, 7, 7]).astype(np.float32) * 0.01)
  263. net = GradWrap(NetWithLoss(backbone))
  264. context.set_auto_parallel_context(parallel_mode="semi_auto_parallel")
  265. compile_net(net, input_)
  266. def test_reshape_net1_1():
  267. reshape_net2(ReshapeNet1(((1, 8), (8, 1))))
  268. def test_reshape_net1_2():
  269. reshape_net2(ReshapeNet1(((1, 8), (8, 2))))
  270. def test_reshape_net2_1():
  271. reshape_net2(ReshapeNet2(((1, 8), (8, 1))))
  272. def test_reshape_net2_2():
  273. reshape_net2(ReshapeNet2(((1, 8), (8, 2))))
  274. def test_reshape_net3_1():
  275. reshape_net2(ReshapeNet3(((1, 8), (8, 1))))
  276. def test_reshape_net3_2():
  277. reshape_net2(ReshapeNet3(((1, 8), (8, 2))))
  278. def test_reshape_net4_1():
  279. try:
  280. reshape_net2(ReshapeNet4(((1, 8), (8, 1))))
  281. except ValueError:
  282. pass
  283. except TypeError:
  284. pass
  285. except RuntimeError:
  286. pass
  287. def test_reshape_net4_2():
  288. try:
  289. reshape_net2(ReshapeNet4(((1, 8), (8, 2))))
  290. except ValueError:
  291. pass
  292. except TypeError:
  293. pass
  294. except RuntimeError:
  295. pass
  296. def test_reshape_net5_1():
  297. reshape_net2(ReshapeNet5(((1, 8), (8, 1))))
  298. def test_reshape_net5_2():
  299. reshape_net2(ReshapeNet5(((1, 8), (8, 2))))
  300. def test_reshape_net6_1():
  301. reshape_net2(ReshapeNet6(((1, 8), (8, 1))))
  302. def test_reshape_net6_2():
  303. reshape_net2(ReshapeNet6(((1, 8), (8, 2))))
  304. class TrainOneStepCell(nn.Cell):
  305. """
  306. Network training package class.
  307. Append an optimizer to the training network after that the construct function
  308. can be called to create the backward graph.
  309. Args:
  310. network (Cell): The training network.
  311. optimizer (Cell): Optimizer for updating the weights.
  312. sens (Number): The adjust parameter. Default: 1.0.
  313. Examples:
  314. >>> net = Net()
  315. >>> loss_fn = nn.SoftmaxCrossEntropyWithLogits()
  316. >>> optim = Momentum(net.trainable_params(), learning_rate=0.1, momentum=0.9)
  317. >>> loss_net = WithLossCell(net, loss_fn)
  318. >>> train_net = TrainOneStepCell(loss_net, optim)
  319. """
  320. def __init__(self, network, optimizer, sens=1.0):
  321. super(TrainOneStepCell, self).__init__(auto_prefix=False)
  322. self.network = network
  323. self.network.add_flags(defer_inline=True)
  324. self.weights = ParameterTuple(network.trainable_params())
  325. self.optimizer = optimizer
  326. self.grad = C.GradOperation('grad',
  327. get_by_list=True,
  328. sens_param=True)
  329. self.sens = sens
  330. def construct(self, data):
  331. weights = self.weights
  332. loss = self.network(data)
  333. sens = P.Fill()(P.DType()(loss), P.Shape()(loss), self.sens)
  334. grads = self.grad(self.network, weights)(data, sens)
  335. return F.depend(loss, self.optimizer(grads))
  336. def reshape_common2(parallel_mode, net):
  337. batch_size = 16
  338. learning_rate = 0.1
  339. momentum = 0.9
  340. epoch_size = 2
  341. predict = Tensor(np.ones([batch_size, 512, 7, 7]), dtype=ms.float32)
  342. label = Tensor(np.ones([batch_size]), dtype=ms.int32)
  343. dataset = Dataset(predict, label, 2, input_num=1)
  344. context.reset_auto_parallel_context()
  345. context.set_auto_parallel_context(parallel_mode=parallel_mode, device_num=16)
  346. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  347. train_net = TrainOneStepCell(net, opt).set_train()
  348. model = Model(train_net)
  349. model.train(epoch_size, dataset, dataset_sink_mode=False)
  350. def test_reshape_common2_0():
  351. reshape_common2(ParallelMode.SEMI_AUTO_PARALLEL, ReshapeNet1(((1, 8), (8, 1))))
  352. def test_reshape_common2_1():
  353. reshape_common2(ParallelMode.SEMI_AUTO_PARALLEL, ReshapeNet1(((1, 8), (8, 2))))
  354. def test_reshape_common2_2():
  355. reshape_common2(ParallelMode.SEMI_AUTO_PARALLEL, ReshapeNet2(((1, 8), (8, 1))))
  356. def test_reshape_common2_3():
  357. reshape_common2(ParallelMode.SEMI_AUTO_PARALLEL, ReshapeNet2(((1, 8), (8, 2))))
  358. def test_reshape_common2_4():
  359. reshape_common2(ParallelMode.SEMI_AUTO_PARALLEL, ReshapeNet3(((1, 8), (8, 1))))
  360. def test_reshape_common2_5():
  361. reshape_common2(ParallelMode.SEMI_AUTO_PARALLEL, ReshapeNet3(((1, 8), (8, 2))))
  362. class BatchNormReshapeNet(nn.Cell):
  363. def __init__(self):
  364. super(BatchNormReshapeNet, self).__init__()
  365. self.vd = P._VirtualDataset()
  366. self.batch_norm = nn.BatchNorm1d(512, affine=False)
  367. self.reshape = P.Reshape()
  368. self.prelu = nn.PReLU(channel=256)
  369. def construct(self, x):
  370. x = self.vd(x)
  371. x = self.batch_norm(x)
  372. x = self.reshape(x, (512, 256))
  373. x = self.prelu(x)
  374. return x
  375. def test_batchnorm_reshape_train():
  376. batch_size = 16
  377. device_num = 16
  378. context.set_auto_parallel_context(device_num=device_num, global_rank=0)
  379. context.set_auto_parallel_context(parallel_mode="semi_auto_parallel")
  380. input_ = Tensor(np.ones([batch_size * device_num, 512]).astype(np.float32) * 0.01)
  381. net = GradWrap(NetWithLoss(BatchNormReshapeNet()))
  382. compile_net(net, input_)
  383. def bn_with_initialize(out_channels):
  384. bn = nn.BatchNorm2d(out_channels, momentum=0.3, eps=1e-5).add_flags_recursive(fp32=True)
  385. return bn
  386. def fc_with_initialize(input_channels, out_channels):
  387. return nn.Dense(input_channels, out_channels).add_flags_recursive(fp16=True)
  388. class BNReshapeDenseBNNet(nn.Cell):
  389. def __init__(self):
  390. super(BNReshapeDenseBNNet, self).__init__()
  391. self.batch_norm = bn_with_initialize(2)
  392. self.reshape = P.Reshape()
  393. self.cast = P.Cast()
  394. self.batch_norm2 = nn.BatchNorm1d(512, affine=False)
  395. self.fc = fc_with_initialize(2 * 32 * 32, 512)
  396. def construct(self, x):
  397. x = self.batch_norm(x)
  398. x = self.reshape(x, (16, 2 * 32 * 32))
  399. x = self.fc(x)
  400. x = self.batch_norm2(x)
  401. return x
  402. def test_bn_reshape_dense_bn_train():
  403. batch_size = 16
  404. device_num = 16
  405. context.set_auto_parallel_context(device_num=device_num, global_rank=0)
  406. input_ = Tensor(np.ones([batch_size, 2, 32, 32]).astype(np.float32) * 0.01)
  407. net = GradWrap(NetWithLoss(BNReshapeDenseBNNet()))
  408. context.set_auto_parallel_context(parallel_mode="semi_auto_parallel")
  409. compile_net(net, input_)
  410. class ParallelReduceMeanNet(nn.Cell):
  411. def __init__(self, conv_in_channel, conv_out_channel,
  412. reducemean_keep_dims=False, reducemean_axis=-1, strategy=None):
  413. super().__init__()
  414. self.conv = nn.Conv2d(in_channels=conv_in_channel, out_channels=conv_out_channel,
  415. kernel_size=1, stride=1, pad_mode='valid', has_bias=True,
  416. weight_init='ones', bias_init='ones')
  417. self.reduce_mean = P.ReduceMean(keep_dims=reducemean_keep_dims)
  418. self.flat = nn.Flatten()
  419. self.reducemean_axis = reducemean_axis
  420. if strategy is not None:
  421. self.reduce_mean.set_strategy(strategy)
  422. def construct(self, inputs):
  423. x = self.conv(inputs)
  424. x = self.reduce_mean(x, self.reducemean_axis)
  425. x = self.flat(x)
  426. return x
  427. class CrossEntropyLoss(nn.Cell):
  428. def __init__(self, reduction='mean'):
  429. super(CrossEntropyLoss, self).__init__()
  430. self.reduce_mean = P.ReduceMean()
  431. self.cross_entropy = SoftmaxCrossEntropyWithLogits()
  432. self.reduction = reduction
  433. def construct(self, logits, label):
  434. loss = self.cross_entropy(logits, label)
  435. if self.reduction == 'mean':
  436. loss = self.reduce_mean(loss, (-1,))
  437. return loss
  438. def test_flatten_reshape(parallel_mode="auto_parallel"):
  439. batch_size = 16
  440. learning_rate = 0.1
  441. momentum = 0.9
  442. epoch_size = 2
  443. context.reset_auto_parallel_context()
  444. context.set_auto_parallel_context(parallel_mode=parallel_mode, device_num=8)
  445. net = ParallelReduceMeanNet(conv_in_channel=3, conv_out_channel=64, reducemean_axis=(2, 3),
  446. strategy=((4, 2, 1, 1),))
  447. loss = CrossEntropyLoss()
  448. predict = Tensor(np.ones([batch_size, 3, 32, 32]), dtype=ms.float32)
  449. label = Tensor(np.ones([batch_size, 64]), dtype=ms.float32)
  450. dataset = Dataset(predict, label, 2, input_num=2)
  451. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  452. model = Model(net, loss_fn=loss, optimizer=opt)
  453. model.train(epoch_size, dataset, dataset_sink_mode=False)
  454. def test_flatten_reshape2(parallel_mode="auto_parallel"):
  455. batch_size = 16
  456. learning_rate = 0.1
  457. momentum = 0.9
  458. epoch_size = 2
  459. context.reset_auto_parallel_context()
  460. context.set_auto_parallel_context(parallel_mode=parallel_mode, device_num=8)
  461. set_algo_parameters(fully_use_devices=False)
  462. net = ParallelReduceMeanNet(conv_in_channel=3, conv_out_channel=64, reducemean_axis=(2, 3),
  463. strategy=((4, 1, 1, 1),))
  464. loss = CrossEntropyLoss()
  465. predict = Tensor(np.ones([batch_size, 3, 32, 32]), dtype=ms.float32)
  466. label = Tensor(np.ones([batch_size, 64]), dtype=ms.float32)
  467. dataset = Dataset(predict, label, 2, input_num=2)
  468. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  469. model = Model(net, loss_fn=loss, optimizer=opt)
  470. model.train(epoch_size, dataset, dataset_sink_mode=False)
  471. class ParallelReshapeNet(nn.Cell):
  472. def __init__(self, dense_in_channel, dense_out_channel, shape, strategy=None):
  473. super().__init__()
  474. self.flat = nn.Flatten()
  475. self.dense = nn.Dense(in_channels=dense_in_channel,
  476. out_channels=dense_out_channel,
  477. weight_init='ones',
  478. bias_init='ones',
  479. has_bias=True)
  480. self.reshape = P.Reshape()
  481. self.shape = shape
  482. self.reshape.set_strategy(strategy)
  483. def construct(self, inputs):
  484. x = self.flat(inputs)
  485. x = self.dense(x)
  486. x = self.reshape(x, self.shape)
  487. return x
  488. # the shape of input and output of reshape is the same
  489. # reshape is optimized before step_parallel
  490. def test_flatten_reshape3(parallel_mode="auto_parallel"):
  491. batch_size = 16
  492. learning_rate = 0.1
  493. momentum = 0.9
  494. epoch_size = 2
  495. context.reset_auto_parallel_context()
  496. context.set_auto_parallel_context(parallel_mode=parallel_mode, device_num=8)
  497. set_algo_parameters(fully_use_devices=False)
  498. net = ParallelReshapeNet(dense_in_channel=2048, dense_out_channel=1000, shape=(128, 1000), strategy=((16, 1),))
  499. loss = CrossEntropyLoss()
  500. predict = Tensor(np.ones([batch_size, 1, 2, 1024]), dtype=ms.float32)
  501. label = Tensor(np.ones([batch_size, 1000]), dtype=ms.float32)
  502. dataset = Dataset(predict, label, 2, input_num=2)
  503. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  504. model = Model(net, loss_fn=loss, optimizer=opt)
  505. model.train(epoch_size, dataset, dataset_sink_mode=False)
  506. class CrossEntropyLoss2(nn.Cell):
  507. def __init__(self, reduction='mean'):
  508. super(CrossEntropyLoss2, self).__init__()
  509. self.cross_entropy = SoftmaxCrossEntropyWithLogits(reduction=reduction)
  510. def construct(self, logits, label):
  511. loss = self.cross_entropy(logits, label)
  512. return loss
  513. def test_flatten_reshape4(parallel_mode="semi_auto_parallel"):
  514. batch_size = 16
  515. learning_rate = 0.1
  516. momentum = 0.9
  517. epoch_size = 2
  518. context.reset_auto_parallel_context()
  519. context.set_auto_parallel_context(parallel_mode=parallel_mode, device_num=8)
  520. set_algo_parameters(fully_use_devices=False)
  521. net = ParallelReduceMeanNet(conv_in_channel=3, conv_out_channel=64, reducemean_keep_dims=True,
  522. strategy=((4, 1, 1, 1),))
  523. loss = CrossEntropyLoss2()
  524. predict = Tensor(np.ones([batch_size, 3, 32, 32]), dtype=ms.float32)
  525. label = Tensor(np.ones([batch_size, 2048]), dtype=ms.float32)
  526. dataset = Dataset(predict, label, 2, input_num=2)
  527. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  528. model = Model(net, loss_fn=loss, optimizer=opt)
  529. model.train(epoch_size, dataset, dataset_sink_mode=False)