parameter.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. from collections import OrderedDict
  2. from typing import Any
  3. import torch
  4. from torch._C import _disabled_torch_function_impl
  5. __all__ = [
  6. "Parameter",
  7. "UninitializedParameter",
  8. "is_lazy",
  9. "Buffer",
  10. "UninitializedBuffer",
  11. "UninitializedTensorMixin",
  12. ]
  13. # Metaclass to combine _TensorMeta and the instance check override for Parameter.
  14. class _ParameterMeta(torch._C._TensorMeta):
  15. # Make `isinstance(t, Parameter)` return True for custom tensor instances that have the _is_param flag.
  16. def __instancecheck__(self, instance) -> bool:
  17. if self is Parameter:
  18. if isinstance(instance, torch.Tensor) and getattr(
  19. instance, "_is_param", False
  20. ):
  21. return True
  22. return super().__instancecheck__(instance)
  23. class Parameter(torch.Tensor, metaclass=_ParameterMeta):
  24. r"""A kind of Tensor that is to be considered a module parameter.
  25. Parameters are :class:`~torch.Tensor` subclasses, that have a
  26. very special property when used with :class:`Module` s - when they're
  27. assigned as Module attributes they are automatically added to the list of
  28. its parameters, and will appear e.g. in :meth:`~Module.parameters` iterator.
  29. Assigning a Tensor doesn't have such effect. This is because one might
  30. want to cache some temporary state, like last hidden state of the RNN, in
  31. the model. If there was no such class as :class:`Parameter`, these
  32. temporaries would get registered too.
  33. Args:
  34. data (Tensor): parameter tensor.
  35. requires_grad (bool, optional): if the parameter requires gradient. Note that
  36. the torch.no_grad() context does NOT affect the default behavior of
  37. Parameter creation--the Parameter will still have `requires_grad=True` in
  38. :class:`~no_grad` mode. See :ref:`locally-disable-grad-doc` for more
  39. details. Default: `True`
  40. """
  41. def __new__(cls, data=None, requires_grad=True):
  42. if data is None:
  43. data = torch.empty(0)
  44. if type(data) is torch.Tensor or type(data) is Parameter:
  45. # For ease of BC maintenance, keep this path for standard Tensor.
  46. # Eventually (tm), we should change the behavior for standard Tensor to match.
  47. return torch.Tensor._make_subclass(cls, data, requires_grad)
  48. # Path for custom tensors: set a flag on the instance to indicate parameter-ness.
  49. t = data.detach().requires_grad_(requires_grad)
  50. if type(t) is not type(data):
  51. raise RuntimeError(
  52. f"Creating a Parameter from an instance of type {type(data).__name__} "
  53. "requires that detach() returns an instance of the same type, but return "
  54. f"type {type(t).__name__} was found instead. To use the type as a "
  55. "Parameter, please correct the detach() semantics defined by "
  56. "its __torch_dispatch__() implementation."
  57. )
  58. t._is_param = True
  59. return t
  60. # Note: the 3 methods below only apply to standard Tensor. Parameters of custom tensor types
  61. # are still considered that custom tensor type and these methods will not be called for them.
  62. def __deepcopy__(self, memo):
  63. if id(self) in memo:
  64. return memo[id(self)]
  65. else:
  66. result = type(self)(
  67. self.data.clone(memory_format=torch.preserve_format), self.requires_grad
  68. )
  69. memo[id(self)] = result
  70. return result
  71. # pyrefly: ignore [bad-override]
  72. def __repr__(self) -> str:
  73. return "Parameter containing:\n" + super().__repr__()
  74. def __reduce_ex__(self, proto):
  75. state = torch._utils._get_obj_state(self)
  76. # See Note [Don't serialize hooks]
  77. hooks = OrderedDict()
  78. if not state:
  79. return (
  80. torch._utils._rebuild_parameter,
  81. (self.data, self.requires_grad, hooks),
  82. )
  83. return (
  84. torch._utils._rebuild_parameter_with_state,
  85. (self.data, self.requires_grad, hooks, state),
  86. )
  87. __torch_function__ = _disabled_torch_function_impl
  88. class UninitializedTensorMixin:
  89. _allowed_methods = [
  90. torch.Tensor.__hash__,
  91. torch.Tensor.size,
  92. torch.Tensor.copy_,
  93. torch.Tensor.is_complex,
  94. torch.Tensor.is_floating_point,
  95. torch.Tensor.half,
  96. torch.Tensor.float,
  97. torch.Tensor.double,
  98. torch.Tensor.char,
  99. torch.Tensor.short,
  100. torch.Tensor.int,
  101. torch.Tensor.long,
  102. torch.Tensor.cuda,
  103. torch.Tensor.cpu,
  104. torch.Tensor.to,
  105. torch.Tensor.get_device,
  106. torch._has_compatible_shallow_copy_type,
  107. ]
  108. def materialize(self, shape, device=None, dtype=None) -> None:
  109. r"""Create a Parameter or Tensor with the same properties of the uninitialized one.
  110. Given a shape, it materializes a parameter in the same device
  111. and with the same `dtype` as the current one or the specified ones in the
  112. arguments.
  113. Args:
  114. shape : (tuple): the shape for the materialized tensor.
  115. device (:class:`torch.device`): the desired device of the parameters
  116. and buffers in this module. Optional.
  117. dtype (:class:`torch.dtype`): the desired floating point type of
  118. the floating point parameters and buffers in this module. Optional.
  119. """
  120. if device is None:
  121. device = self.data.device
  122. if dtype is None:
  123. dtype = self.data.dtype
  124. self.data = torch.empty(shape, device=device, dtype=dtype)
  125. # pyrefly: ignore [bad-override, missing-attribute]
  126. self.__class__ = self.cls_to_become
  127. @property
  128. def shape(self):
  129. raise RuntimeError(
  130. "Can't access the shape of an uninitialized parameter or buffer. "
  131. "This error usually happens in `load_state_dict` when trying to load "
  132. "an uninitialized parameter into an initialized one. "
  133. "Call `forward` to initialize the parameters before accessing their attributes."
  134. )
  135. def share_memory_(self):
  136. raise RuntimeError(
  137. "Can't share memory on an uninitialized parameter or buffer. "
  138. "Call `forward` to initialize the parameters before calling "
  139. "`module.share_memory()`."
  140. )
  141. def __repr__(self) -> str:
  142. return f"<{self.__class__.__name__}>"
  143. def __reduce_ex__(self, proto):
  144. # See Note [Don't serialize hooks]
  145. # pyrefly: ignore [missing-attribute]
  146. return (self.__class__, (self.requires_grad,))
  147. @classmethod
  148. def __torch_function__(cls, func, types, args=(), kwargs=None):
  149. # method-wrapper is to detect access to Tensor properties that are
  150. # wrapped in descriptors
  151. if func in cls._allowed_methods or func.__class__.__name__ == "method-wrapper":
  152. if kwargs is None:
  153. kwargs = {}
  154. # pyrefly: ignore [missing-attribute]
  155. return super().__torch_function__(func, types, args, kwargs)
  156. raise ValueError(
  157. f"Attempted to use an uninitialized parameter in {func}. "
  158. "This error happens when you are using a `LazyModule` or "
  159. f"explicitly manipulating `torch.nn.parameter.{cls.__name__}` "
  160. "objects. When using LazyModules Call `forward` with a dummy batch "
  161. "to initialize the parameters before calling torch functions"
  162. )
  163. def is_lazy(param: Any) -> bool:
  164. """
  165. Returns whether ``param`` is an ``UninitializedParameter`` or ``UninitializedBuffer``.
  166. Args:
  167. param (Any): the input to check.
  168. """
  169. return isinstance(param, UninitializedTensorMixin)
  170. # pyrefly: ignore [inconsistent-inheritance]
  171. class UninitializedParameter(UninitializedTensorMixin, Parameter):
  172. r"""A parameter that is not initialized.
  173. Uninitialized Parameters are a special case of :class:`torch.nn.Parameter`
  174. where the shape of the data is still unknown.
  175. Unlike a :class:`torch.nn.Parameter`, uninitialized parameters
  176. hold no data and attempting to access some properties, like their shape,
  177. will throw a runtime error. The only operations that can be performed on a uninitialized
  178. parameter are changing its datatype, moving it to a different device and
  179. converting it to a regular :class:`torch.nn.Parameter`.
  180. The default device or dtype to use when the parameter is materialized can be set
  181. during construction using e.g. ``device='cuda'``.
  182. """
  183. cls_to_become = Parameter
  184. def __new__(cls, requires_grad=True, device=None, dtype=None) -> None:
  185. factory_kwargs = {"device": device, "dtype": dtype}
  186. data = torch.empty(0, **factory_kwargs)
  187. # pyrefly: ignore [bad-return]
  188. return torch.Tensor._make_subclass(cls, data, requires_grad)
  189. def __deepcopy__(self, memo):
  190. if id(self) in memo:
  191. return memo[id(self)]
  192. else:
  193. result = type(self)(self.requires_grad, self.data.device, self.data.dtype)
  194. memo[id(self)] = result
  195. return result
  196. # Metaclass to combine _TensorMeta and the instance check override for Buffer.
  197. class _BufferMeta(torch._C._TensorMeta):
  198. # Make `isinstance(t, Buffer)` return True for custom tensor instances that have the _is_buffer flag.
  199. def __instancecheck__(self, instance) -> bool:
  200. if self is Buffer:
  201. if isinstance(instance, torch.Tensor) and getattr(
  202. instance, "_is_buffer", False
  203. ):
  204. return True
  205. return super().__instancecheck__(instance)
  206. class Buffer(torch.Tensor, metaclass=_BufferMeta):
  207. r"""A kind of Tensor that should not be considered a model
  208. parameter. For example, BatchNorm's ``running_mean`` is not a parameter, but is part of the module's state.
  209. Buffers are :class:`~torch.Tensor` subclasses, that have a
  210. very special property when used with :class:`Module` s -- when they're
  211. assigned as Module attributes they are automatically added to the list of
  212. its buffers, and will appear e.g. in :meth:`~torch.nn.Module.buffers` iterator.
  213. Assigning a Tensor doesn't have such effect. One can still assign a Tensor as explicitly by using
  214. the :meth:`~torch.nn.Module.register_buffer` function.
  215. Args:
  216. data (Tensor): buffer tensor.
  217. persistent (bool, optional): whether the buffer is part of the module's
  218. :attr:`state_dict`. Default: ``True``
  219. """
  220. def __new__(cls, data=None, *, persistent=True):
  221. if data is None:
  222. data = torch.empty(0)
  223. t = data.detach().requires_grad_(data.requires_grad)
  224. # pyrefly: ignore [missing-attribute]
  225. t.persistent = persistent
  226. # pyrefly: ignore [missing-attribute]
  227. t._is_buffer = True
  228. return t
  229. __torch_function__ = _disabled_torch_function_impl
  230. class UninitializedBuffer(UninitializedTensorMixin, torch.Tensor):
  231. r"""A buffer that is not initialized.
  232. Uninitialized Buffer is a a special case of :class:`torch.Tensor`
  233. where the shape of the data is still unknown.
  234. Unlike a :class:`torch.Tensor`, uninitialized parameters
  235. hold no data and attempting to access some properties, like their shape,
  236. will throw a runtime error. The only operations that can be performed on a uninitialized
  237. parameter are changing its datatype, moving it to a different device and
  238. converting it to a regular :class:`torch.Tensor`.
  239. The default device or dtype to use when the buffer is materialized can be set
  240. during construction using e.g. ``device='cuda'``.
  241. """
  242. cls_to_become = torch.Tensor
  243. def __new__(
  244. cls, requires_grad=False, device=None, dtype=None, persistent=True
  245. ) -> None:
  246. factory_kwargs = {"device": device, "dtype": dtype}
  247. data = torch.empty(0, **factory_kwargs)
  248. ret = torch.Tensor._make_subclass(cls, data, requires_grad)
  249. # pyrefly: ignore [missing-attribute]
  250. ret.persistent = persistent
  251. # pyrefly: ignore [missing-attribute]
  252. ret._is_buffer = True
  253. # pyrefly: ignore [bad-return]
  254. return ret