stateless.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. # mypy: allow-untyped-defs
  2. import contextlib
  3. from collections import defaultdict
  4. from typing import Any, Dict, Iterator, Optional, Set, Tuple, Union
  5. from typing_extensions import deprecated
  6. import torch
  7. from torch import Tensor
  8. from torch.nn.utils._named_member_accessor import NamedMemberAccessor
  9. __all__ = ["functional_call"]
  10. def _untie_named_tensors_map(
  11. module: "torch.nn.Module",
  12. parameters_and_buffers: Dict[str, Tensor],
  13. ) -> Dict[str, Tensor]:
  14. """
  15. Unties all tied tensors in the module to parameters_and_buffers.
  16. This function returns a new untied_parameters_and_buffers dictionary and leave the original
  17. untied_parameters_and_buffers dictionary unchanged. It adds new (missing) keys for tied tensors
  18. in the module to untied_parameters_and_buffers. The value of the new key is the user-given value
  19. in the original parameters_and_buffers dictionary.
  20. If there are more than one user-given values for the same tied tensor, it will raise an error.
  21. For example, if the module has two tied weights self.foo and self.tied_foo and the user passes
  22. {'foo': foo_value, ...}, this will return {'foo': foo_value, 'tied_foo': foo_value, ...}. If the
  23. user passes {'foo': foo_value, 'tied_foo': tied_foo_value, ...}, it will raise an error. If the
  24. user passes {'foo': foo_value, 'tied_foo': foo_value, ...}, it will not raise an error.
  25. Args:
  26. module (torch.nn.Module): the module to determine which tensors are tied.
  27. parameters_and_buffers (Dict[str, Tensor]): a map of {name: tensor} for reparamaterizing the module.
  28. Returns:
  29. A new untied version of the parameters_and_buffers dictionary.
  30. Raises:
  31. ValueError: if there are more than one user-given values for the same tied tensor.
  32. """
  33. # A map of {name: tensor} for all tensors (including tied ones) in the module.
  34. all_named_tensors: Dict[str, Tensor] = {}
  35. all_named_tensors.update(module.named_parameters(remove_duplicate=False))
  36. all_named_tensors.update(module.named_buffers(remove_duplicate=False))
  37. # A map of {tensor: set(all_tied_names)} for all tensor names in the module.
  38. tensor_to_tied_names_map: Dict[Tensor, Set[str]] = defaultdict(set)
  39. for name, tensor in all_named_tensors.items():
  40. tensor_to_tied_names_map[tensor].add(name)
  41. # A map of {tied_name: set(all_tied_names)} for all tensor names in the module.
  42. # If a name is not tied, it will not be in this map.
  43. tied_names_map: Dict[str, Set[str]] = {}
  44. for tied_names in tensor_to_tied_names_map.values():
  45. if len(tied_names) > 1:
  46. for tied_name in tied_names:
  47. tied_names_map[tied_name] = tied_names
  48. # Make sure the user didn't pass multiple values for the same tied tensor.
  49. given_names = set(parameters_and_buffers.keys())
  50. given_names_for_tied_tensors = given_names.intersection(tied_names_map.keys())
  51. for given_name in given_names_for_tied_tensors:
  52. tied_names = tied_names_map[given_name]
  53. if (
  54. # Detect if there are multiple keys present for the same tied tensor.
  55. len(tied_names.intersection(given_names_for_tied_tensors)) > 1
  56. # Only raise an error if the user passed multiple values for the same tied tensor.
  57. # If all given values are the same, don't raise.
  58. and len({parameters_and_buffers[tied_name] for tied_name in tied_names})
  59. != 1
  60. ):
  61. raise ValueError(
  62. f"functional_call got multiple values for keys {sorted(tied_names)}, "
  63. f"which are tied. Consider using tie_weights=False"
  64. )
  65. # Untie the given named tensor map
  66. # Make a copy for not modifying the original dict
  67. untied_parameters_and_buffers = parameters_and_buffers.copy()
  68. for given_name in given_names_for_tied_tensors:
  69. for tied_name in tied_names_map[given_name]:
  70. untied_parameters_and_buffers[tied_name] = parameters_and_buffers[
  71. given_name
  72. ]
  73. return untied_parameters_and_buffers
  74. @contextlib.contextmanager
  75. def _reparametrize_module(
  76. module: "torch.nn.Module",
  77. parameters_and_buffers: Dict[str, Tensor],
  78. *,
  79. tie_weights: bool = False,
  80. strict: bool = False,
  81. stack_weights: bool = False,
  82. ) -> Iterator[None]:
  83. if tie_weights:
  84. untied_parameters_and_buffers = _untie_named_tensors_map(
  85. module, parameters_and_buffers
  86. )
  87. else:
  88. untied_parameters_and_buffers = parameters_and_buffers
  89. accessor = NamedMemberAccessor(module)
  90. if strict:
  91. missing_keys, unexpected_keys = accessor.check_keys(
  92. untied_parameters_and_buffers
  93. )
  94. error_msgs = []
  95. if len(unexpected_keys) > 0:
  96. error_msgs.append(
  97. f"Unexpected key(s): {', '.join(map(repr, unexpected_keys))}."
  98. )
  99. if len(missing_keys) > 0:
  100. error_msgs.append(f"Missing key(s): {', '.join(map(repr, missing_keys))}.")
  101. if len(error_msgs) > 0:
  102. raise RuntimeError(
  103. "Error(s) in reparametrizing for {}:\n\t{}".format(
  104. module._get_name(), "\n\t".join(error_msgs)
  105. )
  106. )
  107. orig_parameters_and_buffers: Dict[str, Tensor] = {}
  108. try:
  109. orig_parameters_and_buffers, _ = accessor.swap_tensors_dict(
  110. untied_parameters_and_buffers, allow_missing=True
  111. )
  112. yield
  113. finally:
  114. if stack_weights:
  115. # When stacking is enabled, we will restore the weights in LIFO order.
  116. orig_parameters_and_buffers = dict(
  117. reversed(orig_parameters_and_buffers.items())
  118. )
  119. new_parameters_and_buffers, _ = accessor.swap_tensors_dict(
  120. orig_parameters_and_buffers, allow_missing=True
  121. )
  122. # Sometimes the module is not completely stateless and has some in-place modifications on
  123. # the _parameters and _buffers dictionaries.
  124. # Write the changed parameters and buffers back to the original dict.
  125. parameters_and_buffers.update(
  126. {
  127. k: new_parameters_and_buffers[k]
  128. for k in parameters_and_buffers
  129. if k in new_parameters_and_buffers
  130. }
  131. )
  132. @deprecated(
  133. "`torch.nn.utils.stateless.functional_call` is deprecated as of PyTorch 2.0 "
  134. "and will be removed in a future version of PyTorch. "
  135. "Please use `torch.func.functional_call` instead which is a drop-in replacement.",
  136. category=FutureWarning,
  137. )
  138. def functional_call(
  139. module: "torch.nn.Module",
  140. parameters_and_buffers: Dict[str, Tensor],
  141. args: Union[Any, Tuple],
  142. kwargs: Optional[Dict[str, Any]] = None,
  143. *,
  144. tie_weights: bool = True,
  145. strict: bool = False,
  146. ):
  147. r"""Perform a functional call on the module by replacing the module parameters and buffers with the provided ones.
  148. .. warning::
  149. This API is deprecated as of PyTorch 2.0 and will be removed in a future
  150. version of PyTorch. Please use :func:`torch.func.functional_call` instead,
  151. which is a drop-in replacement for this API.
  152. .. note:: If the module has active parametrizations, passing a value in the
  153. :attr:`parameters_and_buffers` argument with the name set to the regular parameter
  154. name will completely disable the parametrization.
  155. If you want to apply the parametrization function to the value passed
  156. please set the key as ``{submodule_name}.parametrizations.{parameter_name}.original``.
  157. .. note:: If the module performs in-place operations on parameters/buffers, these will be reflected
  158. in the `parameters_and_buffers` input.
  159. Example::
  160. >>> a = {'foo': torch.zeros(())}
  161. >>> # xdoctest: +SKIP
  162. >>> mod = Foo() # does self.foo = self.foo + 1
  163. >>> print(mod.foo) # tensor(0.)
  164. >>> functional_call(mod, a, torch.ones(()))
  165. >>> print(mod.foo) # tensor(0.)
  166. >>> print(a['foo']) # tensor(1.)
  167. .. note:: If the module has tied weights, whether or not functional_call respects the tying is determined by the
  168. tie_weights flag.
  169. Example::
  170. >>> a = {'foo': torch.zeros(())}
  171. >>> # xdoctest: +SKIP
  172. >>> mod = Foo() # has both self.foo and self.foo_tied which are tied. Returns x + self.foo + self.foo_tied
  173. >>> print(mod.foo) # tensor(1.)
  174. >>> mod(torch.zeros(())) # tensor(2.)
  175. >>> functional_call(mod, a, torch.zeros(())) # tensor(0.) since it will change self.foo_tied too
  176. >>> functional_call(mod, a, torch.zeros(()), tie_weights=False) # tensor(1.)--self.foo_tied is not updated
  177. >>> new_a = {'foo': torch.zeros(()), 'foo_tied': torch.zeros(())}
  178. >>> functional_call(mod, new_a, torch.zeros()) # tensor(0.)
  179. Args:
  180. module (torch.nn.Module): the module to call
  181. parameters_and_buffers (dict of str and Tensor): the parameters that will be used in
  182. the module call.
  183. args (Any or tuple): arguments to be passed to the module call. If not a tuple, considered a single argument.
  184. kwargs (dict): keyword arguments to be passed to the module call
  185. tie_weights (bool, optional): If True, then parameters and buffers tied in the original model will be treated as
  186. tied in the reparamaterized version. Therefore, if True and different values are passed for the tied
  187. parameters and buffers, it will error. If False, it will not respect the originally tied parameters and
  188. buffers unless the values passed for both weights are the same. Default: True.
  189. strict (bool, optional): If True, then the parameters and buffers passed in must match the parameters and
  190. buffers in the original module. Therefore, if True and there are any missing or unexpected keys, it will
  191. error. Default: False.
  192. Returns:
  193. Any: the result of calling ``module``.
  194. """
  195. return _functional_call(
  196. module,
  197. parameters_and_buffers,
  198. args,
  199. kwargs,
  200. tie_weights=tie_weights,
  201. strict=strict,
  202. )
  203. def _functional_call(
  204. module: "torch.nn.Module",
  205. parameters_and_buffers: Dict[str, Tensor],
  206. args: Union[Any, Tuple],
  207. kwargs: Optional[Dict[str, Any]] = None,
  208. *,
  209. tie_weights: bool = True,
  210. strict: bool = False,
  211. ):
  212. # TODO allow kwargs such as unsafe and others for parametrization
  213. if (
  214. torch.jit.is_tracing()
  215. or torch.jit.is_scripting()
  216. or isinstance(
  217. module,
  218. (
  219. torch.jit.RecursiveScriptModule,
  220. torch.jit.ScriptModule,
  221. torch.jit.ScriptFunction,
  222. ),
  223. )
  224. ):
  225. raise RuntimeError("The stateless API can't be used with Jitted modules")
  226. if isinstance(module, torch.nn.DataParallel):
  227. raise RuntimeError(
  228. "The stateless API can't be used with nn.DataParallel module"
  229. )
  230. if kwargs is None:
  231. kwargs = {}
  232. if not isinstance(args, tuple):
  233. args = (args,)
  234. with _reparametrize_module(
  235. module, parameters_and_buffers, tie_weights=tie_weights, strict=strict
  236. ):
  237. return module(*args, **kwargs)