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

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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)
  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. def test_all_to_all_success():
  99. """
  100. Feature: AlltoAll
  101. Description: on 8p, a 4d tensor split at dim 2 and concat at dim 3
  102. Expectation: success
  103. """
  104. context.set_auto_parallel_context(device_num=8, global_rank=0)
  105. class Net(nn.Cell):
  106. def __init__(self):
  107. super(Net, self).__init__()
  108. self.alltoallv = AlltoAll(split_count=8, split_dim=2, concat_dim=3)
  109. def construct(self, x1):
  110. out = self.alltoallv(x1)
  111. return out
  112. net = Net()
  113. _cell_graph_executor.compile(net, _x1)
  114. def test_all_to_all_invalid_split_count_value_failed():
  115. """
  116. Feature: AlltoAll
  117. Description: split_count should be equal to rank size, but not
  118. Expectation: throw ValueError
  119. """
  120. context.set_auto_parallel_context(device_num=8, global_rank=0)
  121. class Net(nn.Cell):
  122. def __init__(self):
  123. super(Net, self).__init__()
  124. self.alltoallv = AlltoAll(split_count=7, split_dim=2, concat_dim=3)
  125. def construct(self, x1):
  126. out = self.alltoallv(x1)
  127. return out
  128. with pytest.raises(ValueError):
  129. net = Net()
  130. _cell_graph_executor.compile(net, _x1)
  131. def test_all_to_all_invalid_split_count_type_failed():
  132. """
  133. Feature: AlltoAll
  134. Description: split_count should be int, but a list is given
  135. Expectation: throw TypeError
  136. """
  137. context.set_auto_parallel_context(device_num=8, global_rank=0)
  138. class Net(nn.Cell):
  139. def __init__(self):
  140. super(Net, self).__init__()
  141. self.alltoallv = AlltoAll(split_count=[8], split_dim=2, concat_dim=3)
  142. def construct(self, x1):
  143. out = self.alltoallv(x1)
  144. return out
  145. with pytest.raises(TypeError):
  146. net = Net()
  147. _cell_graph_executor.compile(net, _x1)
  148. def test_all_to_all_invalid_split_dim_value_failed():
  149. """
  150. Feature: AlltoAll
  151. Description: split_dim over input shape
  152. Expectation: throw IndexError
  153. """
  154. context.set_auto_parallel_context(device_num=8, global_rank=0)
  155. class Net(nn.Cell):
  156. def __init__(self):
  157. super(Net, self).__init__()
  158. self.alltoallv = AlltoAll(split_count=8, split_dim=4, concat_dim=3)
  159. def construct(self, x1):
  160. out = self.alltoallv(x1)
  161. return out
  162. with pytest.raises(IndexError):
  163. net = Net()
  164. _cell_graph_executor.compile(net, _x1)
  165. def test_all_to_all_invalid_split_dim_type_failed():
  166. """
  167. Feature: AlltoAll
  168. Description: split_dim should be int, but a tuple is given
  169. Expectation: throw TypeError
  170. """
  171. context.set_auto_parallel_context(device_num=8, global_rank=0)
  172. class Net(nn.Cell):
  173. def __init__(self):
  174. super(Net, self).__init__()
  175. self.alltoallv = AlltoAll(split_count=8, split_dim=(3,), concat_dim=3)
  176. def construct(self, x1):
  177. out = self.alltoallv(x1)
  178. return out
  179. with pytest.raises(TypeError):
  180. net = Net()
  181. _cell_graph_executor.compile(net, _x1)
  182. def test_all_to_all_invalid_concat_dim_value_failed():
  183. """
  184. Feature: AlltoAll
  185. Description: concat_dim over input shape
  186. Expectation: throw IndexError
  187. """
  188. context.set_auto_parallel_context(device_num=8, global_rank=0)
  189. class Net(nn.Cell):
  190. def __init__(self):
  191. super(Net, self).__init__()
  192. self.alltoallv = AlltoAll(split_count=8, split_dim=3, concat_dim=4)
  193. def construct(self, x1):
  194. out = self.alltoallv(x1)
  195. return out
  196. with pytest.raises(IndexError):
  197. net = Net()
  198. _cell_graph_executor.compile(net, _x1)
  199. def test_all_to_all_invalid_concat_dim_type_failed():
  200. """
  201. Feature: AlltoAll
  202. Description: concat_dim should be int, but a tuple is given
  203. Expectation: throw TypeError
  204. """
  205. context.set_auto_parallel_context(device_num=8, global_rank=0)
  206. class Net(nn.Cell):
  207. def __init__(self):
  208. super(Net, self).__init__()
  209. self.alltoallv = AlltoAll(split_count=8, split_dim=3, concat_dim=([3],))
  210. def construct(self, x1):
  211. out = self.alltoallv(x1)
  212. return out
  213. with pytest.raises(TypeError):
  214. net = Net()
  215. _cell_graph_executor.compile(net, _x1)
  216. def test_all_to_all_invalid_split_count_cannot_be_divisible_failed():
  217. """
  218. Feature: AlltoAll
  219. Description: shape at split_dim should be divisible by split_count, but not
  220. Expectation: throw ValueError
  221. """
  222. context.set_auto_parallel_context(device_num=3, global_rank=0)
  223. class Net(nn.Cell):
  224. def __init__(self):
  225. super(Net, self).__init__()
  226. self.alltoallv = AlltoAll(split_count=3, split_dim=3, concat_dim=3)
  227. def construct(self, x1):
  228. out = self.alltoallv(x1)
  229. return out
  230. with pytest.raises(ValueError):
  231. net = Net()
  232. _cell_graph_executor.compile(net, _x1)
  233. def test_all_to_all_invalid_group_type_failed():
  234. """
  235. Feature: AlltoAll
  236. Description: group should be str, but a tuple is given
  237. Expectation: throw TypeError
  238. """
  239. context.set_auto_parallel_context(device_num=8, global_rank=0)
  240. class Net(nn.Cell):
  241. def __init__(self):
  242. super(Net, self).__init__()
  243. self.alltoallv = AlltoAll(split_count=8, split_dim=3, concat_dim=3, group=3)
  244. def construct(self, x1):
  245. out = self.alltoallv(x1)
  246. return out
  247. with pytest.raises(TypeError):
  248. net = Net()
  249. _cell_graph_executor.compile(net, _x1)
  250. if __name__ == '__main__':
  251. test_all_to_all()