stateless.py 11 KB

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