distributed.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. #!/usr/bin/env python3
  2. # mypy: allow-untyped-defs
  3. # Copyright (c) Facebook, Inc. and its affiliates.
  4. # All rights reserved.
  5. #
  6. # This source code is licensed under the BSD-style license found in the
  7. # LICENSE file in the root directory of this source tree.
  8. import datetime
  9. import os
  10. import socket
  11. from contextlib import closing
  12. import torch.distributed as dist
  13. from torch.distributed.elastic.utils.logging import get_logger
  14. from torch.distributed.elastic.utils.store import barrier
  15. __all__ = ["create_c10d_store", "get_free_port", "get_socket_with_port"]
  16. logger = get_logger(__name__)
  17. _ADDRESS_IN_USE = "Address already in use"
  18. _SOCKET_TIMEOUT = "Socket Timeout"
  19. _TCP_STORE_INIT = "_tcp_store/num_members"
  20. def create_c10d_store(
  21. is_server: bool,
  22. server_addr: str,
  23. server_port: int = -1,
  24. world_size: int = 1,
  25. timeout: float = (60 * 10), # 10 min
  26. wait_for_workers: bool = True,
  27. retries=3,
  28. use_libuv: bool | None = None,
  29. ):
  30. if use_libuv is not None:
  31. logger.warning(
  32. "argument use_libuv is deprecated and ignored. Set USE_LIBUV environment "
  33. 'variable to "0" to disable libuv, or "1" to enable it. If the env var '
  34. "is not set, libuv will be used by default."
  35. )
  36. # check os.environ for use_libuv
  37. use_libuv = os.environ.get("USE_LIBUV", "1") == "1" # libuv is the default option
  38. if server_port == -1 and world_size > 1:
  39. raise ValueError(
  40. f"server_port must be specified when world_size > 1, got server_port={server_port}, world_size={world_size}"
  41. )
  42. if server_port != -1:
  43. logger.info("sever_port: %s, specified, ignoring retries", server_port)
  44. # only retry when server_port is NOT static
  45. attempt = retries if server_port == -1 else 1
  46. while True:
  47. if server_port != -1:
  48. port = server_port
  49. else:
  50. port = get_free_port()
  51. logger.info(
  52. "Creating c10d store on %s:%s\n"
  53. " world_size : %s\n"
  54. " is_server : %s\n"
  55. " timeout(sec): %s\n"
  56. " use_libuv : %s\n",
  57. server_addr,
  58. port,
  59. world_size,
  60. is_server,
  61. timeout,
  62. use_libuv,
  63. )
  64. try:
  65. store = dist.TCPStore(
  66. host_name=server_addr,
  67. port=port,
  68. world_size=world_size,
  69. is_master=is_server,
  70. timeout=datetime.timedelta(seconds=timeout),
  71. wait_for_workers=wait_for_workers,
  72. use_libuv=use_libuv,
  73. )
  74. # skips full rank check when we don't have to wait for all workers
  75. if wait_for_workers:
  76. _check_full_rank(store, world_size, timeout=timeout)
  77. logger.info("Successfully created c10d store")
  78. return store
  79. except RuntimeError as e:
  80. # this is brittle, but the underlying exception type is not properly pybinded
  81. # so we parse the error msg for now, interestingly this is how torch itself
  82. # detects timeouts and port conflicts in their own unittests
  83. # see - caffe2/torch/testing/_internal/common_utils.py
  84. # TODO properly map the exceptions in pybind (c10d/init.cpp)
  85. if str(e) == _ADDRESS_IN_USE: # this will only happen on the server
  86. if attempt < retries:
  87. logger.warning(
  88. "port: %s already in use, attempt: [%s/%s]",
  89. port,
  90. attempt,
  91. retries,
  92. )
  93. attempt += 1
  94. else:
  95. raise RuntimeError(
  96. f"on {server_addr}, port: {port} already in use"
  97. ) from e
  98. else:
  99. raise
  100. def _check_full_rank(store, world_size, timeout):
  101. try:
  102. barrier(store, world_size, key_prefix=_TCP_STORE_INIT, barrier_timeout=timeout)
  103. except RuntimeError as e:
  104. if str(e) == _SOCKET_TIMEOUT:
  105. raise TimeoutError(
  106. f"timed out waiting for all {world_size} members to join"
  107. ) from e
  108. else:
  109. raise
  110. def get_free_port():
  111. """
  112. Returns an unused port on localhost.
  113. This function finds an unused port on localhost by opening to socket to bind
  114. to a port and then closing it.
  115. Returns:
  116. int: an unused port on localhost
  117. Example:
  118. >>> # xdoctest: +SKIP("Nondeterministic")
  119. >>> get_free_port()
  120. 63976
  121. .. note::
  122. The port returned by :func:`get_free_port` is not reserved and may be
  123. taken by another process after this function returns.
  124. """
  125. sock = get_socket_with_port()
  126. with closing(sock):
  127. return sock.getsockname()[1]
  128. def get_socket_with_port() -> socket.socket:
  129. """
  130. Returns a free port on localhost that is "reserved" by binding a temporary
  131. socket on it. Close the socket before passing the port to the entity
  132. that requires it. Usage example
  133. ::
  134. sock = _get_socket_with_port()
  135. with closing(sock):
  136. port = sock.getsockname()[1]
  137. sock.close()
  138. # there is still a race-condition that some other process
  139. # may grab this port before func() runs
  140. func(port)
  141. """
  142. addrs = socket.getaddrinfo(
  143. host="localhost", port=None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM
  144. )
  145. for addr in addrs:
  146. family, type, proto, _, _ = addr
  147. s = socket.socket(family, type, proto)
  148. try:
  149. s.bind(("localhost", 0))
  150. s.listen(0)
  151. return s
  152. except OSError as e:
  153. s.close()
  154. logger.warning("Socket creation attempt failed.", exc_info=e)
  155. raise RuntimeError("Failed to create a socket")