namespace.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # Copyright 2019 Kakao Brain
  2. #
  3. # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
  4. #
  5. # This source code is licensed under the BSD license found in the
  6. # LICENSE file in the root directory of this source tree.
  7. """Provides isolated namespace of skip tensors."""
  8. import abc
  9. from functools import total_ordering
  10. from typing import Any
  11. import uuid
  12. __all__ = ["Namespace"]
  13. @total_ordering
  14. class Namespace(metaclass=abc.ABCMeta):
  15. """Namespace for isolating skip tensors used by :meth:`isolate()
  16. <torchpipe.skip.skippable.Skippable.isolate>`.
  17. """
  18. __slots__ = ("id",)
  19. def __init__(self) -> None:
  20. self.id = uuid.uuid4()
  21. def __repr__(self) -> str:
  22. return f"<Namespace '{self.id}'>"
  23. def __hash__(self) -> int:
  24. return hash(self.id)
  25. # Namespaces should support ordering, since SkipLayout will sort tuples
  26. # including a namespace. But actual order between namespaces is not
  27. # important. That's why they are ordered by version 4 UUID which generates
  28. # random numbers.
  29. def __lt__(self, other: Any) -> bool:
  30. if isinstance(other, Namespace):
  31. return self.id < other.id
  32. return False
  33. def __eq__(self, other: Any) -> bool:
  34. if isinstance(other, Namespace):
  35. return self.id == other.id
  36. return False
  37. # 'None' is the default namespace,
  38. # which means that 'isinstance(None, Namespace)' is 'True'.
  39. Namespace.register(type(None))