parameter.py 9.0 KB

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