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.2 kB

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