stateless.py 11 KB

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