parameter.py 9.3 KB

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