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.

util.py 4.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 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 functools
  10. import socket
  11. from typing import Callable, Optional
  12. import megengine._internal as mgb
  13. from ..core import set_default_device
  14. _master_ip = None
  15. _master_port = 0
  16. _world_size = 0
  17. _rank = 0
  18. _backend = None
  19. def init_process_group(
  20. master_ip: str,
  21. master_port: int,
  22. world_size: int,
  23. rank: int,
  24. dev: int,
  25. backend: Optional[str] = "nccl",
  26. ) -> None:
  27. """Initialize the distributed process group, and also specify the device used in the current process.
  28. :param master_ip: IP address of the master node.
  29. :param master_port: Port available for all processes to communicate.
  30. :param world_size: Total number of processes participating in the job.
  31. :param rank: Rank of the current process.
  32. :param dev: The GPU device id to bind this process to.
  33. :param backend: Communicator backend, currently support 'nccl' and 'ucx'
  34. """
  35. global _master_ip # pylint: disable=global-statement
  36. global _master_port # pylint: disable=global-statement
  37. global _world_size # pylint: disable=global-statement
  38. global _rank # pylint: disable=global-statement
  39. global _backend # pylint: disable=global-statement
  40. if not isinstance(master_ip, str):
  41. raise TypeError("Expect type str but got {}".format(type(master_ip)))
  42. if not isinstance(master_port, int):
  43. raise TypeError("Expect type int but got {}".format(type(master_port)))
  44. if not isinstance(world_size, int):
  45. raise TypeError("Expect type int but got {}".format(type(world_size)))
  46. if not isinstance(rank, int):
  47. raise TypeError("Expect type int but got {}".format(type(rank)))
  48. if not isinstance(backend, str):
  49. raise TypeError("Expect type str but got {}".format(type(backend)))
  50. _master_ip = master_ip
  51. _master_port = master_port
  52. _world_size = world_size
  53. _rank = rank
  54. _backend = backend
  55. set_default_device(mgb.comp_node("gpu" + str(dev)))
  56. if rank == 0:
  57. _master_port = mgb.config.create_mm_server("0.0.0.0", master_port)
  58. if _master_port == -1:
  59. raise Exception("Failed to start server on port {}".format(master_port))
  60. else:
  61. assert master_port > 0, "master_port must be specified for non-zero rank"
  62. def is_distributed() -> bool:
  63. """Return True if the distributed process group has been initialized"""
  64. return _world_size is not None and _world_size > 1
  65. def get_master_ip() -> str:
  66. """Get the IP address of the master node"""
  67. return str(_master_ip)
  68. def get_master_port() -> int:
  69. """Get the port of the rpc server on the master node"""
  70. return _master_port
  71. def get_world_size() -> int:
  72. """Get the total number of processes participating in the job"""
  73. return _world_size
  74. def get_rank() -> int:
  75. """Get the rank of the current process"""
  76. return _rank
  77. def get_backend() -> str:
  78. """Get the backend str"""
  79. return str(_backend)
  80. def group_barrier() -> None:
  81. """Block until all ranks in the group reach this barrier"""
  82. mgb.config.group_barrier(_master_ip, _master_port, _world_size, _rank)
  83. def synchronized(func: Callable):
  84. """Decorator. Decorated function will synchronize when finished.
  85. Specifically, we use this to prevent data race during hub.load"""
  86. @functools.wraps(func)
  87. def wrapper(*args, **kwargs):
  88. if not is_distributed():
  89. return func(*args, **kwargs)
  90. ret = func(*args, **kwargs)
  91. group_barrier()
  92. return ret
  93. return wrapper
  94. def get_free_ports(num: Optional[int] = 1) -> int:
  95. """Get one or more free ports.
  96. Return an integer if num is 1, otherwise return a list of integers
  97. """
  98. socks, ports = [], []
  99. for i in range(num):
  100. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  101. sock.bind(("", 0))
  102. socks.append(sock)
  103. ports.append(sock.getsockname()[1])
  104. for sock in socks:
  105. sock.close()
  106. return ports[0] if num == 1 else ports

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