averager.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. """ A background process that averages your tensors with peers """
  2. from __future__ import annotations
  3. import asyncio
  4. import contextlib
  5. import ctypes
  6. import multiprocessing as mp
  7. import os
  8. import random
  9. import threading
  10. import weakref
  11. from dataclasses import asdict
  12. from typing import Any, AsyncIterator, Dict, Optional, Sequence, Tuple, Union
  13. import numpy as np
  14. import torch
  15. from hivemind.averaging.allreduce import AllreduceException, AllReduceRunner, AveragingMode, GroupID
  16. from hivemind.averaging.control import AveragingStage, StepControl
  17. from hivemind.averaging.group_info import GroupInfo
  18. from hivemind.averaging.load_balancing import load_balance_peers
  19. from hivemind.averaging.matchmaking import Matchmaking, MatchmakingException
  20. from hivemind.averaging.partition import DEFAULT_PART_SIZE_BYTES
  21. from hivemind.compression import (
  22. CompressionBase,
  23. CompressionInfo,
  24. NoCompression,
  25. deserialize_torch_tensor,
  26. serialize_torch_tensor,
  27. )
  28. from hivemind.dht import DHT, DHTID
  29. from hivemind.p2p import P2P, P2PContext, P2PHandlerError, PeerID, ServicerBase
  30. from hivemind.p2p.p2p_daemon_bindings.utils import ControlFailure, DispatchFailure
  31. from hivemind.proto import averaging_pb2
  32. from hivemind.utils import MPFuture, TensorDescriptor, get_logger
  33. from hivemind.utils.asyncio import (
  34. achain,
  35. afirst,
  36. aiter_with_timeout,
  37. anext,
  38. as_aiter,
  39. azip,
  40. enter_asynchronously,
  41. switch_to_uvloop,
  42. )
  43. from hivemind.utils.grpc import combine_from_streaming, split_for_streaming
  44. from hivemind.utils.serializer import MSGPackSerializer, SerializerBase
  45. from hivemind.utils.timed_storage import DHTExpiration, ValueWithExpiration, get_dht_time
  46. # flavour types
  47. GatheredData = Any
  48. logger = get_logger(__name__)
  49. class DecentralizedAverager(mp.Process, ServicerBase):
  50. """
  51. Parameter averaging service. A trainer can run this service in background to periodically average his parameters
  52. with other trainers. The averaging pattern is chosen so that (1) you only need to average with a small
  53. group of peers at a time, but (2) all trainers will converge to global average in a logarithmic number of steps.
  54. :param averaged_tensors: a sequence of pytorch tensors that will be averaged in each all-reduce
  55. :param dht: a DHT node that will be used to find groups
  56. :param start: if True, starts the background process immediately
  57. :param prefix: a shared prefix for all group keys
  58. :param target_group_size: attempts to form groups with up to this many peers (recommended: a power of 2, e.g. 16)
  59. :param initial_group_bits: a string of bits ('0' and '1') that define the initial group key (bucket index)
  60. :param min_matchmaking_time: when looking for group, wait for requests for at least this many seconds
  61. :param compression: optionally compress tensors with this compression algorithm before running all-reduce
  62. :param state_compression: a separate compression strategy for load_state_from_peers (default = no compression)
  63. :param tensor_infos: CompressionInfo for each respective tensor; this determines how the tensor will be comressed
  64. :param averaging_alpha: optional "learning rate" for averaging. If specified, local parameters will be shifted
  65. towards the (estimated) average by this coefficient. By default, local parameters are set equal to average.
  66. :param request_timeout: when looking for group, wait for a response from leader for at most this many seconds.
  67. :note: request_timeout must be smaller than min_matchmaking_time to avoid potential deadlocks.
  68. :param part_size_bytes: tensors for AllReduce are processed in parts of up to this size (after compression)
  69. :param bandwidth: if specified, this value represents the network bandwidth available to averager.
  70. By default, the averager is assumed to have the average bandwidth of his group.
  71. If bandwidth == 0, averager will rely on its groupmates to do all the averaging.
  72. :param client_mode: if False, this averager will accept incoming requests from other peers.
  73. if True, the averager will only join existing groups where at least one peer has client_mode=False.
  74. By default, this flag is copied from DHTNode inside the ``dht`` instance.
  75. :param auxiliary: if this flag is specified, averager.step will only assist others without sending
  76. local tensors for averaging
  77. :param allow_state_sharing: if set to True, other peers can download this peer's state. Can be overwritten
  78. with averager.allow_state_sharing = True / False
  79. :param declare_state_period: re-declare averager as a donor for load_state_from_peers every this many seconds
  80. :param allreduce_timeout: spend at most this many seconds for allreduce (after group is formed)
  81. :param next_chunk_timeout: during all-reduce and load_state_from_peers, if peer does not send next data chunk in
  82. this number of seconds, consider it failed and proceed with remaining peers. default: no timeout
  83. :param sender_timeout: during all_reduce, any sender that fails to send tensor chunk within this many seconds from
  84. previous chunk will be marked as failed and excluded from averaging. default: equal to next_chunk_timeout
  85. :param reducer_timeout: during all_reduce, any reducer that fails to send results chunk within this many seconds
  86. from previous chunk will be marked as failed and excluded from averaging. default: 2 * sender_timeout
  87. :param shutdown_timeout: when calling .shutdown, wait for up to this many seconds before terminating
  88. Example:
  89. >>> averager = DecentralizedAverager(...)
  90. >>> with averager.get_tensors() as tensors:
  91. >>> # run some code, modify tensors if necessary
  92. >>> tensors[0] += 1
  93. >>> # do not use tensors after the lock is released
  94. >>> metadata = averager.step(gather=dict(my_batch_size=32))
  95. >>> # run averaging once (in-place), gather metadata from groupmates
  96. >>> with averager.get_tensors() as tensors_after_averaging:
  97. >>> pass # use the averaged tensors
  98. """
  99. _matchmaking: Matchmaking
  100. _pending_group_assembled: asyncio.Event
  101. _state_updated: asyncio.Event
  102. _p2p: P2P
  103. serializer = MSGPackSerializer
  104. def __init__(
  105. self,
  106. averaged_tensors: Sequence[torch.Tensor],
  107. dht: DHT,
  108. *,
  109. start: bool,
  110. prefix: str,
  111. target_group_size: Optional[int] = None,
  112. min_group_size: int = 2,
  113. initial_group_bits: str = "",
  114. averaging_expiration: Optional[float] = None,
  115. min_matchmaking_time: float = 5.0,
  116. request_timeout: float = 3.0,
  117. averaging_alpha: float = 1.0,
  118. part_size_bytes: int = DEFAULT_PART_SIZE_BYTES,
  119. allreduce_timeout: Optional[float] = None,
  120. next_chunk_timeout: Optional[float] = None,
  121. sender_timeout: Optional[float] = None,
  122. reducer_timeout: Optional[float] = None,
  123. compression: CompressionBase = NoCompression(),
  124. state_compression: CompressionBase = NoCompression(),
  125. tensor_infos: Optional[Sequence[CompressionInfo]] = None,
  126. bandwidth: Optional[float] = None,
  127. min_vector_size: int = 0,
  128. auxiliary: bool = False,
  129. allow_state_sharing: Optional[bool] = None,
  130. declare_state_period: float = 30,
  131. client_mode: Optional[bool] = None,
  132. daemon: bool = True,
  133. shutdown_timeout: float = 5,
  134. ):
  135. assert "." not in prefix, "group prefix must be a string without trailing '.'"
  136. assert bandwidth is None or (
  137. bandwidth >= 0 and np.isfinite(np.float32(bandwidth))
  138. ), "bandwidth must be a non-negative float32"
  139. assert all(bit in "01" for bit in initial_group_bits)
  140. assert not client_mode or not auxiliary, "auxiliary peers must accept incoming connections"
  141. if averaging_expiration is not None:
  142. logger.warning("averaging_expiration is deprecated and will be removed soon, use min_matchmaking_time")
  143. assert min_matchmaking_time == 5.0, "Can't set both averaging_expiration and min_matchmaking_time"
  144. min_matchmaking_time = averaging_expiration
  145. super().__init__()
  146. self.dht = dht
  147. self.prefix = prefix
  148. if client_mode is None:
  149. client_mode = dht.client_mode
  150. if sender_timeout is None:
  151. sender_timeout = next_chunk_timeout
  152. if reducer_timeout is None:
  153. reducer_timeout = 2 * sender_timeout if sender_timeout is not None else None
  154. self.client_mode = client_mode
  155. self._parent_pid = os.getpid()
  156. if self.client_mode:
  157. self.mode = AveragingMode.CLIENT
  158. elif auxiliary:
  159. self.mode = AveragingMode.AUX
  160. else:
  161. self.mode = AveragingMode.NODE
  162. self.daemon = daemon
  163. self._averaged_tensors = tuple(averaged_tensors)
  164. self.lock_averaged_tensors = mp.Lock()
  165. for tensor in self._averaged_tensors:
  166. assert tensor.grad_fn is None, "averaged_tensors must be either parameters or leaf tensors"
  167. tensor.share_memory_()
  168. self.total_size = sum(map(torch.Tensor.numel, self._averaged_tensors))
  169. self.schema_hash = compute_schema_hash(self._averaged_tensors)
  170. self.shutdown_timeout = shutdown_timeout
  171. self.next_chunk_timeout = next_chunk_timeout
  172. self.bandwidth = bandwidth
  173. self.matchmaking_kwargs = dict(
  174. servicer_type=type(self),
  175. prefix=prefix,
  176. initial_group_bits=initial_group_bits,
  177. target_group_size=target_group_size,
  178. min_group_size=min_group_size,
  179. request_timeout=request_timeout,
  180. min_matchmaking_time=min_matchmaking_time,
  181. )
  182. self.allreduce_kwargs = dict(
  183. compression=compression,
  184. part_size_bytes=part_size_bytes,
  185. min_vector_size=min_vector_size,
  186. sender_timeout=sender_timeout,
  187. reducer_timeout=reducer_timeout,
  188. )
  189. self._averaging_alpha, self._allreduce_timeout = averaging_alpha, allreduce_timeout
  190. self._running_groups: Dict[GroupID, AllReduceRunner] = {} # one or more assembled groups that run all-reduce
  191. self._inner_pipe, self._outer_pipe = mp.Pipe(duplex=True) # a control pipe used to communicate with daemon
  192. self._allow_state_sharing = mp.Value(ctypes.c_bool, 0)
  193. self._state_sharing_priority = mp.Value(ctypes.c_double, 0)
  194. if allow_state_sharing is None:
  195. allow_state_sharing = not client_mode and not auxiliary
  196. self.allow_state_sharing = allow_state_sharing
  197. self.declare_state_period = declare_state_period
  198. self.state_compression = state_compression
  199. self.tensor_infos = tensor_infos
  200. self._ready = MPFuture()
  201. # note: we create a background thread weakref and with daemon=True to ensure garbage collection
  202. background_fetcher = threading.Thread(
  203. daemon=True,
  204. target=_background_thread_fetch_current_state,
  205. args=[self.serializer, self._outer_pipe, weakref.WeakMethod(self.get_current_state)],
  206. )
  207. background_fetcher.start()
  208. if start:
  209. self.run_in_background(await_ready=True)
  210. @property
  211. def allow_state_sharing(self) -> bool:
  212. """if set to True, other peers can download this peer's state"""
  213. return bool(self._allow_state_sharing.value)
  214. @allow_state_sharing.setter
  215. def allow_state_sharing(self, value: bool):
  216. if value and self.client_mode:
  217. raise ValueError("Cannot allow state sharing: averager in client mode cannot share its state")
  218. else:
  219. old_value, self._allow_state_sharing.value = self._allow_state_sharing.value, value
  220. if value != old_value:
  221. self._outer_pipe.send(("_trigger_declare_load_state", [], {}))
  222. @property
  223. def state_sharing_priority(self) -> float:
  224. """Others will preferentially downloading state from peers with highest priority."""
  225. return float(self._state_sharing_priority.value)
  226. @state_sharing_priority.setter
  227. def state_sharing_priority(self, value: float):
  228. if value and self.client_mode:
  229. raise ValueError("State sharing priority is unused: averager in client mode cannot share its state")
  230. else:
  231. old_value, self._state_sharing_priority.value = self._state_sharing_priority.value, value
  232. if self.allow_state_sharing and value != old_value:
  233. self._outer_pipe.send(("_trigger_declare_load_state", [], {}))
  234. async def _trigger_declare_load_state(self):
  235. # note: previously tried to set mp.Event instead of this. Awaiting it in executor caused degradation in py39
  236. self._state_updated.set()
  237. @property
  238. def peer_id(self) -> PeerID:
  239. return self.dht.peer_id
  240. @property
  241. def request_timeout(self):
  242. return self._matchmaking.request_timeout
  243. def run(self):
  244. """
  245. Run averager function in a background thread; this is needed to avoid a heisenbug with broken OMP on fork
  246. Turns out, using a non-main thread creates a separate OMP pool that works even if the original pool is corrupted
  247. Read more: https://github.com/pytorch/pytorch/issues/17199
  248. """
  249. thread = threading.Thread(target=self._run_internal, daemon=True)
  250. thread.start()
  251. thread.join()
  252. def _run_internal(self):
  253. """Serve DecentralizedAverager forever. This function will not return until the averager is shut down"""
  254. loop = switch_to_uvloop()
  255. # initialize asyncio synchronization primitives in this event loop
  256. pipe_semaphore = asyncio.Semaphore(value=0)
  257. loop.add_reader(self._inner_pipe.fileno(), pipe_semaphore.release)
  258. async def _run():
  259. try:
  260. self._p2p = await self.dht.replicate_p2p()
  261. if not self.client_mode:
  262. await self.add_p2p_handlers(self._p2p, namespace=self.prefix)
  263. else:
  264. logger.debug("The averager is running in client mode")
  265. self._matchmaking = Matchmaking(
  266. self._p2p,
  267. self.schema_hash,
  268. self.dht,
  269. client_mode=self.client_mode,
  270. **self.matchmaking_kwargs,
  271. )
  272. if not self.client_mode:
  273. asyncio.create_task(self._declare_for_download_periodically())
  274. self._state_updated = asyncio.Event()
  275. self._pending_group_assembled = asyncio.Event()
  276. self._pending_group_assembled.set()
  277. except Exception as e:
  278. # Loglevel is DEBUG since normally the exception is propagated to the caller
  279. logger.debug(e, exc_info=True)
  280. self._ready.set_exception(e)
  281. return
  282. self._ready.set_result(None)
  283. while True:
  284. try:
  285. await asyncio.wait_for(pipe_semaphore.acquire(), timeout=self.request_timeout)
  286. except asyncio.TimeoutError:
  287. pass
  288. if not self._inner_pipe.poll():
  289. continue
  290. try:
  291. method, args, kwargs = self._inner_pipe.recv()
  292. except (OSError, ConnectionError, RuntimeError) as e:
  293. logger.exception(e)
  294. await asyncio.sleep(self.request_timeout)
  295. continue
  296. task = asyncio.create_task(getattr(self, method)(*args, **kwargs))
  297. if method == "_shutdown":
  298. await task
  299. break
  300. loop.run_until_complete(_run())
  301. def run_in_background(self, await_ready: bool = True, timeout: Optional[float] = None) -> None:
  302. """
  303. Starts averager in a background process. if await_ready, this method will wait until background dht
  304. is ready to process incoming requests or for :timeout: seconds max.
  305. """
  306. self.start()
  307. if await_ready:
  308. self.wait_until_ready(timeout)
  309. def wait_until_ready(self, timeout: Optional[float] = None) -> None:
  310. self._ready.result(timeout=timeout)
  311. def shutdown(self) -> None:
  312. """Shut down the averager process"""
  313. if self.is_alive():
  314. self._outer_pipe.send(("_shutdown", [self.shutdown_timeout], {})) # shut down the daemon process
  315. self._inner_pipe.send(("_SHUTDOWN", None)) # shut down background thread in master
  316. self.join(self.shutdown_timeout)
  317. if self.is_alive():
  318. logger.warning("Averager did not shut down within the grace period; terminating it the hard way")
  319. self.terminate()
  320. else:
  321. logger.exception("Averager shutdown has no effect: the process is already not alive")
  322. async def _shutdown(self, timeout: Optional[float]) -> None:
  323. remaining_tasks = set()
  324. for group in self._running_groups.values():
  325. remaining_tasks.update(group.finalize(cancel=True))
  326. await asyncio.wait_for(asyncio.gather(*remaining_tasks), timeout)
  327. def __del__(self):
  328. if self._parent_pid == os.getpid() and self.is_alive():
  329. self.shutdown()
  330. def step(
  331. self,
  332. gather: Optional[GatheredData] = None,
  333. scheduled_time: Optional[DHTExpiration] = None,
  334. weight: Optional[float] = None,
  335. timeout: Optional[float] = None,
  336. allow_retries: bool = True,
  337. require_trigger: bool = False,
  338. wait: bool = True,
  339. ) -> Union[Optional[Dict[PeerID, GatheredData]], StepControl]:
  340. """
  341. Set up the averager to look for a group and run one round of averaging, return True on success, False on failure
  342. :param gather: optionally send this informaton to all peers in the next group and gather it from every groupmate
  343. (this operation is known as all-gather). The gathered data will be available as the output of this function.
  344. :param scheduled_time: when matchmaking, assume that all-reduce will begin at this moment.
  345. By default, schedule all-reduce current time plus min_matchmaking_time seconds
  346. :param weight: averaging weight for this peer, int or float, must be strictly positive
  347. :param allow_retries: if averager fails to run one round of allreduce, this option will allow it to try again
  348. within the specified timeout
  349. :param require_trigger: if True, await for user to call .allow_allreduce() before running all-reduce
  350. :param timeout: if averager was unable to *find* a group in this many seconds, consider allreduce failed
  351. :param wait: if True (default), return when finished. Otherwise return StepControl and run in background.
  352. :returns: on success, update averaged_tensors and return group info; on failure, return None
  353. """
  354. if self.mode == AveragingMode.AUX and weight is not None:
  355. logger.warning("Averager is running in auxiliary mode, weight is unused")
  356. if scheduled_time is None:
  357. scheduled_time = get_dht_time() + self.matchmaking_kwargs["min_matchmaking_time"]
  358. if weight is None:
  359. weight = float(self.mode != AveragingMode.AUX)
  360. deadline = get_dht_time() + timeout if timeout is not None else float("inf")
  361. assert isinstance(weight, (int, float)) and weight >= 0, f"Expected a positive int/float, got {type(weight)}"
  362. assert not (wait and require_trigger), "Non-asynchronous step cannot wait for trigger (use wait=False)"
  363. assert scheduled_time < deadline, "Scheduled start time does not fit within timeout"
  364. user_data_for_gather = self.serializer.dumps(gather) # serialize here to avoid imports in the averager process
  365. data_for_gather = self.serializer.dumps([self.bandwidth, self.mode.value, user_data_for_gather])
  366. step = StepControl(
  367. scheduled_time=scheduled_time,
  368. deadline=deadline,
  369. allow_retries=allow_retries,
  370. weight=weight,
  371. data_for_gather=data_for_gather,
  372. )
  373. future_for_init = MPFuture()
  374. self._outer_pipe.send(("_step", [], dict(step=step, future_for_init=future_for_init)))
  375. step.attach(*future_for_init.result())
  376. if not require_trigger:
  377. step.allow_allreduce()
  378. return step.result() if wait else step
  379. async def _step(self, *, step: StepControl, future_for_init: MPFuture):
  380. try:
  381. trigger, cancel = MPFuture(), MPFuture()
  382. step.attach(trigger, cancel)
  383. future_for_init.set_result((trigger, cancel))
  384. async def find_peers_or_notify_cancel():
  385. group_info = await self._matchmaking.look_for_group(step)
  386. if not step.triggered:
  387. step.stage = AveragingStage.AWAITING_TRIGGER
  388. await step.wait_for_trigger()
  389. return group_info
  390. while not step.done():
  391. try:
  392. self._pending_group_assembled.clear()
  393. step.stage = AveragingStage.LOOKING_FOR_GROUP
  394. matchmaking_task = asyncio.create_task(find_peers_or_notify_cancel())
  395. check_cancel_task = asyncio.create_task(step.wait_for_cancel())
  396. await asyncio.wait({matchmaking_task, check_cancel_task}, return_when=asyncio.FIRST_COMPLETED)
  397. if step.cancelled():
  398. matchmaking_task.cancel()
  399. raise asyncio.CancelledError()
  400. else:
  401. check_cancel_task.cancel()
  402. group_info = await matchmaking_task
  403. if group_info is None:
  404. raise AllreduceException("Averaging step failed: could not find a group")
  405. step.stage = AveragingStage.RUNNING_ALLREDUCE
  406. step.set_result(
  407. await asyncio.wait_for(
  408. self._run_allreduce(
  409. group_info, tensor_infos=self.tensor_infos, weight=step.weight, **self.allreduce_kwargs
  410. ),
  411. timeout=self._allreduce_timeout,
  412. )
  413. )
  414. # averaging is finished, loop will now exit
  415. except (
  416. AllreduceException,
  417. MatchmakingException,
  418. AssertionError,
  419. StopAsyncIteration,
  420. asyncio.CancelledError,
  421. asyncio.InvalidStateError,
  422. P2PHandlerError,
  423. DispatchFailure,
  424. ControlFailure,
  425. ) as e:
  426. if step.done() or not step.allow_retries or get_dht_time() >= step.deadline:
  427. if not step.cancelled():
  428. logger.exception(e)
  429. if not step.done():
  430. step.set_exception(e)
  431. else:
  432. logger.warning(f"{self.__class__.__name__} caught {repr(e)}, retrying")
  433. except BaseException as e:
  434. if not step.done():
  435. step.set_exception(e)
  436. raise
  437. finally:
  438. step.stage = AveragingStage.FINISHED
  439. if not step.done():
  440. step.set_exception(
  441. RuntimeError(
  442. "Internal sanity check failed: averager.step left future pending."
  443. " Please report this to hivemind issues."
  444. )
  445. )
  446. async def _run_allreduce(self, group_info: GroupInfo, min_vector_size: int, **kwargs) -> GatheredData:
  447. """Run All-Reduce in a given group and update tensors in place, return gathered metadata"""
  448. try:
  449. bandwidths, mode_ids, user_gathered_bytes = zip(*map(self.serializer.loads, group_info.gathered))
  450. user_gathered = dict(zip(group_info.peer_ids, map(self.serializer.loads, user_gathered_bytes)))
  451. modes = tuple(map(AveragingMode, mode_ids))
  452. # compute optimal part sizes from peer bandwidths; TODO: replace with proper load balancing
  453. download_bandwidths = [
  454. thr if mode != AveragingMode.CLIENT else 0.0 for thr, mode in zip(bandwidths, modes)
  455. ]
  456. peer_fractions = await asyncio.get_event_loop().run_in_executor(
  457. None, load_balance_peers, self.total_size, download_bandwidths, min_vector_size
  458. )
  459. async with enter_asynchronously(self.get_tensors()) as local_tensors:
  460. allreduce = AllReduceRunner(
  461. p2p=self._p2p,
  462. servicer_type=type(self),
  463. prefix=self.prefix,
  464. group_id=group_info.group_id,
  465. tensors=local_tensors,
  466. ordered_peer_ids=group_info.peer_ids,
  467. peer_fractions=peer_fractions,
  468. gathered=user_gathered,
  469. modes=modes,
  470. **kwargs,
  471. )
  472. with self.register_allreduce_group(group_info.group_id, allreduce):
  473. if modes[group_info.peer_ids.index(self.peer_id)] != AveragingMode.AUX:
  474. iter_results = allreduce.run()
  475. async for tensor, update in azip(as_aiter(*local_tensors), iter_results):
  476. # all-reduce is performed asynchronously while iterating
  477. tensor.add_(update, alpha=self._averaging_alpha)
  478. self._state_updated.set()
  479. else:
  480. async for _ in allreduce: # trigger all-reduce by iterating
  481. raise ValueError("aux peers should not receive averaged tensors")
  482. return allreduce.gathered
  483. except BaseException as e:
  484. if isinstance(e, Exception):
  485. logger.exception(e)
  486. raise MatchmakingException(f"Unable to run All-Reduce: {e}")
  487. @contextlib.contextmanager
  488. def register_allreduce_group(self, group_id: GroupID, allreduce: AllReduceRunner):
  489. """registers a given all-reduce runner to listen for incoming connections"""
  490. try:
  491. self._running_groups[group_id] = allreduce
  492. self._pending_group_assembled.set()
  493. yield
  494. finally:
  495. self._running_groups.pop(group_id, None)
  496. self._pending_group_assembled.set()
  497. @contextlib.contextmanager
  498. def get_tensors(self) -> Sequence[torch.Tensor]:
  499. """
  500. A contextmanager that gives user access to averaged tensors.
  501. It is guaranteed that the averager will not modify tensors while this context is active.
  502. Please do not modify the yielded tensors in-place after the context is released.
  503. """
  504. with self.lock_averaged_tensors:
  505. yield self._averaged_tensors
  506. async def rpc_join_group(
  507. self, request: averaging_pb2.JoinRequest, context: P2PContext
  508. ) -> AsyncIterator[averaging_pb2.MessageFromLeader]:
  509. """accept or reject a join request from another averager; if accepted, run him through allreduce steps"""
  510. async for response in self._matchmaking.rpc_join_group(request, context):
  511. yield response
  512. async def rpc_aggregate_part(
  513. self, stream: AsyncIterator[averaging_pb2.AveragingData], context: P2PContext
  514. ) -> AsyncIterator[averaging_pb2.AveragingData]:
  515. """a groupmate sends us a part of his tensor; we should average it with other peers and return the result"""
  516. request = await anext(stream)
  517. if request.group_id not in self._running_groups:
  518. # this handles a special case when leader accepted us to group AND began allreduce right away,
  519. # but his response with group_id was delayed and other peers got to us first
  520. await self._pending_group_assembled.wait()
  521. group = self._running_groups.get(request.group_id)
  522. if group is None:
  523. yield averaging_pb2.AveragingData(code=averaging_pb2.BAD_GROUP_ID)
  524. return
  525. async for message in group.rpc_aggregate_part(achain(as_aiter(request), stream), context):
  526. yield message
  527. async def _declare_for_download_periodically(self):
  528. download_key = f"{self._matchmaking.group_key_manager.prefix}.all_averagers"
  529. sharing_was_allowed = self.allow_state_sharing
  530. while True:
  531. expiration_time = get_dht_time() + self.declare_state_period
  532. if self.allow_state_sharing or sharing_was_allowed:
  533. # notify either if sharing is allowed or if it was just switched off (to overwrite previous message)
  534. asyncio.create_task(
  535. asyncio.wait_for(
  536. self.dht.store(
  537. download_key,
  538. subkey=self.peer_id.to_bytes(),
  539. value=self.state_sharing_priority if self.allow_state_sharing else None,
  540. expiration_time=expiration_time,
  541. return_future=True,
  542. ),
  543. timeout=expiration_time - get_dht_time(),
  544. )
  545. )
  546. sharing_was_allowed = self.allow_state_sharing
  547. # report again either in state_declare_period or after the field was changed by the user
  548. self._state_updated.clear()
  549. try:
  550. await asyncio.wait_for(self._state_updated.wait(), timeout=max(0.0, expiration_time - get_dht_time()))
  551. except asyncio.TimeoutError:
  552. pass
  553. async def rpc_download_state(
  554. self, _request: averaging_pb2.DownloadRequest, _context: P2PContext
  555. ) -> AsyncIterator[averaging_pb2.DownloadData]:
  556. """
  557. Get the up-to-date trainer state from a peer.
  558. The state consists of two parts: (serialized_metadata, tensors)
  559. - serialized_metadata is a small serialized bytestring meant to store scalars and hyperparameters
  560. - tensors is a sequence of pytorch tensors that represent model parameters or optimizer statistics
  561. """
  562. if not self.allow_state_sharing:
  563. return # deny request and direct peer to the next prospective averager
  564. metadata, tensors, infos = await self._get_current_state_from_host_process()
  565. if infos is None:
  566. infos = [CompressionInfo.from_tensor(tensor, key=i) for i, tensor in enumerate(tensors)]
  567. assert len(tensors) == len(infos)
  568. for tensor, info in zip(tensors, infos):
  569. for part in split_for_streaming(self.state_compression.compress(tensor, info, allow_inplace=False)):
  570. if metadata is not None:
  571. yield averaging_pb2.DownloadData(tensor_part=part, metadata=metadata)
  572. metadata = None
  573. else:
  574. yield averaging_pb2.DownloadData(tensor_part=part)
  575. def get_current_state(self) -> Tuple[Any, Sequence[torch.Tensor], Sequence[CompressionInfo]]:
  576. """
  577. Get current state and send it to a peer. executed in the host process. Meant to be overriden.
  578. :returns: a tuple of (small metadata, sequence of torch tensors)
  579. :note: metadata must be seriablizable with self.serializer (default = MSGPackSerializer)
  580. """
  581. with self.get_tensors() as tensors:
  582. return dict(group_key=self.get_group_bits()), tensors, self.tensor_infos
  583. async def _get_current_state_from_host_process(self):
  584. """Executed in the averager process inside rpc_download_state"""
  585. future = MPFuture()
  586. self._inner_pipe.send(("_TRIGGER_GET_CURRENT_STATE", future))
  587. return await future
  588. def load_state_from_peers(
  589. self, wait: bool = True, timeout: Optional[float] = None
  590. ) -> Optional[Tuple[Any, Sequence[torch.Tensor]]]:
  591. """
  592. Try to download the latest optimizer state one of the existing peer.
  593. :returns: on success, return a 2-tuple with (metadata, tensors), where
  594. - metadata is a small object containing metadata (e.g. hyperparameters, scalars, etc)
  595. - tensors is a sequence of pytorch tensors meant to contain peer's model weights and optimizer statistics
  596. The exact contents of both metadata and tensors are determined by get_current_state method
  597. """
  598. future = MPFuture()
  599. self._outer_pipe.send(("_load_state_from_peers", [], dict(timeout=timeout, future=future)))
  600. return future.result(timeout=timeout) if wait else future
  601. async def _load_state_from_peers(self, future: MPFuture, timeout: Optional[float] = None):
  602. if timeout is not None:
  603. timeout = self.next_chunk_timeout if self.next_chunk_timeout is not None else self.request_timeout
  604. try:
  605. key_manager = self._matchmaking.group_key_manager
  606. peer_priority, _ = self.dht.get(f"{key_manager.prefix}.all_averagers", latest=True) or ({}, None)
  607. peer_priority = {
  608. PeerID(peer_id): (float(info.value), random.random()) # using randomness as a tie breaker
  609. for peer_id, info in peer_priority.items()
  610. if isinstance(info, ValueWithExpiration) and isinstance(info.value, (float, int))
  611. }
  612. if not isinstance(peer_priority, dict) or len(peer_priority) == 0:
  613. logger.info(f"Averager could not load state from peers: peer dict empty or corrupted {peer_priority}")
  614. future.set_result(None)
  615. return
  616. metadata = None
  617. for peer in sorted(peer_priority.keys(), key=peer_priority.get, reverse=True):
  618. if peer != self.peer_id:
  619. logger.info(f"Downloading parameters from peer {peer}")
  620. try:
  621. stub = self.get_stub(self._p2p, peer, namespace=self.prefix)
  622. stream = await stub.rpc_download_state(averaging_pb2.DownloadRequest())
  623. current_tensor_parts, tensors = [], []
  624. async for message in aiter_with_timeout(stream, timeout=timeout):
  625. if message.metadata:
  626. metadata = self.serializer.loads(message.metadata)
  627. if message.tensor_part.dtype and current_tensor_parts:
  628. # tensor_part.dtype indicates the start of the new tensor, so we should wrap up this one
  629. tensors.append(deserialize_torch_tensor(combine_from_streaming(current_tensor_parts)))
  630. current_tensor_parts = []
  631. current_tensor_parts.append(message.tensor_part)
  632. if current_tensor_parts:
  633. tensors.append(deserialize_torch_tensor(combine_from_streaming(current_tensor_parts)))
  634. if not metadata:
  635. logger.debug(f"Peer {peer} did not send its state")
  636. continue
  637. logger.info(f"Finished downloading state from {peer}")
  638. future.set_result((metadata, tensors))
  639. return
  640. except Exception as e:
  641. logger.exception(f"Failed to download state from {peer} - {repr(e)}")
  642. finally:
  643. if not future.done():
  644. future.set_result(None)
  645. def get_group_bits(self, wait: bool = True):
  646. """
  647. :param wait: if True, return bits immediately. Otherwise return awaitable MPFuture
  648. :returns: averager's current group key bits (without prefix)
  649. """
  650. future = MPFuture()
  651. self._outer_pipe.send(("_get_group_bits", [], dict(future=future)))
  652. return future.result() if wait else future
  653. async def _get_group_bits(self, future: MPFuture):
  654. future.set_result(self._matchmaking.group_key_manager.group_bits)
  655. def set_group_bits(self, group_bits: str, wait: bool = True):
  656. """
  657. :param group_bits: group bits (string of '0' or '1') to be used in averager's group key
  658. :param wait: if True, wait until the update is confirmed by the averager. Otherwise return immediately
  659. """
  660. future = MPFuture()
  661. assert all(bit in "01" for bit in group_bits)
  662. self._outer_pipe.send(("_set_group_bits", [], dict(group_bits=group_bits, future=future)))
  663. return future.result() if wait else future
  664. async def _set_group_bits(self, group_bits: str, future: MPFuture):
  665. try:
  666. self._matchmaking.group_key_manager.group_bits = group_bits
  667. return future.set_result(None)
  668. except Exception as e:
  669. if not future.done():
  670. future.set_exception(e)
  671. def _background_thread_fetch_current_state(
  672. serializer: SerializerBase, pipe: mp.connection.Connection, get_current_state_ref: weakref.WeakMethod
  673. ):
  674. """
  675. Executed in the host process as a background thread. Fetches the averager state when asked by peers.
  676. :param serializer: a serializer with which to convert metadata into bytes
  677. :param pipe: DecentralizedAverager's control pipe (from host process side)
  678. :param get_current_state_ref: a WeakMethod wrapped around DecentralizedAverager.get_current_state (instance-bound)
  679. """
  680. while True:
  681. try:
  682. trigger, future = pipe.recv()
  683. except BaseException as e:
  684. logger.debug(f"Averager background thread finished: {repr(e)}")
  685. break
  686. if trigger == "_SHUTDOWN":
  687. break
  688. assert trigger == "_TRIGGER_GET_CURRENT_STATE"
  689. try:
  690. get_current_state = get_current_state_ref()
  691. if get_current_state is None:
  692. break
  693. state = get_current_state()
  694. assert 0 < len(state) <= 3
  695. if len(state) != 3:
  696. state = tuple(state + (None,) * (3 - len(state)))
  697. state_metadata, state_tensors, tensor_infos = state
  698. del get_current_state
  699. state_metadata = serializer.dumps(state_metadata)
  700. state_tensors = tuple(
  701. tensor.cpu().detach().requires_grad_(tensor.requires_grad) for tensor in state_tensors
  702. )
  703. # note: we cast tensors to CPU on host side to avoid initializing cuda in the guest process
  704. future.set_result((state_metadata, state_tensors, tensor_infos))
  705. except BaseException as e:
  706. future.set_exception(e)
  707. logger.warning(e)
  708. continue
  709. def compute_schema_hash(tensors: Sequence[torch.Tensor]) -> bytes:
  710. """A hash that describes follower's tensor shapes, dtypes, devices, but not the actual values"""
  711. schema_dicts = [
  712. {
  713. field_name: str(field_value)
  714. for field_name, field_value in asdict(TensorDescriptor.from_tensor(tensor)).items()
  715. }
  716. for tensor in tensors
  717. ]
  718. return DHTID.generate(source=schema_dicts).to_bytes()