etcd_rendezvous.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  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 json
  9. import logging
  10. import sys
  11. import threading
  12. import time
  13. from typing import Optional
  14. import etcd # type: ignore[import]
  15. from torch.distributed.elastic.rendezvous import (
  16. RendezvousClosedError,
  17. RendezvousError,
  18. RendezvousHandler,
  19. RendezvousParameters,
  20. RendezvousTimeoutError,
  21. )
  22. from .utils import parse_rendezvous_endpoint
  23. from .etcd_store import EtcdStore, cas_delay
  24. _log_fmt = logging.Formatter("%(levelname)s %(asctime)s %(message)s")
  25. _log_handler = logging.StreamHandler(sys.stderr)
  26. _log_handler.setFormatter(_log_fmt)
  27. log = logging.getLogger(__name__)
  28. log.propagate = False
  29. log.setLevel(logging.INFO)
  30. log.addHandler(_log_handler)
  31. # Retryable failure exception means the we were too late to make
  32. # a desired state transition (e.g. because of a race condition),
  33. # and should now restart from the beginning.
  34. # A small delay is recommended to avoid spamming Etcd.
  35. class EtcdRendezvousRetryableFailure(Exception):
  36. pass
  37. # Similar to retryable failure, but the new state we observed suggests we
  38. # can re-try immediately, i.e. without a need for "safety delay".
  39. class EtcdRendezvousRetryImmediately(Exception):
  40. pass
  41. # Default timeout for the rendezvous.
  42. _DEFAULT_TIMEOUT: int = 600 # 10 minutes
  43. # Additional waiting time after reaching the minimum number of nodes
  44. # in case the rendezvous is elastic (min != max).
  45. _DEFAULT_LAST_CALL_TIMEOUT: int = 30 # 30 seconds
  46. # Various constants used internally in EtcdRendezvous
  47. CONST_ETCD_SETUP_TTL = 5
  48. CONST_ETCD_FROZEN_TTL = 10
  49. CONST_ETCD_JOINABLE_EPHEMERAL_TTL = 10
  50. # Ephemeral node TTL for worker's keep-alive key:
  51. CONST_WORKER_KEEPALIVE_TTL = 10
  52. # TTL for the ephemeral run_id-specific directory. All rendezvous state data
  53. # for a specific run_id (job instance) is contained within directory.
  54. # Its only role is to clean-up rendezvous data from old runs (for the case when
  55. # etcd server is persistent), and has no affect on correctnes, but should be
  56. # larger than any timeouts that a worker process is expected to survive:
  57. CONST_RUNID_SUBROOT_TTL = 7200 # 2 hours
  58. class EtcdRendezvousHandler(RendezvousHandler):
  59. """
  60. Implements a
  61. :py:class:`torch.distributed.elastic.rendezvous.RendezvousHandler` interface
  62. backed by
  63. :py:class:`torch.distributed.elastic.rendezvous.etcd_rendezvous.EtcdRendezvous`.
  64. ``EtcdRendezvousHandler`` uses a URL to configure the type of rendezvous to
  65. use and to pass implementation specific configurations to the rendezvous
  66. module. The basic etcd rendezvous configuration URL looks like the following
  67. ::
  68. etcd://<etcd_address>:<port>/<job_id>?min_workers=<min_workers>&max_workers=<max_workers> # noqa: W605
  69. -- example --
  70. etcd://localhost:2379/1234?min_workers=1&max_workers=3
  71. The URL above is interpreted as follows:
  72. 1. Use the rendezvous handler that is registered with the ``etcd``
  73. scheme
  74. 2. The ``etcd`` endpoint to use is ``localhost:2379``
  75. 3. ``job_id == 1234`` is used as the prefix in etcd (this allows one to
  76. share a common etcd server for multiple jobs so long as the
  77. ``job_ids`` are guaranteed to be unique). Note that the job id can be
  78. any string (e.g. does not need to be a number) as long as it is
  79. unique.
  80. 4. ``min_workers=1`` and ``max_workers=3`` specifies a range for
  81. membership size - Torch Distributed Elastic starts running the job as
  82. long as the cluster size is greater than or equal to ``min_workers``
  83. and admits up to ``max_workers`` into the cluster.
  84. Below are a full list of the parameters that can be passed to etcd
  85. rendezvous:
  86. +--------------------------------------------+--------------------------+
  87. | Parameter | Description |
  88. +============================================+==========================+
  89. | min_workers | minimum number of |
  90. | | workers for the |
  91. | | rendezvous to be valid |
  92. +--------------------------------------------+--------------------------+
  93. | max_workers | maximum number of |
  94. | | workers to admit |
  95. +--------------------------------------------+--------------------------+
  96. | timeout | total timeout within |
  97. | | which next_rendezvous is |
  98. | | expected to succeed |
  99. | | (default 600s) |
  100. +--------------------------------------------+--------------------------+
  101. | last_call_timeout | additional wait amount |
  102. | | (“last call”) after min |
  103. | | number of workers has |
  104. | | been reached (defaults |
  105. | | to 30s) |
  106. +--------------------------------------------+--------------------------+
  107. | etcd_prefix | path prefix (from etcd |
  108. | | root), inside which all |
  109. | | etcd nodes will be |
  110. | | created (defaults to |
  111. | | ``/torchelastic/p2p``) |
  112. +--------------------------------------------+--------------------------+
  113. """
  114. def __init__(self, rdzv_impl):
  115. self._rdzv_impl = rdzv_impl
  116. def __del__(self):
  117. # TODO: look into using weakref here instead.
  118. del self._rdzv_impl
  119. def get_backend(self) -> str:
  120. return "etcd"
  121. def next_rendezvous(self):
  122. rdzv_version, rank, world_size = self._rdzv_impl.rendezvous_barrier()
  123. log.info("Creating EtcdStore as the c10d::Store implementation")
  124. store = self._rdzv_impl.setup_kv_store(rdzv_version)
  125. return store, rank, world_size
  126. def is_closed(self):
  127. try:
  128. _, state = self._rdzv_impl.get_rdzv_state()
  129. return state["status"] == "closed"
  130. except etcd.EtcdKeyNotFound:
  131. # No rendezvous state, so it cannot be closed.
  132. return False
  133. def set_closed(self):
  134. self._rdzv_impl.set_closed()
  135. def num_nodes_waiting(self):
  136. try:
  137. _, state = self._rdzv_impl.get_rdzv_state()
  138. if state["status"] == "final":
  139. return state["num_workers_waiting"]
  140. except etcd.EtcdKeyNotFound:
  141. pass
  142. return 0
  143. def get_run_id(self) -> str:
  144. return self._rdzv_impl._run_id
  145. def shutdown(self) -> bool:
  146. try:
  147. self.set_closed()
  148. return True
  149. except BaseException as e:
  150. log.warning(f"Shutdown failed. Error occurred: {str(e)}")
  151. return False
  152. # TODO: we should probably handle a few additional errors,
  153. # like EtcdLeaderElectionInProgress and EtcdWatcherCleared. These are
  154. # only relevant for multi-node Etcd ensemble. A simple retry would work,
  155. # but is verbose to add everywhere. Consider wrapping the client calls
  156. # into auto-retry for these errors?
  157. #
  158. class EtcdRendezvous:
  159. """
  160. A rendezvous implementation that uses `etcd <https://etcd.io/>`__ as
  161. the backend store.
  162. """
  163. def __init__(
  164. self,
  165. client,
  166. prefix,
  167. run_id,
  168. num_min_workers,
  169. num_max_workers,
  170. timeout,
  171. last_call_timeout,
  172. ):
  173. self.client = client
  174. log.info("Etcd machines: " + str(self.client.machines))
  175. self._prefix = prefix
  176. self._run_id = run_id
  177. self._num_min_workers = num_min_workers
  178. self._num_max_workers = num_max_workers
  179. self._timeout = timeout
  180. self._last_call_timeout = last_call_timeout
  181. # For cleaning up TTL refresher threads (for ephemeral keys)
  182. self._lease_run_id_stop = None
  183. self._lease_this_rank_stop = None
  184. if not self._prefix.endswith("/"):
  185. self._prefix += "/"
  186. # Setup a permanent prefix dir, if didn't exist
  187. if self._prefix != "/":
  188. self.create_path_if_not_exists(self._prefix)
  189. # Lease a "sub-root" node specific to this job instance (run_id)
  190. self.create_path_if_not_exists(self.get_path(""), ttl=CONST_RUNID_SUBROOT_TTL)
  191. self._lease_run_id_stop = self.setup_lease_renewal(
  192. self.get_path(""), ttl=CONST_RUNID_SUBROOT_TTL
  193. )
  194. # Subdir for all rendezvous work
  195. self.create_path_if_not_exists(self.get_path("/rdzv"))
  196. # Create a rendezvous version counter, if doesn't exist
  197. try:
  198. self.client.write(
  199. key=self.get_path("/rdzv/version_counter"), value="0", prevExist=False
  200. )
  201. except etcd.EtcdAlreadyExist:
  202. pass
  203. def __del__(self):
  204. # TODO: look into using weakref here instead.
  205. if self._lease_run_id_stop is not None:
  206. self._lease_run_id_stop.set()
  207. if self._lease_this_rank_stop is not None:
  208. self._lease_this_rank_stop.set()
  209. def rendezvous_barrier(self):
  210. """
  211. Main entry point for next rendezvous.
  212. This method is blocking until rendezvous succeeds or a timeout occurs.
  213. Returns:
  214. ``(rdzv_version, rank, world_size)``
  215. Raises:
  216. RendezvousTimeoutError - timeout waiting for rendezvous
  217. RendezvousClosedError - rendezvous is or was closed while waiting
  218. RendezvousError - other persistent errors that
  219. render the rendezvous non-retryable
  220. """
  221. self._rendezvous_deadline = time.time() + self._timeout
  222. while True:
  223. if time.time() > self._rendezvous_deadline:
  224. raise RendezvousTimeoutError()
  225. log.info("Attempting to join next rendezvous")
  226. try:
  227. # Dis-own our lease in the previous rendezvous, if exists
  228. if self._lease_this_rank_stop is not None:
  229. self._lease_this_rank_stop.set()
  230. return self.init_phase()
  231. except EtcdRendezvousRetryImmediately:
  232. # The type of failure suggests we can retry without delay
  233. pass
  234. except EtcdRendezvousRetryableFailure:
  235. # In case of retryable failure, wait a small delay
  236. # to avoid spamming etcd
  237. time.sleep(1)
  238. except RendezvousTimeoutError:
  239. log.info("Rendezvous timeout occurred in EtcdRendezvousHandler")
  240. raise
  241. except RendezvousClosedError:
  242. log.info(
  243. f"Rendezvous for run_id={self._run_id} was observed to be closed"
  244. )
  245. raise
  246. except RendezvousError:
  247. raise
  248. except Exception as e:
  249. # In case of a general exception, wait a small delay
  250. # to avoid spamming etcd
  251. # FIXME: there are a few things that fall under this like
  252. # etcd.EtcdKeyNotFound, etc, which could be handled more explicitly.
  253. log.info("Rendezvous attempt failed, will retry. Reason: " + str(e))
  254. time.sleep(1)
  255. def init_phase(self):
  256. """
  257. Initially, the rendezvous state is expected to be one of:
  258. 1. empty (non-existent) - in this case we try to create a new one.
  259. 2. joinable - we try to join it.
  260. 3. final - we announce ourselves as waiting, and go into monitoring mode
  261. Any other state is considered transitional, and will be retried after
  262. a short delay.
  263. Returns:
  264. ``(rdzv_version, rank, world_size)``
  265. Raises:
  266. RendezvousClosedError - current rendezvous was/is closed
  267. EtcdRendezvousRetryableFailure - observed some intermediate
  268. state, which is best handled by retrying later
  269. """
  270. try:
  271. active_version = self.try_create_rendezvous()
  272. state = json.loads(active_version.value)
  273. log.info("New rendezvous state created: " + str(state))
  274. except etcd.EtcdAlreadyExist:
  275. active_version, state = self.get_rdzv_state()
  276. # Note: it is possible for above query to fail (etcd.EtcdKeyNotFound),
  277. # but this is ok for us - just means we'll restart from beginning.
  278. log.info("Observed existing rendezvous state: " + str(state))
  279. if state["status"] == "closed":
  280. raise RendezvousClosedError()
  281. if state["status"] == "joinable":
  282. return self.join_phase(state["version"])
  283. if state["status"] == "final":
  284. self.handle_existing_rendezvous(state["version"])
  285. raise EtcdRendezvousRetryImmediately()
  286. self.try_wait_for_state_change(etcd_index=active_version.etcd_index + 1)
  287. raise EtcdRendezvousRetryableFailure()
  288. def join_phase(self, expected_version):
  289. """
  290. We observed a rendezvous state in 'joinable' state, and attempt to join this
  291. particular version, and then wait for all other peers to join.
  292. """
  293. # Failure to join will propagate an exception, causing a re-entry.
  294. active_version, this_rank = self.join_rendezvous(expected_version)
  295. state = json.loads(active_version.value)
  296. log.info(
  297. "Joined rendezvous version {} as rank {}. Full state: {}".format(
  298. state["version"], this_rank, state
  299. )
  300. )
  301. # If this worker was first to reach num_min_workers requirement,
  302. # and rendezvous is still joinable (therefore it is elastic),
  303. # then this worker will be repsonsible for waiting out the "last call"
  304. # timeout and closing (i.e. transitioning to 'frozen') the rendezvous
  305. # afterwards.
  306. # As a safety against a potential failure of this worker (during the
  307. # last call timeout), the rendezvous state is made ephemeral
  308. # when min_num_workers is reached.
  309. if this_rank == self._num_min_workers - 1 and state["status"] == "joinable":
  310. log.info("Rank {} is responsible for join last call.".format(this_rank))
  311. last_call_deadline = time.time() + self._last_call_timeout
  312. self.handle_join_last_call(expected_version, last_call_deadline)
  313. log.info("Rank {} finished join last call.".format(this_rank))
  314. # Wait for rendezvous state to be frozen, which means a fixed set of peers
  315. log.info("Waiting for remaining peers.")
  316. active_version = self.wait_for_peers(expected_version)
  317. state = json.loads(active_version.value)
  318. assert (
  319. state["version"] == expected_version
  320. ), "Logic error: failed to observe version mismatch"
  321. return self.confirm_phase(expected_version, this_rank)
  322. def confirm_phase(self, expected_version, this_rank):
  323. """
  324. Once the rendezvous state trainsitions from 'joinable' to 'frozen',
  325. we have every participant confirm their membership and setup per-member
  326. keep-alive TTL keys, and then wait for all other participants to confirm,
  327. which would then successfully conclude this rendezvous.
  328. """
  329. log.info("All peers arrived. Confirming membership.")
  330. self.confirm_membership(expected_version, this_rank)
  331. log.info("Waiting for confirmations from all peers.")
  332. active_version = self.wait_for_final(expected_version)
  333. state = json.loads(active_version.value)
  334. log.info(
  335. "Rendezvous version {} is complete. Final state: {}".format(
  336. state["version"], state
  337. )
  338. )
  339. # Rendezvous version number; our rank in it; world size
  340. return state["version"], this_rank, len(state["participants"])
  341. def handle_existing_rendezvous(self, expected_version):
  342. """
  343. Handle the case when there's an existing (state 'final) rendezvous already
  344. in place, and we have to announce ourselves waiting, and wait until
  345. the next rendezvous opportunity.
  346. """
  347. # If state is 'final' -> increment num_workers_waiting
  348. # Then, observe state changes:
  349. # 1. if it's no longer final -> bail out and re-try
  350. # 2. if keep alives are missing, destroy it and bail out.
  351. active_state = self.announce_self_waiting(expected_version)
  352. log.info(
  353. "Added self to waiting list. Rendezvous full state: {}".format(
  354. active_state.value
  355. )
  356. )
  357. self.wait_for_rendezvous_to_free(expected_version)
  358. log.info("Previously existing rendezvous state changed. Will re-try joining.")
  359. def try_create_rendezvous(self):
  360. """
  361. Create new rendezvous state or raise an exception that indicates
  362. an unexpected state (e.g. already exists)
  363. Raises:
  364. RendezvousError - on unexpected state
  365. """
  366. # Initially active_version is ephemeral - this is to handle the
  367. # possibility that might fail to complete the setup transaction,
  368. # i.e. the transition "setup" -> "joinable".
  369. active_version = self.client.write(
  370. key=self.get_path("/rdzv/active_version"),
  371. value=json.dumps({"status": "setup"}),
  372. prevExist=False,
  373. ttl=CONST_ETCD_SETUP_TTL,
  374. )
  375. try:
  376. version_counter = self.client.get(self.get_path("/rdzv/version_counter"))
  377. version_counter.value = str(int(version_counter.value) + 1)
  378. self.client.update(version_counter)
  379. except (etcd.EtcdKeyNotFound, etcd.EtcdCompareFailed) as e:
  380. raise RendezvousError(
  381. "Unexpected state of EtcdRendezvousHandler, worker needs to die."
  382. ) from e
  383. # Any failure below results in declaring a retryable rendezvous failure.
  384. # The ephemeral /rdzv/active_version will expire and someone can then
  385. # re-try the setup process.
  386. # Create directory node for participant data
  387. self.client.write(
  388. key=self.get_path("/rdzv/v_{}".format(version_counter.value)),
  389. value=None,
  390. dir=True,
  391. prevExist=False,
  392. )
  393. # Publish rendezvous version and signal it is ready-to-be-joined.
  394. # If rendezvous was set closed just before this, a retry will happen,
  395. # where the closed condition will be handled.
  396. return self.client.test_and_set(
  397. key=self.get_path("/rdzv/active_version"),
  398. value=json.dumps(
  399. {
  400. "status": "joinable",
  401. "version": version_counter.value,
  402. "participants": [],
  403. }
  404. ),
  405. prev_value=active_version.value,
  406. )
  407. def join_rendezvous(self, expected_version):
  408. """
  409. Helper method for the join phase.
  410. """
  411. # Use compare-and-swap to add self to rendezvous state:
  412. while True:
  413. cas_delay()
  414. active_version, state = self.get_rdzv_state()
  415. if state["status"] != "joinable":
  416. raise EtcdRendezvousRetryableFailure(
  417. "Rendezvous state became non-joinable before we could join. "
  418. "Must join next one."
  419. )
  420. if state["version"] != expected_version:
  421. raise EtcdRendezvousRetryImmediately(
  422. "Rendezvous version changed. Must try join the new one."
  423. )
  424. assert (
  425. len(state["participants"]) < self._num_max_workers
  426. ), "Logic error: joinable rendezvous should always have space left"
  427. this_rank = len(state["participants"])
  428. state["participants"].append(this_rank)
  429. # When reaching min workers, or changing state to frozen, we'll set
  430. # the active_version node to be ephemeral.
  431. set_ttl: Optional[int] = None
  432. if len(state["participants"]) == self._num_max_workers:
  433. state["status"] = "frozen"
  434. state["keep_alives"] = []
  435. set_ttl = CONST_ETCD_FROZEN_TTL
  436. elif len(state["participants"]) >= self._num_min_workers:
  437. set_ttl = CONST_ETCD_JOINABLE_EPHEMERAL_TTL
  438. try:
  439. # Compare-and-swap.
  440. active_version = self.client.test_and_set(
  441. key=self.get_path("/rdzv/active_version"),
  442. value=json.dumps(state),
  443. prev_value=active_version.value,
  444. ttl=set_ttl,
  445. )
  446. # We succeeded joining.
  447. return active_version, this_rank
  448. except etcd.EtcdCompareFailed:
  449. log.info("Join rendezvous CAS unsuccessful, retrying")
  450. def wait_for_peers(self, expected_version):
  451. """
  452. Helper method for the join phase.
  453. """
  454. active_version, state = self.get_rdzv_state()
  455. while True:
  456. if state["status"] == "frozen" and state["version"] == expected_version:
  457. # Success, all peers arrived.
  458. return active_version
  459. elif state["status"] == "joinable" and state["version"] == expected_version:
  460. # Continue waiting for any interesting events.
  461. active_version, state = self.try_wait_for_state_change(
  462. etcd_index=active_version.etcd_index + 1
  463. )
  464. else:
  465. # No valid transition possible at this point
  466. raise EtcdRendezvousRetryableFailure(
  467. "Rendezvous state transition no longer possible. Must re-enter."
  468. )
  469. def confirm_membership(self, expected_version, this_rank):
  470. """
  471. Helper method for the confirm phase
  472. """
  473. # Compare-and-swap loop
  474. while True:
  475. cas_delay()
  476. active_version, state = self.get_rdzv_state()
  477. if state["status"] != "frozen":
  478. raise EtcdRendezvousRetryImmediately(
  479. "Rendezvous no longer frozen, before we confirmed. "
  480. "Must join next one"
  481. )
  482. if state["version"] != expected_version:
  483. raise EtcdRendezvousRetryImmediately(
  484. "Rendezvous version changed. Must try join the new one."
  485. )
  486. this_lease_key = self.get_path(
  487. "/rdzv/v_{}/rank_{}".format(expected_version, this_rank)
  488. )
  489. self.client.set(this_lease_key, value=None, ttl=CONST_WORKER_KEEPALIVE_TTL)
  490. state["keep_alives"].append(this_lease_key)
  491. if len(state["keep_alives"]) == len(state["participants"]):
  492. # Everyone confirmed (this rank is last to do so)
  493. state["status"] = "final"
  494. state["num_workers_waiting"] = 0
  495. finalize = True
  496. else:
  497. finalize = False
  498. try:
  499. # Compare-and-swap. If new state is still frozen, keep it ephemeral.
  500. active_version = self.client.test_and_set(
  501. key=self.get_path("/rdzv/active_version"),
  502. value=json.dumps(state),
  503. prev_value=active_version.value,
  504. ttl=None if finalize else CONST_ETCD_FROZEN_TTL,
  505. )
  506. self._lease_this_rank_stop = self.setup_lease_renewal(
  507. this_lease_key, ttl=CONST_WORKER_KEEPALIVE_TTL
  508. )
  509. return active_version
  510. except etcd.EtcdCompareFailed:
  511. log.info("Confirm membership CAS unsuccessful, retrying")
  512. def wait_for_final(self, expected_version):
  513. """
  514. Helper method for the confirm phase
  515. """
  516. active_version, state = self.get_rdzv_state()
  517. while True:
  518. if state["status"] == "final" and state["version"] == expected_version:
  519. # Succcess. This rendezvous is final, and we accept it.
  520. return active_version
  521. elif state["status"] == "frozen" and state["version"] == expected_version:
  522. # Continue waiting for any interesting events.
  523. active_version, state = self.try_wait_for_state_change(
  524. etcd_index=active_version.etcd_index + 1
  525. )
  526. else:
  527. # No valid transition possible at this point
  528. raise EtcdRendezvousRetryableFailure(
  529. "Rendezvous state transition no longer possible. Must re-enter."
  530. )
  531. def announce_self_waiting(self, expected_version):
  532. """
  533. Announce this worker is waiting (via num_workers_waiting counter) to join next
  534. rendezvous, but only if state and version match.
  535. """
  536. while True:
  537. cas_delay()
  538. active_version, state = self.get_rdzv_state()
  539. if state["status"] != "final" or state["version"] != expected_version:
  540. raise EtcdRendezvousRetryImmediately()
  541. # Increment counter to signal an additional waiting worker.
  542. state["num_workers_waiting"] += 1
  543. try:
  544. active_version = self.client.test_and_set(
  545. key=self.get_path("/rdzv/active_version"),
  546. value=json.dumps(state),
  547. prev_value=active_version.value,
  548. )
  549. return active_version
  550. except etcd.EtcdCompareFailed:
  551. log.info("Announce self as waiting CAS unsuccessful, retrying")
  552. def wait_for_rendezvous_to_free(self, expected_version):
  553. """
  554. When there's an existing valid rendezvous in state 'final', we have to
  555. wait until the next opportunity to join.
  556. Such opportunity may come from:
  557. 1. rendezvous state changed by someone else, in which case we unblock and retry.
  558. 2. rendezvous becomes invalid because at least one member failed to renew their
  559. leased keep_alive node. We detect this, and destroy the rendezvous.
  560. """
  561. active_version, state = self.get_rdzv_state()
  562. while True:
  563. if state["status"] != "final" or state["version"] != expected_version:
  564. return
  565. # Check if current rendezvous state is valid, in the sense that all
  566. # its members are alive (renewing their lease).
  567. # If not, try destroy this rendezvous, so a new one can be created.
  568. alive_members = self.client.get(
  569. self.get_path("/rdzv/v_{version}".format(version=expected_version))
  570. )
  571. keep_alive_keys = [ch.key for ch in alive_members.children]
  572. for key in state["keep_alives"]:
  573. if key not in keep_alive_keys:
  574. # This participant didn't renew their lease. We'll declare this
  575. # rendezvous version as dead (but only if it hadn't changed)
  576. log.info("Keep-alive key {} is not renewed.".format(key))
  577. log.info(
  578. "Rendevous version {} is incomplete. ".format(expected_version)
  579. )
  580. log.info("Attempting to destroy it.")
  581. # Compare-and-delete operation. Throws if compare failed,
  582. # which means rendezvous was already destroyed/re-created/closed,
  583. # and we can try to re-enter the barrier.
  584. self.client.delete(
  585. key=self.get_path("/rdzv/active_version"),
  586. prevValue=active_version.value,
  587. )
  588. log.info(
  589. "Destroyed rendezvous version {} successfully.".format(
  590. expected_version
  591. )
  592. )
  593. # We can return (and retry) immediately
  594. return
  595. # Existing rendezvous seems valid, no reason to destroy it.
  596. # We just have to wait until something changes and re-check.
  597. try:
  598. overall_timeout = (
  599. max(self._rendezvous_deadline - time.time(), 0.0) + 1.0
  600. )
  601. self.client.watch(
  602. key=self.get_path("/rdzv"),
  603. index=active_version.etcd_index + 1,
  604. recursive=True,
  605. timeout=overall_timeout,
  606. )
  607. except (etcd.EtcdEventIndexCleared, etcd.EtcdWatchTimedOut):
  608. pass
  609. if time.time() > self._rendezvous_deadline:
  610. raise RendezvousTimeoutError()
  611. active_version, state = self.get_rdzv_state()
  612. def handle_join_last_call(self, expected_version, deadline):
  613. """
  614. After we reach min number of workers, one particular worker takes on the
  615. responsibility of waiting an additional timeout before closing the join window.
  616. If the worker responsible for this fails, the rendezvous will be destroyed due
  617. to expiring TTL, and the other participants will re-rendezvous.
  618. Here we expect to see state <joinable, expected_version>
  619. Exit gracefully if either:
  620. 1. state becomes <frozen, expected_version>
  621. 2. timeout happens (reaching deadline), in which case
  622. we try the tranisiton to <frozen, expected_version>
  623. Exit with exception otherwise.
  624. """
  625. active_version, state = self.get_rdzv_state()
  626. while True:
  627. if state["status"] == "frozen" and state["version"] == expected_version:
  628. # Worker set became frozen before last-call timeout. This is possible
  629. # when num_max_workers is reached before the tiemout.
  630. return
  631. if state["status"] != "joinable" or state["version"] != expected_version:
  632. raise EtcdRendezvousRetryableFailure(
  633. "Rendezvous state transition no longer possible. Must re-enter."
  634. )
  635. # If timeout occurred, attempt a state transition (joinable -> frozen)
  636. if time.time() >= deadline:
  637. state["status"] = "frozen"
  638. state["keep_alives"] = []
  639. try:
  640. active_version = self.client.test_and_set(
  641. key=self.get_path("/rdzv/active_version"),
  642. value=json.dumps(state),
  643. prev_value=active_version.value,
  644. ttl=CONST_ETCD_FROZEN_TTL,
  645. )
  646. # We successfully made this rendezvous frozen.
  647. return
  648. except etcd.EtcdCompareFailed:
  649. log.info("Join last-call transition CAS unsuccessful. Will retry")
  650. cas_delay()
  651. active_version, state = self.get_rdzv_state()
  652. continue
  653. # Timeout did not occur, so we must refresh TTL, and wait for
  654. # further changes. Note: we only want TTL to be refreshed if
  655. # state is still joinable, hence we use CAS for that here,
  656. # even though we don't change any of the data.
  657. try:
  658. active_version = self.client.test_and_set(
  659. key=self.get_path("/rdzv/active_version"),
  660. value=active_version.value,
  661. prev_value=active_version.value,
  662. ttl=CONST_ETCD_JOINABLE_EPHEMERAL_TTL,
  663. )
  664. # Minimize "oversleeping":
  665. timeout = min(
  666. CONST_ETCD_JOINABLE_EPHEMERAL_TTL / 2,
  667. deadline - time.time() + 1.0, # Oversleeping by 1s is ok.
  668. )
  669. active_version, state = self.try_wait_for_state_change(
  670. etcd_index=active_version.etcd_index + 1, timeout=timeout
  671. )
  672. except etcd.EtcdCompareFailed:
  673. log.info("Join last-call TTL refresh CAS unsuccessful, will retry")
  674. cas_delay()
  675. active_version, state = self.get_rdzv_state()
  676. def set_closed(self):
  677. """
  678. Mark rendezvous 'closed' for current run_id, which is used to signal other
  679. participants to not attempt to perform (re-)rendezvous. This is useful
  680. when one of the workers decides the job is complete.
  681. """
  682. while True:
  683. active_version, state = self.get_rdzv_state()
  684. if state["status"] == "closed":
  685. # Already closed by someone else.
  686. return
  687. state["status"] = "closed"
  688. try:
  689. self.client.test_and_set(
  690. key=self.get_path("/rdzv/active_version"),
  691. value=json.dumps(state),
  692. prev_value=active_version.value,
  693. )
  694. return
  695. except etcd.EtcdCompareFailed:
  696. log.info("Set closed CAS unsuccessful, retrying")
  697. cas_delay()
  698. def get_rdzv_state(self):
  699. active_version = self.client.get(key=self.get_path("/rdzv/active_version"))
  700. return active_version, json.loads(active_version.value)
  701. def try_wait_for_state_change(self, etcd_index, timeout=None):
  702. # Don't sleep past the overall deadline (at least more than by 1s)
  703. overall_timeout = max(self._rendezvous_deadline - time.time(), 0.0) + 1.0
  704. timeout = overall_timeout if timeout is None else min(timeout, overall_timeout)
  705. try:
  706. self.client.watch(
  707. self.get_path("/rdzv/active_version"), index=etcd_index, timeout=timeout
  708. )
  709. except (etcd.EtcdEventIndexCleared, etcd.EtcdWatchTimedOut):
  710. pass
  711. if time.time() > self._rendezvous_deadline:
  712. raise RendezvousTimeoutError()
  713. # Unfortunately, we have to do another fetch in order to get last etcd_index.
  714. return self.get_rdzv_state()
  715. def get_path(self, path):
  716. if not path.startswith("/"):
  717. path = "/" + path
  718. return "{prefix}run_{run_id}{path}".format(
  719. prefix=self._prefix, run_id=self._run_id, path=path
  720. )
  721. def create_path_if_not_exists(self, full_path, ttl=None):
  722. try:
  723. self.client.write(
  724. key=full_path, value=None, dir=True, prevExist=False, ttl=ttl
  725. )
  726. except etcd.EtcdAlreadyExist:
  727. pass
  728. def setup_lease_renewal(self, full_path, ttl):
  729. # NOTE: For ephemeral key TTL renewal (~lease) to work correctly,
  730. # make sure you don't call any long-blocking methods that do not
  731. # release the Python's GIL! An example of this is calling a pybind11
  732. # extension function that is blocking / long-running, but is not
  733. # doing a scoped release of the GIL.
  734. def lease_worker(client, path, ttl, stop_event):
  735. while True:
  736. try:
  737. client.refresh(path, ttl=ttl)
  738. except etcd.EtcdKeyNotFound:
  739. break
  740. except ConnectionRefusedError:
  741. # This error usually occurs during test when the server already got terminated but the
  742. # python garbage collector have not yet invoked the __del__ method.
  743. break
  744. if stop_event.wait(timeout=ttl / 2):
  745. break
  746. lease_stop_event = threading.Event()
  747. lease_thread = threading.Thread(
  748. target=lease_worker, args=(self.client, full_path, ttl, lease_stop_event)
  749. )
  750. lease_thread.daemon = True
  751. lease_thread.start()
  752. return lease_stop_event
  753. def store_extra_data(self, rdzv_version, key, value):
  754. node = self.get_path("/rdzv/v_{}/extra_data".format(rdzv_version))
  755. try:
  756. # If first time we are storing anything:
  757. extra_data = self.client.write(
  758. key=node, value=json.dumps({key: value}), prevExist=False
  759. )
  760. return
  761. except etcd.EtcdAlreadyExist:
  762. pass
  763. # CAS loop, to make sure we don't lose concurrent stores.
  764. while True:
  765. # We never delete extra_data. Failure here should be fatal, no special handling.
  766. extra_data = self.client.get(node)
  767. new_extra_data_value = json.loads(extra_data.value)
  768. new_extra_data_value[key] = value
  769. try:
  770. extra_data = self.client.test_and_set(
  771. key=node,
  772. value=json.dumps(new_extra_data_value),
  773. prev_value=extra_data.value,
  774. )
  775. return
  776. except etcd.EtcdCompareFailed:
  777. log.info("Store extra_data CAS unsuccessful, retrying")
  778. time.sleep(0.1)
  779. def load_extra_data(self, rdzv_version, key, timeout=None):
  780. # 'extra_data' node itself, and the directory it is located in:
  781. node = self.get_path("/rdzv/v_{}/extra_data".format(rdzv_version))
  782. node_dir = self.get_path("/rdzv/v_{}".format(rdzv_version))
  783. # TODO: implement timeout
  784. # https://github.com/pytorch/elastic/issues/12
  785. while True:
  786. # Combined wait for the node itself, and the key inside it.
  787. root = self.client.get(node_dir)
  788. # Find the extra_data node, if it exists
  789. extra_data = [n for n in root.children if n.key == node]
  790. assert len(extra_data) <= 1
  791. # Node for extra_data exists, check the desired key inside it.
  792. if len(extra_data) == 1:
  793. extra_data_dict = json.loads(extra_data[0].value)
  794. if key in extra_data_dict:
  795. return extra_data_dict[key]
  796. # The 'extra_data' node doesn't exist, or they key isn't published yet.
  797. # Wait for interesting events on the extra_data node and retry.
  798. try:
  799. self.client.watch(node, index=root.etcd_index + 1)
  800. except (etcd.EtcdEventIndexCleared, etcd.EtcdWatchTimedOut):
  801. pass
  802. def setup_kv_store(self, rdzv_version):
  803. store_path = self.get_path(f"/rdzv/v_{rdzv_version}/kv")
  804. self.create_path_if_not_exists(store_path)
  805. return EtcdStore(etcd_client=self.client, etcd_store_prefix=store_path)
  806. def _create_etcd_client(params: RendezvousParameters) -> etcd.Client:
  807. """
  808. Creates a new ``etcd.Client`` from the specified ``RendezvousParameters``.
  809. """
  810. hostname, port = parse_rendezvous_endpoint(params.endpoint, 2379)
  811. # The communication protocol
  812. protocol = params.config.get("protocol")
  813. if protocol is None:
  814. protocol = "http"
  815. else:
  816. if protocol != "http" and protocol != "https":
  817. raise ValueError("The etcd protocol must be HTTP or HTTPS.")
  818. # The SSL client certificate
  819. ssl_cert = params.config.get("cert")
  820. if ssl_cert is not None:
  821. cert_key = params.config.get("key")
  822. if cert_key is not None:
  823. # The etcd client expects the certificate key as the second element
  824. # of the `cert` tuple.
  825. ssl_cert = (ssl_cert, cert_key)
  826. # The root certificate
  827. ca_cert = params.config.get("cacert")
  828. return etcd.Client(
  829. hostname,
  830. port,
  831. protocol=protocol,
  832. cert=ssl_cert,
  833. ca_cert=ca_cert,
  834. allow_reconnect=True,
  835. )
  836. # Handler for torch.distributed "static" registration
  837. def create_rdzv_handler(params: RendezvousParameters) -> RendezvousHandler:
  838. """
  839. Usage:
  840. ::
  841. rdzv_params = RendezvousParameters(
  842. backend="etcd",
  843. endpoint="192.168.0.42:2379",
  844. run_id="123",
  845. min_nodes=4,
  846. max_nodes=8,
  847. timeout=300,
  848. last_call_timeout=30,
  849. etcd_prefix="custom_prefix",
  850. protocol="https",
  851. cacert="/etc/kubernetes/certs/ca.crt",
  852. cert="/etc/kubernetes/certs/client.crt",
  853. key="/etc/kubernetes/certs/client.key")
  854. # -- or --
  855. rdzv_params = RendezvousParameters(
  856. backend="etcd",
  857. endpoint="192.168.0.42:2379",
  858. run_id="123",
  859. min_nodes=4,
  860. max_nodes=8)
  861. etcd_rdzv_handler = create_etcd_rendezvous_handler(rdzv_params)
  862. Where:
  863. run_id - unique id for this training job instance,
  864. min_nodes - min number of workers expected to join the rendezvous,
  865. max_nodes - max number of workers allowed to join the rendezvous,
  866. defaults to min_workers is not specified.
  867. timeout - total timeout within which next_rendezvous is expected to
  868. succeed; a RendezvousTimeoutError is raised otherwise;
  869. Defaults is 600 (10 minutes).
  870. last_call_timeout - additional wait amount ("last call") after
  871. min number of workers has been reached.
  872. Defaults to 30 seconds.
  873. etcd_prefix - path prefix (from etcd root), inside which all
  874. etcd nodes will be created.
  875. Default is "/torchelastic/p2p".
  876. protocol - http (default) or https to access etcd.
  877. cacert - CA cert to access etcd, only makes sense with https.
  878. cert - client cert to access etcd, only makes sense with https.
  879. key - client key to access etcd, only makes sense with https.
  880. """
  881. client = _create_etcd_client(params)
  882. etcd_prefix = params.get("etcd_prefix", "/torchelastic/p2p")
  883. rdzv = EtcdRendezvous(
  884. client=client,
  885. prefix=etcd_prefix,
  886. run_id=params.run_id,
  887. num_min_workers=params.min_nodes,
  888. num_max_workers=params.max_nodes,
  889. timeout=params.get_as_int("timeout", _DEFAULT_TIMEOUT),
  890. last_call_timeout=params.get_as_int("last_call_timeout", _DEFAULT_LAST_CALL_TIMEOUT),
  891. )
  892. return EtcdRendezvousHandler(rdzv_impl=rdzv)