lazy.py 9.0 KB

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