distributed.py 5.8 KB

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