expert_uid.py 1.6 KB

1234567891011121314151617181920212223242526272829
  1. import re
  2. from typing import NamedTuple, Tuple, Union
  3. from hivemind.p2p.p2p_daemon_bindings.datastructures import PeerInfo
  4. ExpertUID, ExpertPrefix, Coordinate, Score = str, str, int, float
  5. UidEndpoint = NamedTuple("UidEndpoint", [("uid", ExpertUID), ("peer_info", PeerInfo)])
  6. UID_DELIMITER = "." # when declaring experts, DHT store all prefixes of that expert's uid, split over this prefix
  7. FLAT_EXPERT = -1 # grid prefix reserved for storing 1d expert uids. Used to speed up find_best_experts in 1d case.
  8. UID_PATTERN = re.compile("^(([^.])+)([.](?:[0]|([1-9]([0-9]*))))+$") # e.g. ffn_expert.98.76.54 - prefix + some dims
  9. PREFIX_PATTERN = re.compile("^(([^.])+)([.](?:[0]|([1-9]([0-9]*))))*[.]$") # e.g. expert. or ffn.45. (ends with ".")
  10. # formally, prefixes = {uid.split(UID_DELIMITER)[:length] for length in range(1, uid.count(UID_DELIMITER) + 2)}
  11. def is_valid_uid(maybe_uid: str) -> bool:
  12. """An uid must contain a string expert type, followed by one or more .-separated numeric indices"""
  13. return bool(UID_PATTERN.fullmatch(maybe_uid))
  14. def is_valid_prefix(maybe_prefix: str) -> bool:
  15. """An uid prefix must contain a string expert type, followed by optional numeric indices and a trailing period"""
  16. return bool(PREFIX_PATTERN.fullmatch(maybe_prefix))
  17. def split_uid(uid_or_prefix: Union[ExpertUID, ExpertPrefix]) -> Tuple[ExpertPrefix, Coordinate]:
  18. """Separate an expert UID or prefix into a new ExpertPrefix and integer for the last coordinate"""
  19. uid_or_prefix = uid_or_prefix.rstrip(UID_DELIMITER)
  20. pivot = uid_or_prefix.rindex(UID_DELIMITER) + 1
  21. return uid_or_prefix[:pivot], int(uid_or_prefix[pivot:])