stateless.py 11 KB

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