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_distributed.py 6.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import multiprocessing as mp
  10. import platform
  11. import queue
  12. import numpy as np
  13. import pytest
  14. import megengine as mge
  15. import megengine.distributed as dist
  16. from megengine.core.ops.builtin import CollectiveComm, ParamPackConcat, ParamPackSplit
  17. from megengine.device import get_default_device
  18. from megengine.distributed.helper import (
  19. get_device_count_by_fork,
  20. param_pack_concat,
  21. param_pack_split,
  22. )
  23. def _assert_q_empty(q):
  24. try:
  25. res = q.get(timeout=1)
  26. except Exception as e:
  27. assert isinstance(e, queue.Empty)
  28. else:
  29. assert False, "queue is not empty"
  30. def _assert_q_val(q, val):
  31. ret = q.get()
  32. assert ret == val
  33. @pytest.mark.require_ngpu(2)
  34. @pytest.mark.parametrize("backend", ["nccl"])
  35. @pytest.mark.isolated_distributed
  36. def test_init_process_group(backend):
  37. world_size = 2
  38. server = dist.Server()
  39. port = server.py_server_port
  40. def worker(rank):
  41. dist.init_process_group("localhost", port, world_size, rank, rank, backend)
  42. assert dist.is_distributed() == True
  43. assert dist.get_rank() == rank
  44. assert dist.get_world_size() == world_size
  45. assert dist.get_backend() == backend
  46. py_server_addr = dist.get_py_server_addr()
  47. assert py_server_addr[0] == "localhost"
  48. assert py_server_addr[1] == port
  49. mm_server_addr = dist.get_mm_server_addr()
  50. assert mm_server_addr[0] == "localhost"
  51. assert mm_server_addr[1] > 0
  52. assert isinstance(dist.get_client(), dist.Client)
  53. procs = []
  54. for rank in range(world_size):
  55. p = mp.Process(target=worker, args=(rank,))
  56. p.start()
  57. procs.append(p)
  58. for p in procs:
  59. p.join(20)
  60. assert p.exitcode == 0
  61. @pytest.mark.require_ngpu(3)
  62. @pytest.mark.isolated_distributed
  63. def test_new_group():
  64. world_size = 3
  65. ranks = [2, 0]
  66. @dist.launcher
  67. def worker():
  68. rank = dist.get_rank()
  69. if rank in ranks:
  70. group = dist.new_group(ranks)
  71. assert group.size == 2
  72. assert group.key == "2,0"
  73. assert group.rank == ranks.index(rank)
  74. dt = get_default_device()[:-1]
  75. assert group.comp_node == "{}{}:2".format(dt, rank)
  76. worker()
  77. @pytest.mark.require_ngpu(2)
  78. @pytest.mark.isolated_distributed
  79. def test_group_barrier():
  80. world_size = 2
  81. server = dist.Server()
  82. port = server.py_server_port
  83. def worker(rank, q):
  84. dist.init_process_group("localhost", port, world_size, rank, rank)
  85. dist.group_barrier()
  86. if rank == 0:
  87. dist.group_barrier()
  88. q.put(0) # to be observed in rank 1
  89. else:
  90. _assert_q_empty(q) # q.put(0) is not executed in rank 0
  91. dist.group_barrier()
  92. _assert_q_val(q, 0) # q.put(0) executed in rank 0
  93. Q = mp.Queue()
  94. procs = []
  95. for rank in range(world_size):
  96. p = mp.Process(target=worker, args=(rank, Q))
  97. p.start()
  98. procs.append(p)
  99. for p in procs:
  100. p.join(20)
  101. assert p.exitcode == 0
  102. @pytest.mark.require_ngpu(2)
  103. @pytest.mark.isolated_distributed
  104. def test_synchronized():
  105. world_size = 2
  106. server = dist.Server()
  107. port = server.py_server_port
  108. @dist.synchronized
  109. def func(rank, q):
  110. q.put(rank)
  111. def worker(rank, q):
  112. dist.init_process_group("localhost", port, world_size, rank, rank)
  113. dist.group_barrier()
  114. if rank == 0:
  115. func(0, q) # q.put(0)
  116. q.put(2)
  117. else:
  118. _assert_q_val(q, 0) # func executed in rank 0
  119. _assert_q_empty(q) # q.put(2) is not executed
  120. func(1, q)
  121. _assert_q_val(
  122. q, 1
  123. ) # func in rank 1 executed earlier than q.put(2) in rank 0
  124. _assert_q_val(q, 2) # q.put(2) executed in rank 0
  125. Q = mp.Queue()
  126. procs = []
  127. for rank in range(world_size):
  128. p = mp.Process(target=worker, args=(rank, Q))
  129. p.start()
  130. procs.append(p)
  131. for p in procs:
  132. p.join(20)
  133. assert p.exitcode == 0
  134. @pytest.mark.require_ngpu(2)
  135. @pytest.mark.isolated_distributed
  136. def test_user_set_get():
  137. @dist.launcher
  138. def worker():
  139. # set in race condition
  140. dist.get_client().user_set("foo", 1)
  141. # get in race condition
  142. ret = dist.get_client().user_get("foo")
  143. assert ret == 1
  144. worker()
  145. def test_oprmm_hashable():
  146. lhs = (CollectiveComm(), ParamPackConcat(), ParamPackSplit())
  147. rhs = (CollectiveComm(), ParamPackConcat(), ParamPackSplit())
  148. assert lhs == rhs
  149. assert hash(lhs) == hash(rhs)
  150. def test_param_pack_split():
  151. a = mge.Tensor(np.ones((10,), np.int32))
  152. b, c = param_pack_split(a, [0, 1, 1, 10], [(1,), (3, 3)])
  153. assert np.allclose(b.numpy(), a.numpy()[1])
  154. assert np.allclose(c.numpy(), a.numpy()[1:].reshape(3, 3))
  155. def test_param_pack_concat():
  156. a = mge.Tensor(np.ones((1,), np.int32))
  157. b = mge.Tensor(np.ones((3, 3), np.int32))
  158. offsets_val = [0, 1, 1, 10]
  159. offsets = mge.Tensor(offsets_val, np.int32)
  160. c = param_pack_concat([a, b], offsets, offsets_val)
  161. assert np.allclose(np.concatenate([a.numpy(), b.numpy().flatten()]), c.numpy())
  162. @pytest.mark.require_ngpu(2)
  163. @pytest.mark.parametrize("early_return", [False, True], ids=["common", "early_return"])
  164. @pytest.mark.parametrize("output_size", [10, 10000], ids=["small_size", "large_size"])
  165. @pytest.mark.isolated_distributed
  166. def test_collect_results(early_return, output_size):
  167. @dist.launcher
  168. def worker():
  169. if early_return:
  170. exit(0)
  171. return [dist.get_rank()] * output_size
  172. results = worker()
  173. world_size = len(results)
  174. assert world_size > 0
  175. expects = (
  176. [None] * world_size
  177. if early_return
  178. else [[dev] * output_size for dev in range(world_size)]
  179. )
  180. assert results == expects

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台