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.

onehot_model_parallel.py 5.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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 os
  16. import numpy as np
  17. import mindspore as ms
  18. import mindspore.communication.management as distributedTool
  19. import mindspore.context as context
  20. from mindspore.common.tensor import Tensor
  21. from mindspore.nn import Cell
  22. from mindspore.ops import operations as P
  23. device_num = 2
  24. device_id = int(os.getenv('DEVICE_ID'))
  25. rank_id = 0
  26. def setup_module():
  27. global device_num
  28. global rank_id
  29. np.random.seed(0)
  30. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  31. context.set_context(device_id=device_id)
  32. distributedTool.init()
  33. device_num = distributedTool.get_group_size()
  34. rank_id = distributedTool.get_rank()
  35. context.set_auto_parallel_context(device_num=device_num,
  36. global_rank=rank_id)
  37. def teardown_module():
  38. distributedTool.release()
  39. class Onehot(Cell):
  40. def __init__(self, axis=-1, depth=1, on_value=1.0, off_value=0.0, strategy=None):
  41. super(Onehot, self).__init__()
  42. trans_stra = None
  43. if strategy:
  44. trans_stra = (strategy[0],)
  45. self.onehot = P.OneHot().shard(strategy=strategy)
  46. self.depth = depth
  47. self.on_value = Tensor(on_value, ms.float32)
  48. self.off_value = Tensor(off_value, ms.float32)
  49. self.transpose = P.Transpose().shard(strategy=trans_stra)
  50. self.sub = P.Sub().shard(strategy=((1, 1), (1, 1)))
  51. self.axis = axis
  52. def construct(self, input_, indices):
  53. x = self.onehot(indices, self.depth, self.on_value, self.off_value)
  54. x = self.transpose(x, (1, 0))
  55. x = self.sub(input_, x)
  56. return x
  57. class DataGenerator():
  58. def get_parallel_blocks(self, input_, strategy):
  59. blocks = [input_]
  60. i = 0
  61. for stra in strategy:
  62. temp = []
  63. while blocks:
  64. block = blocks.pop(0)
  65. temp.extend(np.split(block, stra, axis=i))
  66. blocks.extend(temp)
  67. i += 1
  68. return blocks
  69. def generate_data(self, shape):
  70. data = np.random.rand(*shape)
  71. return data
  72. def input_data(self, shape):
  73. data = (self.generate_data(shape) * 2).astype(np.float32)
  74. stra = [1] * len(shape)
  75. stra[0] = device_num
  76. datas = self.get_parallel_blocks(data, stra)
  77. return Tensor(data), Tensor(datas[rank_id])
  78. def label_data(self, shape, classes):
  79. data = (self.generate_data(shape) * (classes - 1)).astype(np.int32)
  80. stra = [1] * len(shape)
  81. stra[0] = device_num
  82. datas = self.get_parallel_blocks(data, stra)
  83. return Tensor(data), Tensor(datas[rank_id])
  84. class OneHotFactory:
  85. def __init__(self, batch_size, classes, on_value=1.0, off_value=0.0, axis=None, strategy=None):
  86. data_gen = DataGenerator()
  87. self.input_full, self.input_part = data_gen.input_data((classes, batch_size))
  88. self.label_full, self.label_part = data_gen.label_data((batch_size,), classes)
  89. self.depth = classes
  90. self.on_value = on_value
  91. self.off_value = off_value
  92. self.axis = axis
  93. self.strategy = strategy
  94. def forward_mindspore_single_impl(self):
  95. net = Onehot(axis=self.axis,
  96. depth=self.depth,
  97. on_value=self.on_value,
  98. off_value=self.off_value)
  99. out = net(self.input_full, self.label_full)
  100. return out
  101. def forward_mindspore_parallel_impl(self):
  102. context.set_auto_parallel_context(parallel_mode="semi_auto_parallel")
  103. net = Onehot(axis=self.axis,
  104. depth=self.depth,
  105. on_value=self.on_value,
  106. off_value=self.off_value, strategy=self.strategy)
  107. out = net.compile_and_run(self.input_full, self.label_full)
  108. return out
  109. def forward_cmp(self):
  110. out_mindspore_single = self.forward_mindspore_single_impl().asnumpy()
  111. context.reset_auto_parallel_context()
  112. out_mindspore_parallel = self.forward_mindspore_parallel_impl().asnumpy()
  113. context.reset_auto_parallel_context()
  114. assert np.allclose(out_mindspore_single, out_mindspore_parallel, 0.0001, 0.0001)
  115. def test_reid_onehot_forward_int32_128_depth1024_model_parallel():
  116. fact = OneHotFactory(batch_size=128,
  117. classes=1024,
  118. on_value=1.000000,
  119. off_value=0.000000,
  120. axis=-1,
  121. strategy=((1, device_num), (), ()))
  122. fact.forward_cmp()
  123. def test_reid_onehot_forward_int32_1024_depth128_model_parallel():
  124. fact = OneHotFactory(batch_size=1024,
  125. classes=128,
  126. on_value=1.000000,
  127. off_value=0.000000,
  128. axis=-1,
  129. strategy=((1, device_num), (), ()))
  130. fact.forward_cmp()