lazy.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. from __future__ import annotations
  2. from abc import ABC, ABCMeta, abstractmethod
  3. import logging
  4. from typing import Any, Callable
  5. from collections import deque
  6. import numpy as np
  7. from numpy.typing import DTypeLike
  8. logger = logging.getLogger(__name__)
  9. class LazyMeta(ABCMeta):
  10. def __new__(cls, name: str, bases: tuple[type, ...], namespace: dict[str, Any], **kwargs):
  11. def __getattr__(self, __name: str) -> Any:
  12. meta_attr = getattr(self._meta, __name)
  13. if callable(meta_attr):
  14. return type(self)._wrap_fn(
  15. (lambda s, *args, **kwargs: getattr(s, __name)(*args, **kwargs)),
  16. use_self=self,
  17. )
  18. elif isinstance(meta_attr, self._tensor_type):
  19. # e.g. self.T with torch.Tensor should still be wrapped
  20. return type(self)._wrap_fn(lambda s: getattr(s, __name))(self)
  21. else:
  22. # no need to wrap non-tensor properties,
  23. # and they likely don't depend on the actual contents of the tensor
  24. return meta_attr
  25. namespace["__getattr__"] = __getattr__
  26. # need to make a builder for the wrapped wrapper to copy the name,
  27. # or else it fails with very cryptic error messages,
  28. # because somehow the same string would end up in every closures
  29. def mk_wrap(op_name: str, *, meta_noop: bool = False):
  30. # need to wrap the wrapper to get self
  31. def wrapped_special_op(self, *args, **kwargs):
  32. return type(self)._wrap_fn(
  33. getattr(type(self)._tensor_type, op_name),
  34. meta_noop=meta_noop,
  35. )(self, *args, **kwargs)
  36. return wrapped_special_op
  37. # special methods bypass __getattr__, so they need to be added manually
  38. # ref: https://docs.python.org/3/reference/datamodel.html#special-lookup
  39. # NOTE: doing this from a metaclass is very convenient
  40. # TODO: make this even more comprehensive
  41. for binary_op in (
  42. "lt", "le", "eq", "ne", "ge", "gt", "not"
  43. "abs", "add", "and", "floordiv", "invert", "lshift", "mod", "mul", "matmul",
  44. "neg", "or", "pos", "pow", "rshift", "sub", "truediv", "xor",
  45. "iadd", "iand", "ifloordiv", "ilshift", "imod", "imul", "ior", "irshift", "isub", "ixor",
  46. "radd", "rand", "rfloordiv", "rmul", "ror", "rpow", "rsub", "rtruediv", "rxor",
  47. ):
  48. attr_name = f"__{binary_op}__"
  49. # the result of these operators usually has the same shape and dtype as the input,
  50. # so evaluation on the meta tensor can be skipped.
  51. namespace[attr_name] = mk_wrap(attr_name, meta_noop=True)
  52. for special_op in (
  53. "getitem", "setitem", "len",
  54. ):
  55. attr_name = f"__{special_op}__"
  56. namespace[attr_name] = mk_wrap(attr_name, meta_noop=False)
  57. return super().__new__(cls, name, bases, namespace, **kwargs)
  58. # Tree of lazy tensors
  59. class LazyBase(ABC, metaclass=LazyMeta):
  60. _tensor_type: type
  61. _meta: Any
  62. _data: Any | None
  63. _lazy: deque[LazyBase] # shared within a graph, to avoid deep recursion when making eager
  64. _args: tuple
  65. _func: Callable[[tuple], Any] | None
  66. def __init__(self, *, meta: Any, data: Any | None = None, lazy: deque[LazyBase] | None = None, args: tuple = (), func: Callable[[tuple], Any] | None = None):
  67. super().__init__()
  68. self._meta = meta
  69. self._data = data
  70. self._lazy = lazy if lazy is not None else deque()
  71. self._args = args
  72. self._func = func
  73. assert self._func is not None or self._data is not None
  74. if self._data is None:
  75. self._lazy.append(self)
  76. def __init_subclass__(cls) -> None:
  77. if "_tensor_type" not in cls.__dict__:
  78. raise TypeError(f"property '_tensor_type' must be defined for {cls!r}")
  79. return super().__init_subclass__()
  80. @staticmethod
  81. def _recurse_apply(o: Any, fn: Callable[[Any], Any]) -> Any:
  82. # TODO: dict and set
  83. if isinstance(o, (list, tuple)):
  84. L = []
  85. for item in o:
  86. L.append(LazyBase._recurse_apply(item, fn))
  87. if isinstance(o, tuple):
  88. L = tuple(L)
  89. return L
  90. elif isinstance(o, LazyBase):
  91. return fn(o)
  92. else:
  93. return o
  94. @classmethod
  95. def _wrap_fn(cls, fn: Callable, *, use_self: LazyBase | None = None, meta_noop: bool | DTypeLike = False) -> Callable[[Any], Any]:
  96. def wrapped_fn(*args, **kwargs):
  97. if kwargs is None:
  98. kwargs = {}
  99. args = ((use_self,) if use_self is not None else ()) + args
  100. meta_args = LazyBase._recurse_apply(args, lambda t: t._meta)
  101. if isinstance(meta_noop, bool) and not meta_noop:
  102. try:
  103. res = fn(*meta_args, **kwargs)
  104. except NotImplementedError:
  105. # running some operations on PyTorch's Meta tensors can cause this exception
  106. res = None
  107. else:
  108. # some operators don't need to actually run on the meta tensors
  109. assert len(args) > 0
  110. res = args[0]
  111. assert isinstance(res, cls)
  112. res = res._meta
  113. # allow operations to override the dtype
  114. if meta_noop is not True:
  115. res = cls.meta_with_dtype(res, meta_noop)
  116. if isinstance(res, cls._tensor_type):
  117. def collect_replace(t: LazyBase):
  118. if collect_replace.shared_lazy is None:
  119. collect_replace.shared_lazy = t._lazy
  120. else:
  121. collect_replace.shared_lazy.extend(t._lazy)
  122. t._lazy = collect_replace.shared_lazy
  123. # emulating a static variable
  124. collect_replace.shared_lazy = None
  125. LazyBase._recurse_apply(args, collect_replace)
  126. shared_lazy = collect_replace.shared_lazy
  127. return cls(meta=cls.eager_to_meta(res), lazy=shared_lazy, args=args, func=lambda a: fn(*a, **kwargs))
  128. else:
  129. del res # not needed
  130. # non-tensor return likely relies on the contents of the args
  131. # (e.g. the result of torch.equal)
  132. eager_args = cls.to_eager(args)
  133. return fn(*eager_args, **kwargs)
  134. return wrapped_fn
  135. @classmethod
  136. def to_eager(cls, t: Any) -> Any:
  137. def simple_to_eager(_t: LazyBase) -> Any:
  138. def already_eager_to_eager(_t: LazyBase) -> Any:
  139. assert _t._data is not None
  140. return _t._data
  141. while _t._data is None:
  142. lt = _t._lazy.popleft()
  143. if lt._data is not None:
  144. raise ValueError(f"{lt} did not belong in the lazy queue")
  145. assert lt._func is not None
  146. lt._args = cls._recurse_apply(lt._args, already_eager_to_eager)
  147. lt._data = lt._func(lt._args)
  148. # sanity check
  149. assert lt._data.dtype == lt._meta.dtype
  150. assert lt._data.shape == lt._meta.shape
  151. return _t._data
  152. # recurse into lists and/or tuples, keeping their structure
  153. return cls._recurse_apply(t, simple_to_eager)
  154. @classmethod
  155. def eager_to_meta(cls, t: Any) -> Any:
  156. return cls.meta_with_dtype(t, t.dtype)
  157. # must be overridden, meta tensor init is backend-specific
  158. @classmethod
  159. @abstractmethod
  160. def meta_with_dtype(cls, m: Any, dtype: Any) -> Any: pass
  161. @classmethod
  162. def from_eager(cls, t: Any) -> Any:
  163. if type(t) is cls:
  164. # already eager
  165. return t
  166. elif isinstance(t, cls._tensor_type):
  167. return cls(meta=cls.eager_to_meta(t), data=t)
  168. else:
  169. return TypeError(f"{type(t)!r} is not compatible with {cls._tensor_type!r}")
  170. class LazyNumpyTensor(LazyBase):
  171. _tensor_type = np.ndarray
  172. @classmethod
  173. def meta_with_dtype(cls, m: np.ndarray[Any, Any], dtype: DTypeLike) -> np.ndarray[Any, Any]:
  174. # The initial idea was to use np.nan as the fill value,
  175. # but non-float types like np.int16 can't use that.
  176. # So zero it is.
  177. cheat = np.zeros(1, dtype)
  178. return np.lib.stride_tricks.as_strided(cheat, m.shape, (0 for _ in m.shape))
  179. def astype(self, dtype, *args, **kwargs):
  180. meta = type(self).meta_with_dtype(self._meta, dtype)
  181. full_args = (self, dtype,) + args
  182. # very important to pass the shared _lazy deque, or else there's an infinite loop somewhere.
  183. return type(self)(meta=meta, args=full_args, lazy=self._lazy, func=(lambda a: a[0].astype(*a[1:], **kwargs)))
  184. def tofile(self, *args, **kwargs):
  185. eager = LazyNumpyTensor.to_eager(self)
  186. return eager.tofile(*args, **kwargs)
  187. # TODO: __array_function__