lazy.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 | tuple[DTypeLike, Callable[[tuple[int, ...]], tuple[int, ...]]] = 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 and shape
  114. if meta_noop is not True:
  115. if isinstance(meta_noop, tuple):
  116. dtype, shape = meta_noop
  117. assert callable(shape)
  118. res = cls.meta_with_dtype_and_shape(dtype, shape(res.shape))
  119. else:
  120. res = cls.meta_with_dtype_and_shape(meta_noop, res.shape)
  121. if isinstance(res, cls._tensor_type):
  122. class CollectSharedLazy:
  123. # emulating a static variable
  124. shared_lazy: None | deque[LazyBase] = None
  125. @staticmethod
  126. def collect_replace(t: LazyBase):
  127. if CollectSharedLazy.shared_lazy is None:
  128. CollectSharedLazy.shared_lazy = t._lazy
  129. else:
  130. CollectSharedLazy.shared_lazy.extend(t._lazy)
  131. t._lazy = CollectSharedLazy.shared_lazy
  132. LazyBase._recurse_apply(args, CollectSharedLazy.collect_replace)
  133. shared_lazy = CollectSharedLazy.shared_lazy
  134. return cls(meta=cls.eager_to_meta(res), lazy=shared_lazy, args=args, func=lambda a: fn(*a, **kwargs))
  135. else:
  136. del res # not needed
  137. # non-tensor return likely relies on the contents of the args
  138. # (e.g. the result of torch.equal)
  139. eager_args = cls.to_eager(args)
  140. return fn(*eager_args, **kwargs)
  141. return wrapped_fn
  142. @classmethod
  143. def to_eager(cls, t: Any) -> Any:
  144. def simple_to_eager(_t: LazyBase) -> Any:
  145. def already_eager_to_eager(_t: LazyBase) -> Any:
  146. assert _t._data is not None
  147. return _t._data
  148. while _t._data is None:
  149. lt = _t._lazy.popleft()
  150. if lt._data is not None:
  151. # Lazy tensor did not belong in the lazy queue.
  152. # Weirdly only happens with Bloom models...
  153. # likely because tensors aren't unique in the queue.
  154. # The final output is still the same as in eager mode,
  155. # so it's safe to ignore this.
  156. continue
  157. assert lt._func is not None
  158. lt._args = cls._recurse_apply(lt._args, already_eager_to_eager)
  159. lt._data = lt._func(lt._args)
  160. # sanity check
  161. assert lt._data is not None
  162. assert lt._data.dtype == lt._meta.dtype
  163. assert lt._data.shape == lt._meta.shape
  164. return _t._data
  165. # recurse into lists and/or tuples, keeping their structure
  166. return cls._recurse_apply(t, simple_to_eager)
  167. @classmethod
  168. def eager_to_meta(cls, t: Any) -> Any:
  169. return cls.meta_with_dtype_and_shape(t.dtype, t.shape)
  170. # must be overridden, meta tensor init is backend-specific
  171. @classmethod
  172. @abstractmethod
  173. def meta_with_dtype_and_shape(cls, dtype: Any, shape: Any) -> Any: pass
  174. @classmethod
  175. def from_eager(cls, t: Any) -> Any:
  176. if type(t) is cls:
  177. # already eager
  178. return t
  179. elif isinstance(t, cls._tensor_type):
  180. return cls(meta=cls.eager_to_meta(t), data=t)
  181. else:
  182. return TypeError(f"{type(t)!r} is not compatible with {cls._tensor_type!r}")
  183. class LazyNumpyTensor(LazyBase):
  184. _tensor_type = np.ndarray
  185. @classmethod
  186. def meta_with_dtype_and_shape(cls, dtype: DTypeLike, shape: tuple[int, ...]) -> np.ndarray[Any, Any]:
  187. # The initial idea was to use np.nan as the fill value,
  188. # but non-float types like np.int16 can't use that.
  189. # So zero it is.
  190. cheat = np.zeros(1, dtype)
  191. return np.lib.stride_tricks.as_strided(cheat, shape, (0 for _ in shape))
  192. def astype(self, dtype, *args, **kwargs):
  193. meta = type(self).meta_with_dtype_and_shape(dtype, self._meta.shape)
  194. full_args = (self, dtype,) + args
  195. # very important to pass the shared _lazy deque, or else there's an infinite loop somewhere.
  196. return type(self)(meta=meta, args=full_args, lazy=self._lazy, func=(lambda a: a[0].astype(*a[1:], **kwargs)))
  197. def tofile(self, *args, **kwargs):
  198. eager = LazyNumpyTensor.to_eager(self)
  199. return eager.tofile(*args, **kwargs)
  200. # TODO: __array_function__