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_alltoall.py 9.7 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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 re
  15. import pytest
  16. import numpy as np
  17. import mindspore as ms
  18. import mindspore.nn as nn
  19. from mindspore import Tensor
  20. from mindspore import context
  21. from mindspore.common.api import _cell_graph_executor
  22. from mindspore.common.parameter import Parameter
  23. from mindspore.nn.loss import SoftmaxCrossEntropyWithLogits
  24. from mindspore.nn.optim.momentum import Momentum
  25. from mindspore.ops import operations as P
  26. from mindspore.ops.operations.comm_ops import _AlltoAll
  27. from mindspore.parallel._utils import _reset_op_id
  28. from mindspore.train import Model
  29. from mindspore.context import ParallelMode
  30. from mindspore.communication.management import GlobalComm, init
  31. from tests.dataset_mock import MindData
  32. context.set_context(device_target="Ascend")
  33. GlobalComm.CHECK_ENVS = False
  34. init("hccl")
  35. GlobalComm.CHECK_ENVS = True
  36. _x1 = Tensor(np.ones([64, 3, 224, 224]), dtype=ms.float32)
  37. class Dataset(MindData):
  38. def __init__(self, predict, label, length=3):
  39. super(Dataset, self).__init__(size=length)
  40. self.predict = predict
  41. self.label = label
  42. self.index = 0
  43. self.length = length
  44. def __iter__(self):
  45. return self
  46. def __next__(self):
  47. if self.index >= self.length:
  48. raise StopIteration
  49. self.index += 1
  50. return self.predict, self.label
  51. def reset(self):
  52. self.index = 0
  53. class AllToAllNet(nn.Cell):
  54. def __init__(self, strategy1):
  55. super(AllToAllNet, self).__init__()
  56. self.matmul = P.MatMul().shard(((1, 1), (1, 8)))
  57. self.matmul_weight = Parameter(Tensor(np.ones([128, 256]), dtype=ms.float32), name="weight")
  58. self.transpose1 = P.Transpose().shard(strategy1)
  59. def construct(self, x):
  60. x = self.matmul(x, self.matmul_weight)
  61. x = self.transpose1(x, (1, 0))
  62. return x
  63. def all_to_all_net(strategy1):
  64. return AllToAllNet(strategy1=strategy1)
  65. def all_to_all_common(strategy1):
  66. learning_rate = 0.1
  67. momentum = 0.9
  68. epoch_size = 2
  69. context.reset_auto_parallel_context()
  70. context.set_auto_parallel_context(parallel_mode=ParallelMode.SEMI_AUTO_PARALLEL, device_num=8)
  71. predict = Tensor(np.ones([32, 128]), dtype=ms.float32)
  72. label = Tensor(np.ones([32]), dtype=ms.int32)
  73. dataset = Dataset(predict, label, 2)
  74. net = all_to_all_net(strategy1)
  75. loss = SoftmaxCrossEntropyWithLogits(sparse=True)
  76. loss.softmax_cross_entropy.shard(((8, 1), (8, 1)))
  77. loss.one_hot.shard(((8, 1), (), ()))
  78. opt = Momentum(net.trainable_params(), learning_rate, momentum)
  79. model = Model(net, loss, opt)
  80. model.train(epoch_size, dataset, dataset_sink_mode=False)
  81. strategys = _cell_graph_executor._get_shard_strategy(model._train_network)
  82. return strategys
  83. def test_all_to_all():
  84. strategy1 = ((8, 1),)
  85. context.set_context(mode=context.GRAPH_MODE, save_graphs=False)
  86. _reset_op_id()
  87. strategys = all_to_all_common(strategy1)
  88. print(strategys)
  89. for (k, v) in strategys.items():
  90. if re.search('SoftmaxCrossEntropyWithLogits-op', k) is not None:
  91. assert v == [[8, 1], [8, 1]]
  92. elif re.search('OneHot-op', k) is not None:
  93. assert v == [[8, 1], [], []]
  94. elif re.search('Transpose-op', k) is not None:
  95. assert v == [[8, 1]]
  96. elif re.search('MatMul-op', k) is not None:
  97. assert v == [[1, 1], [1, 8]]
  98. context.set_context(save_graphs=False)
  99. def test_all_to_all_success():
  100. """
  101. Feature: AlltoAll
  102. Description: on 8p, a 4d tensor split at dim 2 and concat at dim 3
  103. Expectation: success
  104. """
  105. context.set_auto_parallel_context(device_num=8, global_rank=0)
  106. class Net(nn.Cell):
  107. def __init__(self):
  108. super(Net, self).__init__()
  109. self.alltoallv = _AlltoAll(split_count=8, split_dim=2, concat_dim=3)
  110. def construct(self, x1):
  111. out = self.alltoallv(x1)
  112. return out
  113. net = Net()
  114. _cell_graph_executor.compile(net, _x1)
  115. def test_all_to_all_invalid_split_count_value_failed():
  116. """
  117. Feature: AlltoAll
  118. Description: split_count should be equal to rank size, but not
  119. Expectation: throw ValueError
  120. """
  121. context.set_auto_parallel_context(device_num=8, global_rank=0)
  122. class Net(nn.Cell):
  123. def __init__(self):
  124. super(Net, self).__init__()
  125. self.alltoallv = _AlltoAll(split_count=7, split_dim=2, concat_dim=3)
  126. def construct(self, x1):
  127. out = self.alltoallv(x1)
  128. return out
  129. with pytest.raises(ValueError):
  130. net = Net()
  131. _cell_graph_executor.compile(net, _x1)
  132. def test_all_to_all_invalid_split_count_type_failed():
  133. """
  134. Feature: AlltoAll
  135. Description: split_count should be int, but a list is given
  136. Expectation: throw TypeError
  137. """
  138. context.set_auto_parallel_context(device_num=8, global_rank=0)
  139. class Net(nn.Cell):
  140. def __init__(self):
  141. super(Net, self).__init__()
  142. self.alltoallv = _AlltoAll(split_count=[8], split_dim=2, concat_dim=3)
  143. def construct(self, x1):
  144. out = self.alltoallv(x1)
  145. return out
  146. with pytest.raises(TypeError):
  147. net = Net()
  148. _cell_graph_executor.compile(net, _x1)
  149. def test_all_to_all_invalid_split_dim_value_failed():
  150. """
  151. Feature: AlltoAll
  152. Description: split_dim over input shape
  153. Expectation: throw IndexError
  154. """
  155. context.set_auto_parallel_context(device_num=8, global_rank=0)
  156. class Net(nn.Cell):
  157. def __init__(self):
  158. super(Net, self).__init__()
  159. self.alltoallv = _AlltoAll(split_count=8, split_dim=4, concat_dim=3)
  160. def construct(self, x1):
  161. out = self.alltoallv(x1)
  162. return out
  163. with pytest.raises(IndexError):
  164. net = Net()
  165. _cell_graph_executor.compile(net, _x1)
  166. def test_all_to_all_invalid_split_dim_type_failed():
  167. """
  168. Feature: AlltoAll
  169. Description: split_dim should be int, but a tuple is given
  170. Expectation: throw TypeError
  171. """
  172. context.set_auto_parallel_context(device_num=8, global_rank=0)
  173. class Net(nn.Cell):
  174. def __init__(self):
  175. super(Net, self).__init__()
  176. self.alltoallv = _AlltoAll(split_count=8, split_dim=(3,), concat_dim=3)
  177. def construct(self, x1):
  178. out = self.alltoallv(x1)
  179. return out
  180. with pytest.raises(TypeError):
  181. net = Net()
  182. _cell_graph_executor.compile(net, _x1)
  183. def test_all_to_all_invalid_concat_dim_value_failed():
  184. """
  185. Feature: AlltoAll
  186. Description: concat_dim over input shape
  187. Expectation: throw IndexError
  188. """
  189. context.set_auto_parallel_context(device_num=8, global_rank=0)
  190. class Net(nn.Cell):
  191. def __init__(self):
  192. super(Net, self).__init__()
  193. self.alltoallv = _AlltoAll(split_count=8, split_dim=3, concat_dim=4)
  194. def construct(self, x1):
  195. out = self.alltoallv(x1)
  196. return out
  197. with pytest.raises(IndexError):
  198. net = Net()
  199. _cell_graph_executor.compile(net, _x1)
  200. def test_all_to_all_invalid_concat_dim_type_failed():
  201. """
  202. Feature: AlltoAll
  203. Description: concat_dim should be int, but a tuple is given
  204. Expectation: throw TypeError
  205. """
  206. context.set_auto_parallel_context(device_num=8, global_rank=0)
  207. class Net(nn.Cell):
  208. def __init__(self):
  209. super(Net, self).__init__()
  210. self.alltoallv = _AlltoAll(split_count=8, split_dim=3, concat_dim=([3],))
  211. def construct(self, x1):
  212. out = self.alltoallv(x1)
  213. return out
  214. with pytest.raises(TypeError):
  215. net = Net()
  216. _cell_graph_executor.compile(net, _x1)
  217. def test_all_to_all_invalid_split_count_cannot_be_divisible_failed():
  218. """
  219. Feature: AlltoAll
  220. Description: shape at split_dim should be divisible by split_count, but not
  221. Expectation: throw ValueError
  222. """
  223. context.set_auto_parallel_context(device_num=3, global_rank=0)
  224. class Net(nn.Cell):
  225. def __init__(self):
  226. super(Net, self).__init__()
  227. self.alltoallv = _AlltoAll(split_count=3, split_dim=3, concat_dim=3)
  228. def construct(self, x1):
  229. out = self.alltoallv(x1)
  230. return out
  231. with pytest.raises(ValueError):
  232. net = Net()
  233. _cell_graph_executor.compile(net, _x1)
  234. def test_all_to_all_invalid_group_type_failed():
  235. """
  236. Feature: AlltoAll
  237. Description: group should be str, but a tuple is given
  238. Expectation: throw TypeError
  239. """
  240. context.set_auto_parallel_context(device_num=8, global_rank=0)
  241. class Net(nn.Cell):
  242. def __init__(self):
  243. super(Net, self).__init__()
  244. self.alltoallv = _AlltoAll(split_count=8, split_dim=3, concat_dim=3, group=3)
  245. def construct(self, x1):
  246. out = self.alltoallv(x1)
  247. return out
  248. with pytest.raises(TypeError):
  249. net = Net()
  250. _cell_graph_executor.compile(net, _x1)
  251. if __name__ == '__main__':
  252. test_all_to_all()