key_manager.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import random
  2. import re
  3. from typing import List, Optional, Tuple
  4. import numpy as np
  5. from hivemind.averaging.group_info import GroupInfo
  6. from hivemind.dht import DHT
  7. from hivemind.p2p import PeerID
  8. from hivemind.utils import DHTExpiration, ValueWithExpiration, get_dht_time, get_logger
  9. GroupKey = str
  10. GROUP_PATTERN = re.compile("^(([^.])+)[.]0b[01]*$") # e.g. bert_exp4_averaging.0b01001101
  11. logger = get_logger(__name__)
  12. def is_valid_group(maybe_group: str) -> bool:
  13. """A group identifier must contain group type, followed by one or more .-separated indices, and any ?metadata"""
  14. return bool(GROUP_PATTERN.fullmatch(maybe_group))
  15. class GroupKeyManager:
  16. """
  17. Utility class that declares and fetches averaging-related keys using a DHT
  18. """
  19. def __init__(
  20. self,
  21. dht: DHT,
  22. prefix: str,
  23. initial_group_bits: str,
  24. target_group_size: int,
  25. ):
  26. assert all(bit in "01" for bit in initial_group_bits)
  27. self.dht, self.prefix, self.group_bits = dht, prefix, initial_group_bits
  28. self.target_group_size = target_group_size
  29. self.peer_id = dht.peer_id
  30. @property
  31. def current_key(self) -> GroupKey:
  32. return f"{self.prefix}.0b{self.group_bits}"
  33. async def declare_averager(
  34. self, group_key: GroupKey, peer_id: PeerID, expiration_time: float, looking_for_group: bool = True
  35. ) -> bool:
  36. """
  37. Add (or remove) the averager to a given allreduce bucket
  38. :param group_key: allreduce group key, e.g. my_averager.0b011011101
  39. :param peer_id: averager public peer_id for incoming requests
  40. :param expiration_time: intent to run allreduce before this timestamp
  41. :param looking_for_group: by default (True), declare the averager as "looking for group" in a given group;
  42. If False, this will instead mark that the averager as no longer looking for group, (e.g. it already finished)
  43. :return: True if declared, False if declaration was rejected by DHT peers
  44. :note: when leaving (i.e. is_active=False), please specify the same expiration_time as when entering the group
  45. :note: setting is_active=False does *not* guarantee that others will immediately stop to query you.
  46. """
  47. expiration_time = expiration_time if looking_for_group else float(np.nextafter(expiration_time, float("inf")))
  48. return await self.dht.store(
  49. key=group_key,
  50. subkey=peer_id.to_bytes(),
  51. value=looking_for_group,
  52. expiration_time=expiration_time,
  53. return_future=True,
  54. )
  55. async def get_averagers(self, group_key: GroupKey, only_active: bool) -> List[Tuple[PeerID, DHTExpiration]]:
  56. """
  57. Find and return averagers that were declared with a given all-reduce key
  58. :param group_key: finds averagers that have the this group key, e.g. my_averager.0b011011101
  59. :param only_active: if True, return only active averagers that are looking for group (i.e. with value = True)
  60. if False, return all averagers under a given group_key regardless of value
  61. :return: peer_ids and expirations of every matching averager
  62. """
  63. assert is_valid_group(group_key), f"Group key {group_key} is invalid, must follow {GROUP_PATTERN}"
  64. result = await self.dht.get(group_key, latest=True, return_future=True)
  65. if result is None or not isinstance(result.value, dict):
  66. logger.debug(f"Allreduce group not found: {group_key}, creating new group.")
  67. return []
  68. averagers = []
  69. for key, looking_for_group in result.value.items():
  70. try:
  71. if only_active and not looking_for_group.value:
  72. continue
  73. averagers.append((PeerID(key), looking_for_group.expiration_time))
  74. except Exception as e:
  75. logger.warning(f"Could not parse group key {key} ({looking_for_group}, exc={e})")
  76. return averagers
  77. async def update_key_on_group_assembled(self, group_info: GroupInfo, is_leader: bool = True):
  78. """this function is triggered every time an averager finds an allreduce group"""
  79. rng = random.Random(group_info.group_id)
  80. index = group_info.peer_ids.index(self.peer_id)
  81. generalized_index = rng.sample(range(self.target_group_size), group_info.group_size)[index]
  82. nbits = int(np.ceil(np.log2(self.target_group_size)))
  83. new_bits = bin(generalized_index)[2:].rjust(nbits, "0")
  84. self.group_bits = (self.group_bits + new_bits)[-len(self.group_bits) :] if self.group_bits else ""
  85. logger.debug(f"{self.peer_id} - updated group key to {self.group_bits}")
  86. async def update_key_on_not_enough_peers(self):
  87. """this function is triggered whenever averager fails to assemble group within timeout"""
  88. pass # to be implemented in subclasses