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_gather_v2_primitive.py 8.0 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. # ============================================================================
  15. import numpy as np
  16. import mindspore as ms
  17. import mindspore.nn as nn
  18. from mindspore import Tensor
  19. from mindspore import context
  20. from mindspore.common import dtype as mstype
  21. from mindspore.common.parameter import ParameterTuple
  22. from mindspore.communication.management import init
  23. from mindspore.nn import Dense, Cell
  24. from mindspore.nn.loss.loss import _Loss
  25. from mindspore.nn.optim import Momentum
  26. from mindspore.ops import composite as C
  27. from mindspore.ops import functional as F
  28. from mindspore.ops import operations as P
  29. from mindspore.train import Model, ParallelMode
  30. context.set_context(mode=context.GRAPH_MODE)
  31. device_number = 32
  32. batch_size_per_device = 128
  33. class Dataset():
  34. def __init__(self, predict, length=3):
  35. self.predict = predict
  36. self.index = 0
  37. self.length = length
  38. def __iter__(self):
  39. return self
  40. def __next__(self):
  41. if self.index >= self.length:
  42. raise StopIteration
  43. self.index += 1
  44. return (self.predict,)
  45. def reset(self):
  46. self.index = 0
  47. def get_dataset_size(self):
  48. return 128
  49. def get_repeat_count(self):
  50. return 1
  51. class GatherV2(_Loss):
  52. def __init__(self, index_dim, strategy, index_size=16):
  53. super(GatherV2, self).__init__()
  54. self.pow = P.Pow()
  55. emb1_list = 21
  56. emb2_list = 2
  57. if index_dim == 1:
  58. emb_list = list(range(index_size))
  59. emb1_list = emb_list[0::2]
  60. emb2_list = emb_list[1::2]
  61. if index_dim == 2:
  62. emb_list = np.arange(index_size * 16)
  63. emb1_list = np.reshape(emb_list[0::2], (int(index_size / 2), 16))
  64. emb2_list = np.reshape(emb_list[1::2], (int(index_size / 2), 16))
  65. self.emb1_param = Tensor(emb1_list, dtype=mstype.int32)
  66. self.emb2_param = Tensor(emb2_list, dtype=mstype.int32)
  67. self.gatherv2 = P.GatherV2().set_strategy(strategy).add_prim_attr("data_parallel", True)
  68. def construct(self, nembeddings):
  69. emb1 = self.gatherv2(nembeddings, self.emb1_param, 0)
  70. emb2 = self.gatherv2(nembeddings, self.emb2_param, 0)
  71. return self.pow((emb1 - emb2), 2.0)
  72. def fc_with_initialize(input_channels, out_channels):
  73. return Dense(input_channels, out_channels)
  74. class BuildTrainNetwork(nn.Cell):
  75. def __init__(self, network, criterion):
  76. super(BuildTrainNetwork, self).__init__()
  77. self.network = network
  78. self.criterion = criterion
  79. def construct(self, input_data):
  80. embeddings = self.network(input_data)
  81. loss = self.criterion(embeddings)
  82. return loss
  83. class TrainOneStepCell(Cell):
  84. def __init__(self, network, optimizer, sens=1.0):
  85. super(TrainOneStepCell, self).__init__(auto_prefix=False)
  86. self.network = network
  87. self.network.add_flags(defer_inline=True)
  88. self.weights = ParameterTuple(network.trainable_params())
  89. self.optimizer = optimizer
  90. self.grad = C.GradOperation('grad',
  91. get_by_list=True,
  92. sens_param=True)
  93. self.sens = sens
  94. def construct(self, data):
  95. weights = self.weights
  96. loss = self.network(data)
  97. sens = P.Fill()(P.DType()(loss), P.Shape()(loss), self.sens)
  98. grads = self.grad(self.network, weights)(data, sens)
  99. return F.depend(loss, self.optimizer(grads))
  100. def net_trains(criterion, rank):
  101. init()
  102. lr = 0.1
  103. momentum = 0.9
  104. max_epoch = 20
  105. input_channels = 256
  106. out_channels = 512
  107. context.set_context(mode=context.GRAPH_MODE, save_graphs=False)
  108. context.reset_auto_parallel_context()
  109. context.set_auto_parallel_context(parallel_mode=ParallelMode.SEMI_AUTO_PARALLEL, device_num=device_number,
  110. global_rank=rank)
  111. predict = Tensor(np.ones([batch_size_per_device, input_channels]), dtype=ms.float32)
  112. dataset = Dataset(predict, 4)
  113. network = fc_with_initialize(input_channels, out_channels)
  114. network.set_train()
  115. train_network = BuildTrainNetwork(network, criterion)
  116. train_network.set_train()
  117. opt = Momentum(train_network.trainable_params(), lr, momentum)
  118. train_net = TrainOneStepCell(train_network, opt).set_train()
  119. model = Model(train_net)
  120. model.train(max_epoch, dataset, dataset_sink_mode=False)
  121. context.reset_auto_parallel_context()
  122. def test_auto_batch_parallel():
  123. gather_v2_strategy = None
  124. criterion = GatherV2(1, strategy=gather_v2_strategy, index_size=batch_size_per_device * device_number)
  125. rank = 2
  126. net_trains(criterion, rank)
  127. def test_2d_index_auto_batch_parallel():
  128. gather_v2_strategy = None
  129. criterion = GatherV2(2, strategy=gather_v2_strategy, index_size=batch_size_per_device * device_number)
  130. rank = 2
  131. net_trains(criterion, rank)
  132. def test_batch_parallel():
  133. gather_v2_strategy = ((device_number, 1),)
  134. criterion = GatherV2(1, strategy=gather_v2_strategy, index_size=batch_size_per_device * device_number)
  135. rank = 2
  136. net_trains(criterion, rank)
  137. def test_strategy1():
  138. gather_v2_strategy = ((16, 2),)
  139. rank = 2
  140. criterion = GatherV2(1, strategy=gather_v2_strategy, index_size=batch_size_per_device * device_number)
  141. net_trains(criterion, rank)
  142. def test_strategy2():
  143. gather_v2_strategy = ((1, device_number),)
  144. rank = 2
  145. criterion = GatherV2(1, strategy=gather_v2_strategy, index_size=batch_size_per_device * device_number)
  146. net_trains(criterion, rank)
  147. def test_strategy3():
  148. gather_v2_strategy = ((8, 1),)
  149. rank = 2
  150. criterion = GatherV2(1, strategy=gather_v2_strategy, index_size=batch_size_per_device * device_number)
  151. net_trains(criterion, rank)
  152. class GatherV2Axis1(_Loss):
  153. def __init__(self, index_dim, strategy, index_size=16):
  154. super(GatherV2Axis1, self).__init__()
  155. self.pow = P.Pow()
  156. emb1_list = 21
  157. emb2_list = 2
  158. if index_dim == 1:
  159. emb_list = list(range(index_size))
  160. emb1_list = emb_list[0::2]
  161. emb2_list = emb_list[1::2]
  162. if index_dim == 2:
  163. emb_list = np.arange(index_size * index_size)
  164. emb1_list = np.reshape(emb_list[0::2], (int(index_size / 2), index_size))
  165. emb2_list = np.reshape(emb_list[1::2], (int(index_size / 2), index_size))
  166. self.emb1_param = Tensor(emb1_list, dtype=mstype.int32)
  167. self.emb2_param = Tensor(emb2_list, dtype=mstype.int32)
  168. self.gatherv2 = P.GatherV2().set_strategy(strategy)
  169. def construct(self, nembeddings):
  170. emb1 = self.gatherv2(nembeddings, self.emb1_param, 1)
  171. emb2 = self.gatherv2(nembeddings, self.emb2_param, 1)
  172. return self.pow((emb1 - emb2), 2.0)
  173. def test_axis1_auto_batch_parallel():
  174. gather_v2_strategy = None
  175. criterion = GatherV2Axis1(1, strategy=gather_v2_strategy, index_size=512)
  176. rank = 2
  177. net_trains(criterion, rank)
  178. def test_axis1_batch_parallel():
  179. gather_v2_strategy = ((device_number, 1), (1,))
  180. criterion = GatherV2Axis1(1, strategy=gather_v2_strategy, index_size=512)
  181. rank = 2
  182. net_trains(criterion, rank)
  183. def test_axis1_strategy1():
  184. gather_v2_strategy = ((16, 2), (1,))
  185. rank = 17
  186. criterion = GatherV2Axis1(1, strategy=gather_v2_strategy, index_size=512)
  187. net_trains(criterion, rank)