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