distributed.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. #!/usr/bin/env python3
  2. # Copyright (c) Facebook, Inc. and its affiliates.
  3. # All rights reserved.
  4. #
  5. # This source code is licensed under the BSD-style license found in the
  6. # LICENSE file in the root directory of this source tree.
  7. import datetime
  8. import socket
  9. from contextlib import closing
  10. import torch.distributed as dist
  11. from torch.distributed.elastic.utils.logging import get_logger
  12. log = get_logger()
  13. _ADDRESS_IN_USE = "Address already in use"
  14. _SOCKET_TIMEOUT = "Socket Timeout"
  15. _MEMBER_CHECKIN = "_tcp_store/num_members"
  16. _LAST_MEMBER_CHECKIN = "_tcp_store/last_member"
  17. def create_c10d_store(
  18. is_server: bool,
  19. server_addr: str,
  20. server_port: int = -1,
  21. world_size: int = 1,
  22. timeout: float = (60 * 10), # 10 min
  23. wait_for_workers: bool = True,
  24. retries=3,
  25. ):
  26. if server_port == -1 and world_size > 1:
  27. raise ValueError(
  28. f"server_port must be specified when world_size > 1, got server_port={server_port}, world_size={world_size}"
  29. )
  30. if server_port != -1:
  31. log.info(f"sever_port: {server_port}, specified, ignoring retries")
  32. # only retry when server_port is NOT static
  33. attempt = retries if server_port == -1 else 1
  34. while True:
  35. if server_port != -1:
  36. port = server_port
  37. else:
  38. port = get_free_port()
  39. log.info(
  40. f"Creating c10d store on {server_addr}:{port}\n"
  41. f" world_size : {world_size}\n"
  42. f" is_server : {is_server}\n"
  43. f" timeout(sec): {timeout}\n"
  44. )
  45. try:
  46. store = dist.TCPStore(
  47. host_name=server_addr,
  48. port=port,
  49. world_size=world_size,
  50. is_master=is_server,
  51. timeout=datetime.timedelta(seconds=timeout),
  52. wait_for_workers=wait_for_workers,
  53. )
  54. # skips full rank check when we don't have to wait for all workers
  55. if wait_for_workers:
  56. _check_full_rank(store, world_size)
  57. log.info("Successfully created c10d store")
  58. return store
  59. except RuntimeError as e:
  60. # this is brittle, but the underlying exception type is not properly pybinded
  61. # so we parse the error msg for now, interestingly this is how torch itself
  62. # detects timeouts and port conflicts in their own unittests
  63. # see - caffe2/torch/testing/_internal/common_utils.py
  64. # TODO properly map the exceptions in pybind (c10d/init.cpp)
  65. if str(e) == _ADDRESS_IN_USE: # this will only happen on the server
  66. if attempt < retries:
  67. log.warning(
  68. f"port: {port} already in use, attempt: [{attempt}/{retries}]"
  69. )
  70. attempt += 1
  71. else:
  72. raise RuntimeError(
  73. f"on {server_addr}, port: {port} already in use"
  74. ) from e
  75. else:
  76. raise
  77. def _check_full_rank(store, world_size):
  78. idx = store.add(_MEMBER_CHECKIN, 1)
  79. if idx == world_size:
  80. store.set(_LAST_MEMBER_CHECKIN, "<val_ignored>")
  81. try:
  82. store.get(_LAST_MEMBER_CHECKIN)
  83. except RuntimeError as e:
  84. if str(e) == _SOCKET_TIMEOUT:
  85. raise TimeoutError(
  86. f"timed out waiting for all {world_size} members to join"
  87. ) from e
  88. else:
  89. raise
  90. def get_free_port():
  91. sock = get_socket_with_port()
  92. with closing(sock):
  93. return sock.getsockname()[1]
  94. def get_socket_with_port() -> socket.socket:
  95. """
  96. Returns a free port on localhost that is "reserved" by binding a temporary
  97. socket on it. Close the socket before passing the port to the entity
  98. that requires it. Usage example
  99. ::
  100. sock = _get_socket_with_port()
  101. with closing(sock):
  102. port = sock.getsockname()[1]
  103. sock.close()
  104. # there is still a race-condition that some other process
  105. # may grab this port before func() runs
  106. func(port)
  107. """
  108. addrs = socket.getaddrinfo(
  109. host="localhost", port=None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM
  110. )
  111. for addr in addrs:
  112. family, type, proto, _, _ = addr
  113. s = socket.socket(family, type, proto)
  114. try:
  115. s.bind(("localhost", 0))
  116. s.listen(0)
  117. return s
  118. except OSError as e:
  119. s.close()
  120. log.info("Socket creation attempt failed.", exc_info=e)
  121. raise RuntimeError("Failed to create a socket")